diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000000000000000000000000000000000000..ce24915a6037a46f90fad5a54c1d30ae0f225a85 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,5 @@ +extensions +extensions-disabled +extensions-builtin/sd_forge_controlnet +repositories +venv \ No newline at end of file diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000000000000000000000000000000000000..2e7258f6b135709026b99147214848aca7ec0c90 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,98 @@ +/* global module */ +module.exports = { + env: { + browser: true, + es2021: true, + }, + extends: "eslint:recommended", + parserOptions: { + ecmaVersion: "latest", + }, + rules: { + "arrow-spacing": "error", + "block-spacing": "error", + "brace-style": "error", + "comma-dangle": ["error", "only-multiline"], + "comma-spacing": "error", + "comma-style": ["error", "last"], + "curly": ["error", "multi-line", "consistent"], + "eol-last": "error", + "func-call-spacing": "error", + "function-call-argument-newline": ["error", "consistent"], + "function-paren-newline": ["error", "consistent"], + "indent": ["error", 4], + "key-spacing": "error", + "keyword-spacing": "error", + "linebreak-style": ["error", "unix"], + "no-extra-semi": "error", + "no-mixed-spaces-and-tabs": "error", + "no-multi-spaces": "error", + "no-redeclare": ["error", {builtinGlobals: false}], + "no-trailing-spaces": "error", + "no-unused-vars": "off", + "no-whitespace-before-property": "error", + "object-curly-newline": ["error", {consistent: true, multiline: true}], + "object-curly-spacing": ["error", "never"], + "operator-linebreak": ["error", "after"], + "quote-props": ["error", "consistent-as-needed"], + "semi": ["error", "always"], + "semi-spacing": "error", + "semi-style": ["error", "last"], + "space-before-blocks": "error", + "space-before-function-paren": ["error", "never"], + "space-in-parens": ["error", "never"], + "space-infix-ops": "error", + "space-unary-ops": "error", + "switch-colon-spacing": "error", + "template-curly-spacing": ["error", "never"], + "unicode-bom": "error", + }, + globals: { + //script.js + gradioApp: "readonly", + executeCallbacks: "readonly", + onAfterUiUpdate: "readonly", + onOptionsChanged: "readonly", + onUiLoaded: "readonly", + onUiUpdate: "readonly", + uiCurrentTab: "writable", + uiElementInSight: "readonly", + uiElementIsVisible: "readonly", + //ui.js + opts: "writable", + all_gallery_buttons: "readonly", + selected_gallery_button: "readonly", + selected_gallery_index: "readonly", + switch_to_txt2img: "readonly", + switch_to_img2img_tab: "readonly", + switch_to_img2img: "readonly", + switch_to_sketch: "readonly", + switch_to_inpaint: "readonly", + switch_to_inpaint_sketch: "readonly", + switch_to_extras: "readonly", + get_tab_index: "readonly", + create_submit_args: "readonly", + restart_reload: "readonly", + updateInput: "readonly", + onEdit: "readonly", + //extraNetworks.js + requestGet: "readonly", + popup: "readonly", + // profilerVisualization.js + createVisualizationTable: "readonly", + // from python + localization: "readonly", + // progrssbar.js + randomId: "readonly", + requestProgress: "readonly", + // imageviewer.js + modalPrevImage: "readonly", + modalNextImage: "readonly", + // localStorage.js + localSet: "readonly", + localGet: "readonly", + localRemove: "readonly", + // resizeHandle.js + setupResizeHandle: "writable" + } +}; diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000000000000000000000000000000000000..4104da632b8fcacf3a6f52eba093e63059749725 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# Apply ESlint +9c54b78d9dde5601e916f308d9a9d6953ec39430 \ No newline at end of file diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..e51f204b2540ba6b69998bf9080dcb65296ff7b9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +extensions-builtin/sd-civitai-browser-plus-main/aria2/lin/aria2 filter=lfs diff=lfs merge=lfs -text +extensions-builtin/sd-civitai-browser-plus-main/aria2/win/aria2.exe filter=lfs diff=lfs merge=lfs -text +extensions-builtin/sd-model-downloader/images/instructions.png filter=lfs diff=lfs merge=lfs -text +extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/sample-55dcafc6.webp filter=lfs diff=lfs merge=lfs -text +extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/icon.icns filter=lfs diff=lfs merge=lfs -text +extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/icon.png filter=lfs diff=lfs merge=lfs -text +extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/globalSetting/sample.webp filter=lfs diff=lfs merge=lfs -text +models/reactor/faces/FileDate.exe filter=lfs diff=lfs merge=lfs -text +modules/Roboto-Regular.ttf filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bbdca3011564d40fa16825c6bf749aba05e3863c --- /dev/null +++ b/.gitignore @@ -0,0 +1,57 @@ +huggingface_space_mirror/ +random_test.py +__pycache__ +*.ckpt +*.safetensors +*.pth +*.dev.js +*_s.py +*_u.py +*_m.py +*_i.py +.DS_Store +/output/ +/outputs/ +/ESRGAN/* +/SwinIR/* +/repositories +/venv +/tmp +/output +/model.ckpt +/models/**/* +/GFPGANv1.3.pth +/gfpgan/weights/*.pth +/ui-config.json +/outputs +/config.json +/log +/webui.settings.bat +/embeddings +/styles.csv +/params.txt +/styles.csv.bak +/webui-user.bat +/webui-user.sh +/interrogate +/user.css +/.idea +notification.mp3 +/SwinIR +/textual_inversion +.vscode +/extensions +/test/stdout.txt +/test/stderr.txt +/cache.json* +/config_states/ +/node_modules +/package-lock.json +/.coverage* +/test/test_outputs +/cache +trace.json +/sysinfo-????-??-??-??-??.json +/test/results.xml +coverage.xml +**/tests/**/expectations diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000000000000000000000000000000000000..53254e5dcfd871c8c0f0f4dec9dceeb1ba967eda --- /dev/null +++ b/.pylintrc @@ -0,0 +1,3 @@ +# See https://pylint.pycqa.org/en/latest/user_guide/messages/message_control.html +[MESSAGES CONTROL] +disable=C,R,W,E,I diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..5f7e59351cba4e39ac894fa1887345e77f4fb787 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,1085 @@ +## 1.10.1 + +### Bug Fixes: +* fix image upscale on cpu ([#16275](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16275)) + + +## 1.10.0 + +### Features: +* A lot of performance improvements (see below in Performance section) +* Stable Diffusion 3 support ([#16030](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16030), [#16164](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16164), [#16212](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16212)) + * Recommended Euler sampler; DDIM and other timestamp samplers currently not supported + * T5 text model is disabled by default, enable it in settings +* New schedulers: + * Align Your Steps ([#15751](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15751)) + * KL Optimal ([#15608](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15608)) + * Normal ([#16149](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16149)) + * DDIM ([#16149](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16149)) + * Simple ([#16142](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16142)) + * Beta ([#16235](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16235)) +* New sampler: DDIM CFG++ ([#16035](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16035)) + +### Minor: +* Option to skip CFG on early steps ([#15607](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15607)) +* Add --models-dir option ([#15742](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15742)) +* Allow mobile users to open context menu by using two fingers press ([#15682](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15682)) +* Infotext: add Lora name as TI hashes for bundled Textual Inversion ([#15679](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15679)) +* Check model's hash after downloading it to prevent corruped downloads ([#15602](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15602)) +* More extension tag filtering options ([#15627](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15627)) +* When saving AVIF, use JPEG's quality setting ([#15610](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15610)) +* Add filename pattern: `[basename]` ([#15978](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15978)) +* Add option to enable clip skip for clip L on SDXL ([#15992](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15992)) +* Option to prevent screen sleep during generation ([#16001](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16001)) +* ToggleLivePriview button in image viewer ([#16065](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16065)) +* Remove ui flashing on reloading and fast scrollong ([#16153](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16153)) +* option to disable save button log.csv ([#16242](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16242)) + +### Extensions and API: +* Add process_before_every_sampling hook ([#15984](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15984)) +* Return HTTP 400 instead of 404 on invalid sampler error ([#16140](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16140)) + +### Performance: +* [Performance 1/6] use_checkpoint = False ([#15803](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15803)) +* [Performance 2/6] Replace einops.rearrange with torch native ops ([#15804](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15804)) +* [Performance 4/6] Precompute is_sdxl_inpaint flag ([#15806](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15806)) +* [Performance 5/6] Prevent unnecessary extra networks bias backup ([#15816](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15816)) +* [Performance 6/6] Add --precision half option to avoid casting during inference ([#15820](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15820)) +* [Performance] LDM optimization patches ([#15824](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15824)) +* [Performance] Keep sigmas on CPU ([#15823](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15823)) +* Check for nans in unet only once, after all steps have been completed +* Added pption to run torch profiler for image generation + +### Bug Fixes: +* Fix for grids without comprehensive infotexts ([#15958](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15958)) +* feat: lora partial update precede full update ([#15943](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15943)) +* Fix bug where file extension had an extra '.' under some circumstances ([#15893](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15893)) +* Fix corrupt model initial load loop ([#15600](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15600)) +* Allow old sampler names in API ([#15656](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15656)) +* more old sampler scheduler compatibility ([#15681](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15681)) +* Fix Hypertile xyz ([#15831](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15831)) +* XYZ CSV skipinitialspace ([#15832](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15832)) +* fix soft inpainting on mps and xpu, torch_utils.float64 ([#15815](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15815)) +* fix extention update when not on main branch ([#15797](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15797)) +* update pickle safe filenames +* use relative path for webui-assets css ([#15757](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15757)) +* When creating a virtual environment, upgrade pip in webui.bat/webui.sh ([#15750](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15750)) +* Fix AttributeError ([#15738](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15738)) +* use script_path for webui root in launch_utils ([#15705](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15705)) +* fix extra batch mode P Transparency ([#15664](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15664)) +* use gradio theme colors in css ([#15680](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15680)) +* Fix dragging text within prompt input ([#15657](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15657)) +* Add correct mimetype for .mjs files ([#15654](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15654)) +* QOL Items - handle metadata issues more cleanly for SD models, Loras and embeddings ([#15632](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15632)) +* replace wsl-open with wslpath and explorer.exe ([#15968](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15968)) +* Fix SDXL Inpaint ([#15976](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15976)) +* multi size grid ([#15988](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15988)) +* fix Replace preview ([#16118](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16118)) +* Possible fix of wrong scale in weight decomposition ([#16151](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16151)) +* Ensure use of python from venv on Mac and Linux ([#16116](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16116)) +* Prioritize python3.10 over python3 if both are available on Linux and Mac (with fallback) ([#16092](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16092)) +* stoping generation extras ([#16085](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16085)) +* Fix SD2 loading ([#16078](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16078), [#16079](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16079)) +* fix infotext Lora hashes for hires fix different lora ([#16062](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16062)) +* Fix sampler scheduler autocorrection warning ([#16054](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16054)) +* fix ui flashing on reloading and fast scrollong ([#16153](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16153)) +* fix upscale logic ([#16239](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16239)) +* [bug] do not break progressbar on non-job actions (add wrap_gradio_call_no_job) ([#16202](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16202)) +* fix OSError: cannot write mode P as JPEG ([#16194](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16194)) + +### Other: +* fix changelog #15883 -> #15882 ([#15907](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15907)) +* ReloadUI backgroundColor --background-fill-primary ([#15864](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15864)) +* Use different torch versions for Intel and ARM Macs ([#15851](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15851)) +* XYZ override rework ([#15836](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15836)) +* scroll extensions table on overflow ([#15830](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15830)) +* img2img batch upload method ([#15817](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15817)) +* chore: sync v1.8.0 packages according to changelog ([#15783](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15783)) +* Add AVIF MIME type support to mimetype definitions ([#15739](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15739)) +* Update imageviewer.js ([#15730](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15730)) +* no-referrer ([#15641](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15641)) +* .gitignore trace.json ([#15980](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15980)) +* Bump spandrel to 0.3.4 ([#16144](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16144)) +* Defunct --max-batch-count ([#16119](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16119)) +* docs: update bug_report.yml ([#16102](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16102)) +* Maintaining Project Compatibility for Python 3.9 Users Without Upgrade Requirements. ([#16088](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16088), [#16169](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16169), [#16192](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16192)) +* Update torch for ARM Macs to 2.3.1 ([#16059](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16059)) +* remove deprecated setting dont_fix_second_order_samplers_schedule ([#16061](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16061)) +* chore: fix typos ([#16060](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16060)) +* shlex.join launch args in console log ([#16170](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16170)) +* activate venv .bat ([#16231](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16231)) +* add ids to the resize tabs in img2img ([#16218](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16218)) +* update installation guide linux ([#16178](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16178)) +* Robust sysinfo ([#16173](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16173)) +* do not send image size on paste inpaint ([#16180](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16180)) +* Fix noisy DS_Store files for MacOS ([#16166](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16166)) + + +## 1.9.4 + +### Bug Fixes: +* pin setuptools version to fix the startup error ([#15882](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15882)) + +## 1.9.3 + +### Bug Fixes: +* fix get_crop_region_v2 ([#15594](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15594)) + +## 1.9.2 + +### Extensions and API: +* restore 1.8.0-style naming of scripts + +## 1.9.1 + +### Minor: +* Add avif support ([#15582](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15582)) +* Add filename patterns: `[sampler_scheduler]` and `[scheduler]` ([#15581](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15581)) + +### Extensions and API: +* undo adding scripts to sys.modules +* Add schedulers API endpoint ([#15577](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15577)) +* Remove API upscaling factor limits ([#15560](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15560)) + +### Bug Fixes: +* Fix images do not match / Coordinate 'right' is less than 'left' ([#15534](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15534)) +* fix: remove_callbacks_for_function should also remove from the ordered map ([#15533](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15533)) +* fix x1 upscalers ([#15555](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15555)) +* Fix cls.__module__ value in extension script ([#15532](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15532)) +* fix typo in function call (eror -> error) ([#15531](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15531)) + +### Other: +* Hide 'No Image data blocks found.' message ([#15567](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15567)) +* Allow webui.sh to be runnable from arbitrary directories containing a .git file ([#15561](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15561)) +* Compatibility with Debian 11, Fedora 34+ and openSUSE 15.4+ ([#15544](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15544)) +* numpy DeprecationWarning product -> prod ([#15547](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15547)) +* get_crop_region_v2 ([#15583](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15583), [#15587](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15587)) + + +## 1.9.0 + +### Features: +* Make refiner switchover based on model timesteps instead of sampling steps ([#14978](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14978)) +* add an option to have old-style directory view instead of tree view; stylistic changes for extra network sorting/search controls +* add UI for reordering callbacks, support for specifying callback order in extension metadata ([#15205](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15205)) +* Sgm uniform scheduler for SDXL-Lightning models ([#15325](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15325)) +* Scheduler selection in main UI ([#15333](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15333), [#15361](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15361), [#15394](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15394)) + +### Minor: +* "open images directory" button now opens the actual dir ([#14947](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14947)) +* Support inference with LyCORIS BOFT networks ([#14871](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14871), [#14973](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14973)) +* make extra network card description plaintext by default, with an option to re-enable HTML as it was +* resize handle for extra networks ([#15041](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15041)) +* cmd args: `--unix-filenames-sanitization` and `--filenames-max-length` ([#15031](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15031)) +* show extra networks parameters in HTML table rather than raw JSON ([#15131](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15131)) +* Add DoRA (weight-decompose) support for LoRA/LoHa/LoKr ([#15160](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15160), [#15283](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15283)) +* Add '--no-prompt-history' cmd args for disable last generation prompt history ([#15189](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15189)) +* update preview on Replace Preview ([#15201](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15201)) +* only fetch updates for extensions' active git branches ([#15233](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15233)) +* put upscale postprocessing UI into an accordion ([#15223](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15223)) +* Support dragdrop for URLs to read infotext ([#15262](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15262)) +* use diskcache library for caching ([#15287](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15287), [#15299](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15299)) +* Allow PNG-RGBA for Extras Tab ([#15334](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15334)) +* Support cover images embedded in safetensors metadata ([#15319](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15319)) +* faster interrupt when using NN upscale ([#15380](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15380)) +* Extras upscaler: an input field to limit maximul side length for the output image ([#15293](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15293), [#15415](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15415), [#15417](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15417), [#15425](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15425)) +* add an option to hide postprocessing options in Extras tab + +### Extensions and API: +* ResizeHandleRow - allow overriden column scale parametr ([#15004](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15004)) +* call script_callbacks.ui_settings_callback earlier; fix extra-options-section built-in extension killing the ui if using a setting that doesn't exist +* make it possible to use zoom.js outside webui context ([#15286](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15286), [#15288](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15288)) +* allow variants for extension name in metadata.ini ([#15290](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15290)) +* make reloading UI scripts optional when doing Reload UI, and off by default +* put request: gr.Request at start of img2img function similar to txt2img +* open_folder as util ([#15442](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15442)) +* make it possible to import extensions' script files as `import scripts.` ([#15423](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15423)) + +### Performance: +* performance optimization for extra networks HTML pages +* optimization for extra networks filtering +* optimization for extra networks sorting + +### Bug Fixes: +* prevent escape button causing an interrupt when no generation has been made yet +* [bug] avoid doble upscaling in inpaint ([#14966](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14966)) +* possible fix for reload button not appearing in some cases for extra networks. +* fix: the `split_threshold` parameter does not work when running Split oversized images ([#15006](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15006)) +* Fix resize-handle visability for vertical layout (mobile) ([#15010](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15010)) +* register_tmp_file also for mtime ([#15012](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15012)) +* Protect alphas_cumprod during refiner switchover ([#14979](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14979)) +* Fix EXIF orientation in API image loading ([#15062](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15062)) +* Only override emphasis if actually used in prompt ([#15141](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15141)) +* Fix emphasis infotext missing from `params.txt` ([#15142](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15142)) +* fix extract_style_text_from_prompt #15132 ([#15135](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15135)) +* Fix Soft Inpaint for AnimateDiff ([#15148](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15148)) +* edit-attention: deselect surrounding whitespace ([#15178](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15178)) +* chore: fix font not loaded ([#15183](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15183)) +* use natural sort in extra networks when ordering by path +* Fix built-in lora system bugs caused by torch.nn.MultiheadAttention ([#15190](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15190)) +* Avoid error from None in get_learned_conditioning ([#15191](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15191)) +* Add entry to MassFileLister after writing metadata ([#15199](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15199)) +* fix issue with Styles when Hires prompt is used ([#15269](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15269), [#15276](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15276)) +* Strip comments from hires fix prompt ([#15263](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15263)) +* Make imageviewer event listeners browser consistent ([#15261](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15261)) +* Fix AttributeError in OFT when trying to get MultiheadAttention weight ([#15260](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15260)) +* Add missing .mean() back ([#15239](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15239)) +* fix "Restore progress" button ([#15221](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15221)) +* fix ui-config for InputAccordion [custom_script_source] ([#15231](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15231)) +* handle 0 wheel deltaY ([#15268](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15268)) +* prevent alt menu for firefox ([#15267](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15267)) +* fix: fix syntax errors ([#15179](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15179)) +* restore outputs path ([#15307](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15307)) +* Escape btn_copy_path filename ([#15316](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15316)) +* Fix extra networks buttons when filename contains an apostrophe ([#15331](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15331)) +* escape brackets in lora random prompt generator ([#15343](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15343)) +* fix: Python version check for PyTorch installation compatibility ([#15390](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15390)) +* fix typo in call_queue.py ([#15386](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15386)) +* fix: when find already_loaded model, remove loaded by array index ([#15382](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15382)) +* minor bug fix of sd model memory management ([#15350](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15350)) +* Fix CodeFormer weight ([#15414](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15414)) +* Fix: Remove script callbacks in ordered_callbacks_map ([#15428](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15428)) +* fix limited file write (thanks, Sylwia) +* Fix extra-single-image API not doing upscale failed ([#15465](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15465)) +* error handling paste_field callables ([#15470](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15470)) + +### Hardware: +* Add training support and change lspci for Ascend NPU ([#14981](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14981)) +* Update to ROCm5.7 and PyTorch ([#14820](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14820)) +* Better workaround for Navi1, removing --pre for Navi3 ([#15224](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15224)) +* Ascend NPU wiki page ([#15228](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15228)) + +### Other: +* Update comment for Pad prompt/negative prompt v0 to add a warning about truncation, make it override the v1 implementation +* support resizable columns for touch (tablets) ([#15002](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15002)) +* Fix #14591 using translated content to do categories mapping ([#14995](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14995)) +* Use `absolute` path for normalized filepath ([#15035](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15035)) +* resizeHandle handle double tap ([#15065](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15065)) +* --dat-models-path cmd flag ([#15039](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15039)) +* Add a direct link to the binary release ([#15059](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15059)) +* upscaler_utils: Reduce logging ([#15084](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15084)) +* Fix various typos with crate-ci/typos ([#15116](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15116)) +* fix_jpeg_live_preview ([#15102](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15102)) +* [alternative fix] can't load webui if selected wrong extra option in ui ([#15121](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15121)) +* Error handling for unsupported transparency ([#14958](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14958)) +* Add model description to searched terms ([#15198](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15198)) +* bump action version ([#15272](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15272)) +* PEP 604 annotations ([#15259](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15259)) +* Automatically Set the Scale by value when user selects an Upscale Model ([#15244](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15244)) +* move postprocessing-for-training into builtin extensions ([#15222](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15222)) +* type hinting in shared.py ([#15211](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15211)) +* update ruff to 0.3.3 +* Update pytorch lightning utilities ([#15310](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15310)) +* Add Size as an XYZ Grid option ([#15354](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15354)) +* Use HF_ENDPOINT variable for HuggingFace domain with default ([#15443](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15443)) +* re-add update_file_entry ([#15446](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15446)) +* create_infotext allow index and callable, re-work Hires prompt infotext ([#15460](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15460)) +* update restricted_opts to include more options for --hide-ui-dir-config ([#15492](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15492)) + + +## 1.8.0 + +### Features: +* Update torch to version 2.1.2 +* Soft Inpainting ([#14208](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14208)) +* FP8 support ([#14031](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14031), [#14327](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14327)) +* Support for SDXL-Inpaint Model ([#14390](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14390)) +* Use Spandrel for upscaling and face restoration architectures ([#14425](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14425), [#14467](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14467), [#14473](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14473), [#14474](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14474), [#14477](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14477), [#14476](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14476), [#14484](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14484), [#14500](https://github.com/AUTOMATIC1111/stable-difusion-webui/pull/14500), [#14501](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14501), [#14504](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14504), [#14524](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14524), [#14809](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14809)) +* Automatic backwards version compatibility (when loading infotexts from old images with program version specified, will add compatibility settings) +* Implement zero terminal SNR noise schedule option (**[SEED BREAKING CHANGE](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Seed-breaking-changes#180-dev-170-225-2024-01-01---zero-terminal-snr-noise-schedule-option)**, [#14145](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14145), [#14979](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14979)) +* Add a [✨] button to run hires fix on selected image in the gallery (with help from [#14598](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14598), [#14626](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14626), [#14728](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14728)) +* [Separate assets repository](https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets); serve fonts locally rather than from google's servers +* Official LCM Sampler Support ([#14583](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14583)) +* Add support for DAT upscaler models ([#14690](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14690), [#15039](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15039)) +* Extra Networks Tree View ([#14588](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14588), [#14900](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14900)) +* NPU Support ([#14801](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14801)) +* Prompt comments support + +### Minor: +* Allow pasting in WIDTHxHEIGHT strings into the width/height fields ([#14296](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14296)) +* add option: Live preview in full page image viewer ([#14230](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14230), [#14307](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14307)) +* Add keyboard shortcuts for generate/skip/interrupt ([#14269](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14269)) +* Better TCMALLOC support on different platforms ([#14227](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14227), [#14883](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14883), [#14910](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14910)) +* Lora not found warning ([#14464](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14464)) +* Adding negative prompts to Loras in extra networks ([#14475](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14475)) +* xyz_grid: allow varying the seed along an axis separate from axis options ([#12180](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12180)) +* option to convert VAE to bfloat16 (implementation of [#9295](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/9295)) +* Better IPEX support ([#14229](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14229), [#14353](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14353), [#14559](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14559), [#14562](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14562), [#14597](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14597)) +* Option to interrupt after current generation rather than immediately ([#13653](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13653), [#14659](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14659)) +* Fullscreen Preview control fading/disable ([#14291](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14291)) +* Finer settings freezing control ([#13789](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13789)) +* Increase Upscaler Limits ([#14589](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14589)) +* Adjust brush size with hotkeys ([#14638](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14638)) +* Add checkpoint info to csv log file when saving images ([#14663](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14663)) +* Make more columns resizable ([#14740](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14740), [#14884](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14884)) +* Add an option to not overlay original image for inpainting for #14727 +* Add Pad conds v0 option to support same generation with DDIM as before 1.6.0 +* Add "Interrupting..." placeholder. +* Button for refresh extensions list ([#14857](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14857)) +* Add an option to disable normalization after calculating emphasis. ([#14874](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14874)) +* When counting tokens, also include enabled styles (can be disabled in settings to revert to previous behavior) +* Configuration for the [📂] button for image gallery ([#14947](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14947)) +* Support inference with LyCORIS BOFT networks ([#14871](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14871), [#14973](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14973)) +* support resizable columns for touch (tablets) ([#15002](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15002)) + +### Extensions and API: +* Removed packages from requirements: basicsr, gfpgan, realesrgan; as well as their dependencies: absl-py, addict, beautifulsoup4, future, gdown, grpcio, importlib-metadata, lmdb, lpips, Markdown, platformdirs, PySocks, soupsieve, tb-nightly, tensorboard-data-server, tomli, Werkzeug, yapf, zipp, soupsieve +* Enable task ids for API ([#14314](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14314)) +* add override_settings support for infotext API +* rename generation_parameters_copypaste module to infotext_utils +* prevent crash due to Script __init__ exception ([#14407](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14407)) +* Bump numpy to 1.26.2 ([#14471](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14471)) +* Add utility to inspect a model's dtype/device ([#14478](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14478)) +* Implement general forward method for all method in built-in lora ext ([#14547](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14547)) +* Execute model_loaded_callback after moving to target device ([#14563](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14563)) +* Add self to CFGDenoiserParams ([#14573](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14573)) +* Allow TLS with API only mode (--nowebui) ([#14593](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14593)) +* New callback: postprocess_image_after_composite ([#14657](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14657)) +* modules/api/api.py: add api endpoint to refresh embeddings list ([#14715](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14715)) +* set_named_arg ([#14773](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14773)) +* add before_token_counter callback and use it for prompt comments +* ResizeHandleRow - allow overridden column scale parameter ([#15004](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15004)) + +### Performance: +* Massive performance improvement for extra networks directories with a huge number of files in them in an attempt to tackle #14507 ([#14528](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14528)) +* Reduce unnecessary re-indexing extra networks directory ([#14512](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14512)) +* Avoid unnecessary `isfile`/`exists` calls ([#14527](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14527)) + +### Bug Fixes: +* fix multiple bugs related to styles multi-file support ([#14203](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14203), [#14276](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14276), [#14707](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14707)) +* Lora fixes ([#14300](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14300), [#14237](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14237), [#14546](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14546), [#14726](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14726)) +* Re-add setting lost as part of e294e46 ([#14266](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14266)) +* fix extras caption BLIP ([#14330](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14330)) +* include infotext into saved init image for img2img ([#14452](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14452)) +* xyz grid handle axis_type is None ([#14394](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14394)) +* Update Added (Fixed) IPV6 Functionality When there is No Webui Argument Passed webui.py ([#14354](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14354)) +* fix API thread safe issues of txt2img and img2img ([#14421](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14421)) +* handle selectable script_index is None ([#14487](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14487)) +* handle config.json failed to load ([#14525](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14525), [#14767](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14767)) +* paste infotext cast int as float ([#14523](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14523)) +* Ensure GRADIO_ANALYTICS_ENABLED is set early enough ([#14537](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14537)) +* Fix logging configuration again ([#14538](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14538)) +* Handle CondFunc exception when resolving attributes ([#14560](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14560)) +* Fix extras big batch crashes ([#14699](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14699)) +* Fix using wrong model caused by alias ([#14655](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14655)) +* Add # to the invalid_filename_chars list ([#14640](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14640)) +* Fix extension check for requirements ([#14639](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14639)) +* Fix tab indexes are reset after restart UI ([#14637](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14637)) +* Fix nested manual cast ([#14689](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14689)) +* Keep postprocessing upscale selected tab after restart ([#14702](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14702)) +* XYZ grid: filter out blank vals when axis is int or float type (like int axis seed) ([#14754](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14754)) +* fix CLIP Interrogator topN regex ([#14775](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14775)) +* Fix dtype error in MHA layer/change dtype checking mechanism for manual cast ([#14791](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14791)) +* catch load style.csv error ([#14814](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14814)) +* fix error when editing extra networks card +* fix extra networks metadata failing to work properly when you create the .json file with metadata for the first time. +* util.walk_files extensions case insensitive ([#14879](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14879)) +* if extensions page not loaded, prevent apply ([#14873](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14873)) +* call the right function for token counter in img2img +* Fix the bugs that search/reload will disappear when using other ExtraNetworks extensions ([#14939](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14939)) +* Gracefully handle mtime read exception from cache ([#14933](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14933)) +* Only trigger interrupt on `Esc` when interrupt button visible ([#14932](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14932)) +* Disable prompt token counters option actually disables token counting rather than just hiding results. +* avoid double upscaling in inpaint ([#14966](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14966)) +* Fix #14591 using translated content to do categories mapping ([#14995](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14995)) +* fix: the `split_threshold` parameter does not work when running Split oversized images ([#15006](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15006)) +* Fix resize-handle for mobile ([#15010](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15010), [#15065](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15065)) + +### Other: +* Assign id for "extra_options". Replace numeric field with slider. ([#14270](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14270)) +* change state dict comparison to ref compare ([#14216](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14216)) +* Bump torch-rocm to 5.6/5.7 ([#14293](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14293)) +* Base output path off data path ([#14446](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14446)) +* reorder training preprocessing modules in extras tab ([#14367](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14367)) +* Remove `cleanup_models` code ([#14472](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14472)) +* only rewrite ui-config when there is change ([#14352](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14352)) +* Fix lint issue from 501993eb ([#14495](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14495)) +* Update README.md ([#14548](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14548)) +* hires button, fix seeds () +* Logging: set formatter correctly for fallback logger too ([#14618](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14618)) +* Read generation info from infotexts rather than json for internal needs (save, extract seed from generated pic) ([#14645](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14645)) +* improve get_crop_region ([#14709](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14709)) +* Bump safetensors' version to 0.4.2 ([#14782](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14782)) +* add tooltip create_submit_box ([#14803](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14803)) +* extensions tab table row hover highlight ([#14885](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14885)) +* Always add timestamp to displayed image ([#14890](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14890)) +* Added core.filemode=false so doesn't track changes in file permission… ([#14930](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14930)) +* Normalize command-line argument paths ([#14934](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14934), [#15035](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15035)) +* Use original App Title in progress bar ([#14916](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14916)) +* register_tmp_file also for mtime ([#15012](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15012)) + +## 1.7.0 + +### Features: +* settings tab rework: add search field, add categories, split UI settings page into many +* add altdiffusion-m18 support ([#13364](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13364)) +* support inference with LyCORIS GLora networks ([#13610](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13610)) +* add lora-embedding bundle system ([#13568](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13568)) +* option to move prompt from top row into generation parameters +* add support for SSD-1B ([#13865](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13865)) +* support inference with OFT networks ([#13692](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13692)) +* script metadata and DAG sorting mechanism ([#13944](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13944)) +* support HyperTile optimization ([#13948](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13948)) +* add support for SD 2.1 Turbo ([#14170](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14170)) +* remove Train->Preprocessing tab and put all its functionality into Extras tab +* initial IPEX support for Intel Arc GPU ([#14171](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14171)) + +### Minor: +* allow reading model hash from images in img2img batch mode ([#12767](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12767)) +* add option to align with sgm repo's sampling implementation ([#12818](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12818)) +* extra field for lora metadata viewer: `ss_output_name` ([#12838](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12838)) +* add action in settings page to calculate all SD checkpoint hashes ([#12909](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12909)) +* add button to copy prompt to style editor ([#12975](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12975)) +* add --skip-load-model-at-start option ([#13253](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13253)) +* write infotext to gif images +* read infotext from gif images ([#13068](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13068)) +* allow configuring the initial state of InputAccordion in ui-config.json ([#13189](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13189)) +* allow editing whitespace delimiters for ctrl+up/ctrl+down prompt editing ([#13444](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13444)) +* prevent accidentally closing popup dialogs ([#13480](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13480)) +* added option to play notification sound or not ([#13631](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13631)) +* show the preview image in the full screen image viewer if available ([#13459](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13459)) +* support for webui.settings.bat ([#13638](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13638)) +* add an option to not print stack traces on ctrl+c +* start/restart generation by Ctrl (Alt) + Enter ([#13644](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13644)) +* update prompts_from_file script to allow concatenating entries with the general prompt ([#13733](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13733)) +* added a visible checkbox to input accordion +* added an option to hide all txt2img/img2img parameters in an accordion ([#13826](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13826)) +* added 'Path' sorting option for Extra network cards ([#13968](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13968)) +* enable prompt hotkeys in style editor ([#13931](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13931)) +* option to show batch img2img results in UI ([#14009](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14009)) +* infotext updates: add option to disregard certain infotext fields, add option to not include VAE in infotext, add explanation to infotext settings page, move some options to infotext settings page +* add FP32 fallback support on sd_vae_approx ([#14046](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14046)) +* support XYZ scripts / split hires path from unet ([#14126](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14126)) +* allow use of multiple styles csv files ([#14125](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14125)) +* make extra network card description plaintext by default, with an option (Treat card description as HTML) to re-enable HTML as it was (originally by [#13241](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13241)) + +### Extensions and API: +* update gradio to 3.41.2 +* support installed extensions list api ([#12774](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12774)) +* update pnginfo API to return dict with parsed values +* add noisy latent to `ExtraNoiseParams` for callback ([#12856](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12856)) +* show extension datetime in UTC ([#12864](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12864), [#12865](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12865), [#13281](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13281)) +* add an option to choose how to combine hires fix and refiner +* include program version in info response. ([#13135](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13135)) +* sd_unet support for SDXL +* patch DDPM.register_betas so that users can put given_betas in model yaml ([#13276](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13276)) +* xyz_grid: add prepare ([#13266](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13266)) +* allow multiple localization files with same language in extensions ([#13077](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13077)) +* add onEdit function for js and rework token-counter.js to use it +* fix the key error exception when processing override_settings keys ([#13567](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13567)) +* ability for extensions to return custom data via api in response.images ([#13463](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13463)) +* call state.jobnext() before postproces*() ([#13762](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13762)) +* add option to set notification sound volume ([#13884](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13884)) +* update Ruff to 0.1.6 ([#14059](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14059)) +* add Block component creation callback ([#14119](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14119)) +* catch uncaught exception with ui creation scripts ([#14120](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14120)) +* use extension name for determining an extension is installed in the index ([#14063](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14063)) +* update is_installed() from launch_utils.py to fix reinstalling already installed packages ([#14192](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14192)) + +### Bug Fixes: +* fix pix2pix producing bad results +* fix defaults settings page breaking when any of main UI tabs are hidden +* fix error that causes some extra networks to be disabled if both and are present in the prompt +* fix for Reload UI function: if you reload UI on one tab, other opened tabs will no longer stop working +* prevent duplicate resize handler ([#12795](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12795)) +* small typo: vae resolve bug ([#12797](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12797)) +* hide broken image crop tool ([#12792](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12792)) +* don't show hidden samplers in dropdown for XYZ script ([#12780](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12780)) +* fix style editing dialog breaking if it's opened in both img2img and txt2img tabs +* hide --gradio-auth and --api-auth values from /internal/sysinfo report +* add missing infotext for RNG in options ([#12819](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12819)) +* fix notification not playing when built-in webui tab is inactive ([#12834](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12834)) +* honor `--skip-install` for extension installers ([#12832](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12832)) +* don't print blank stdout in extension installers ([#12833](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12833), [#12855](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12855)) +* get progressbar to display correctly in extensions tab +* keep order in list of checkpoints when loading model that doesn't have a checksum +* fix inpainting models in txt2img creating black pictures +* fix generation params regex ([#12876](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12876)) +* fix batch img2img output dir with script ([#12926](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12926)) +* fix #13080 - Hypernetwork/TI preview generation ([#13084](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13084)) +* fix bug with sigma min/max overrides. ([#12995](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12995)) +* more accurate check for enabling cuDNN benchmark on 16XX cards ([#12924](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12924)) +* don't use multicond parser for negative prompt counter ([#13118](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13118)) +* fix data-sort-name containing spaces ([#13412](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13412)) +* update card on correct tab when editing metadata ([#13411](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13411)) +* fix viewing/editing metadata when filename contains an apostrophe ([#13395](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13395)) +* fix: --sd_model in "Prompts from file or textbox" script is not working ([#13302](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13302)) +* better Support for Portable Git ([#13231](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13231)) +* fix issues when webui_dir is not work_dir ([#13210](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13210)) +* fix: lora-bias-backup don't reset cache ([#13178](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13178)) +* account for customizable extra network separators whyen removing extra network text from the prompt ([#12877](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12877)) +* re fix batch img2img output dir with script ([#13170](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13170)) +* fix `--ckpt-dir` path separator and option use `short name` for checkpoint dropdown ([#13139](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13139)) +* consolidated allowed preview formats, Fix extra network `.gif` not woking as preview ([#13121](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13121)) +* fix venv_dir=- environment variable not working as expected on linux ([#13469](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13469)) +* repair unload sd checkpoint button +* edit-attention fixes ([#13533](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13533)) +* fix bug when using --gfpgan-models-path ([#13718](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13718)) +* properly apply sort order for extra network cards when selected from dropdown +* fixes generation restart not working for some users when 'Ctrl+Enter' is pressed ([#13962](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13962)) +* thread safe extra network list_items ([#13014](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13014)) +* fix not able to exit metadata popup when pop up is too big ([#14156](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14156)) +* fix auto focal point crop for opencv >= 4.8 ([#14121](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14121)) +* make 'use-cpu all' actually apply to 'all' ([#14131](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14131)) +* extras tab batch: actually use original filename +* make webui not crash when running with --disable-all-extensions option + +### Other: +* non-local condition ([#12814](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12814)) +* fix minor typos ([#12827](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12827)) +* remove xformers Python version check ([#12842](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12842)) +* style: file-metadata word-break ([#12837](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12837)) +* revert SGM noise multiplier change for img2img because it breaks hires fix +* do not change quicksettings dropdown option when value returned is `None` ([#12854](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12854)) +* [RC 1.6.0 - zoom is partly hidden] Update style.css ([#12839](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12839)) +* chore: change extension time format ([#12851](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12851)) +* WEBUI.SH - Use torch 2.1.0 release candidate for Navi 3 ([#12929](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12929)) +* add Fallback at images.read_info_from_image if exif data was invalid ([#13028](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13028)) +* update cmd arg description ([#12986](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12986)) +* fix: update shared.opts.data when add_option ([#12957](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12957), [#13213](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13213)) +* restore missing tooltips ([#12976](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12976)) +* use default dropdown padding on mobile ([#12880](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12880)) +* put enable console prompts option into settings from commandline args ([#13119](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13119)) +* fix some deprecated types ([#12846](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12846)) +* bump to torchsde==0.2.6 ([#13418](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13418)) +* update dragdrop.js ([#13372](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13372)) +* use orderdict as lru cache:opt/bug ([#13313](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13313)) +* XYZ if not include sub grids do not save sub grid ([#13282](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13282)) +* initialize state.time_start befroe state.job_count ([#13229](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13229)) +* fix fieldname regex ([#13458](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13458)) +* change denoising_strength default to None. ([#13466](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13466)) +* fix regression ([#13475](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13475)) +* fix IndexError ([#13630](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13630)) +* fix: checkpoints_loaded:{checkpoint:state_dict}, model.load_state_dict issue in dict value empty ([#13535](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13535)) +* update bug_report.yml ([#12991](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12991)) +* requirements_versions httpx==0.24.1 ([#13839](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13839)) +* fix parenthesis auto selection ([#13829](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13829)) +* fix #13796 ([#13797](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13797)) +* corrected a typo in `modules/cmd_args.py` ([#13855](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13855)) +* feat: fix randn found element of type float at pos 2 ([#14004](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14004)) +* adds tqdm handler to logging_config.py for progress bar integration ([#13996](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13996)) +* hotfix: call shared.state.end() after postprocessing done ([#13977](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13977)) +* fix dependency address patch 1 ([#13929](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13929)) +* save sysinfo as .json ([#14035](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14035)) +* move exception_records related methods to errors.py ([#14084](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14084)) +* compatibility ([#13936](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13936)) +* json.dump(ensure_ascii=False) ([#14108](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14108)) +* dir buttons start with / so only the correct dir will be shown and no… ([#13957](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13957)) +* alternate implementation for unet forward replacement that does not depend on hijack being applied +* re-add `keyedit_delimiters_whitespace` setting lost as part of commit e294e46 ([#14178](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14178)) +* fix `save_samples` being checked early when saving masked composite ([#14177](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14177)) +* slight optimization for mask and mask_composite ([#14181](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14181)) +* add import_hook hack to work around basicsr/torchvision incompatibility ([#14186](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14186)) + +## 1.6.1 + +### Bug Fixes: + * fix an error causing the webui to fail to start ([#13839](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13839)) + +## 1.6.0 + +### Features: + * refiner support [#12371](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12371) + * add NV option for Random number generator source setting, which allows to generate same pictures on CPU/AMD/Mac as on NVidia videocards + * add style editor dialog + * hires fix: add an option to use a different checkpoint for second pass ([#12181](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12181)) + * option to keep multiple loaded models in memory ([#12227](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12227)) + * new samplers: Restart, DPM++ 2M SDE Exponential, DPM++ 2M SDE Heun, DPM++ 2M SDE Heun Karras, DPM++ 2M SDE Heun Exponential, DPM++ 3M SDE, DPM++ 3M SDE Karras, DPM++ 3M SDE Exponential ([#12300](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12300), [#12519](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12519), [#12542](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12542)) + * rework DDIM, PLMS, UniPC to use CFG denoiser same as in k-diffusion samplers: + * makes all of them work with img2img + * makes prompt composition possible (AND) + * makes them available for SDXL + * always show extra networks tabs in the UI ([#11808](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/11808)) + * use less RAM when creating models ([#11958](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/11958), [#12599](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12599)) + * textual inversion inference support for SDXL + * extra networks UI: show metadata for SD checkpoints + * checkpoint merger: add metadata support + * prompt editing and attention: add support for whitespace after the number ([ red : green : 0.5 ]) (seed breaking change) ([#12177](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12177)) + * VAE: allow selecting own VAE for each checkpoint (in user metadata editor) + * VAE: add selected VAE to infotext + * options in main UI: add own separate setting for txt2img and img2img, correctly read values from pasted infotext, add setting for column count ([#12551](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12551)) + * add resize handle to txt2img and img2img tabs, allowing to change the amount of horizontable space given to generation parameters and resulting image gallery ([#12687](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12687), [#12723](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12723)) + * change default behavior for batching cond/uncond -- now it's on by default, and is disabled by an UI setting (Optimizatios -> Batch cond/uncond) - if you are on lowvram/medvram and are getting OOM exceptions, you will need to enable it + * show current position in queue and make it so that requests are processed in the order of arrival ([#12707](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12707)) + * add `--medvram-sdxl` flag that only enables `--medvram` for SDXL models + * prompt editing timeline has separate range for first pass and hires-fix pass (seed breaking change) ([#12457](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12457)) + +### Minor: + * img2img batch: RAM savings, VRAM savings, .tif, .tiff in img2img batch ([#12120](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12120), [#12514](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12514), [#12515](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12515)) + * postprocessing/extras: RAM savings ([#12479](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12479)) + * XYZ: in the axis labels, remove pathnames from model filenames + * XYZ: support hires sampler ([#12298](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12298)) + * XYZ: new option: use text inputs instead of dropdowns ([#12491](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12491)) + * add gradio version warning + * sort list of VAE checkpoints ([#12297](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12297)) + * use transparent white for mask in inpainting, along with an option to select the color ([#12326](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12326)) + * move some settings to their own section: img2img, VAE + * add checkbox to show/hide dirs for extra networks + * Add TAESD(or more) options for all the VAE encode/decode operation ([#12311](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12311)) + * gradio theme cache, new gradio themes, along with explanation that the user can input his own values ([#12346](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12346), [#12355](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12355)) + * sampler fixes/tweaks: s_tmax, s_churn, s_noise, s_tmax ([#12354](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12354), [#12356](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12356), [#12357](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12357), [#12358](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12358), [#12375](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12375), [#12521](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12521)) + * update README.md with correct instructions for Linux installation ([#12352](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12352)) + * option to not save incomplete images, on by default ([#12338](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12338)) + * enable cond cache by default + * git autofix for repos that are corrupted ([#12230](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12230)) + * allow to open images in new browser tab by middle mouse button ([#12379](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12379)) + * automatically open webui in browser when running "locally" ([#12254](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12254)) + * put commonly used samplers on top, make DPM++ 2M Karras the default choice + * zoom and pan: option to auto-expand a wide image, improved integration ([#12413](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12413), [#12727](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12727)) + * option to cache Lora networks in memory + * rework hires fix UI to use accordion + * face restoration and tiling moved to settings - use "Options in main UI" setting if you want them back + * change quicksettings items to have variable width + * Lora: add Norm module, add support for bias ([#12503](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12503)) + * Lora: output warnings in UI rather than fail for unfitting loras; switch to logging for error output in console + * support search and display of hashes for all extra network items ([#12510](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12510)) + * add extra noise param for img2img operations ([#12564](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12564)) + * support for Lora with bias ([#12584](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12584)) + * make interrupt quicker ([#12634](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12634)) + * configurable gallery height ([#12648](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12648)) + * make results column sticky ([#12645](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12645)) + * more hash filename patterns ([#12639](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12639)) + * make image viewer actually fit the whole page ([#12635](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12635)) + * make progress bar work independently from live preview display which results in it being updated a lot more often + * forbid Full live preview method for medvram and add a setting to undo the forbidding + * make it possible to localize tooltips and placeholders + * add option to align with sgm repo's sampling implementation ([#12818](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12818)) + * Restore faces and Tiling generation parameters have been moved to settings out of main UI + * if you want to put them back into main UI, use `Options in main UI` setting on the UI page. + +### Extensions and API: + * gradio 3.41.2 + * also bump versions for packages: transformers, GitPython, accelerate, scikit-image, timm, tomesd + * support tooltip kwarg for gradio elements: gr.Textbox(label='hello', tooltip='world') + * properly clear the total console progressbar when using txt2img and img2img from API + * add cmd_arg --disable-extra-extensions and --disable-all-extensions ([#12294](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12294)) + * shared.py and webui.py split into many files + * add --loglevel commandline argument for logging + * add a custom UI element that combines accordion and checkbox + * avoid importing gradio in tests because it spams warnings + * put infotext label for setting into OptionInfo definition rather than in a separate list + * make `StableDiffusionProcessingImg2Img.mask_blur` a property, make more inline with PIL `GaussianBlur` ([#12470](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12470)) + * option to make scripts UI without gr.Group + * add a way for scripts to register a callback for before/after just a single component's creation + * use dataclass for StableDiffusionProcessing + * store patches for Lora in a specialized module instead of inside torch + * support http/https URLs in API ([#12663](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12663), [#12698](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12698)) + * add extra noise callback ([#12616](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12616)) + * dump current stack traces when exiting with SIGINT + * add type annotations for extra fields of shared.sd_model + +### Bug Fixes: + * Don't crash if out of local storage quota for javascriot localStorage + * XYZ plot do not fail if an exception occurs + * fix missing TI hash in infotext if generation uses both negative and positive TI ([#12269](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12269)) + * localization fixes ([#12307](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12307)) + * fix sdxl model invalid configuration after the hijack + * correctly toggle extras checkbox for infotext paste ([#12304](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12304)) + * open raw sysinfo link in new page ([#12318](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12318)) + * prompt parser: Account for empty field in alternating words syntax ([#12319](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12319)) + * add tab and carriage return to invalid filename chars ([#12327](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12327)) + * fix api only Lora not working ([#12387](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12387)) + * fix options in main UI misbehaving when there's just one element + * make it possible to use a sampler from infotext even if it's hidden in the dropdown + * fix styles missing from the prompt in infotext when making a grid of batch of multiplie images + * prevent bogus progress output in console when calculating hires fix dimensions + * fix --use-textbox-seed + * fix broken `Lora/Networks: use old method` option ([#12466](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12466)) + * properly return `None` for VAE hash when using `--no-hashing` ([#12463](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12463)) + * MPS/macOS fixes and optimizations ([#12526](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12526)) + * add second_order to samplers that mistakenly didn't have it + * when refreshing cards in extra networks UI, do not discard user's custom resolution + * fix processing error that happens if batch_size is not a multiple of how many prompts/negative prompts there are ([#12509](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12509)) + * fix inpaint upload for alpha masks ([#12588](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12588)) + * fix exception when image sizes are not integers ([#12586](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12586)) + * fix incorrect TAESD Latent scale ([#12596](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12596)) + * auto add data-dir to gradio-allowed-path ([#12603](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12603)) + * fix exception if extensuions dir is missing ([#12607](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12607)) + * fix issues with api model-refresh and vae-refresh ([#12638](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12638)) + * fix img2img background color for transparent images option not being used ([#12633](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12633)) + * attempt to resolve NaN issue with unstable VAEs in fp32 mk2 ([#12630](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12630)) + * implement missing undo hijack for SDXL + * fix xyz swap axes ([#12684](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12684)) + * fix errors in backup/restore tab if any of config files are broken ([#12689](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12689)) + * fix SD VAE switch error after model reuse ([#12685](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12685)) + * fix trying to create images too large for the chosen format ([#12667](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12667)) + * create Gradio temp directory if necessary ([#12717](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12717)) + * prevent possible cache loss if exiting as it's being written by using an atomic operation to replace the cache with the new version + * set devices.dtype_unet correctly + * run RealESRGAN on GPU for non-CUDA devices ([#12737](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12737)) + * prevent extra network buttons being obscured by description for very small card sizes ([#12745](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12745)) + * fix error that causes some extra networks to be disabled if both and are present in the prompt + * fix defaults settings page breaking when any of main UI tabs are hidden + * fix incorrect save/display of new values in Defaults page in settings + * fix for Reload UI function: if you reload UI on one tab, other opened tabs will no longer stop working + * fix an error that prevents VAE being reloaded after an option change if a VAE near the checkpoint exists ([#12797](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12737)) + * hide broken image crop tool ([#12792](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12737)) + * don't show hidden samplers in dropdown for XYZ script ([#12780](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12737)) + * fix style editing dialog breaking if it's opened in both img2img and txt2img tabs + * fix a bug allowing users to bypass gradio and API authentication (reported by vysecurity) + * fix notification not playing when built-in webui tab is inactive ([#12834](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12834)) + * honor `--skip-install` for extension installers ([#12832](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12832)) + * don't print blank stdout in extension installers ([#12833](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12832), [#12855](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12855)) + * do not change quicksettings dropdown option when value returned is `None` ([#12854](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12854)) + * get progressbar to display correctly in extensions tab + + +## 1.5.2 + +### Bug Fixes: + * fix memory leak when generation fails + * update doggettx cross attention optimization to not use an unreasonable amount of memory in some edge cases -- suggestion by MorkTheOrk + + +## 1.5.1 + +### Minor: + * support parsing text encoder blocks in some new LoRAs + * delete scale checker script due to user demand + +### Extensions and API: + * add postprocess_batch_list script callback + +### Bug Fixes: + * fix TI training for SD1 + * fix reload altclip model error + * prepend the pythonpath instead of overriding it + * fix typo in SD_WEBUI_RESTARTING + * if txt2img/img2img raises an exception, finally call state.end() + * fix composable diffusion weight parsing + * restyle Startup profile for black users + * fix webui not launching with --nowebui + * catch exception for non git extensions + * fix some options missing from /sdapi/v1/options + * fix for extension update status always saying "unknown" + * fix display of extra network cards that have `<>` in the name + * update lora extension to work with python 3.8 + + +## 1.5.0 + +### Features: + * SD XL support + * user metadata system for custom networks + * extended Lora metadata editor: set activation text, default weight, view tags, training info + * Lora extension rework to include other types of networks (all that were previously handled by LyCORIS extension) + * show github stars for extensions + * img2img batch mode can read extra stuff from png info + * img2img batch works with subdirectories + * hotkeys to move prompt elements: alt+left/right + * restyle time taken/VRAM display + * add textual inversion hashes to infotext + * optimization: cache git extension repo information + * move generate button next to the generated picture for mobile clients + * hide cards for networks of incompatible Stable Diffusion version in Lora extra networks interface + * skip installing packages with pip if they all are already installed - startup speedup of about 2 seconds + +### Minor: + * checkbox to check/uncheck all extensions in the Installed tab + * add gradio user to infotext and to filename patterns + * allow gif for extra network previews + * add options to change colors in grid + * use natural sort for items in extra networks + * Mac: use empty_cache() from torch 2 to clear VRAM + * added automatic support for installing the right libraries for Navi3 (AMD) + * add option SWIN_torch_compile to accelerate SwinIR upscale + * suppress printing TI embedding info at start to console by default + * speedup extra networks listing + * added `[none]` filename token. + * removed thumbs extra networks view mode (use settings tab to change width/height/scale to get thumbs) + * add always_discard_next_to_last_sigma option to XYZ plot + * automatically switch to 32-bit float VAE if the generated picture has NaNs without the need for `--no-half-vae` commandline flag. + +### Extensions and API: + * api endpoints: /sdapi/v1/server-kill, /sdapi/v1/server-restart, /sdapi/v1/server-stop + * allow Script to have custom metaclass + * add model exists status check /sdapi/v1/options + * rename --add-stop-route to --api-server-stop + * add `before_hr` script callback + * add callback `after_extra_networks_activate` + * disable rich exception output in console for API by default, use WEBUI_RICH_EXCEPTIONS env var to enable + * return http 404 when thumb file not found + * allow replacing extensions index with environment variable + +### Bug Fixes: + * fix for catch errors when retrieving extension index #11290 + * fix very slow loading speed of .safetensors files when reading from network drives + * API cache cleanup + * fix UnicodeEncodeError when writing to file CLIP Interrogator batch mode + * fix warning of 'has_mps' deprecated from PyTorch + * fix problem with extra network saving images as previews losing generation info + * fix throwing exception when trying to resize image with I;16 mode + * fix for #11534: canvas zoom and pan extension hijacking shortcut keys + * fixed launch script to be runnable from any directory + * don't add "Seed Resize: -1x-1" to API image metadata + * correctly remove end parenthesis with ctrl+up/down + * fixing --subpath on newer gradio version + * fix: check fill size none zero when resize (fixes #11425) + * use submit and blur for quick settings textbox + * save img2img batch with images.save_image() + * prevent running preload.py for disabled extensions + * fix: previously, model name was added together with directory name to infotext and to [model_name] filename pattern; directory name is now not included + + +## 1.4.1 + +### Bug Fixes: + * add queue lock for refresh-checkpoints + +## 1.4.0 + +### Features: + * zoom controls for inpainting + * run basic torch calculation at startup in parallel to reduce the performance impact of first generation + * option to pad prompt/neg prompt to be same length + * remove taming_transformers dependency + * custom k-diffusion scheduler settings + * add an option to show selected settings in main txt2img/img2img UI + * sysinfo tab in settings + * infer styles from prompts when pasting params into the UI + * an option to control the behavior of the above + +### Minor: + * bump Gradio to 3.32.0 + * bump xformers to 0.0.20 + * Add option to disable token counters + * tooltip fixes & optimizations + * make it possible to configure filename for the zip download + * `[vae_filename]` pattern for filenames + * Revert discarding penultimate sigma for DPM-Solver++(2M) SDE + * change UI reorder setting to multiselect + * read version info form CHANGELOG.md if git version info is not available + * link footer API to Wiki when API is not active + * persistent conds cache (opt-in optimization) + +### Extensions: + * After installing extensions, webui properly restarts the process rather than reloads the UI + * Added VAE listing to web API. Via: /sdapi/v1/sd-vae + * custom unet support + * Add onAfterUiUpdate callback + * refactor EmbeddingDatabase.register_embedding() to allow unregistering + * add before_process callback for scripts + * add ability for alwayson scripts to specify section and let user reorder those sections + +### Bug Fixes: + * Fix dragging text to prompt + * fix incorrect quoting for infotext values with colon in them + * fix "hires. fix" prompt sharing same labels with txt2img_prompt + * Fix s_min_uncond default type int + * Fix for #10643 (Inpainting mask sometimes not working) + * fix bad styling for thumbs view in extra networks #10639 + * fix for empty list of optimizations #10605 + * small fixes to prepare_tcmalloc for Debian/Ubuntu compatibility + * fix --ui-debug-mode exit + * patch GitPython to not use leaky persistent processes + * fix duplicate Cross attention optimization after UI reload + * torch.cuda.is_available() check for SdOptimizationXformers + * fix hires fix using wrong conds in second pass if using Loras. + * handle exception when parsing generation parameters from png info + * fix upcast attention dtype error + * forcing Torch Version to 1.13.1 for RX 5000 series GPUs + * split mask blur into X and Y components, patch Outpainting MK2 accordingly + * don't die when a LoRA is a broken symlink + * allow activation of Generate Forever during generation + + +## 1.3.2 + +### Bug Fixes: + * fix files served out of tmp directory even if they are saved to disk + * fix postprocessing overwriting parameters + +## 1.3.1 + +### Features: + * revert default cross attention optimization to Doggettx + +### Bug Fixes: + * fix bug: LoRA don't apply on dropdown list sd_lora + * fix png info always added even if setting is not enabled + * fix some fields not applying in xyz plot + * fix "hires. fix" prompt sharing same labels with txt2img_prompt + * fix lora hashes not being added properly to infotex if there is only one lora + * fix --use-cpu failing to work properly at startup + * make --disable-opt-split-attention command line option work again + +## 1.3.0 + +### Features: + * add UI to edit defaults + * token merging (via dbolya/tomesd) + * settings tab rework: add a lot of additional explanations and links + * load extensions' Git metadata in parallel to loading the main program to save a ton of time during startup + * update extensions table: show branch, show date in separate column, and show version from tags if available + * TAESD - another option for cheap live previews + * allow choosing sampler and prompts for second pass of hires fix - hidden by default, enabled in settings + * calculate hashes for Lora + * add lora hashes to infotext + * when pasting infotext, use infotext's lora hashes to find local loras for `` entries whose hashes match loras the user has + * select cross attention optimization from UI + +### Minor: + * bump Gradio to 3.31.0 + * bump PyTorch to 2.0.1 for macOS and Linux AMD + * allow setting defaults for elements in extensions' tabs + * allow selecting file type for live previews + * show "Loading..." for extra networks when displaying for the first time + * suppress ENSD infotext for samplers that don't use it + * clientside optimizations + * add options to show/hide hidden files and dirs in extra networks, and to not list models/files in hidden directories + * allow whitespace in styles.csv + * add option to reorder tabs + * move some functionality (swap resolution and set seed to -1) to client + * option to specify editor height for img2img + * button to copy image resolution into img2img width/height sliders + * switch from pyngrok to ngrok-py + * lazy-load images in extra networks UI + * set "Navigate image viewer with gamepad" option to false by default, by request + * change upscalers to download models into user-specified directory (from commandline args) rather than the default models/<...> + * allow hiding buttons in ui-config.json + +### Extensions: + * add /sdapi/v1/script-info api + * use Ruff to lint Python code + * use ESlint to lint Javascript code + * add/modify CFG callbacks for Self-Attention Guidance extension + * add command and endpoint for graceful server stopping + * add some locals (prompts/seeds/etc) from processing function into the Processing class as fields + * rework quoting for infotext items that have commas in them to use JSON (should be backwards compatible except for cases where it didn't work previously) + * add /sdapi/v1/refresh-loras api checkpoint post request + * tests overhaul + +### Bug Fixes: + * fix an issue preventing the program from starting if the user specifies a bad Gradio theme + * fix broken prompts from file script + * fix symlink scanning for extra networks + * fix --data-dir ignored when launching via webui-user.bat COMMANDLINE_ARGS + * allow web UI to be ran fully offline + * fix inability to run with --freeze-settings + * fix inability to merge checkpoint without adding metadata + * fix extra networks' save preview image not adding infotext for jpeg/webm + * remove blinking effect from text in hires fix and scale resolution preview + * make links to `http://<...>.git` extensions work in the extension tab + * fix bug with webui hanging at startup due to hanging git process + + +## 1.2.1 + +### Features: + * add an option to always refer to LoRA by filenames + +### Bug Fixes: + * never refer to LoRA by an alias if multiple LoRAs have same alias or the alias is called none + * fix upscalers disappearing after the user reloads UI + * allow bf16 in safe unpickler (resolves problems with loading some LoRAs) + * allow web UI to be ran fully offline + * fix localizations not working + * fix error for LoRAs: `'LatentDiffusion' object has no attribute 'lora_layer_mapping'` + +## 1.2.0 + +### Features: + * do not wait for Stable Diffusion model to load at startup + * add filename patterns: `[denoising]` + * directory hiding for extra networks: dirs starting with `.` will hide their cards on extra network tabs unless specifically searched for + * LoRA: for the `<...>` text in prompt, use name of LoRA that is in the metadata of the file, if present, instead of filename (both can be used to activate LoRA) + * LoRA: read infotext params from kohya-ss's extension parameters if they are present and if his extension is not active + * LoRA: fix some LoRAs not working (ones that have 3x3 convolution layer) + * LoRA: add an option to use old method of applying LoRAs (producing same results as with kohya-ss) + * add version to infotext, footer and console output when starting + * add links to wiki for filename pattern settings + * add extended info for quicksettings setting and use multiselect input instead of a text field + +### Minor: + * bump Gradio to 3.29.0 + * bump PyTorch to 2.0.1 + * `--subpath` option for gradio for use with reverse proxy + * Linux/macOS: use existing virtualenv if already active (the VIRTUAL_ENV environment variable) + * do not apply localizations if there are none (possible frontend optimization) + * add extra `None` option for VAE in XYZ plot + * print error to console when batch processing in img2img fails + * create HTML for extra network pages only on demand + * allow directories starting with `.` to still list their models for LoRA, checkpoints, etc + * put infotext options into their own category in settings tab + * do not show licenses page when user selects Show all pages in settings + +### Extensions: + * tooltip localization support + * add API method to get LoRA models with prompt + +### Bug Fixes: + * re-add `/docs` endpoint + * fix gamepad navigation + * make the lightbox fullscreen image function properly + * fix squished thumbnails in extras tab + * keep "search" filter for extra networks when user refreshes the tab (previously it showed everything after you refreshed) + * fix webui showing the same image if you configure the generation to always save results into same file + * fix bug with upscalers not working properly + * fix MPS on PyTorch 2.0.1, Intel Macs + * make it so that custom context menu from contextMenu.js only disappears after user's click, ignoring non-user click events + * prevent Reload UI button/link from reloading the page when it's not yet ready + * fix prompts from file script failing to read contents from a drag/drop file + + +## 1.1.1 +### Bug Fixes: + * fix an error that prevents running webui on PyTorch<2.0 without --disable-safe-unpickle + +## 1.1.0 +### Features: + * switch to PyTorch 2.0.0 (except for AMD GPUs) + * visual improvements to custom code scripts + * add filename patterns: `[clip_skip]`, `[hasprompt<>]`, `[batch_number]`, `[generation_number]` + * add support for saving init images in img2img, and record their hashes in infotext for reproducibility + * automatically select current word when adjusting weight with ctrl+up/down + * add dropdowns for X/Y/Z plot + * add setting: Stable Diffusion/Random number generator source: makes it possible to make images generated from a given manual seed consistent across different GPUs + * support Gradio's theme API + * use TCMalloc on Linux by default; possible fix for memory leaks + * add optimization option to remove negative conditioning at low sigma values #9177 + * embed model merge metadata in .safetensors file + * extension settings backup/restore feature #9169 + * add "resize by" and "resize to" tabs to img2img + * add option "keep original size" to textual inversion images preprocess + * image viewer scrolling via analog stick + * button to restore the progress from session lost / tab reload + +### Minor: + * bump Gradio to 3.28.1 + * change "scale to" to sliders in Extras tab + * add labels to tool buttons to make it possible to hide them + * add tiled inference support for ScuNET + * add branch support for extension installation + * change Linux installation script to install into current directory rather than `/home/username` + * sort textual inversion embeddings by name (case-insensitive) + * allow styles.csv to be symlinked or mounted in docker + * remove the "do not add watermark to images" option + * make selected tab configurable with UI config + * make the extra networks UI fixed height and scrollable + * add `disable_tls_verify` arg for use with self-signed certs + +### Extensions: + * add reload callback + * add `is_hr_pass` field for processing + +### Bug Fixes: + * fix broken batch image processing on 'Extras/Batch Process' tab + * add "None" option to extra networks dropdowns + * fix FileExistsError for CLIP Interrogator + * fix /sdapi/v1/txt2img endpoint not working on Linux #9319 + * fix disappearing live previews and progressbar during slow tasks + * fix fullscreen image view not working properly in some cases + * prevent alwayson_scripts args param resizing script_arg list when they are inserted in it + * fix prompt schedule for second order samplers + * fix image mask/composite for weird resolutions #9628 + * use correct images for previews when using AND (see #9491) + * one broken image in img2img batch won't stop all processing + * fix image orientation bug in train/preprocess + * fix Ngrok recreating tunnels every reload + * fix `--realesrgan-models-path` and `--ldsr-models-path` not working + * fix `--skip-install` not working + * use SAMPLE file format in Outpainting Mk2 & Poorman + * do not fail all LoRAs if some have failed to load when making a picture + +## 1.0.0 + * everything diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..2c781aff450c8604eb3cf876d2c3585a96a5a590 --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,7 @@ +cff-version: 1.2.0 +message: "If you use this software, please cite it as below." +authors: + - given-names: AUTOMATIC1111 +title: "Stable Diffusion Web UI" +date-released: 2022-08-22 +url: "https://github.com/AUTOMATIC1111/stable-diffusion-webui" diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..6aefeb7e2c97049295952c70c6eb4550d051cde6 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1 @@ +* @lllyasviel diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..c3301edaea13abb11068055f08b5d9e8ab42786a --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,688 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (c) 2023 AUTOMATIC1111 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. + + +---------------------------------Facebook BNB------------------------------- + +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/NEWS.md b/NEWS.md new file mode 100644 index 0000000000000000000000000000000000000000..3fbb001b2eed6ef9ff15f916d8d3b910e117184b --- /dev/null +++ b/NEWS.md @@ -0,0 +1,7 @@ +About Gradio 5: will try to upgrade to Gradio 5 at about 2025 March. If failed, then will try again on about 2025 June. relatively positive that we can have Gradio5 before next summer. + +2024 Oct 28: A new branch `sd35` is contributed by [#2183](https://github.com/lllyasviel/stable-diffusion-webui-forge/pull/2183) . I will take a look at quants and sampling and transformer's clip-g vs that clip-g rewrite before merging to main ... (Oct 29: okay maybe medium also need to take a look later) + +About Flux ControlNet (sync [here](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/932)): The rewrite of ControlNet Intergrated will ~start at about Sep 29~ (delayed) ~start at about Oct 15~ (delayed) ~start at about Oct 30~ (delayed) start at about Nov 20. (When this note is announced, the main targets include some diffusers formatted Flux ControlNets and some community implementation of Union ControlNets. However, this may be extended if stronger models come out after this note.) + +2024 Sep 7: New sampler `Flux Realistic` is available now! Recommended scheduler is "simple". \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3d0d202a714970b42032b69d523e0ba59a1134c3 --- /dev/null +++ b/README.md @@ -0,0 +1,213 @@ +# Stable Diffusion WebUI Forge + +Stable Diffusion WebUI Forge is a platform on top of [Stable Diffusion WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) (based on [Gradio](https://www.gradio.app/) ) to make development easier, optimize resource management, speed up inference, and study experimental features. + +The name "Forge" is inspired from "Minecraft Forge". This project is aimed at becoming SD WebUI's Forge. + +Forge is currently based on SD-WebUI 1.10.1 at [this commit](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/82a973c04367123ae98bd9abdf80d9eda9b910e2). (Because original SD-WebUI is almost static now, Forge will sync with original WebUI every 90 days, or when important fixes.) + +News are moved to this link: [Click here to see the News section](https://github.com/lllyasviel/stable-diffusion-webui-forge/blob/main/NEWS.md) + +# Quick List + +[Gradio 4 UI Must Read (TLDR: You need to use RIGHT MOUSE BUTTON to move canvas!)](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/853) + +[Flux Tutorial (BitsandBytes Models, NF4, "GPU Weight", "Offload Location", "Offload Method", etc)](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/981) + +[Flux Tutorial 2 (Seperated Full Models, GGUF, Technically Correct Comparison between GGUF and NF4, etc)](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/1050) + +[Forge Extension List and Extension Replacement List (Temporary)](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/1754) + +[How to make LoRAs more precise on low-bit models; How to Skip" Patching LoRAs"; How to only load LoRA one time rather than each generation; How to report LoRAs that do not work](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/1038) + +[Report Flux Performance Problems (TLDR: DO NOT set "GPU Weight" too high! Lower "GPU Weight" solves 99% problems!)](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/1181) + +[How to solve "Connection errored out" / "Press anykey to continue ..." / etc](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/1474) + +[(Save Flux BitsandBytes UNet/Checkpoint)](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/1224#discussioncomment-10384104) + +[LayerDiffuse Transparent Image Editing](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/854) + +[Tell us what is missing in ControlNet Integrated](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/932) + +[(Policy) Soft Advertisement Removal Policy](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/1286) + +(Flux BNB NF4 / GGUF Q8_0/Q5_0/Q5_1/Q4_0/Q4_1 are all natively supported with GPU weight slider and Quene/Async Swap toggle and swap location toggle. All Flux BNB NF4 / GGUF Q8_0/Q5_0/Q4_0 have LoRA support.) + +# Installing Forge + +**Just use this one-click installation package (with git and python included).** + +[>>> Click Here to Download One-Click Package (CUDA 12.1 + Pytorch 2.3.1) <<<](https://github.com/lllyasviel/stable-diffusion-webui-forge/releases/download/latest/webui_forge_cu121_torch231.7z) + +Some other CUDA/Torch Versions: + +[Forge with CUDA 12.1 + Pytorch 2.3.1](https://github.com/lllyasviel/stable-diffusion-webui-forge/releases/download/latest/webui_forge_cu121_torch231.7z) <- **Recommended** + +[Forge with CUDA 12.4 + Pytorch 2.4](https://github.com/lllyasviel/stable-diffusion-webui-forge/releases/download/latest/webui_forge_cu124_torch24.7z) <- **Fastest**, but MSVC may be broken, xformers may not work + +[Forge with CUDA 12.1 + Pytorch 2.1](https://github.com/lllyasviel/stable-diffusion-webui-forge/releases/download/latest/webui_forge_cu121_torch21.7z) <- the previously used old environments + +After you download, you uncompress, use `update.bat` to update, and use `run.bat` to run. + +Note that running `update.bat` is important, otherwise you may be using a previous version with potential bugs unfixed. + +![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/c49bd60d-82bd-4086-9859-88d472582b94) + +### Advanced Install + +If you are proficient in Git and you want to install Forge as another branch of SD-WebUI, please see [here](https://github.com/continue-revolution/sd-webui-animatediff/blob/forge/master/docs/how-to-use.md#you-have-a1111-and-you-know-git). In this way, you can reuse all SD checkpoints and all extensions you installed previously in your OG SD-WebUI, but you should know what you are doing. + +If you know what you are doing, you can also install Forge using same method as SD-WebUI. (Install Git, Python, Git Clone the forge repo `https://github.com/lllyasviel/stable-diffusion-webui-forge.git` and then run webui-user.bat). + +### Previous Versions + +You can download previous versions [here](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/849). + +# Forge Status + +Based on manual test one-by-one: + +| Component | Status | Last Test | +|-----------------------------------------------------|---------------------------------------------|--------------| +| Basic Diffusion | Normal | 2024 Aug 26 | +| GPU Memory Management System | Normal | 2024 Aug 26 | +| LoRAs | Normal | 2024 Aug 26 | +| All Preprocessors | Normal | 2024 Aug 26 | +| All ControlNets | Normal | 2024 Aug 26 | +| All IP-Adapters | Normal | 2024 Aug 26 | +| All Instant-IDs | Normal | 2024 July 27 | +| All Reference-only Methods | Normal | 2024 July 27 | +| All Integrated Extensions | Normal | 2024 July 27 | +| Popular Extensions (Adetailer, etc) | Normal | 2024 July 27 | +| Gradio 4 UIs | Normal | 2024 July 27 | +| Gradio 4 Forge Canvas | Normal | 2024 Aug 26 | +| LoRA/Checkpoint Selection UI for Gradio 4 | Normal | 2024 July 27 | +| Photopea/OpenposeEditor/etc for ControlNet | Normal | 2024 July 27 | +| Wacom 128 level touch pressure support for Canvas | Normal | 2024 July 15 | +| Microsoft Surface touch pressure support for Canvas | Broken, pending fix | 2024 July 29 | +| ControlNets (Union) | Not implemented yet, pending implementation | 2024 Aug 26 | +| ControlNets (Flux) | Not implemented yet, pending implementation | 2024 Aug 26 | +| API endpoints (txt2img, img2img, etc) | Normal, but pending improved Flux support | 2024 Aug 29 | +| OFT LoRAs | Broken, pending fix | 2024 Sep 9 | + +Feel free to open issue if anything is broken and I will take a look every several days. If I do not update this "Forge Status" then it means I cannot reproduce any problem. In that case, fresh re-install should help most. + +# UnetPatcher + +Below are self-supported **single file** of all codes to implement FreeU V2. + +See also `extension-builtin/sd_forge_freeu/scripts/forge_freeu.py`: + +```python +import torch +import gradio as gr + +from modules import scripts + + +def Fourier_filter(x, threshold, scale): + # FFT + x_freq = torch.fft.fftn(x.float(), dim=(-2, -1)) + x_freq = torch.fft.fftshift(x_freq, dim=(-2, -1)) + + B, C, H, W = x_freq.shape + mask = torch.ones((B, C, H, W), device=x.device) + + crow, ccol = H // 2, W // 2 + mask[..., crow - threshold:crow + threshold, ccol - threshold:ccol + threshold] = scale + x_freq = x_freq * mask + + # IFFT + x_freq = torch.fft.ifftshift(x_freq, dim=(-2, -1)) + x_filtered = torch.fft.ifftn(x_freq, dim=(-2, -1)).real + + return x_filtered.to(x.dtype) + + +def patch_freeu_v2(unet_patcher, b1, b2, s1, s2): + model_channels = unet_patcher.model.diffusion_model.config["model_channels"] + scale_dict = {model_channels * 4: (b1, s1), model_channels * 2: (b2, s2)} + on_cpu_devices = {} + + def output_block_patch(h, hsp, transformer_options): + scale = scale_dict.get(h.shape[1], None) + if scale is not None: + hidden_mean = h.mean(1).unsqueeze(1) + B = hidden_mean.shape[0] + hidden_max, _ = torch.max(hidden_mean.view(B, -1), dim=-1, keepdim=True) + hidden_min, _ = torch.min(hidden_mean.view(B, -1), dim=-1, keepdim=True) + hidden_mean = (hidden_mean - hidden_min.unsqueeze(2).unsqueeze(3)) / (hidden_max - hidden_min).unsqueeze(2).unsqueeze(3) + + h[:, :h.shape[1] // 2] = h[:, :h.shape[1] // 2] * ((scale[0] - 1) * hidden_mean + 1) + + if hsp.device not in on_cpu_devices: + try: + hsp = Fourier_filter(hsp, threshold=1, scale=scale[1]) + except: + print("Device", hsp.device, "does not support the torch.fft.") + on_cpu_devices[hsp.device] = True + hsp = Fourier_filter(hsp.cpu(), threshold=1, scale=scale[1]).to(hsp.device) + else: + hsp = Fourier_filter(hsp.cpu(), threshold=1, scale=scale[1]).to(hsp.device) + + return h, hsp + + m = unet_patcher.clone() + m.set_model_output_block_patch(output_block_patch) + return m + + +class FreeUForForge(scripts.Script): + sorting_priority = 12 # It will be the 12th item on UI. + + def title(self): + return "FreeU Integrated" + + def show(self, is_img2img): + # make this extension visible in both txt2img and img2img tab. + return scripts.AlwaysVisible + + def ui(self, *args, **kwargs): + with gr.Accordion(open=False, label=self.title()): + freeu_enabled = gr.Checkbox(label='Enabled', value=False) + freeu_b1 = gr.Slider(label='B1', minimum=0, maximum=2, step=0.01, value=1.01) + freeu_b2 = gr.Slider(label='B2', minimum=0, maximum=2, step=0.01, value=1.02) + freeu_s1 = gr.Slider(label='S1', minimum=0, maximum=4, step=0.01, value=0.99) + freeu_s2 = gr.Slider(label='S2', minimum=0, maximum=4, step=0.01, value=0.95) + + return freeu_enabled, freeu_b1, freeu_b2, freeu_s1, freeu_s2 + + def process_before_every_sampling(self, p, *script_args, **kwargs): + # This will be called before every sampling. + # If you use highres fix, this will be called twice. + + freeu_enabled, freeu_b1, freeu_b2, freeu_s1, freeu_s2 = script_args + + if not freeu_enabled: + return + + unet = p.sd_model.forge_objects.unet + + unet = patch_freeu_v2(unet, freeu_b1, freeu_b2, freeu_s1, freeu_s2) + + p.sd_model.forge_objects.unet = unet + + # Below codes will add some logs to the texts below the image outputs on UI. + # The extra_generation_params does not influence results. + p.extra_generation_params.update(dict( + freeu_enabled=freeu_enabled, + freeu_b1=freeu_b1, + freeu_b2=freeu_b2, + freeu_s1=freeu_s1, + freeu_s2=freeu_s2, + )) + + return +``` + +See also [Forge's Unet Implementation](https://github.com/lllyasviel/stable-diffusion-webui-forge/blob/main/backend/nn/unet.py). + +# Under Construction + +WebUI Forge is now under some constructions, and docs / UI / functionality may change with updates. diff --git a/_typos.toml b/_typos.toml new file mode 100644 index 0000000000000000000000000000000000000000..1c63fe7033122ec47c61088e01b6905ca34ca1c5 --- /dev/null +++ b/_typos.toml @@ -0,0 +1,5 @@ +[default.extend-words] +# Part of "RGBa" (Pillow's pre-multiplied alpha RGB mode) +Ba = "Ba" +# HSA is something AMD uses for their GPUs +HSA = "HSA" diff --git a/backend/loader.py b/backend/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..d5b6ca905f0f92c4307cc2c0ae13cdae86b97550 --- /dev/null +++ b/backend/loader.py @@ -0,0 +1,337 @@ +import os +import torch +import logging +import importlib + +import backend.args +import huggingface_guess + +from diffusers import DiffusionPipeline +from transformers import modeling_utils + +from backend import memory_management +from backend.utils import read_arbitrary_config, load_torch_file, beautiful_print_gguf_state_dict_statics +from backend.state_dict import try_filter_state_dict, load_state_dict +from backend.operations import using_forge_operations +from backend.nn.vae import IntegratedAutoencoderKL +from backend.nn.clip import IntegratedCLIP +from backend.nn.unet import IntegratedUNet2DConditionModel + +from backend.diffusion_engine.sd15 import StableDiffusion +from backend.diffusion_engine.sd20 import StableDiffusion2 +from backend.diffusion_engine.sdxl import StableDiffusionXL +from backend.diffusion_engine.flux import Flux + + +possible_models = [StableDiffusion, StableDiffusion2, StableDiffusionXL, Flux] + + +logging.getLogger("diffusers").setLevel(logging.ERROR) +dir_path = os.path.dirname(__file__) + + +def load_huggingface_component(guess, component_name, lib_name, cls_name, repo_path, state_dict): + config_path = os.path.join(repo_path, component_name) + + if component_name in ['feature_extractor', 'safety_checker']: + return None + + if lib_name in ['transformers', 'diffusers']: + if component_name in ['scheduler']: + cls = getattr(importlib.import_module(lib_name), cls_name) + return cls.from_pretrained(os.path.join(repo_path, component_name)) + if component_name.startswith('tokenizer'): + cls = getattr(importlib.import_module(lib_name), cls_name) + comp = cls.from_pretrained(os.path.join(repo_path, component_name)) + comp._eventual_warn_about_too_long_sequence = lambda *args, **kwargs: None + return comp + if cls_name in ['AutoencoderKL']: + assert isinstance(state_dict, dict) and len(state_dict) > 16, 'You do not have VAE state dict!' + + config = IntegratedAutoencoderKL.load_config(config_path) + + with using_forge_operations(device=memory_management.cpu, dtype=memory_management.vae_dtype()): + model = IntegratedAutoencoderKL.from_config(config) + + if 'decoder.up_blocks.0.resnets.0.norm1.weight' in state_dict.keys(): #diffusers format + state_dict = huggingface_guess.diffusers_convert.convert_vae_state_dict(state_dict) + load_state_dict(model, state_dict, ignore_start='loss.') + return model + if component_name.startswith('text_encoder') and cls_name in ['CLIPTextModel', 'CLIPTextModelWithProjection']: + assert isinstance(state_dict, dict) and len(state_dict) > 16, 'You do not have CLIP state dict!' + + from transformers import CLIPTextConfig, CLIPTextModel + config = CLIPTextConfig.from_pretrained(config_path) + + to_args = dict(device=memory_management.cpu, dtype=memory_management.text_encoder_dtype()) + + with modeling_utils.no_init_weights(): + with using_forge_operations(**to_args, manual_cast_enabled=True): + model = IntegratedCLIP(CLIPTextModel, config, add_text_projection=True).to(**to_args) + + load_state_dict(model, state_dict, ignore_errors=[ + 'transformer.text_projection.weight', + 'transformer.text_model.embeddings.position_ids', + 'logit_scale' + ], log_name=cls_name) + + return model + if cls_name == 'T5EncoderModel': + assert isinstance(state_dict, dict) and len(state_dict) > 16, 'You do not have T5 state dict!' + + from backend.nn.t5 import IntegratedT5 + config = read_arbitrary_config(config_path) + + storage_dtype = memory_management.text_encoder_dtype() + state_dict_dtype = memory_management.state_dict_dtype(state_dict) + + if state_dict_dtype in [torch.float8_e4m3fn, torch.float8_e5m2, 'nf4', 'fp4', 'gguf']: + print(f'Using Detected T5 Data Type: {state_dict_dtype}') + storage_dtype = state_dict_dtype + if state_dict_dtype in ['nf4', 'fp4', 'gguf']: + print(f'Using pre-quant state dict!') + if state_dict_dtype in ['gguf']: + beautiful_print_gguf_state_dict_statics(state_dict) + else: + print(f'Using Default T5 Data Type: {storage_dtype}') + + if storage_dtype in ['nf4', 'fp4', 'gguf']: + with modeling_utils.no_init_weights(): + with using_forge_operations(device=memory_management.cpu, dtype=memory_management.text_encoder_dtype(), manual_cast_enabled=False, bnb_dtype=storage_dtype): + model = IntegratedT5(config) + else: + with modeling_utils.no_init_weights(): + with using_forge_operations(device=memory_management.cpu, dtype=storage_dtype, manual_cast_enabled=True): + model = IntegratedT5(config) + + load_state_dict(model, state_dict, log_name=cls_name, ignore_errors=['transformer.encoder.embed_tokens.weight', 'logit_scale']) + + return model + if cls_name in ['UNet2DConditionModel', 'FluxTransformer2DModel']: + assert isinstance(state_dict, dict) and len(state_dict) > 16, 'You do not have model state dict!' + + model_loader = None + if cls_name == 'UNet2DConditionModel': + model_loader = lambda c: IntegratedUNet2DConditionModel.from_config(c) + if cls_name == 'FluxTransformer2DModel': + from backend.nn.flux import IntegratedFluxTransformer2DModel + model_loader = lambda c: IntegratedFluxTransformer2DModel(**c) + + unet_config = guess.unet_config.copy() + state_dict_parameters = memory_management.state_dict_parameters(state_dict) + state_dict_dtype = memory_management.state_dict_dtype(state_dict) + + storage_dtype = memory_management.unet_dtype(model_params=state_dict_parameters, supported_dtypes=guess.supported_inference_dtypes) + + unet_storage_dtype_overwrite = backend.args.dynamic_args.get('forge_unet_storage_dtype') + + if unet_storage_dtype_overwrite is not None: + storage_dtype = unet_storage_dtype_overwrite + elif state_dict_dtype in [torch.float8_e4m3fn, torch.float8_e5m2, 'nf4', 'fp4', 'gguf']: + print(f'Using Detected UNet Type: {state_dict_dtype}') + storage_dtype = state_dict_dtype + if state_dict_dtype in ['nf4', 'fp4', 'gguf']: + print(f'Using pre-quant state dict!') + if state_dict_dtype in ['gguf']: + beautiful_print_gguf_state_dict_statics(state_dict) + + load_device = memory_management.get_torch_device() + computation_dtype = memory_management.get_computation_dtype(load_device, parameters=state_dict_parameters, supported_dtypes=guess.supported_inference_dtypes) + offload_device = memory_management.unet_offload_device() + + if storage_dtype in ['nf4', 'fp4', 'gguf']: + initial_device = memory_management.unet_inital_load_device(parameters=state_dict_parameters, dtype=computation_dtype) + with using_forge_operations(device=initial_device, dtype=computation_dtype, manual_cast_enabled=False, bnb_dtype=storage_dtype): + model = model_loader(unet_config) + else: + initial_device = memory_management.unet_inital_load_device(parameters=state_dict_parameters, dtype=storage_dtype) + need_manual_cast = storage_dtype != computation_dtype + to_args = dict(device=initial_device, dtype=storage_dtype) + + with using_forge_operations(**to_args, manual_cast_enabled=need_manual_cast): + model = model_loader(unet_config).to(**to_args) + + load_state_dict(model, state_dict) + + if hasattr(model, '_internal_dict'): + model._internal_dict = unet_config + else: + model.config = unet_config + + model.storage_dtype = storage_dtype + model.computation_dtype = computation_dtype + model.load_device = load_device + model.initial_device = initial_device + model.offload_device = offload_device + + return model + + print(f'Skipped: {component_name} = {lib_name}.{cls_name}') + return None + + +def replace_state_dict(sd, asd, guess): + vae_key_prefix = guess.vae_key_prefix[0] + text_encoder_key_prefix = guess.text_encoder_key_prefix[0] + + if 'enc.blk.0.attn_k.weight' in asd: + wierd_t5_format_from_city96 = { + "enc.": "encoder.", + ".blk.": ".block.", + "token_embd": "shared", + "output_norm": "final_layer_norm", + "attn_q": "layer.0.SelfAttention.q", + "attn_k": "layer.0.SelfAttention.k", + "attn_v": "layer.0.SelfAttention.v", + "attn_o": "layer.0.SelfAttention.o", + "attn_norm": "layer.0.layer_norm", + "attn_rel_b": "layer.0.SelfAttention.relative_attention_bias", + "ffn_up": "layer.1.DenseReluDense.wi_1", + "ffn_down": "layer.1.DenseReluDense.wo", + "ffn_gate": "layer.1.DenseReluDense.wi_0", + "ffn_norm": "layer.1.layer_norm", + } + wierd_t5_pre_quant_keys_from_city96 = ['shared.weight'] + asd_new = {} + for k, v in asd.items(): + for s, d in wierd_t5_format_from_city96.items(): + k = k.replace(s, d) + asd_new[k] = v + for k in wierd_t5_pre_quant_keys_from_city96: + asd_new[k] = asd_new[k].dequantize_as_pytorch_parameter() + asd.clear() + asd = asd_new + + if "decoder.conv_in.weight" in asd: + keys_to_delete = [k for k in sd if k.startswith(vae_key_prefix)] + for k in keys_to_delete: + del sd[k] + for k, v in asd.items(): + sd[vae_key_prefix + k] = v + + if 'text_model.encoder.layers.0.layer_norm1.weight' in asd: + keys_to_delete = [k for k in sd if k.startswith(f"{text_encoder_key_prefix}clip_l.")] + for k in keys_to_delete: + del sd[k] + for k, v in asd.items(): + sd[f"{text_encoder_key_prefix}clip_l.transformer.{k}"] = v + + if 'encoder.block.0.layer.0.SelfAttention.k.weight' in asd: + keys_to_delete = [k for k in sd if k.startswith(f"{text_encoder_key_prefix}t5xxl.")] + for k in keys_to_delete: + del sd[k] + for k, v in asd.items(): + sd[f"{text_encoder_key_prefix}t5xxl.transformer.{k}"] = v + + return sd + + +def preprocess_state_dict(sd): + if any("double_block" in k for k in sd.keys()): + if not any(k.startswith("model.diffusion_model") for k in sd.keys()): + sd = {f"model.diffusion_model.{k}": v for k, v in sd.items()} + + return sd + + +def split_state_dict(sd, additional_state_dicts: list = None): + sd = load_torch_file(sd) + sd = preprocess_state_dict(sd) + guess = huggingface_guess.guess(sd) + + if isinstance(additional_state_dicts, list): + for asd in additional_state_dicts: + asd = load_torch_file(asd) + sd = replace_state_dict(sd, asd, guess) + + guess.clip_target = guess.clip_target(sd) + guess.model_type = guess.model_type(sd) + guess.ztsnr = 'ztsnr' in sd + + state_dict = { + guess.unet_target: try_filter_state_dict(sd, guess.unet_key_prefix), + guess.vae_target: try_filter_state_dict(sd, guess.vae_key_prefix) + } + + sd = guess.process_clip_state_dict(sd) + + for k, v in guess.clip_target.items(): + state_dict[v] = try_filter_state_dict(sd, [k + '.']) + + state_dict['ignore'] = sd + + print_dict = {k: len(v) for k, v in state_dict.items()} + print(f'StateDict Keys: {print_dict}') + + del state_dict['ignore'] + + return state_dict, guess + + +@torch.inference_mode() +def forge_loader(sd, additional_state_dicts=None): + try: + state_dicts, estimated_config = split_state_dict(sd, additional_state_dicts=additional_state_dicts) + except: + raise ValueError('Failed to recognize model type!') + + repo_name = estimated_config.huggingface_repo + + local_path = os.path.join(dir_path, 'huggingface', repo_name) + config: dict = DiffusionPipeline.load_config(local_path) + huggingface_components = {} + for component_name, v in config.items(): + if isinstance(v, list) and len(v) == 2: + lib_name, cls_name = v + component_sd = state_dicts.get(component_name, None) + component = load_huggingface_component(estimated_config, component_name, lib_name, cls_name, local_path, component_sd) + if component_sd is not None: + del state_dicts[component_name] + if component is not None: + huggingface_components[component_name] = component + + yaml_config = None + yaml_config_prediction_type = None + + try: + import yaml + from pathlib import Path + config_filename = os.path.splitext(sd)[0] + '.yaml' + if Path(config_filename).is_file(): + with open(config_filename, 'r') as stream: + yaml_config = yaml.safe_load(stream) + except ImportError: + pass + + # Fix Huggingface prediction type using .yaml config or estimated config detection + prediction_types = { + 'EPS': 'epsilon', + 'V_PREDICTION': 'v_prediction', + 'EDM': 'edm', + } + + has_prediction_type = 'scheduler' in huggingface_components and hasattr(huggingface_components['scheduler'], 'config') and 'prediction_type' in huggingface_components['scheduler'].config + + if yaml_config is not None: + yaml_config_prediction_type: str = ( + yaml_config.get('model', {}).get('params', {}).get('parameterization', '') + or yaml_config.get('model', {}).get('params', {}).get('denoiser_config', {}).get('params', {}).get('scaling_config', {}).get('target', '') + ) + if yaml_config_prediction_type == 'v' or yaml_config_prediction_type.endswith(".VScaling"): + yaml_config_prediction_type = 'v_prediction' + else: + # Use estimated prediction config if no suitable prediction type found + yaml_config_prediction_type = '' + + if has_prediction_type: + if yaml_config_prediction_type: + huggingface_components['scheduler'].config.prediction_type = yaml_config_prediction_type + else: + huggingface_components['scheduler'].config.prediction_type = prediction_types.get(estimated_config.model_type.name, huggingface_components['scheduler'].config.prediction_type) + + for M in possible_models: + if any(isinstance(estimated_config, x) for x in M.matched_guesses): + return M(estimated_config=estimated_config, huggingface_components=huggingface_components) + + print('Failed to recognize model type!') + return None diff --git a/backend/stream.py b/backend/stream.py new file mode 100644 index 0000000000000000000000000000000000000000..f3fcd7bc6aac829f66c7e8811128587299d07052 --- /dev/null +++ b/backend/stream.py @@ -0,0 +1,61 @@ +import torch +from backend.args import args + + +def stream_context(): + if torch.cuda.is_available(): + return torch.cuda.stream + + if torch.xpu.is_available(): + return torch.xpu.stream + + return None + + +def get_current_stream(): + try: + if torch.cuda.is_available(): + device = torch.device(torch.cuda.current_device()) + stream = torch.cuda.current_stream(device) + with torch.cuda.stream(stream): + torch.zeros((1, 1)).to(device, torch.float32) + stream.synchronize() + return stream + if torch.xpu.is_available(): + device = torch.device("xpu") + stream = torch.xpu.current_stream(device) + with torch.xpu.stream(stream): + torch.zeros((1, 1)).to(device, torch.float32) + stream.synchronize() + return stream + except: + return None + + +def get_new_stream(): + try: + if torch.cuda.is_available(): + device = torch.device(torch.cuda.current_device()) + stream = torch.cuda.Stream(device) + with torch.cuda.stream(stream): + torch.zeros((1, 1)).to(device, torch.float32) + stream.synchronize() + return stream + if torch.xpu.is_available(): + device = torch.device("xpu") + stream = torch.xpu.Stream(device) + with torch.xpu.stream(stream): + torch.zeros((1, 1)).to(device, torch.float32) + stream.synchronize() + return stream + except: + return None + + +def should_use_stream(): + return stream_activated and current_stream is not None and mover_stream is not None + + +current_stream = get_current_stream() +mover_stream = get_new_stream() +stream_activated = args.cuda_stream diff --git a/config.json b/config.json new file mode 100644 index 0000000000000000000000000000000000000000..31f62c50573d67813f3a6f634d10b4118be60005 --- /dev/null +++ b/config.json @@ -0,0 +1,450 @@ +{ + "SCUNET_tile": 256, + "SCUNET_tile_overlap": 8, + "SWIN_tile": 192, + "SWIN_tile_overlap": 8, + "SWIN_torch_compile": false, + "control_net_detectedmap_dir": "detected_maps", + "control_net_models_path": "", + "control_net_modules_path": "", + "control_net_unit_count": 1, + "control_net_model_cache_size": 5, + "control_net_no_detectmap": false, + "control_net_detectmap_autosaving": false, + "control_net_allow_script_control": false, + "control_net_sync_field_args": true, + "controlnet_show_batch_images_in_ui": false, + "controlnet_increment_seed_during_batch": false, + "controlnet_disable_openpose_edit": false, + "controlnet_disable_photopea_edit": false, + "controlnet_photopea_warning": true, + "controlnet_input_thumbnail": true, + "use_aria2": true, + "disable_dns": false, + "show_log": false, + "split_aria2": 64, + "aria2_flags": "", + "unpack_zip": false, + "save_api_info": false, + "auto_save_all_img": false, + "custom_api_key": "", + "hide_early_access": true, + "use_LORA": true, + "dot_subfolders": true, + "use_local_html": false, + "local_path_in_html": false, + "page_header": false, + "video_playback": true, + "individual_meta_btn": true, + "model_desc_to_json": true, + "civitai_not_found_print": true, + "civitai_send_to_browser": false, + "image_location": "", + "sub_image_location": true, + "save_to_custom": false, + "custom_civitai_proxy": "", + "cabundle_path_proxy": "", + "disable_sll_proxy": false, + "Checkpoint_default_subfolder": "None", + "LORA_LoCon_default_subfolder": "None", + "TextualInversion_default_subfolder": "None", + "Poses_default_subfolder": "None", + "Controlnet_default_subfolder": "None", + "Hypernetwork_default_subfolder": "None", + "MotionModule_default_subfolder": "None", + "SWINIR_upscale_default_subfolder": "None", + "REALESRGAN_upscale_default_subfolder": "None", + "GFPGAN_upscale_default_subfolder": "None", + "BSRGAN_upscale_default_subfolder": "None", + "ESRGAN_upscale_default_subfolder": "None", + "VAE_default_subfolder": "None", + "AestheticGradient_default_subfolder": "None", + "Wildcards_default_subfolder": "None", + "Workflows_default_subfolder": "None", + "Other_default_subfolder": "None", + "arh_javascript_aspect_ratio_show": true, + "arh_javascript_aspect_ratio": "1:1, 3:2, 4:3, 5:4, 16:9", + "arh_ui_javascript_selection_method": "Aspect Ratios Dropdown", + "arh_hide_accordion_by_default": true, + "arh_expand_by_default": false, + "arh_ui_component_order_key": "MaxDimensionScaler, MinDimensionScaler, PredefinedAspectRatioButtons, PredefinedPercentageButtons", + "arh_show_max_width_or_height": false, + "arh_max_width_or_height": 1024.0, + "arh_show_min_width_or_height": false, + "arh_min_width_or_height": 1024.0, + "arh_show_predefined_aspect_ratios": false, + "arh_predefined_aspect_ratio_use_max_dim": false, + "arh_predefined_aspect_ratios": "1:1, 4:3, 16:9, 9:16, 21:9", + "arh_show_predefined_percentages": false, + "arh_predefined_percentages": "25, 50, 75, 125, 150, 175, 200", + "arh_predefined_percentages_display_key": "Incremental/decremental percentage (-50%, +50%)", + "sd_model_checkpoint": "GB-ANIME.safetensors", + "forge_async_loading": "Queue", + "forge_inference_memory": 1024, + "forge_pin_shared_memory": "CPU", + "outdir_samples": "", + "outdir_txt2img_samples": "outputs/txt2img-images", + "outdir_img2img_samples": "outputs/img2img-images", + "outdir_extras_samples": "outputs/extras-images", + "outdir_grids": "", + "outdir_txt2img_grids": "outputs/txt2img-grids", + "outdir_img2img_grids": "outputs/img2img-grids", + "outdir_save": "log/images", + "outdir_init_images": "outputs/init-images", + "samples_save": true, + "samples_format": "jpg", + "samples_filename_pattern": "", + "save_images_add_number": true, + "save_images_replace_action": "Replace", + "grid_save": true, + "grid_format": "jpg", + "grid_extended_filename": false, + "grid_only_if_multiple": true, + "grid_prevent_empty_spots": false, + "grid_zip_filename_pattern": "", + "n_rows": -1, + "font": "", + "grid_text_active_color": "#000000", + "grid_text_inactive_color": "#999999", + "grid_background_color": "#ffffff", + "save_images_before_face_restoration": false, + "save_images_before_highres_fix": false, + "save_images_before_color_correction": false, + "save_mask": false, + "save_mask_composite": false, + "jpeg_quality": 100, + "webp_lossless": false, + "export_for_4chan": true, + "img_downscale_threshold": 4, + "target_side_length": 4000, + "img_max_size_mp": 200, + "use_original_name_batch": true, + "use_upscaler_name_as_suffix": false, + "save_selected_only": true, + "save_write_log_csv": true, + "save_init_img": false, + "temp_dir": "", + "clean_temp_dir_at_start": false, + "save_incomplete_images": false, + "notification_audio": true, + "notification_volume": 100, + "save_to_dirs": true, + "grid_save_to_dirs": true, + "use_save_to_dirs_for_ui": false, + "directories_filename_pattern": "[date]", + "directories_max_prompt_words": 8, + "forge_try_reproduce": "None", + "auto_backcompat": true, + "use_old_emphasis_implementation": false, + "use_old_karras_scheduler_sigmas": false, + "no_dpmpp_sde_batch_determinism": false, + "use_old_hires_fix_width_height": false, + "hires_fix_use_firstpass_conds": false, + "use_old_scheduling": false, + "use_downcasted_alpha_bar": false, + "refiner_switch_by_sample_steps": false, + "lora_functional": false, + "extra_networks_show_hidden_directories": true, + "extra_networks_dir_button_function": false, + "extra_networks_hidden_models": "When searched", + "extra_networks_default_multiplier": 1, + "extra_networks_card_width": 0, + "extra_networks_card_height": 0, + "extra_networks_card_text_scale": 1, + "extra_networks_card_show_desc": true, + "extra_networks_card_description_is_html": false, + "extra_networks_card_order_field": "Path", + "extra_networks_card_order": "Ascending", + "extra_networks_tree_view_style": "Dirs", + "extra_networks_tree_view_default_enabled": true, + "extra_networks_tree_view_default_width": 180, + "extra_networks_add_text_separator": " ", + "ui_extra_networks_tab_reorder": "", + "textual_inversion_print_at_load": false, + "textual_inversion_add_hashes_to_infotext": true, + "sd_hypernetwork": "None", + "sd_lora": "None", + "lora_preferred_name": "Alias from file", + "lora_add_hashes_to_infotext": true, + "lora_bundled_ti_to_infotext": true, + "lora_filter_disabled": true, + "lora_in_memory_limit": 0, + "lora_not_found_warning_console": false, + "lora_not_found_gradio_warning": false, + "cross_attention_optimization": "Automatic", + "s_min_uncond": 0, + "s_min_uncond_all": false, + "token_merging_ratio": 0, + "token_merging_ratio_img2img": 0, + "token_merging_ratio_hr": 0, + "pad_cond_uncond": false, + "pad_cond_uncond_v0": false, + "persistent_cond_cache": true, + "batch_cond_uncond": true, + "fp8_storage": "Disable", + "cache_fp16_weight": false, + "hide_samplers": [], + "eta_ddim": 0, + "eta_ancestral": 1, + "ddim_discretize": "uniform", + "s_churn": 0, + "s_tmin": 0, + "s_tmax": 0, + "s_noise": 1, + "sigma_min": 0, + "sigma_max": 0, + "rho": 0, + "eta_noise_seed_delta": 0, + "always_discard_next_to_last_sigma": false, + "sgm_noise_multiplier": false, + "uni_pc_variant": "bh1", + "uni_pc_skip_type": "time_uniform", + "uni_pc_order": 3, + "uni_pc_lower_order_final": true, + "sd_noise_schedule": "Default", + "skip_early_cond": 0, + "beta_dist_alpha": 0.6, + "beta_dist_beta": 0.6, + "sd_checkpoints_limit": 1, + "sd_checkpoints_keep_in_cpu": true, + "sd_checkpoint_cache": 0, + "sd_unet": "Automatic", + "enable_quantization": false, + "emphasis": "Original", + "enable_batch_seeds": true, + "comma_padding_backtrack": 20, + "sdxl_clip_l_skip": false, + "upcast_attn": false, + "randn_source": "GPU", + "tiling": false, + "hires_fix_refiner_pass": "second pass", + "enable_prompt_comments": true, + "sd3_enable_t5": false, + "sdxl_crop_top": 0, + "sdxl_crop_left": 0, + "sdxl_refiner_low_aesthetic_score": 2.5, + "sdxl_refiner_high_aesthetic_score": 6, + "sd_vae_checkpoint_cache": 0, + "sd_vae_overrides_per_model_preferences": true, + "auto_vae_precision_bfloat16": false, + "auto_vae_precision": true, + "sd_vae_encode_method": "Full", + "sd_vae_decode_method": "Full", + "inpainting_mask_weight": 1, + "initial_noise_multiplier": 1, + "img2img_extra_noise": 0, + "img2img_color_correction": false, + "img2img_fix_steps": false, + "img2img_background_color": "#ffffff", + "img2img_sketch_default_brush_color": "#ffffff", + "img2img_inpaint_mask_brush_color": "#ffffff", + "img2img_inpaint_sketch_default_brush_color": "#ffffff", + "img2img_inpaint_mask_high_contrast": true, + "img2img_inpaint_mask_scribble_alpha": 75, + "return_mask": false, + "return_mask_composite": false, + "img2img_batch_show_results_limit": 32, + "overlay_inpaint": true, + "img2img_autosize": false, + "img2img_batch_use_original_name": false, + "return_grid": true, + "do_not_show_images": false, + "js_modal_lightbox": true, + "js_modal_lightbox_initially_zoomed": true, + "js_modal_lightbox_gamepad": false, + "js_modal_lightbox_gamepad_repeat": 250, + "sd_webui_modal_lightbox_icon_opacity": 1, + "sd_webui_modal_lightbox_toolbar_opacity": 0.9, + "gallery_height": "", + "open_dir_button_choice": "Subdirectory", + "hires_button_gallery_insert": false, + "enable_pnginfo": true, + "save_txt": false, + "add_model_name_to_info": true, + "add_model_hash_to_info": true, + "add_vae_name_to_info": true, + "add_vae_hash_to_info": true, + "add_user_name_to_info": false, + "add_version_to_infotext": true, + "disable_weights_auto_swap": true, + "infotext_skip_pasting": [], + "infotext_styles": "Apply if any", + "show_progressbar": true, + "live_previews_enable": false, + "live_previews_image_format": "webp", + "show_progress_grid": true, + "show_progress_every_n_steps": 10, + "show_progress_type": "Approx NN", + "live_preview_allow_lowvram_full": false, + "live_preview_content": "Prompt", + "live_preview_refresh_period": 1000, + "live_preview_fast_interrupt": false, + "js_live_preview_in_modal_lightbox": false, + "prevent_screen_sleep_during_generation": true, + "keyedit_precision_attention": 0.1, + "keyedit_precision_extra": 0.05, + "keyedit_delimiters": ".,\\/!?%^*;:{}=`~() ", + "keyedit_delimiters_whitespace": [ + "Tab", + "Carriage Return", + "Line Feed" + ], + "keyedit_move": true, + "disable_token_counters": false, + "include_styles_into_token_counters": true, + "extra_options_txt2img": [], + "extra_options_img2img": [], + "extra_options_cols": 1, + "extra_options_accordion": false, + "compact_prompt_box": false, + "samplers_in_dropdown": true, + "dimensions_and_batch_together": true, + "sd_checkpoint_dropdown_use_short": false, + "hires_fix_show_sampler": false, + "hires_fix_show_prompts": false, + "txt2img_settings_accordion": false, + "img2img_settings_accordion": false, + "interrupt_after_current": true, + "flux_t2i_width": 540, + "flux_t2i_height": 960, + "flux_t2i_cfg": 1, + "flux_t2i_hr_cfg": 1, + "flux_t2i_d_cfg": 3.5, + "flux_t2i_hr_d_cfg": 3.5, + "flux_i2i_width": 1920, + "flux_i2i_height": 1080, + "flux_i2i_cfg": 1, + "flux_i2i_d_cfg": 3.5, + "flux_GPU_MB": 14071, + "flux_t2i_sampler": "Euler", + "flux_t2i_scheduler": "Simple", + "flux_i2i_sampler": "Euler", + "flux_i2i_scheduler": "Simple", + "sd_t2i_width": 540, + "sd_t2i_height": 960, + "sd_t2i_cfg": 4, + "sd_t2i_hr_cfg": 7, + "sd_i2i_width": 1920, + "sd_i2i_height": 1080, + "sd_i2i_cfg": 5, + "sd_t2i_sampler": "Euler a", + "sd_t2i_scheduler": "Automatic", + "sd_i2i_sampler": "Euler a", + "sd_i2i_scheduler": "Automatic", + "xl_t2i_width": 540, + "xl_t2i_height": 960, + "xl_t2i_cfg": 5, + "xl_t2i_hr_cfg": 5, + "xl_i2i_width": 1024, + "xl_i2i_height": 1024, + "xl_i2i_cfg": 5, + "xl_GPU_MB": 14071, + "xl_t2i_sampler": "DPM++ 2M SDE", + "xl_t2i_scheduler": "Karras", + "xl_i2i_sampler": "DPM++ 2M SDE", + "xl_i2i_scheduler": "Karras", + "localization": "None", + "quick_setting_list": [], + "ui_tab_order": [], + "hidden_tabs": [], + "tabs_without_quick_settings_bar": [ + "Spaces" + ], + "ui_reorder_list": [], + "gradio_theme": "Default", + "gradio_themes_cache": true, + "show_progress_in_title": true, + "send_seed": true, + "send_size": true, + "enable_reloading_ui_scripts": false, + "api_enable_requests": true, + "api_forbid_local_requests": true, + "api_useragent": "", + "prioritized_callbacks_app_started": [], + "prioritized_callbacks_ui_tabs": [], + "prioritized_callbacks_ui_settings": [], + "prioritized_callbacks_after_component": [], + "prioritized_callbacks_infotext_pasted": [], + "prioritized_callbacks_before_ui": [], + "prioritized_callbacks_on_reload": [], + "prioritized_callbacks_script_before_process": [], + "prioritized_callbacks_script_process": [], + "prioritized_callbacks_script_postprocess": [], + "prioritized_callbacks_script_postprocess_batch": [], + "prioritized_callbacks_script_postprocess_batch_list": [], + "prioritized_callbacks_script_post_sample": [], + "prioritized_callbacks_script_on_mask_blend": [], + "prioritized_callbacks_script_postprocess_image": [], + "prioritized_callbacks_script_postprocess_maskoverlay": [], + "prioritized_callbacks_script_after_component": [], + "profiling_enable": false, + "profiling_activities": [ + "CPU" + ], + "profiling_record_shapes": true, + "profiling_profile_memory": true, + "profiling_with_stack": true, + "profiling_filename": "trace.json", + "auto_launch_browser": "Local", + "enable_console_prompts": false, + "show_warnings": false, + "show_gradio_deprecation_warnings": true, + "memmon_poll_rate": 8, + "samples_log_stdout": false, + "multiple_tqdm": true, + "enable_upscale_progressbar": true, + "print_hypernet_extra": false, + "list_hidden_files": true, + "disable_mmap_load_safetensors": false, + "hide_ldm_prints": true, + "dump_stacks_on_signal": false, + "face_restoration": false, + "face_restoration_model": "CodeFormer", + "code_former_weight": 0.5, + "face_restoration_unload": false, + "postprocessing_enable_in_main_ui": [], + "postprocessing_disable_in_extras": [], + "postprocessing_operation_order": [], + "upscaling_max_images_in_cache": 5, + "postprocessing_existing_caption_action": "Ignore", + "ESRGAN_tile": 192, + "ESRGAN_tile_overlap": 8, + "realesrgan_enabled_models": [ + "R-ESRGAN 4x+", + "R-ESRGAN 4x+ Anime6B" + ], + "dat_enabled_models": [ + "DAT x2", + "DAT x3", + "DAT x4" + ], + "DAT_tile": 192, + "DAT_tile_overlap": 8, + "set_scale_by_when_changing_upscaler": false, + "unload_models_when_training": false, + "pin_memory": false, + "save_optimizer_state": false, + "save_training_settings_to_txt": true, + "dataset_filename_word_regex": "", + "dataset_filename_join_string": " ", + "training_image_repeats_per_epoch": 1, + "training_write_csv_every": 500, + "training_xattention_optimizations": false, + "training_enable_tensorboard": false, + "training_tensorboard_save_images": false, + "training_tensorboard_flush_every": 120, + "interrogate_keep_models_in_memory": false, + "interrogate_return_ranks": false, + "interrogate_clip_num_beams": 1, + "interrogate_clip_min_length": 24, + "interrogate_clip_max_length": 48, + "interrogate_clip_dict_limit": 1500, + "interrogate_clip_skip_categories": [], + "interrogate_deepbooru_score_threshold": 0.5, + "deepbooru_sort_alpha": true, + "deepbooru_use_spaces": true, + "deepbooru_escape": true, + "deepbooru_filter_tags": "", + "sd_checkpoint_hash": "c2dd0f873a3b6546cd9f3cceeae91a3f0cc44a94ae09dd2f18f3b8076e836428", + "forge_preset": "sd" +} \ No newline at end of file diff --git a/download_supported_configs.py b/download_supported_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..50fc99029cb0c7085e171487f9647d4b6394f448 --- /dev/null +++ b/download_supported_configs.py @@ -0,0 +1,24 @@ +import os +import shutil + +from diffusers.loaders.single_file_utils import DIFFUSERS_DEFAULT_PIPELINE_PATHS +from huggingface_hub import snapshot_download + + +token = None +DIFFUSERS_DEFAULT_PIPELINE_PATHS['Kolor'] = {"pretrained_model_name_or_path": "Kwai-Kolors/Kolors"} +DIFFUSERS_DEFAULT_PIPELINE_PATHS['hunyuan'] = {"pretrained_model_name_or_path": "Tencent-Hunyuan/HunyuanDiT-Diffusers"} +DIFFUSERS_DEFAULT_PIPELINE_PATHS['flux'] = {"pretrained_model_name_or_path": "black-forest-labs/FLUX.1-dev"} +DIFFUSERS_DEFAULT_PIPELINE_PATHS['flux_schnell'] = {"pretrained_model_name_or_path": "black-forest-labs/FLUX.1-schnell"} + +for config_name, config in DIFFUSERS_DEFAULT_PIPELINE_PATHS.items(): + try: + pretrained_model_name_or_path = config["pretrained_model_name_or_path"] + local_dir = os.path.join('backend', 'huggingface', pretrained_model_name_or_path) + os.makedirs(local_dir, exist_ok=True) + snapshot_download(pretrained_model_name_or_path, local_dir=local_dir, allow_patterns=['*.json', '*.txt'], + token=token, force_download=True) + shutil.rmtree(os.path.join(local_dir, '.cache')) + print(pretrained_model_name_or_path) + except Exception as e: + print(e) diff --git a/embeddings/Asian-Less-Neg.pt b/embeddings/Asian-Less-Neg.pt new file mode 100644 index 0000000000000000000000000000000000000000..a02e5708621a39a65b395b57b676b885555151e8 --- /dev/null +++ b/embeddings/Asian-Less-Neg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22d2f003e76f94dcf891b821a3f447f25c73b2e0542f089427b33ff344070a96 +size 16244 diff --git a/embeddings/BadDream.pt b/embeddings/BadDream.pt new file mode 100644 index 0000000000000000000000000000000000000000..74f22c1ca9d0623b381d2ca7b9451f797bb322d1 --- /dev/null +++ b/embeddings/BadDream.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:758aac44351557ccfae2fc6bdf3a29670464e4e4eabb61f08c5b8531c221649c +size 212843 diff --git a/embeddings/CyberRealistic_Negative-neg.pt b/embeddings/CyberRealistic_Negative-neg.pt new file mode 100644 index 0000000000000000000000000000000000000000..5883b535ca36fcd3b5a43f32e847dca89c61dfcd --- /dev/null +++ b/embeddings/CyberRealistic_Negative-neg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65f3ea567c04c22f92024c5b55cbeca580bc330c4290aeb647ebd86273b3ffb8 +size 197662 diff --git a/embeddings/EasyNegativeV2.safetensors b/embeddings/EasyNegativeV2.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..ca7d8450836f0129d92218f07b02bcdd55025993 --- /dev/null +++ b/embeddings/EasyNegativeV2.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:339cc9210f70ef842b716588373d95b52351d7e6d111b858e133e3b1e3bd8088 +size 49232 diff --git a/embeddings/FastNegativeEmbedding.pt b/embeddings/FastNegativeEmbedding.pt new file mode 100644 index 0000000000000000000000000000000000000000..0e173c4cbd9df1f7b84f1bc80246bdc8898252ea --- /dev/null +++ b/embeddings/FastNegativeEmbedding.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:687b669d8234a418005ca9bfda93464b1721285b0a6a8d92490df0f02124ab7c +size 160683 diff --git a/embeddings/HyperStylizeV6.pt b/embeddings/HyperStylizeV6.pt new file mode 100644 index 0000000000000000000000000000000000000000..125788bbc66536c0102a299a23139f38883938af --- /dev/null +++ b/embeddings/HyperStylizeV6.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a09539451c9161038c9ac0a322ad8ffafffb097a70874b65e31eb06f0bb2e412 +size 16299 diff --git a/embeddings/MajicNegative_V2.pt b/embeddings/MajicNegative_V2.pt new file mode 100644 index 0000000000000000000000000000000000000000..2c84360d5bfe7b69ae74b43326184bb44acb317d --- /dev/null +++ b/embeddings/MajicNegative_V2.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a53884ef726b2ac96d3bfb9d4712cb7c6f7720fc1dcf6ca2a00a3f8f4c4134ae +size 231403 diff --git a/embeddings/Place Textual Inversion embeddings here.txt b/embeddings/Place Textual Inversion embeddings here.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/embeddings/UnrealisticDream.pt b/embeddings/UnrealisticDream.pt new file mode 100644 index 0000000000000000000000000000000000000000..3dcad827d98346d237b34148248cc75f389bbc91 --- /dev/null +++ b/embeddings/UnrealisticDream.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a77451e7ea075c7f72d488d2b740b3d3970c671c0ac39dd3155f3c3b129df959 +size 114539 diff --git a/embeddings/bad-artist-anime.pt b/embeddings/bad-artist-anime.pt new file mode 100644 index 0000000000000000000000000000000000000000..41dc1ef4174928ea838448c87d06f5926dfa4ef2 --- /dev/null +++ b/embeddings/bad-artist-anime.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f7bea88750c97a0b8c9ba9f5bc0d13648c3a17a69aaac855903229d5f58c34b +size 7083 diff --git a/embeddings/bad-artist.pt b/embeddings/bad-artist.pt new file mode 100644 index 0000000000000000000000000000000000000000..f95b94ce32dbf17e69dc88c96cfc0bccc0792a83 --- /dev/null +++ b/embeddings/bad-artist.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2d356134903e8f47bf6cf519bdf577cdcee42fc717ef264498162e94f130843a +size 7083 diff --git a/embeddings/bad-hands-5.pt b/embeddings/bad-hands-5.pt new file mode 100644 index 0000000000000000000000000000000000000000..b6bc361f5f8b9bd6b840f64d5fbdcfec33b770cd --- /dev/null +++ b/embeddings/bad-hands-5.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa7651be154c46a2f4868788ef84a92b3083b0c0c5c46f5012a56698bfd2a1ba +size 7083 diff --git a/embeddings/bad-image-v2-39000.pt b/embeddings/bad-image-v2-39000.pt new file mode 100644 index 0000000000000000000000000000000000000000..b94b627a71e65b19641f626556d0f9d579c32c12 --- /dev/null +++ b/embeddings/bad-image-v2-39000.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b9281d7c6adc221b8ea9067b678f4b6ff4cc94735e2d50885070380d5496037 +size 14439 diff --git a/embeddings/bad-picture-chill-75v.pt b/embeddings/bad-picture-chill-75v.pt new file mode 100644 index 0000000000000000000000000000000000000000..a7e141e998366ceacd1020164612a891f529dd25 --- /dev/null +++ b/embeddings/bad-picture-chill-75v.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d9cc5f549d7972f24803a3a9880a923fb9a1b68c1443da3ce1ff2f7eff25ae9 +size 231524 diff --git a/embeddings/bad_pictures.pt b/embeddings/bad_pictures.pt new file mode 100644 index 0000000000000000000000000000000000000000..fef9c14eb9e67b1b4e1596b862721e3ee7e8b3ed --- /dev/null +++ b/embeddings/bad_pictures.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:522ac70ba997df4a911e4977e6a9790e7d15236596e8e0c8318330f2af4ab095 +size 99322 diff --git a/embeddings/bad_prompt.pt b/embeddings/bad_prompt.pt new file mode 100644 index 0000000000000000000000000000000000000000..827eec348c2a1d57b36f300b0ea5b2d574f00ede --- /dev/null +++ b/embeddings/bad_prompt.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9dfe1c982e2a1917054fa827ee1f981c6e6102984f981c691e4f8c817e292cb +size 50091 diff --git a/embeddings/bad_prompt_version2.pt b/embeddings/bad_prompt_version2.pt new file mode 100644 index 0000000000000000000000000000000000000000..ba1d6fac9edfeb79e9626de22e954f5fc86e17c2 --- /dev/null +++ b/embeddings/bad_prompt_version2.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f35e7dd816ae04bb3f774a9a17ebfbc50c0e3a53f69a9a40bed05936d3a3812 +size 25515 diff --git a/embeddings/badhandv4.pt b/embeddings/badhandv4.pt new file mode 100644 index 0000000000000000000000000000000000000000..23aafda62308b40ce4db2a992872bc83c87834c2 --- /dev/null +++ b/embeddings/badhandv4.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e40d722fc3d0c2decb62debfaf8058db30ccdae9ab00ff64b183907b435708e +size 19371 diff --git a/embeddings/charturnerv2.pt b/embeddings/charturnerv2.pt new file mode 100644 index 0000000000000000000000000000000000000000..402be11936ef4ccaa30daaa876e8751ceb46ed40 --- /dev/null +++ b/embeddings/charturnerv2.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a91b570185766ff71f242f83d5beb6d658348900edb706a2092ba23d6e1e2cf8 +size 47028 diff --git a/embeddings/easynegative.safetensors b/embeddings/easynegative.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..17452fae90299ad12781fe9c4163dedab3d376ed --- /dev/null +++ b/embeddings/easynegative.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c74b4e810b030f6b75fde959e2db678c268d07115b85356d3c0138ba5eb42340 +size 24655 diff --git a/embeddings/epiCNegative.pt b/embeddings/epiCNegative.pt new file mode 100644 index 0000000000000000000000000000000000000000..aeab06620dbbb47c2556c6646e97fb07be603ec5 --- /dev/null +++ b/embeddings/epiCNegative.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88b8f468357be0d90b993b6b5b4763b603244089b426f40fddcf96b070002f38 +size 228306 diff --git a/embeddings/epiCRealism.pt b/embeddings/epiCRealism.pt new file mode 100644 index 0000000000000000000000000000000000000000..a544b1a7f0795133f77d8231f2f35f6d20481e8b --- /dev/null +++ b/embeddings/epiCRealism.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3719288307e4183d01f3aa7737ce952d15fc9e21da13fa0ecea1be4e8c166b10 +size 173010 diff --git a/embeddings/negative_hand-neg.pt b/embeddings/negative_hand-neg.pt new file mode 100644 index 0000000000000000000000000000000000000000..12b236f9cc04fdefa77521378e25d55f14886a7b --- /dev/null +++ b/embeddings/negative_hand-neg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73b524a2da121eb1b7ad04dea11da286277813120700ff8f1d8522516f7b30ab +size 25533 diff --git a/embeddings/ng_deepnegative_v1_75t.pt b/embeddings/ng_deepnegative_v1_75t.pt new file mode 100644 index 0000000000000000000000000000000000000000..849edda8ba90c8cf83865abd84ed828f23720592 --- /dev/null +++ b/embeddings/ng_deepnegative_v1_75t.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54e7e4826d53949a3d0dde40aea023b1e456a618c608a7630e3999fd38f93245 +size 231339 diff --git a/embeddings/pureerosface_v1.pt b/embeddings/pureerosface_v1.pt new file mode 100644 index 0000000000000000000000000000000000000000..05caed4642b9ecd8011b01d5d58b06bbcd27e06d --- /dev/null +++ b/embeddings/pureerosface_v1.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dedb4322e42e360fe01775ba817be03ac6a6c307744562bb0d6759368bc681da +size 4011 diff --git a/embeddings/rmadanegative402_sd15-neg.pt b/embeddings/rmadanegative402_sd15-neg.pt new file mode 100644 index 0000000000000000000000000000000000000000..acfc9e0a5999b197f72c3553728c4a7e6031260f --- /dev/null +++ b/embeddings/rmadanegative402_sd15-neg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad488e18aa29f12e8fc18d1d2ccc041ff0052d4657c96f1b06cab880f4ba4f40 +size 231381 diff --git a/embeddings/ulzzang-6500-v1.1.bin b/embeddings/ulzzang-6500-v1.1.bin new file mode 100644 index 0000000000000000000000000000000000000000..eb4719f87992faa377711e23691580eb8f19935f --- /dev/null +++ b/embeddings/ulzzang-6500-v1.1.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c1af299c7e8c2283892a7ad61a5fe5574e88c9c2ee77cd0cdfc0615155fa315 +size 10185 diff --git a/embeddings/ulzzang-6500.pt b/embeddings/ulzzang-6500.pt new file mode 100644 index 0000000000000000000000000000000000000000..589159f6db855ec412f2103a79f4644ffc6be3e9 --- /dev/null +++ b/embeddings/ulzzang-6500.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66d481a222ee4638e254a411890f2a8716e4ce5c3e1b1957891c7628bbdeac78 +size 10155 diff --git a/embeddings/verybadimagenegative_v1.3.pt b/embeddings/verybadimagenegative_v1.3.pt new file mode 100644 index 0000000000000000000000000000000000000000..e5304ebcb481b120a35ad93e85c1ae5febacf638 --- /dev/null +++ b/embeddings/verybadimagenegative_v1.3.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d70463f87042e2b5951c303542f3e171cf49af9b7df53b2f20779493786eb143 +size 31659 diff --git a/environment-wsl2.yaml b/environment-wsl2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0c4ae6809997ec38e7cf62cf0f71360b8cb61a7e --- /dev/null +++ b/environment-wsl2.yaml @@ -0,0 +1,11 @@ +name: automatic +channels: + - pytorch + - defaults +dependencies: + - python=3.10 + - pip=23.0 + - cudatoolkit=11.8 + - pytorch=2.0 + - torchvision=0.15 + - numpy=1.23 diff --git a/extensions-builtin/SwinIR/__pycache__/preload.cpython-311.pyc b/extensions-builtin/SwinIR/__pycache__/preload.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88258019be2703ba3e94001a734cb21a7c146137 Binary files /dev/null and b/extensions-builtin/SwinIR/__pycache__/preload.cpython-311.pyc differ diff --git a/extensions-builtin/SwinIR/preload.py b/extensions-builtin/SwinIR/preload.py new file mode 100644 index 0000000000000000000000000000000000000000..567e44bcaa1d40ca5dabed7744c94c5b2c68e87f --- /dev/null +++ b/extensions-builtin/SwinIR/preload.py @@ -0,0 +1,6 @@ +import os +from modules import paths + + +def preload(parser): + parser.add_argument("--swinir-models-path", type=str, help="Path to directory with SwinIR model file(s).", default=os.path.join(paths.models_path, 'SwinIR')) diff --git a/extensions-builtin/SwinIR/scripts/swinir_model.py b/extensions-builtin/SwinIR/scripts/swinir_model.py new file mode 100644 index 0000000000000000000000000000000000000000..d16609c75ce4bf46e7541f879ff734de9bea52ac --- /dev/null +++ b/extensions-builtin/SwinIR/scripts/swinir_model.py @@ -0,0 +1,98 @@ +import logging +import sys + +import torch +from PIL import Image + +from modules import devices, modelloader, script_callbacks, shared, upscaler_utils +from modules.upscaler import Upscaler, UpscalerData +from modules_forge.utils import prepare_free_memory + +SWINIR_MODEL_URL = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth" + +logger = logging.getLogger(__name__) + + +class UpscalerSwinIR(Upscaler): + def __init__(self, dirname): + self._cached_model = None # keep the model when SWIN_torch_compile is on to prevent re-compile every runs + self._cached_model_config = None # to clear '_cached_model' when changing model (v1/v2) or settings + self.name = "SwinIR" + self.model_url = SWINIR_MODEL_URL + self.model_name = "SwinIR 4x" + self.user_path = dirname + super().__init__() + scalers = [] + model_files = self.find_models(ext_filter=[".pt", ".pth"]) + for model in model_files: + if model.startswith("http"): + name = self.model_name + else: + name = modelloader.friendly_name(model) + model_data = UpscalerData(name, model, self) + scalers.append(model_data) + self.scalers = scalers + + def do_upscale(self, img: Image.Image, model_file: str) -> Image.Image: + prepare_free_memory() + + current_config = (model_file, shared.opts.SWIN_tile) + + if self._cached_model_config == current_config: + model = self._cached_model + else: + try: + model = self.load_model(model_file) + except Exception as e: + print(f"Failed loading SwinIR model {model_file}: {e}", file=sys.stderr) + return img + self._cached_model = model + self._cached_model_config = current_config + + img = upscaler_utils.upscale_2( + img, + model, + tile_size=shared.opts.SWIN_tile, + tile_overlap=shared.opts.SWIN_tile_overlap, + scale=model.scale, + desc="SwinIR", + ) + devices.torch_gc() + return img + + def load_model(self, path, scale=4): + if path.startswith("http"): + filename = modelloader.load_file_from_url( + url=path, + model_dir=self.model_download_path, + file_name=f"{self.model_name.replace(' ', '_')}.pth", + ) + else: + filename = path + + model_descriptor = modelloader.load_spandrel_model( + filename, + device=self._get_device(), + prefer_half=(devices.dtype == torch.float16), + expected_architecture="SwinIR", + ) + if getattr(shared.opts, 'SWIN_torch_compile', False): + try: + model_descriptor.model.compile() + except Exception: + logger.warning("Failed to compile SwinIR model, fallback to JIT", exc_info=True) + return model_descriptor + + def _get_device(self): + return devices.get_device_for('swinir') + + +def on_ui_settings(): + import gradio as gr + + shared.opts.add_option("SWIN_tile", shared.OptionInfo(192, "Tile size for all SwinIR.", gr.Slider, {"minimum": 16, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling"))) + shared.opts.add_option("SWIN_tile_overlap", shared.OptionInfo(8, "Tile overlap, in pixels for SwinIR. Low values = visible seam.", gr.Slider, {"minimum": 0, "maximum": 48, "step": 1}, section=('upscaling', "Upscaling"))) + shared.opts.add_option("SWIN_torch_compile", shared.OptionInfo(False, "Use torch.compile to accelerate SwinIR.", gr.Checkbox, {"interactive": True}, section=('upscaling', "Upscaling")).info("Takes longer on first run")) + + +script_callbacks.on_ui_settings(on_ui_settings) diff --git a/extensions-builtin/extra-options-section/scripts/extra_options_section.py b/extensions-builtin/extra-options-section/scripts/extra_options_section.py new file mode 100644 index 0000000000000000000000000000000000000000..ff95411232d9ba3446ac917972ec1407361b759e --- /dev/null +++ b/extensions-builtin/extra-options-section/scripts/extra_options_section.py @@ -0,0 +1,87 @@ +import math + +import gradio as gr +from modules import scripts, shared, ui_components, ui_settings, infotext_utils, errors +from modules.ui_components import FormColumn + + +class ExtraOptionsSection(scripts.Script): + section = "extra_options" + + def __init__(self): + self.comps = None + self.setting_names = None + + def title(self): + return "Extra options" + + def show(self, is_img2img): + return scripts.AlwaysVisible + + def ui(self, is_img2img): + self.comps = [] + self.setting_names = [] + self.infotext_fields = [] + extra_options = shared.opts.extra_options_img2img if is_img2img else shared.opts.extra_options_txt2img + elem_id_tabname = "extra_options_" + ("img2img" if is_img2img else "txt2img") + + not_allowed = ['sd_model_checkpoint', 'sd_vae', 'CLIP_stop_at_last_layers', 'forge_additional_modules'] + for na in not_allowed: + if na in extra_options: + extra_options.remove(na) + + mapping = {k: v for v, k in infotext_utils.infotext_to_setting_name_mapping} + + with gr.Blocks() as interface: + with gr.Accordion("Options", open=False, elem_id=elem_id_tabname) if shared.opts.extra_options_accordion and extra_options else gr.Group(elem_id=elem_id_tabname): + + row_count = math.ceil(len(extra_options) / shared.opts.extra_options_cols) + + for row in range(row_count): + with gr.Row(): + for col in range(shared.opts.extra_options_cols): + index = row * shared.opts.extra_options_cols + col + if index >= len(extra_options): + break + + setting_name = extra_options[index] + + with FormColumn(): + try: + comp = ui_settings.create_setting_component(setting_name) + except KeyError: + errors.report(f"Can't add extra options for {setting_name} in ui") + continue + + self.comps.append(comp) + self.setting_names.append(setting_name) + + setting_infotext_name = mapping.get(setting_name) + if setting_infotext_name is not None: + self.infotext_fields.append((comp, setting_infotext_name)) + + def get_settings_values(): + res = [ui_settings.get_value_for_setting(key) for key in self.setting_names] + return res[0] if len(res) == 1 else res + + interface.load(fn=get_settings_values, inputs=[], outputs=self.comps, queue=False, show_progress=False) + + return self.comps + + def before_process(self, p, *args): + for name, value in zip(self.setting_names, args): + if name not in p.override_settings: + p.override_settings[name] = value + + +shared.options_templates.update(shared.options_section(('settings_in_ui', "Settings in UI", "ui"), { + "settings_in_ui": shared.OptionHTML(""" +This page allows you to add some settings to the main interface of txt2img and img2img tabs. +"""), + "extra_options_txt2img": shared.OptionInfo([], "Settings for txt2img", ui_components.DropdownMulti, lambda: {"choices": list(shared.opts.data_labels.keys())}).js("info", "settingsHintsShowQuicksettings").info("setting entries that also appear in txt2img interfaces").needs_reload_ui(), + "extra_options_img2img": shared.OptionInfo([], "Settings for img2img", ui_components.DropdownMulti, lambda: {"choices": list(shared.opts.data_labels.keys())}).js("info", "settingsHintsShowQuicksettings").info("setting entries that also appear in img2img interfaces").needs_reload_ui(), + "extra_options_cols": shared.OptionInfo(1, "Number of columns for added settings", gr.Slider, {"step": 1, "minimum": 1, "maximum": 20}).info("displayed amount will depend on the actual browser window width").needs_reload_ui(), + "extra_options_accordion": shared.OptionInfo(False, "Place added settings into an accordion").needs_reload_ui() +})) + + diff --git a/extensions-builtin/forge_legacy_preprocessors/.gitignore b/extensions-builtin/forge_legacy_preprocessors/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..60d06e51ec71848d6700eac9c6f3db544ef3c1a0 --- /dev/null +++ b/extensions-builtin/forge_legacy_preprocessors/.gitignore @@ -0,0 +1,185 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# 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 logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_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 + +# 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 + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_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 +*.pt +*.pth +*.ckpt +*.bin +*.safetensors + +# Editor setting metadata +.idea/ +.vscode/ +detected_maps/ +annotator/downloads/ + +# test results and expectations +web_tests/results/ +web_tests/expectations/ +tests/web_api/full_coverage/results/ +tests/web_api/full_coverage/expectations/ + +*_diff.png + +# Presets +presets/ + +# Ignore existing dir of hand refiner if exists. +annotator/hand_refiner_portable \ No newline at end of file diff --git a/extensions-builtin/forge_legacy_preprocessors/LICENSE b/extensions-builtin/forge_legacy_preprocessors/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/extensions-builtin/forge_legacy_preprocessors/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/extensions-builtin/forge_legacy_preprocessors/install.py b/extensions-builtin/forge_legacy_preprocessors/install.py new file mode 100644 index 0000000000000000000000000000000000000000..443be6a0e15376f5e3f43d79ed1e8076b3373295 --- /dev/null +++ b/extensions-builtin/forge_legacy_preprocessors/install.py @@ -0,0 +1,160 @@ +import launch +import pkg_resources +import sys +import os +import shutil +import platform +from pathlib import Path +from typing import Tuple, Optional + + +repo_root = Path(__file__).parent +main_req_file = repo_root / "requirements.txt" + + +def comparable_version(version: str) -> Tuple: + return tuple(map(int, version.split("."))) + + +def get_installed_version(package: str) -> Optional[str]: + try: + return pkg_resources.get_distribution(package).version + except Exception: + return None + + +def extract_base_package(package_string: str) -> str: + base_package = package_string.split("@git")[0] + return base_package + + +def install_requirements(req_file): + with open(req_file) as file: + for package in file: + try: + package = package.strip() + if "==" in package: + package_name, package_version = package.split("==") + installed_version = get_installed_version(package_name) + if installed_version != package_version: + launch.run_pip( + f"install -U {package}", + f"forge_legacy_preprocessor requirement: changing {package_name} version from {installed_version} to {package_version}", + ) + elif ">=" in package: + package_name, package_version = package.split(">=") + installed_version = get_installed_version(package_name) + if not installed_version or comparable_version( + installed_version + ) < comparable_version(package_version): + launch.run_pip( + f"install -U {package}", + f"forge_legacy_preprocessor requirement: changing {package_name} version from {installed_version} to {package_version}", + ) + elif not launch.is_installed(extract_base_package(package)): + launch.run_pip( + f"install {package}", + f"forge_legacy_preprocessor requirement: {package}", + ) + except Exception as e: + print(e) + print( + f"Warning: Failed to install {package}, some preprocessors may not work." + ) + + +def try_install_from_wheel(pkg_name: str, wheel_url: str, version: Optional[str] = None): + current_version = get_installed_version(pkg_name) + if current_version is not None: + # No version requirement. + if version is None: + return + # Version requirement already satisfied. + if comparable_version(current_version) >= comparable_version(version): + return + try: + launch.run_pip( + f"install -U {wheel_url}", + f"forge_legacy_preprocessor requirement: {pkg_name}", + ) + except Exception as e: + print(e) + print(f"Warning: Failed to install {pkg_name}. Some processors will not work.") + + +def try_install_insight_face(): + """Attempt to install insightface library. The library is necessary to use ip-adapter faceid. + Note: Building insightface library from source requires compiling C++ code, which should be avoided + in principle. Here the solution is to download a precompiled wheel.""" + if get_installed_version("insightface") is not None: + return + + default_win_wheel = "https://github.com/Gourieff/Assets/raw/main/Insightface/insightface-0.7.3-cp310-cp310-win_amd64.whl" + wheel_url = os.environ.get("INSIGHTFACE_WHEEL", default_win_wheel) + + system = platform.system().lower() + architecture = platform.machine().lower() + python_version = sys.version_info + if wheel_url != default_win_wheel or ( + system == "windows" + and "amd64" in architecture + and python_version.major == 3 + and python_version.minor == 10 + ): + try: + launch.run_pip( + f"install {wheel_url}", + "forge_legacy_preprocessor requirement: insightface", + ) + except Exception as e: + print(e) + print( + "Legacy Preprocessor init warning: Unable to install insightface automatically. " + ) + else: + print( + "Legacy Preprocessor init warning: Unable to install insightface automatically. " + "Please try run `pip install insightface` manually." + ) + + +def try_remove_legacy_submodule(): + """Try remove annotators/hand_refiner_portable submodule dir.""" + submodule = repo_root / "annotator" / "hand_refiner_portable" + if os.path.exists(submodule): + try: + shutil.rmtree(submodule) + except Exception as e: + print(e) + print( + f"Failed to remove submodule {submodule} automatically. You can manually delete the directory." + ) + + +install_requirements(main_req_file) +try_install_insight_face() +try_install_from_wheel( + "handrefinerportable", + wheel_url=os.environ.get( + "HANDREFINER_WHEEL", + "https://github.com/huchenlei/HandRefinerPortable/releases/download/v1.0.1/handrefinerportable-2024.2.12.0-py2.py3-none-any.whl", + ), + version="2024.2.12.0", +) +try_install_from_wheel( + "depth_anything", + wheel_url=os.environ.get( + "DEPTH_ANYTHING_WHEEL", + "https://github.com/huchenlei/Depth-Anything/releases/download/v1.0.0/depth_anything-2024.1.22.0-py2.py3-none-any.whl", + ), +) + +try_install_from_wheel( + "depth_anything_v2", + wheel_url=os.environ.get( + "DEPTH_ANYTHING_V2_WHEEL", + "https://github.com/MackinationsAi/UDAV2-ControlNet/releases/download/v1.0.0/depth_anything_v2-2024.7.1.0-py2.py3-none-any.whl", + ), +) + +try_remove_legacy_submodule() diff --git a/extensions-builtin/forge_legacy_preprocessors/requirements.txt b/extensions-builtin/forge_legacy_preprocessors/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d12e85b09d7b0d997bbb1a8f5d56bb2a2ec1ef01 --- /dev/null +++ b/extensions-builtin/forge_legacy_preprocessors/requirements.txt @@ -0,0 +1,5 @@ +fvcore +mediapipe +onnxruntime +opencv-python>=4.8.0 +svglib diff --git a/extensions-builtin/forge_preprocessor_inpaint/scripts/lama_config.yaml b/extensions-builtin/forge_preprocessor_inpaint/scripts/lama_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..55fd91b5bcacd654e3045a2331e9c186818e6edc --- /dev/null +++ b/extensions-builtin/forge_preprocessor_inpaint/scripts/lama_config.yaml @@ -0,0 +1,157 @@ +run_title: b18_ffc075_batch8x15 +training_model: + kind: default + visualize_each_iters: 1000 + concat_mask: true + store_discr_outputs_for_vis: true +losses: + l1: + weight_missing: 0 + weight_known: 10 + perceptual: + weight: 0 + adversarial: + kind: r1 + weight: 10 + gp_coef: 0.001 + mask_as_fake_target: true + allow_scale_mask: true + feature_matching: + weight: 100 + resnet_pl: + weight: 30 + weights_path: ${env:TORCH_HOME} + +optimizers: + generator: + kind: adam + lr: 0.001 + discriminator: + kind: adam + lr: 0.0001 +visualizer: + key_order: + - image + - predicted_image + - discr_output_fake + - discr_output_real + - inpainted + rescale_keys: + - discr_output_fake + - discr_output_real + kind: directory + outdir: /group-volume/User-Driven-Content-Generation/r.suvorov/inpainting/experiments/r.suvorov_2021-04-30_14-41-12_train_simple_pix2pix2_gap_sdpl_novgg_large_b18_ffc075_batch8x15/samples +location: + data_root_dir: /group-volume/User-Driven-Content-Generation/datasets/inpainting_data_root_large + out_root_dir: /group-volume/User-Driven-Content-Generation/${env:USER}/inpainting/experiments + tb_dir: /group-volume/User-Driven-Content-Generation/${env:USER}/inpainting/tb_logs +data: + batch_size: 15 + val_batch_size: 2 + num_workers: 3 + train: + indir: ${location.data_root_dir}/train + out_size: 256 + mask_gen_kwargs: + irregular_proba: 1 + irregular_kwargs: + max_angle: 4 + max_len: 200 + max_width: 100 + max_times: 5 + min_times: 1 + box_proba: 1 + box_kwargs: + margin: 10 + bbox_min_size: 30 + bbox_max_size: 150 + max_times: 3 + min_times: 1 + segm_proba: 0 + segm_kwargs: + confidence_threshold: 0.5 + max_object_area: 0.5 + min_mask_area: 0.07 + downsample_levels: 6 + num_variants_per_mask: 1 + rigidness_mode: 1 + max_foreground_coverage: 0.3 + max_foreground_intersection: 0.7 + max_mask_intersection: 0.1 + max_hidden_area: 0.1 + max_scale_change: 0.25 + horizontal_flip: true + max_vertical_shift: 0.2 + position_shuffle: true + transform_variant: distortions + dataloader_kwargs: + batch_size: ${data.batch_size} + shuffle: true + num_workers: ${data.num_workers} + val: + indir: ${location.data_root_dir}/val + img_suffix: .png + dataloader_kwargs: + batch_size: ${data.val_batch_size} + shuffle: false + num_workers: ${data.num_workers} + visual_test: + indir: ${location.data_root_dir}/korean_test + img_suffix: _input.png + pad_out_to_modulo: 32 + dataloader_kwargs: + batch_size: 1 + shuffle: false + num_workers: ${data.num_workers} +generator: + kind: ffc_resnet + input_nc: 4 + output_nc: 3 + ngf: 64 + n_downsampling: 3 + n_blocks: 18 + add_out_act: sigmoid + init_conv_kwargs: + ratio_gin: 0 + ratio_gout: 0 + enable_lfu: false + downsample_conv_kwargs: + ratio_gin: ${generator.init_conv_kwargs.ratio_gout} + ratio_gout: ${generator.downsample_conv_kwargs.ratio_gin} + enable_lfu: false + resnet_conv_kwargs: + ratio_gin: 0.75 + ratio_gout: ${generator.resnet_conv_kwargs.ratio_gin} + enable_lfu: false +discriminator: + kind: pix2pixhd_nlayer + input_nc: 3 + ndf: 64 + n_layers: 4 +evaluator: + kind: default + inpainted_key: inpainted + integral_kind: ssim_fid100_f1 +trainer: + kwargs: + gpus: -1 + accelerator: ddp + max_epochs: 200 + gradient_clip_val: 1 + log_gpu_memory: None + limit_train_batches: 25000 + val_check_interval: ${trainer.kwargs.limit_train_batches} + log_every_n_steps: 1000 + precision: 32 + terminate_on_nan: false + check_val_every_n_epoch: 1 + num_sanity_val_steps: 8 + limit_val_batches: 1000 + replace_sampler_ddp: false + checkpoint_kwargs: + verbose: true + save_top_k: 5 + save_last: true + period: 1 + monitor: val_ssim_fid100_f1_total_mean + mode: max diff --git a/extensions-builtin/forge_preprocessor_inpaint/scripts/preprocessor_inpaint.py b/extensions-builtin/forge_preprocessor_inpaint/scripts/preprocessor_inpaint.py new file mode 100644 index 0000000000000000000000000000000000000000..21f222d99c3e96bb8e4be26ea559a04f93ba8894 --- /dev/null +++ b/extensions-builtin/forge_preprocessor_inpaint/scripts/preprocessor_inpaint.py @@ -0,0 +1,167 @@ +import os +import cv2 +import torch +import numpy as np +import yaml +import einops + +from omegaconf import OmegaConf +from modules_forge.supported_preprocessor import Preprocessor, PreprocessorParameter +from modules_forge.utils import numpy_to_pytorch, resize_image_with_pad +from modules_forge.shared import preprocessor_dir, add_supported_preprocessor +from modules.modelloader import load_file_from_url +from annotator.lama.saicinpainting.training.trainers import load_checkpoint + + +class PreprocessorInpaint(Preprocessor): + def __init__(self): + super().__init__() + self.name = 'inpaint_global_harmonious' + self.tags = ['Inpaint'] + self.model_filename_filters = ['inpaint'] + self.slider_resolution = PreprocessorParameter(visible=False) + self.fill_mask_with_one_when_resize_and_fill = True + self.expand_mask_when_resize_and_fill = True + + def process_before_every_sampling(self, process, cond, mask, *args, **kwargs): + mask = mask.round() + mixed_cond = cond * (1.0 - mask) - mask + return mixed_cond, None + + +class PreprocessorInpaintOnly(PreprocessorInpaint): + def __init__(self): + super().__init__() + self.name = 'inpaint_only' + self.image = None + self.mask = None + self.latent = None + + def process_before_every_sampling(self, process, cond, mask, *args, **kwargs): + mask = mask.round() + self.image = cond + self.mask = mask + + vae = process.sd_model.forge_objects.vae + # This is a powerful VAE with integrated memory management, bf16, and tiled fallback. + + latent_image = vae.encode(self.image.movedim(1, -1)) + latent_image = process.sd_model.forge_objects.vae.first_stage_model.process_in(latent_image) + + B, C, H, W = latent_image.shape + + latent_mask = self.mask + latent_mask = torch.nn.functional.interpolate(latent_mask, size=(H * 8, W * 8), mode="bilinear").round() + latent_mask = torch.nn.functional.max_pool2d(latent_mask, (8, 8)).round().to(latent_image) + + unet = process.sd_model.forge_objects.unet.clone() + + def pre_cfg(model, c, uc, x, timestep, model_options): + noisy_latent = latent_image.to(x) + timestep[:, None, None, None].to(x) * torch.randn_like(latent_image).to(x) + x = x * latent_mask.to(x) + noisy_latent.to(x) * (1.0 - latent_mask.to(x)) + return model, c, uc, x, timestep, model_options + + def post_cfg(args): + denoised = args['denoised'] + denoised = denoised * latent_mask.to(denoised) + latent_image.to(denoised) * (1.0 - latent_mask.to(denoised)) + return denoised + + unet.add_sampler_pre_cfg_function(pre_cfg) + unet.set_model_sampler_post_cfg_function(post_cfg) + + process.sd_model.forge_objects.unet = unet + + self.latent = latent_image + + mixed_cond = cond * (1.0 - mask) - mask + + return mixed_cond, None + + def process_after_every_sampling(self, process, params, *args, **kwargs): + a1111_batch_result = args[0] + new_results = [] + + for img in a1111_batch_result.images: + sigma = 7 + mask = self.mask[0, 0].detach().cpu().numpy().astype(np.float32) + mask = cv2.dilate(mask, np.ones((sigma, sigma), dtype=np.uint8)) + mask = cv2.blur(mask, (sigma, sigma))[None] + mask = torch.from_numpy(np.ascontiguousarray(mask).copy()).to(img).clip(0, 1) + raw = self.image[0].to(img).clip(0, 1) + img = img.clip(0, 1) + new_results.append(raw * (1.0 - mask) + img * mask) + + a1111_batch_result.images = new_results + return + + +class PreprocessorInpaintLama(PreprocessorInpaintOnly): + def __init__(self): + super().__init__() + self.name = 'inpaint_only+lama' + + def load_model(self): + remote_model_path = "https://huggingface.co/lllyasviel/Annotators/resolve/main/ControlNetLama.pth" + model_path = load_file_from_url(remote_model_path, model_dir=preprocessor_dir) + config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lama_config.yaml') + cfg = yaml.safe_load(open(config_path, 'rt')) + cfg = OmegaConf.create(cfg) + cfg.training_model.predict_only = True + cfg.visualizer.kind = 'noop' + model = load_checkpoint(cfg, os.path.abspath(model_path), strict=False, map_location='cpu') + self.setup_model_patcher(model) + return + + def __call__(self, input_image, resolution, slider_1=None, slider_2=None, slider_3=None, input_mask=None, **kwargs): + if input_mask is None: + return input_image + + H, W, C = input_image.shape + raw_color = input_image.copy() + raw_mask = input_mask.copy() + + input_image, remove_pad = resize_image_with_pad(input_image, 256) + input_mask, remove_pad = resize_image_with_pad(input_mask, 256) + input_mask = input_mask[..., :1] + + self.load_model() + + self.move_all_model_patchers_to_gpu() + + color = np.ascontiguousarray(input_image).astype(np.float32) / 255.0 + mask = np.ascontiguousarray(input_mask).astype(np.float32) / 255.0 + with torch.no_grad(): + color = self.send_tensor_to_model_device(torch.from_numpy(color)) + mask = self.send_tensor_to_model_device(torch.from_numpy(mask)) + mask = (mask > 0.5).float() + color = color * (1 - mask) + image_feed = torch.cat([color, mask], dim=2) + image_feed = einops.rearrange(image_feed, 'h w c -> 1 c h w') + prd_color = self.model_patcher.model(image_feed)[0] + prd_color = einops.rearrange(prd_color, 'c h w -> h w c') + prd_color = prd_color * mask + color * (1 - mask) + prd_color *= 255.0 + prd_color = prd_color.detach().cpu().numpy().clip(0, 255).astype(np.uint8) + + prd_color = remove_pad(prd_color) + prd_color = cv2.resize(prd_color, (W, H)) + + alpha = raw_mask.astype(np.float32) / 255.0 + fin_color = prd_color.astype(np.float32) * alpha + raw_color.astype(np.float32) * (1 - alpha) + fin_color = fin_color.clip(0, 255).astype(np.uint8) + + return fin_color + + def process_before_every_sampling(self, process, cond, mask, *args, **kwargs): + cond, mask = super().process_before_every_sampling(process, cond, mask, *args, **kwargs) + sigma_max = process.sd_model.forge_objects.unet.model.predictor.sigma_max + original_noise = kwargs['noise'] + process.modified_noise = original_noise + self.latent.to(original_noise) / sigma_max.to(original_noise) + return cond, mask + + +add_supported_preprocessor(PreprocessorInpaint()) + +add_supported_preprocessor(PreprocessorInpaintOnly()) + +add_supported_preprocessor(PreprocessorInpaintLama()) diff --git a/extensions-builtin/forge_preprocessor_marigold/scripts/preprocessor_marigold.py b/extensions-builtin/forge_preprocessor_marigold/scripts/preprocessor_marigold.py new file mode 100644 index 0000000000000000000000000000000000000000..659c23ae5bb227b62c42352e1638a2ea6ec066bd --- /dev/null +++ b/extensions-builtin/forge_preprocessor_marigold/scripts/preprocessor_marigold.py @@ -0,0 +1,68 @@ +from modules_forge.supported_preprocessor import Preprocessor, PreprocessorParameter +from modules_forge.shared import preprocessor_dir, add_supported_preprocessor +from modules_forge.utils import resize_image_with_pad + + +import os +import torch +import numpy as np + +from marigold.model.marigold_pipeline import MarigoldPipeline +from huggingface_hub import snapshot_download +from modules_forge.diffusers_patcher import DiffusersModelPatcher +from modules_forge.utils import numpy_to_pytorch, HWC3 + + +class PreprocessorMarigold(Preprocessor): + def __init__(self): + super().__init__() + self.name = 'depth_marigold' + self.tags = ['Depth'] + self.model_filename_filters = ['depth'] + self.slider_resolution = PreprocessorParameter( + label='Resolution', minimum=128, maximum=2048, value=768, step=8, visible=True) + self.slider_1 = PreprocessorParameter(visible=False) + self.slider_2 = PreprocessorParameter(visible=False) + self.slider_3 = PreprocessorParameter(visible=False) + self.show_control_mode = True + self.do_not_need_model = False + self.sorting_priority = 100 # higher goes to top in the list + self.diffusers_patcher = None + + def load_model(self): + if self.model_patcher is not None: + return + + self.diffusers_patcher = DiffusersModelPatcher( + pipeline_class=MarigoldPipeline, + pretrained_path="Bingxin/Marigold", + enable_xformers=False, + noise_scheduler_type='DDIMScheduler') + + return + + def __call__(self, input_image, resolution, slider_1=None, slider_2=None, slider_3=None, **kwargs): + input_image, remove_pad = resize_image_with_pad(input_image, resolution) + + self.load_model() + + H, W, C = input_image.shape + + self.diffusers_patcher.prepare_memory_before_sampling( + batchsize=1, latent_width=W // 8, latent_height=H // 8 + ) + + with torch.no_grad(): + img = numpy_to_pytorch(input_image).movedim(-1, 1) + img = self.diffusers_patcher.move_tensor_to_current_device(img) + + img = img * 2.0 - 1.0 + depth = self.diffusers_patcher.pipeline(img, num_inference_steps=20, show_pbar=False) + depth = 0.5 - depth * 0.5 + depth = depth.movedim(1, -1)[0].cpu().numpy() + depth_image = HWC3((depth * 255.0).clip(0, 255).astype(np.uint8)) + + return remove_pad(depth_image) + + +add_supported_preprocessor(PreprocessorMarigold()) diff --git a/extensions-builtin/forge_preprocessor_revision/scripts/preprocessor_revision.py b/extensions-builtin/forge_preprocessor_revision/scripts/preprocessor_revision.py new file mode 100644 index 0000000000000000000000000000000000000000..007bc7a3a6a9afeea46a0f384b6b21ae02308f84 --- /dev/null +++ b/extensions-builtin/forge_preprocessor_revision/scripts/preprocessor_revision.py @@ -0,0 +1,111 @@ +import torch +import copy + +from modules_forge.supported_preprocessor import PreprocessorClipVision, PreprocessorParameter +from modules_forge.shared import add_supported_preprocessor + + +def revision_conditioning_modifier(model, x, timestep, uncond, cond, cond_scale, model_options, seed): + revision_conditions = model_options['revision_conditions'] + + noise_augmentor = getattr(model, 'noise_augmentor', None) + + noise_augment_merge = 0.0 + ignore_prompt = False + + adm_inputs = [] + weights = [] + noise_aug = [] + for revision_condition in revision_conditions: + adm_cond = revision_condition['cond'].image_embeds + weight = revision_condition["weight"] + noise_augment = revision_condition["noise_aug"] + + if noise_augmentor is not None: + noise_level = round((noise_augmentor.max_noise_level - 1) * noise_augment) + c_adm, noise_level_emb = noise_augmentor(adm_cond.to(x.device), + noise_level=torch.tensor([noise_level], device=x.device), seed=seed) + adm_out = torch.cat((c_adm, noise_level_emb), 1) * weight + else: + adm_out = adm_cond * weight # skip noise augmentation + + weights.append(weight) + noise_aug.append(noise_augment) + adm_inputs.append(adm_out) + if revision_condition["ignore_prompt"]: + ignore_prompt = True + + if len(noise_aug) > 1: + adm_out = torch.stack(adm_inputs).sum(0) + if noise_augmentor is not None: + noise_augment = noise_augment_merge + noise_level = round((noise_augmentor.max_noise_level - 1) * noise_augment) + c_adm, noise_level_emb = noise_augmentor(adm_out[:, :noise_augmentor.time_embed.dim], + noise_level=torch.tensor([noise_level], device=x.device)) + adm_out = torch.cat((c_adm, noise_level_emb), 1) + + new_y = adm_out[:, :1280] + cond = copy.deepcopy(cond) + uncond = copy.deepcopy(uncond) + + for c in cond: + c['model_conds']['y'].cond[:, :1280] = new_y.clone() + + for c in uncond: + c['model_conds']['y'].cond[:, :1280] = torch.zeros_like(new_y) + + if ignore_prompt: + for c in cond + uncond: + c['model_conds']['c_crossattn'].cond = torch.zeros_like(c['model_conds']['c_crossattn'].cond) + + return model, x, timestep, uncond, cond, cond_scale, model_options, seed + + +class PreprocessorClipVisionForRevision(PreprocessorClipVision): + def __init__(self, name, url, filename, ignore_prompt=False): + super().__init__(name, url, filename) + self.tags = ['Revision'] + self.model_filename_filters = ['Revision'] + self.do_not_need_model = True + self.ignore_prompt = ignore_prompt + self.slider_1 = PreprocessorParameter( + label="Noise Augmentation", minimum=0.0, maximum=1.0, value=0.0, visible=False) # hiding the noise slider since it has no effect + + def process_before_every_sampling(self, process, cond, mask, *args, **kwargs): + unit = kwargs['unit'] + + weight = float(unit.weight) + noise_aug = float(unit.threshold_a) + + unet = process.sd_model.forge_objects.unet.clone() + + if 'revision_conditions' not in unet.model_options: + unet.model_options['revision_conditions'] = [] + + unet.model_options['revision_conditions'].append(dict( + cond=cond, + weight=weight, + noise_aug=noise_aug, + ignore_prompt=self.ignore_prompt + )) + + unet.add_conditioning_modifier(revision_conditioning_modifier, ensure_uniqueness=True) + + process.sd_model.forge_objects.unet = unet + + return cond, mask + + +add_supported_preprocessor(PreprocessorClipVisionForRevision( + name='CLIP-G (Revision)', + url='https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/image_encoder/model.safetensors', + filename='CLIP-ViT-bigG.safetensors', + ignore_prompt=False +)) + +add_supported_preprocessor(PreprocessorClipVisionForRevision( + name='CLIP-G (Revision ignore prompt)', + url='https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/image_encoder/model.safetensors', + filename='CLIP-ViT-bigG.safetensors', + ignore_prompt=True +)) diff --git a/extensions-builtin/forge_preprocessor_tile/scripts/preprocessor_tile.py b/extensions-builtin/forge_preprocessor_tile/scripts/preprocessor_tile.py new file mode 100644 index 0000000000000000000000000000000000000000..9ed7bb31feeea9ebf9f6127203cc467bee887bf7 --- /dev/null +++ b/extensions-builtin/forge_preprocessor_tile/scripts/preprocessor_tile.py @@ -0,0 +1,102 @@ +import torch + +from modules_forge.supported_preprocessor import Preprocessor, PreprocessorParameter +from modules_forge.shared import add_supported_preprocessor + + +def blur(x, k): + y = torch.nn.functional.pad(x, (k, k, k, k), mode='replicate') + y = torch.nn.functional.avg_pool2d(y, (k * 2 + 1, k * 2 + 1), stride=(1, 1)) + return y + + +class PreprocessorTile(Preprocessor): + def __init__(self): + super().__init__() + self.name = 'tile_resample' + self.tags = ['Tile'] + self.model_filename_filters = ['tile'] + self.slider_resolution = PreprocessorParameter(visible=False) + self.latent = None + + def register_latent(self, process, cond): + vae = process.sd_model.forge_objects.vae + # This is a powerful VAE with integrated memory management, bf16, and tiled fallback. + + latent_image = vae.encode(cond.movedim(1, -1)) + latent_image = process.sd_model.forge_objects.vae.first_stage_model.process_in(latent_image) + self.latent = latent_image + return self.latent + + +class PreprocessorTileColorFix(PreprocessorTile): + def __init__(self): + super().__init__() + self.name = 'tile_colorfix' + self.slider_1 = PreprocessorParameter(label='Variation', value=8.0, minimum=3.0, maximum=32.0, step=1.0, visible=True) + self.variation = 8 + self.sharpness = None + + def process_before_every_sampling(self, process, cond, mask, *args, **kwargs): + self.variation = int(kwargs['unit'].threshold_a) + + latent = self.register_latent(process, cond) + + unet = process.sd_model.forge_objects.unet.clone() + sigma_data = process.sd_model.forge_objects.unet.model.predictor.sigma_data + + if getattr(process, 'is_hr_pass', False): + k = int(self.variation * 2) + else: + k = int(self.variation) + + def block_proc(h, flag, transformer_options): + location, block_id = transformer_options['block'] + cond_mark = transformer_options['cond_mark'][:, None, None, None] # cond is 0 + + if location == 'input' and block_id == 0 and flag == 'before': + sigma = transformer_options['sigmas'].to(h) + self.x_input = h[:, :4] # Inpaint fix + self.x_input_sigma_space = self.x_input * (sigma ** 2 + sigma_data ** 2) ** 0.5 + + if location == 'last' and block_id == 0 and flag == 'after': + sigma = transformer_options['sigmas'].to(h) + eps_estimation = h[:, :4] + denoised = self.x_input_sigma_space - eps_estimation * sigma + + denoised = denoised - blur(denoised, k) + blur(latent.to(denoised), k) + + if isinstance(self.sharpness, float): + detail_weight = float(self.sharpness) * 0.01 + neg = detail_weight * blur(denoised, k) + (1 - detail_weight) * denoised + denoised = (1 - cond_mark) * denoised + cond_mark * neg + + eps_modified = (self.x_input_sigma_space - denoised) / sigma + + return eps_modified + + return h + + unet.add_block_modifier(block_proc) + + process.sd_model.forge_objects.unet = unet + + return cond, mask + + +class PreprocessorTileColorFixSharp(PreprocessorTileColorFix): + def __init__(self): + super().__init__() + self.name = 'tile_colorfix+sharp' + self.slider_2 = PreprocessorParameter(label='Sharpness', value=1.0, minimum=0.0, maximum=2.0, step=0.01, visible=True) + + def process_before_every_sampling(self, process, cond, mask, *args, **kwargs): + self.sharpness = float(kwargs['unit'].threshold_b) + return super().process_before_every_sampling(process, cond, mask, *args, **kwargs) + + +add_supported_preprocessor(PreprocessorTile()) + +add_supported_preprocessor(PreprocessorTileColorFix()) + +add_supported_preprocessor(PreprocessorTileColorFixSharp()) diff --git a/extensions-builtin/forge_space_birefnet/forge_app.py b/extensions-builtin/forge_space_birefnet/forge_app.py new file mode 100644 index 0000000000000000000000000000000000000000..96b686b2fd1a3318821d1a5e216605b62caf6879 --- /dev/null +++ b/extensions-builtin/forge_space_birefnet/forge_app.py @@ -0,0 +1,145 @@ + +import spaces +import os +import gradio as gr +from gradio_imageslider import ImageSlider +from loadimg import load_img +from transformers import AutoModelForImageSegmentation +import torch +from torchvision import transforms + +import glob +import pathlib +from PIL import Image + + +with spaces.capture_gpu_object() as birefnet_gpu_obj: + birefnet = AutoModelForImageSegmentation.from_pretrained( + "ZhengPeng7/BiRefNet", trust_remote_code=True + ) + +spaces.automatically_move_to_gpu_when_forward(birefnet) + +transform_image = transforms.Compose( + [ + transforms.Resize((1024, 1024)), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ] +) + + +@spaces.GPU(gpu_objects=[birefnet_gpu_obj], manual_load=True) +def fn(image): + im = load_img(image, output_type="pil") + im = im.convert("RGB") + image_size = im.size + origin = im.copy() + image = load_img(im) + input_images = transform_image(image).unsqueeze(0).to(spaces.gpu) + # Prediction + with torch.no_grad(): + preds = birefnet(input_images)[-1].sigmoid().cpu() + pred = preds[0].squeeze() + pred_pil = transforms.ToPILImage()(pred) + mask = pred_pil.resize(image_size) + image.putalpha(mask) + return (image, origin) + +@spaces.GPU(gpu_objects=[birefnet_gpu_obj], manual_load=True) +def batch_process(input_folder, output_folder, save_png, save_flat): + # Ensure output folder exists + os.makedirs(output_folder, exist_ok=True) + + # Supported image extensions + image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.webp'] + + # Collect all image files from input folder + input_images = [] + for ext in image_extensions: + input_images.extend(glob.glob(os.path.join(input_folder, f'*{ext}'))) + + # Process each image + processed_images = [] + for image_path in input_images: + try: + # Load image + im = load_img(image_path, output_type="pil") + im = im.convert("RGB") + image_size = im.size + image = load_img(im) + + # Prepare image for processing + input_image = transform_image(image).unsqueeze(0).to(spaces.gpu) + + # Prediction + with torch.no_grad(): + preds = birefnet(input_image)[-1].sigmoid().cpu() + + pred = preds[0].squeeze() + pred_pil = transforms.ToPILImage()(pred) + mask = pred_pil.resize(image_size) + + # Apply mask + image.putalpha(mask) + + # Save processed image + output_filename = os.path.join(output_folder, f"{pathlib.Path(image_path).name}") + + if save_flat: + background = Image.new('RGBA', image.size, (255, 255, 255)) + image = Image.alpha_composite(background, image) + image = image.convert("RGB") + elif output_filename.lower().endswith(".jpg") or output_filename.lower().endswith(".jpeg"): + # jpegs don't support alpha channel, so add .png extension (not change, to avoid potential overwrites) + output_filename += ".png" + if save_png and not output_filename.lower().endswith(".png"): + output_filename += ".png" + + image.save(output_filename) + + processed_images.append(output_filename) + + except Exception as e: + print(f"Error processing {image_path}: {str(e)}") + + return processed_images + +slider1 = ImageSlider(label="birefnet", type="pil") +slider2 = ImageSlider(label="birefnet", type="pil") +image = gr.Image(label="Upload an image") +text = gr.Textbox(label="URL to image, or local path to image", max_lines=1) + + +chameleon = load_img(spaces.convert_root_path() + "chameleon.jpg", output_type="pil") + +url = "https://hips.hearstapps.com/hmg-prod/images/gettyimages-1229892983-square.jpg" +tab1 = gr.Interface( + fn, inputs=image, outputs=slider1, examples=[chameleon], api_name="image", allow_flagging="never" +) + +tab2 = gr.Interface( + fn, inputs=text, outputs=slider2, examples=[url], api_name="text", allow_flagging="never" +) + +tab3 = gr.Interface( + batch_process, + inputs=[ + gr.Textbox(label="Input folder path", max_lines=1), + gr.Textbox(label="Output folder path (will overwrite)", max_lines=1), + gr.Checkbox(label="Always save as PNG", value=True), + gr.Checkbox(label="Save flat (no mask)", value=False) + ], + outputs=gr.File(label="Processed images", type="filepath", file_count="multiple"), + api_name="batch", + allow_flagging="never" +) + +demo = gr.TabbedInterface( + [tab1, tab2, tab3], + ["image", "URL", "batch"], + title="birefnet for background removal" +) + +if __name__ == "__main__": + demo.launch(inbrowser=True) diff --git a/extensions-builtin/forge_space_birefnet/space_meta.json b/extensions-builtin/forge_space_birefnet/space_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..5d70c1b7cca835fbd09f5e509889da101d5c27d9 --- /dev/null +++ b/extensions-builtin/forge_space_birefnet/space_meta.json @@ -0,0 +1,6 @@ +{ + "tag": "Image Processing: Matting, Saliency, and Background Removal", + "title": "BiRefNet for Background Removal", + "repo_id": "not-lain/background-removal", + "revision": "16bb0ccc3ff2fd889dba82e623c0d9953d81d946" +} diff --git a/extensions-builtin/forge_space_florence_2/forge_app.py b/extensions-builtin/forge_space_florence_2/forge_app.py new file mode 100644 index 0000000000000000000000000000000000000000..7ebcd606484141f5508ff1339a7ccf699c3a69dd --- /dev/null +++ b/extensions-builtin/forge_space_florence_2/forge_app.py @@ -0,0 +1,356 @@ +import spaces +import gradio as gr +from transformers import AutoProcessor, AutoModelForCausalLM +import os + +import copy + +from PIL import Image, ImageDraw, ImageFont +import io +import matplotlib.pyplot as plt +import matplotlib.patches as patches + +import random + +from modules import shared + + +with spaces.capture_gpu_object() as gpu_object: + models = { + # 'microsoft/Florence-2-large-ft': AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-large-ft', attn_implementation='sdpa', trust_remote_code=True).to("cuda").eval(), + 'microsoft/Florence-2-large': AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-large', trust_remote_code=True).to("cuda").eval(), + # 'microsoft/Florence-2-base-ft': AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-base-ft', trust_remote_code=True).to("cuda").eval(), + 'microsoft/Florence-2-base': AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True).to("cuda").eval(), + } + + processors = { + # 'microsoft/Florence-2-large-ft': AutoProcessor.from_pretrained('microsoft/Florence-2-large-ft', trust_remote_code=True), + 'microsoft/Florence-2-large': AutoProcessor.from_pretrained('microsoft/Florence-2-large', trust_remote_code=True), + # 'microsoft/Florence-2-base-ft': AutoProcessor.from_pretrained('microsoft/Florence-2-base-ft', trust_remote_code=True), + 'microsoft/Florence-2-base': AutoProcessor.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True), + } + + +DESCRIPTION = "# [Florence-2 Demo](https://huggingface.co/microsoft/Florence-2-large)" + +colormap = ['blue','orange','green','purple','brown','pink','gray','olive','cyan','red', + 'lime','indigo','violet','aqua','magenta','coral','gold','tan','skyblue'] + +def fig_to_pil(fig): + buf = io.BytesIO() + fig.savefig(buf, format='png') + buf.seek(0) + return Image.open(buf) + +@spaces.GPU(gpu_objects=[gpu_object], manual_load=False) +def run_example(task_prompt, image, text_input=None, model_id='microsoft/Florence-2-large'): + model = models[model_id] + processor = processors[model_id] + if text_input is None: + prompt = task_prompt + else: + prompt = task_prompt + text_input + inputs = processor(text=prompt, images=image, return_tensors="pt").to("cuda") + generated_ids = model.generate( + input_ids=inputs["input_ids"], + pixel_values=inputs["pixel_values"], + max_new_tokens=1024, + early_stopping=False, + do_sample=False, + num_beams=3, + ) + generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0] + parsed_answer = processor.post_process_generation( + generated_text, + task=task_prompt, + image_size=(image.width, image.height) + ) + return parsed_answer + +def plot_bbox(image, data): + fig, ax = plt.subplots() + ax.imshow(image) + for bbox, label in zip(data['bboxes'], data['labels']): + x1, y1, x2, y2 = bbox + rect = patches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=1, edgecolor='r', facecolor='none') + ax.add_patch(rect) + plt.text(x1, y1, label, color='white', fontsize=8, bbox=dict(facecolor='red', alpha=0.5)) + ax.axis('off') + return fig + +def draw_polygons(image, prediction, fill_mask=False): + + draw = ImageDraw.Draw(image) + scale = 1 + for polygons, label in zip(prediction['polygons'], prediction['labels']): + color = random.choice(colormap) + fill_color = random.choice(colormap) if fill_mask else None + for _polygon in polygons: + _polygon = np.array(_polygon).reshape(-1, 2) + if len(_polygon) < 3: + print('Invalid polygon:', _polygon) + continue + _polygon = (_polygon * scale).reshape(-1).tolist() + if fill_mask: + draw.polygon(_polygon, outline=color, fill=fill_color) + else: + draw.polygon(_polygon, outline=color) + draw.text((_polygon[0] + 8, _polygon[1] + 2), label, fill=color) + return image + +def convert_to_od_format(data): + bboxes = data.get('bboxes', []) + labels = data.get('bboxes_labels', []) + od_results = { + 'bboxes': bboxes, + 'labels': labels + } + return od_results + +def draw_ocr_bboxes(image, prediction): + scale = 1 + draw = ImageDraw.Draw(image) + bboxes, labels = prediction['quad_boxes'], prediction['labels'] + for box, label in zip(bboxes, labels): + color = random.choice(colormap) + new_box = (np.array(box) * scale).tolist() + draw.polygon(new_box, width=3, outline=color) + draw.text((new_box[0]+8, new_box[1]+2), + "{}".format(label), + align="right", + fill=color) + return image + + +def process_image(image, task_prompt, text_input=None, model_id='microsoft/Florence-2-large'): + if task_prompt == 'Caption': + task_prompt = '' + results = run_example(task_prompt, image, model_id=model_id) + return results, None + elif task_prompt == 'Detailed Caption': + task_prompt = '' + results = run_example(task_prompt, image, model_id=model_id) + return results, None + elif task_prompt == 'More Detailed Caption': + task_prompt = '' + results = run_example(task_prompt, image, model_id=model_id) + return results, None + elif task_prompt == 'Caption + Grounding': + task_prompt = '' + results = run_example(task_prompt, image, model_id=model_id) + text_input = results[task_prompt] + task_prompt = '' + results = run_example(task_prompt, image, text_input, model_id) + results[''] = text_input + fig = plot_bbox(image, results['']) + return results, fig_to_pil(fig) + elif task_prompt == 'Detailed Caption + Grounding': + task_prompt = '' + results = run_example(task_prompt, image, model_id=model_id) + text_input = results[task_prompt] + task_prompt = '' + results = run_example(task_prompt, image, text_input, model_id) + results[''] = text_input + fig = plot_bbox(image, results['']) + return results, fig_to_pil(fig) + elif task_prompt == 'More Detailed Caption + Grounding': + task_prompt = '' + results = run_example(task_prompt, image, model_id=model_id) + text_input = results[task_prompt] + task_prompt = '' + results = run_example(task_prompt, image, text_input, model_id) + results[''] = text_input + fig = plot_bbox(image, results['']) + return results, fig_to_pil(fig) + elif task_prompt == 'Object Detection': + task_prompt = '' + results = run_example(task_prompt, image, model_id=model_id) + fig = plot_bbox(image, results['']) + return results, fig_to_pil(fig) + elif task_prompt == 'Dense Region Caption': + task_prompt = '' + results = run_example(task_prompt, image, model_id=model_id) + fig = plot_bbox(image, results['']) + return results, fig_to_pil(fig) + elif task_prompt == 'Region Proposal': + task_prompt = '' + results = run_example(task_prompt, image, model_id=model_id) + fig = plot_bbox(image, results['']) + return results, fig_to_pil(fig) + elif task_prompt == 'Caption to Phrase Grounding': + task_prompt = '' + results = run_example(task_prompt, image, text_input, model_id) + fig = plot_bbox(image, results['']) + return results, fig_to_pil(fig) + elif task_prompt == 'Referring Expression Segmentation': + task_prompt = '' + results = run_example(task_prompt, image, text_input, model_id) + output_image = copy.deepcopy(image) + output_image = draw_polygons(output_image, results[''], fill_mask=True) + return results, output_image + elif task_prompt == 'Region to Segmentation': + task_prompt = '' + results = run_example(task_prompt, image, text_input, model_id) + output_image = copy.deepcopy(image) + output_image = draw_polygons(output_image, results[''], fill_mask=True) + return results, output_image + elif task_prompt == 'Open Vocabulary Detection': + task_prompt = '' + results = run_example(task_prompt, image, text_input, model_id) + bbox_results = convert_to_od_format(results['']) + fig = plot_bbox(image, bbox_results) + return results, fig_to_pil(fig) + elif task_prompt == 'Region to Category': + task_prompt = '' + results = run_example(task_prompt, image, text_input, model_id) + return results, None + elif task_prompt == 'Region to Description': + task_prompt = '' + results = run_example(task_prompt, image, text_input, model_id) + return results, None + elif task_prompt == 'OCR': + task_prompt = '' + results = run_example(task_prompt, image, model_id=model_id) + return results, None + elif task_prompt == 'OCR with Region': + task_prompt = '' + results = run_example(task_prompt, image, model_id=model_id) + output_image = copy.deepcopy(image) + output_image = draw_ocr_bboxes(output_image, results['']) + return results, output_image + else: + return "", None # Return empty string and None for unknown task prompts + + +@spaces.GPU(gpu_objects=[gpu_object], manual_load=False) +def run_example_batch(directory, task_prompt, model_id='microsoft/Florence-2-large', save_caption=False): + model = models[model_id] + processor = processors[model_id] + + match task_prompt: + case 'More Detailed Caption': + prompt = '' + case 'Detailed Caption': + prompt = '' + case 'Caption': + prompt = '' + case _: + prompt = '' + + results = "" + + # batch_images block lifted from modules/img2img.py + if isinstance(directory, str): + batch_images = list(shared.walk_files(directory, allowed_extensions=(".png", ".jpg", ".jpeg", ".webp", ".tif", ".tiff", ".avif"))) + else: + batch_images = [os.path.abspath(x.name) for x in directory] + + for file in batch_images: + image = Image.open(file) + + if image: + inputs = processor(text=prompt, images=image, return_tensors="pt").to("cuda") + generated_ids = model.generate( + input_ids=inputs["input_ids"], + pixel_values=inputs["pixel_values"], + max_new_tokens=1024, + early_stopping=False, + do_sample=False, + num_beams=3, + ) + generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0] + parsed_answer = processor.post_process_generation( + generated_text, + task=task_prompt, + image_size=(image.width, image.height) + ) + + parsed_answer = parsed_answer[task_prompt] + results += f"File: {file}\nCaption: {parsed_answer}\n\n" + + if save_caption: + caption_file = file + ".txt" + with open(caption_file, 'w') as f: + f.write(parsed_answer) + + return results + + +css = """ + #output { + height: 500px; + overflow: auto; + border: 1px solid #ccc; + } +""" + +caption_task_list = [ + 'Caption', 'Detailed Caption', 'More Detailed Caption' +] + +single_task_list =[ + 'Caption', 'Detailed Caption', 'More Detailed Caption', 'Object Detection', + 'Dense Region Caption', 'Region Proposal', 'Caption to Phrase Grounding', + 'Referring Expression Segmentation', 'Region to Segmentation', + 'Open Vocabulary Detection', 'Region to Category', 'Region to Description', + 'OCR', 'OCR with Region' +] + +cascaded_task_list =[ + 'Caption + Grounding', 'Detailed Caption + Grounding', 'More Detailed Caption + Grounding' +] + + +def update_task_dropdown(choice): + if choice == 'Cascaded task': + return gr.Dropdown(choices=cascaded_task_list, value='Caption + Grounding') + else: + return gr.Dropdown(choices=single_task_list, value='Caption') + + +with gr.Blocks(css=css) as demo: + gr.Markdown(DESCRIPTION) + with gr.Tab(label="Florence-2 Image Captioning"): + with gr.Row(): + with gr.Column(): + input_img = gr.Image(label="Input picture", type="pil") + model_selector = gr.Dropdown(choices=list(models.keys()), label="Model", value=list(models.keys())[0]) + task_type = gr.Radio(choices=['Single task', 'Cascaded task'], label='Task type selector', value='Single task') + task_prompt = gr.Dropdown(choices=single_task_list, label="Task prompt", value="More Detailed Caption") + task_type.change(fn=update_task_dropdown, inputs=task_type, outputs=task_prompt) + text_input = gr.Textbox(label="Text input (optional)") + submit_btn = gr.Button(value="Submit") + with gr.Column(): + output_text = gr.Textbox(label="Output Text") + output_img = gr.Image(label="Output Image") + + gr.Examples( + examples=[ + [spaces.convert_root_path() + "image1.jpg", "More Detailed Caption"], + [spaces.convert_root_path() + "image2.jpg", 'OCR with Region'] + ], + inputs=[input_img, task_prompt], + outputs=[output_text, output_img], + fn=process_image, + cache_examples=False, + label='Try examples' + ) + + submit_btn.click(process_image, [input_img, task_prompt, text_input, model_selector], [output_text, output_img]) + + with gr.Tab(label="Batch captioning"): + with gr.Row(): + with gr.Column(): + input_directory = gr.Textbox(label="Input directory") + model_selector = gr.Dropdown(choices=list(models.keys()), label="Model", value=list(models.keys())[0]) + task_prompt = gr.Dropdown(choices=caption_task_list, label="Task prompt", value="More Detailed Caption") + save_captions = gr.Checkbox(label="Save captions to textfiles (same filename, same directory)", value=False) + batch_btn = gr.Button(value="Submit") + with gr.Column(): + output_text = gr.Textbox(label="Output captions") + + batch_btn.click(run_example_batch, [input_directory, task_prompt, model_selector, save_captions], output_text) + + +if __name__ == "__main__": + demo.launch() diff --git a/extensions-builtin/forge_space_florence_2/space_meta.json b/extensions-builtin/forge_space_florence_2/space_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..5bb7f2374fcd24d5f4d1e6a111ef193ffb85ab14 --- /dev/null +++ b/extensions-builtin/forge_space_florence_2/space_meta.json @@ -0,0 +1,6 @@ +{ + "tag": "Computer Vision: Image Caption, Object Detection, and Image Segmentation", + "title": "Florence-2: Image Captioning and Object Detection", + "repo_id": "gokaygokay/Florence-2", + "revision": "9ff9f99df447d124bf0261f1de6a22898ccdce4e" +} diff --git a/extensions-builtin/forge_space_geowizard/forge_app.py b/extensions-builtin/forge_space_geowizard/forge_app.py new file mode 100644 index 0000000000000000000000000000000000000000..159df4e88abf30af3282ffcf2426b40ff5c6edb3 --- /dev/null +++ b/extensions-builtin/forge_space_geowizard/forge_app.py @@ -0,0 +1,192 @@ +import spaces + +import functools +import os +import shutil +import sys +import git + +import gradio as gr +import numpy as np +import torch as torch +from PIL import Image + +from gradio_imageslider import ImageSlider + +import spaces + + +import argparse +import os +import logging + +import numpy as np +import torch +from PIL import Image +from tqdm.auto import tqdm +import glob +import json +import cv2 + +import sys + +from geo_models.geowizard_pipeline import DepthNormalEstimationPipeline +from geo_utils.seed_all import seed_all +import matplotlib.pyplot as plt +from geo_utils.de_normalized import align_scale_shift +from geo_utils.depth2normal import * + +from diffusers import DiffusionPipeline, DDIMScheduler, AutoencoderKL +from geo_models.unet_2d_condition import UNet2DConditionModel + +from transformers import CLIPTextModel, CLIPTokenizer +from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection +import torchvision.transforms.functional as TF +from torchvision.transforms import InterpolationMode + +device = spaces.gpu + +with spaces.capture_gpu_object() as gpu_object: + vae = AutoencoderKL.from_pretrained(spaces.convert_root_path(), subfolder='vae') + scheduler = DDIMScheduler.from_pretrained(spaces.convert_root_path(), subfolder='scheduler') + image_encoder = CLIPVisionModelWithProjection.from_pretrained(spaces.convert_root_path(), subfolder="image_encoder") + feature_extractor = CLIPImageProcessor.from_pretrained(spaces.convert_root_path(), subfolder="feature_extractor") + unet = UNet2DConditionModel.from_pretrained(spaces.convert_root_path(), subfolder="unet") + +pipe = DepthNormalEstimationPipeline(vae=vae, + image_encoder=image_encoder, + feature_extractor=feature_extractor, + unet=unet, + scheduler=scheduler) + +outputs_dir = "./outputs" + +spaces.automatically_move_pipeline_components(pipe) +spaces.automatically_move_to_gpu_when_forward(pipe.vae.encoder, target_model=pipe.vae) +spaces.automatically_move_to_gpu_when_forward(pipe.vae.decoder, target_model=pipe.vae) +spaces.automatically_move_to_gpu_when_forward(pipe.vae.post_quant_conv, target_model=pipe.vae) +# spaces.change_attention_from_diffusers_to_forge(vae) +# spaces.change_attention_from_diffusers_to_forge(unet) +# pipe = pipe.to(device) + + +@spaces.GPU(gpu_objects=gpu_object, manual_load=True) +def depth_normal(img, + denoising_steps, + ensemble_size, + processing_res, + seed, + domain): + seed = int(seed) + if seed >= 0: + torch.manual_seed(seed) + + pipe_out = pipe( + img, + denoising_steps=denoising_steps, + ensemble_size=ensemble_size, + processing_res=processing_res, + batch_size=0, + domain=domain, + show_progress_bar=True, + ) + + depth_colored = Image.fromarray(((1. - pipe_out.depth_np) * 255.0).clip(0, 255).astype(np.uint8)) + normal_colored = pipe_out.normal_colored + + return depth_colored, normal_colored + + +def run_demo(): + custom_theme = gr.themes.Soft(primary_hue="blue").set( + button_secondary_background_fill="*neutral_100", + button_secondary_background_fill_hover="*neutral_200") + custom_css = '''#disp_image { + text-align: center; /* Horizontally center the content */ + }''' + + _TITLE = '''GeoWizard: Unleashing the Diffusion Priors for 3D Geometry Estimation from a Single Image''' + _DESCRIPTION = ''' +
+ Generate consistent depth and normal from single image. High quality and rich details. (PS: We find the demo running on ZeroGPU output slightly inferior results compared to A100 or 3060 with everything exactly the same.) + +
+ ''' + _GPU_ID = 0 + + with gr.Blocks(title=_TITLE, theme=custom_theme, css=custom_css) as demo: + with gr.Row(): + with gr.Column(scale=1): + gr.Markdown('# ' + _TITLE) + gr.Markdown(_DESCRIPTION) + with gr.Row(variant='panel'): + with gr.Column(scale=1): + input_image = gr.Image(type='pil', image_mode='RGBA', height=320, label='Input image') + + example_folder = os.path.join(spaces.convert_root_path(), "files") + example_fns = [os.path.join(example_folder, example) for example in os.listdir(example_folder)] + gr.Examples( + examples=example_fns, + inputs=[input_image], + cache_examples=False, + label='Examples (click one of the images below to start)', + examples_per_page=30 + ) + with gr.Column(scale=1): + with gr.Accordion('Advanced options', open=True): + with gr.Column(): + domain = gr.Radio( + [ + ("Outdoor", "outdoor"), + ("Indoor", "indoor"), + ("Object", "object"), + ], + label="Data Type (Must Select One matches your image)", + value="indoor", + ) + denoising_steps = gr.Slider( + label="Number of denoising steps (More steps, better quality)", + minimum=1, + maximum=50, + step=1, + value=10, + ) + ensemble_size = gr.Slider( + label="Ensemble size (More steps, higher accuracy)", + minimum=1, + maximum=15, + step=1, + value=3, + ) + seed = gr.Number(0, label='Random Seed. Negative values for not specifying') + + processing_res = gr.Radio( + [ + ("Native", 0), + ("Recommended", 768), + ], + label="Processing resolution", + value=768, + ) + + run_btn = gr.Button('Generate', variant='primary', interactive=True) + with gr.Row(): + with gr.Column(): + depth = gr.Image(interactive=False, show_label=False) + with gr.Column(): + normal = gr.Image(interactive=False, show_label=False) + + run_btn.click(fn=depth_normal, + inputs=[input_image, denoising_steps, + ensemble_size, + processing_res, + seed, + domain], + outputs=[depth, normal] + ) + return demo + + +demo = run_demo() +if __name__ == '__main__': + demo.queue().launch(share=True, max_threads=80) diff --git a/extensions-builtin/forge_space_geowizard/geo_models/attention.py b/extensions-builtin/forge_space_geowizard/geo_models/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..6b7ada5fb2f6887f2a99ac9dbf135e2a1257a972 --- /dev/null +++ b/extensions-builtin/forge_space_geowizard/geo_models/attention.py @@ -0,0 +1,684 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +# Some modifications are reimplemented in public environments by Xiao Fu and Mu Hu + + +from typing import Any, Dict, Optional + +import torch +import torch.nn.functional as F +from torch import nn +# import xformers + +from diffusers.utils import USE_PEFT_BACKEND +from diffusers.utils.torch_utils import maybe_allow_in_graph +from diffusers.models.activations import GEGLU, GELU, ApproximateGELU +from diffusers.models.attention_processor import Attention +from diffusers.models.embeddings import SinusoidalPositionalEmbedding +from diffusers.models.lora import LoRACompatibleLinear +from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm + + +def _chunked_feed_forward( + ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int, lora_scale: Optional[float] = None +): + # "feed_forward_chunk_size" can be used to save memory + if hidden_states.shape[chunk_dim] % chunk_size != 0: + raise ValueError( + f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`." + ) + + num_chunks = hidden_states.shape[chunk_dim] // chunk_size + if lora_scale is None: + ff_output = torch.cat( + [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)], + dim=chunk_dim, + ) + else: + # TOOD(Patrick): LoRA scale can be removed once PEFT refactor is complete + ff_output = torch.cat( + [ff(hid_slice, scale=lora_scale) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)], + dim=chunk_dim, + ) + + return ff_output + + +@maybe_allow_in_graph +class GatedSelfAttentionDense(nn.Module): + r""" + A gated self-attention dense layer that combines visual features and object features. + + Parameters: + query_dim (`int`): The number of channels in the query. + context_dim (`int`): The number of channels in the context. + n_heads (`int`): The number of heads to use for attention. + d_head (`int`): The number of channels in each head. + """ + + def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int): + super().__init__() + + # we need a linear projection since we need cat visual feature and obj feature + self.linear = nn.Linear(context_dim, query_dim) + + self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head) + self.ff = FeedForward(query_dim, activation_fn="geglu") + + self.norm1 = nn.LayerNorm(query_dim) + self.norm2 = nn.LayerNorm(query_dim) + + self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0))) + self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0))) + + self.enabled = True + + def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor: + if not self.enabled: + return x + + n_visual = x.shape[1] + objs = self.linear(objs) + + x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :] + x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x)) + + return x + + +@maybe_allow_in_graph +class BasicTransformerBlock(nn.Module): + r""" + A basic Transformer block. + + Parameters: + dim (`int`): The number of channels in the input and output. + num_attention_heads (`int`): The number of heads to use for multi-head attention. + attention_head_dim (`int`): The number of channels in each head. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention. + activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward. + num_embeds_ada_norm (: + obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`. + attention_bias (: + obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter. + only_cross_attention (`bool`, *optional*): + Whether to use only cross-attention layers. In this case two cross attention layers are used. + double_self_attention (`bool`, *optional*): + Whether to use two self-attention layers. In this case no cross attention layers are used. + upcast_attention (`bool`, *optional*): + Whether to upcast the attention computation to float32. This is useful for mixed precision training. + norm_elementwise_affine (`bool`, *optional*, defaults to `True`): + Whether to use learnable elementwise affine parameters for normalization. + norm_type (`str`, *optional*, defaults to `"layer_norm"`): + The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`. + final_dropout (`bool` *optional*, defaults to False): + Whether to apply a final dropout after the last feed-forward layer. + attention_type (`str`, *optional*, defaults to `"default"`): + The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`. + positional_embeddings (`str`, *optional*, defaults to `None`): + The type of positional embeddings to apply to. + num_positional_embeddings (`int`, *optional*, defaults to `None`): + The maximum number of positional embeddings to apply. + """ + + def __init__( + self, + dim: int, + num_attention_heads: int, + attention_head_dim: int, + dropout=0.0, + cross_attention_dim: Optional[int] = None, + activation_fn: str = "geglu", + num_embeds_ada_norm: Optional[int] = None, + attention_bias: bool = False, + only_cross_attention: bool = False, + double_self_attention: bool = False, + upcast_attention: bool = False, + norm_elementwise_affine: bool = True, + norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single' + norm_eps: float = 1e-5, + final_dropout: bool = False, + attention_type: str = "default", + positional_embeddings: Optional[str] = None, + num_positional_embeddings: Optional[int] = None, + ada_norm_continous_conditioning_embedding_dim: Optional[int] = None, + ada_norm_bias: Optional[int] = None, + ff_inner_dim: Optional[int] = None, + ff_bias: bool = True, + attention_out_bias: bool = True, + ): + super().__init__() + self.only_cross_attention = only_cross_attention + + self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero" + self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm" + self.use_ada_layer_norm_single = norm_type == "ada_norm_single" + self.use_layer_norm = norm_type == "layer_norm" + self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous" + + if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: + raise ValueError( + f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to" + f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}." + ) + + if positional_embeddings and (num_positional_embeddings is None): + raise ValueError( + "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined." + ) + + if positional_embeddings == "sinusoidal": + self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings) + else: + self.pos_embed = None + + # Define 3 blocks. Each block has its own normalization layer. + # 1. Self-Attn + if self.use_ada_layer_norm: + self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm) + elif self.use_ada_layer_norm_zero: + self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm) + elif self.use_ada_layer_norm_continuous: + self.norm1 = AdaLayerNormContinuous( + dim, + ada_norm_continous_conditioning_embedding_dim, + norm_elementwise_affine, + norm_eps, + ada_norm_bias, + "rms_norm", + ) + else: + self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps) + + + self.attn1 = CustomJointAttention( + query_dim=dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + cross_attention_dim=cross_attention_dim if only_cross_attention else None, + upcast_attention=upcast_attention, + out_bias=attention_out_bias + ) + + # 2. Cross-Attn + if cross_attention_dim is not None or double_self_attention: + # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. + # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during + # the second cross attention block. + + if self.use_ada_layer_norm: + self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm) + elif self.use_ada_layer_norm_continuous: + self.norm2 = AdaLayerNormContinuous( + dim, + ada_norm_continous_conditioning_embedding_dim, + norm_elementwise_affine, + norm_eps, + ada_norm_bias, + "rms_norm", + ) + else: + self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine) + + self.attn2 = Attention( + query_dim=dim, + cross_attention_dim=cross_attention_dim if not double_self_attention else None, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + upcast_attention=upcast_attention, + out_bias=attention_out_bias, + ) # is self-attn if encoder_hidden_states is none + else: + self.norm2 = None + self.attn2 = None + + # 3. Feed-forward + if self.use_ada_layer_norm_continuous: + self.norm3 = AdaLayerNormContinuous( + dim, + ada_norm_continous_conditioning_embedding_dim, + norm_elementwise_affine, + norm_eps, + ada_norm_bias, + "layer_norm", + ) + elif not self.use_ada_layer_norm_single: + self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine) + + self.ff = FeedForward( + dim, + dropout=dropout, + activation_fn=activation_fn, + final_dropout=final_dropout, + inner_dim=ff_inner_dim, + bias=ff_bias, + ) + + # 4. Fuser + if attention_type == "gated" or attention_type == "gated-text-image": + self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim) + + # 5. Scale-shift for PixArt-Alpha. + if self.use_ada_layer_norm_single: + self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5) + + # let chunk size default to None + self._chunk_size = None + self._chunk_dim = 0 + + def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0): + # Sets chunk feed-forward + self._chunk_size = chunk_size + self._chunk_dim = dim + + def forward( + self, + hidden_states: torch.FloatTensor, + attention_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + timestep: Optional[torch.LongTensor] = None, + cross_attention_kwargs: Dict[str, Any] = None, + class_labels: Optional[torch.LongTensor] = None, + added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None, + ) -> torch.FloatTensor: + # Notice that normalization is always applied before the real computation in the following blocks. + + # 0. Self-Attention + batch_size = hidden_states.shape[0] + + if self.use_ada_layer_norm: + norm_hidden_states = self.norm1(hidden_states, timestep) + elif self.use_ada_layer_norm_zero: + norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1( + hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype + ) + elif self.use_layer_norm: + norm_hidden_states = self.norm1(hidden_states) + elif self.use_ada_layer_norm_continuous: + norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"]) + elif self.use_ada_layer_norm_single: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ( + self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1) + ).chunk(6, dim=1) + norm_hidden_states = self.norm1(hidden_states) + norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa + norm_hidden_states = norm_hidden_states.squeeze(1) + else: + raise ValueError("Incorrect norm used") + + if self.pos_embed is not None: + norm_hidden_states = self.pos_embed(norm_hidden_states) + + # 1. Retrieve lora scale. + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + + # 2. Prepare GLIGEN inputs + cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {} + gligen_kwargs = cross_attention_kwargs.pop("gligen", None) + + attn_output = self.attn1( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None, + attention_mask=attention_mask, + **cross_attention_kwargs, + ) + if self.use_ada_layer_norm_zero: + attn_output = gate_msa.unsqueeze(1) * attn_output + elif self.use_ada_layer_norm_single: + attn_output = gate_msa * attn_output + + hidden_states = attn_output + hidden_states + if hidden_states.ndim == 4: + hidden_states = hidden_states.squeeze(1) + + # 2.5 GLIGEN Control + if gligen_kwargs is not None: + hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"]) + + # 3. Cross-Attention + if self.attn2 is not None: + if self.use_ada_layer_norm: + norm_hidden_states = self.norm2(hidden_states, timestep) + elif self.use_ada_layer_norm_zero or self.use_layer_norm: + norm_hidden_states = self.norm2(hidden_states) + elif self.use_ada_layer_norm_single: + # For PixArt norm2 isn't applied here: + # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103 + norm_hidden_states = hidden_states + elif self.use_ada_layer_norm_continuous: + norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"]) + else: + raise ValueError("Incorrect norm") + + if self.pos_embed is not None and self.use_ada_layer_norm_single is False: + norm_hidden_states = self.pos_embed(norm_hidden_states) + + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=encoder_attention_mask, + **cross_attention_kwargs, + ) + hidden_states = attn_output + hidden_states + + # 4. Feed-forward + if self.use_ada_layer_norm_continuous: + norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"]) + elif not self.use_ada_layer_norm_single: + norm_hidden_states = self.norm3(hidden_states) + + if self.use_ada_layer_norm_zero: + norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] + + if self.use_ada_layer_norm_single: + norm_hidden_states = self.norm2(hidden_states) + norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp + + if self._chunk_size is not None: + # "feed_forward_chunk_size" can be used to save memory + ff_output = _chunked_feed_forward( + self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale + ) + else: + ff_output = self.ff(norm_hidden_states, scale=lora_scale) + + if self.use_ada_layer_norm_zero: + ff_output = gate_mlp.unsqueeze(1) * ff_output + elif self.use_ada_layer_norm_single: + ff_output = gate_mlp * ff_output + + hidden_states = ff_output + hidden_states + if hidden_states.ndim == 4: + hidden_states = hidden_states.squeeze(1) + + return hidden_states + + +class CustomJointAttention(Attention): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + from backend.attention import AttentionProcessorForge + self.set_processor(AttentionProcessorForge()) + + +@maybe_allow_in_graph +class TemporalBasicTransformerBlock(nn.Module): + r""" + A basic Transformer block for video like data. + + Parameters: + dim (`int`): The number of channels in the input and output. + time_mix_inner_dim (`int`): The number of channels for temporal attention. + num_attention_heads (`int`): The number of heads to use for multi-head attention. + attention_head_dim (`int`): The number of channels in each head. + cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention. + """ + + def __init__( + self, + dim: int, + time_mix_inner_dim: int, + num_attention_heads: int, + attention_head_dim: int, + cross_attention_dim: Optional[int] = None, + ): + super().__init__() + self.is_res = dim == time_mix_inner_dim + + self.norm_in = nn.LayerNorm(dim) + + # Define 3 blocks. Each block has its own normalization layer. + # 1. Self-Attn + self.norm_in = nn.LayerNorm(dim) + self.ff_in = FeedForward( + dim, + dim_out=time_mix_inner_dim, + activation_fn="geglu", + ) + + self.norm1 = nn.LayerNorm(time_mix_inner_dim) + self.attn1 = Attention( + query_dim=time_mix_inner_dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + cross_attention_dim=None, + ) + + # 2. Cross-Attn + if cross_attention_dim is not None: + # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. + # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during + # the second cross attention block. + self.norm2 = nn.LayerNorm(time_mix_inner_dim) + self.attn2 = Attention( + query_dim=time_mix_inner_dim, + cross_attention_dim=cross_attention_dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + ) # is self-attn if encoder_hidden_states is none + else: + self.norm2 = None + self.attn2 = None + + # 3. Feed-forward + self.norm3 = nn.LayerNorm(time_mix_inner_dim) + self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu") + + # let chunk size default to None + self._chunk_size = None + self._chunk_dim = None + + def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs): + # Sets chunk feed-forward + self._chunk_size = chunk_size + # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off + self._chunk_dim = 1 + + def forward( + self, + hidden_states: torch.FloatTensor, + num_frames: int, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + # Notice that normalization is always applied before the real computation in the following blocks. + # 0. Self-Attention + batch_size = hidden_states.shape[0] + + batch_frames, seq_length, channels = hidden_states.shape + batch_size = batch_frames // num_frames + + hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels) + hidden_states = hidden_states.permute(0, 2, 1, 3) + hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels) + + residual = hidden_states + hidden_states = self.norm_in(hidden_states) + + if self._chunk_size is not None: + hidden_states = _chunked_feed_forward(self.ff_in, hidden_states, self._chunk_dim, self._chunk_size) + else: + hidden_states = self.ff_in(hidden_states) + + if self.is_res: + hidden_states = hidden_states + residual + + norm_hidden_states = self.norm1(hidden_states) + attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None) + hidden_states = attn_output + hidden_states + + # 3. Cross-Attention + if self.attn2 is not None: + norm_hidden_states = self.norm2(hidden_states) + attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states) + hidden_states = attn_output + hidden_states + + # 4. Feed-forward + norm_hidden_states = self.norm3(hidden_states) + + if self._chunk_size is not None: + ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size) + else: + ff_output = self.ff(norm_hidden_states) + + if self.is_res: + hidden_states = ff_output + hidden_states + else: + hidden_states = ff_output + + hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels) + hidden_states = hidden_states.permute(0, 2, 1, 3) + hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels) + + return hidden_states + + +class SkipFFTransformerBlock(nn.Module): + def __init__( + self, + dim: int, + num_attention_heads: int, + attention_head_dim: int, + kv_input_dim: int, + kv_input_dim_proj_use_bias: bool, + dropout=0.0, + cross_attention_dim: Optional[int] = None, + attention_bias: bool = False, + attention_out_bias: bool = True, + ): + super().__init__() + if kv_input_dim != dim: + self.kv_mapper = nn.Linear(kv_input_dim, dim, kv_input_dim_proj_use_bias) + else: + self.kv_mapper = None + + self.norm1 = RMSNorm(dim, 1e-06) + + self.attn1 = Attention( + query_dim=dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + cross_attention_dim=cross_attention_dim, + out_bias=attention_out_bias, + ) + + self.norm2 = RMSNorm(dim, 1e-06) + + self.attn2 = Attention( + query_dim=dim, + cross_attention_dim=cross_attention_dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + out_bias=attention_out_bias, + ) + + def forward(self, hidden_states, encoder_hidden_states, cross_attention_kwargs): + cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {} + + if self.kv_mapper is not None: + encoder_hidden_states = self.kv_mapper(F.silu(encoder_hidden_states)) + + norm_hidden_states = self.norm1(hidden_states) + + attn_output = self.attn1( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + **cross_attention_kwargs, + ) + + hidden_states = attn_output + hidden_states + + norm_hidden_states = self.norm2(hidden_states) + + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + **cross_attention_kwargs, + ) + + hidden_states = attn_output + hidden_states + + return hidden_states + + +class FeedForward(nn.Module): + r""" + A feed-forward layer. + + Parameters: + dim (`int`): The number of channels in the input. + dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`. + mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward. + final_dropout (`bool` *optional*, defaults to False): Apply a final dropout. + bias (`bool`, defaults to True): Whether to use a bias in the linear layer. + """ + + def __init__( + self, + dim: int, + dim_out: Optional[int] = None, + mult: int = 4, + dropout: float = 0.0, + activation_fn: str = "geglu", + final_dropout: bool = False, + inner_dim=None, + bias: bool = True, + ): + super().__init__() + if inner_dim is None: + inner_dim = int(dim * mult) + dim_out = dim_out if dim_out is not None else dim + linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear + + if activation_fn == "gelu": + act_fn = GELU(dim, inner_dim, bias=bias) + if activation_fn == "gelu-approximate": + act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias) + elif activation_fn == "geglu": + act_fn = GEGLU(dim, inner_dim, bias=bias) + elif activation_fn == "geglu-approximate": + act_fn = ApproximateGELU(dim, inner_dim, bias=bias) + + self.net = nn.ModuleList([]) + # project in + self.net.append(act_fn) + # project dropout + self.net.append(nn.Dropout(dropout)) + # project out + self.net.append(linear_cls(inner_dim, dim_out, bias=bias)) + # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout + if final_dropout: + self.net.append(nn.Dropout(dropout)) + + def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor: + compatible_cls = (GEGLU,) if USE_PEFT_BACKEND else (GEGLU, LoRACompatibleLinear) + for module in self.net: + if isinstance(module, compatible_cls): + hidden_states = module(hidden_states, scale) + else: + hidden_states = module(hidden_states) + return hidden_states diff --git a/extensions-builtin/forge_space_geowizard/space_meta.json b/extensions-builtin/forge_space_geowizard/space_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..b83745b43469289f1eb1806046c9aef162c8123e --- /dev/null +++ b/extensions-builtin/forge_space_geowizard/space_meta.json @@ -0,0 +1,6 @@ +{ + "tag": "Computer Vision: Depth, Normal, and Geometry", + "title": "GeoWizard: Unleashing the Diffusion Priors for 3D Geometry Estimation from a Single Image", + "repo_id": "lemonaddie/geowizard", + "revision": "e25e940c5c94c05be7ca84182a0aec7eb414edaa" +} diff --git a/extensions-builtin/forge_space_iclight/forge_app.py b/extensions-builtin/forge_space_iclight/forge_app.py new file mode 100644 index 0000000000000000000000000000000000000000..abf0dae02016753758928e3c0dad11c40351210e --- /dev/null +++ b/extensions-builtin/forge_space_iclight/forge_app.py @@ -0,0 +1,464 @@ +import spaces +import math +import os +import gradio as gr +import numpy as np +import torch +import safetensors.torch as sf +import db_examples + +from PIL import Image +from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline +from diffusers import AutoencoderKL, UNet2DConditionModel, DDIMScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler +from diffusers.models.attention_processor import AttnProcessor2_0 +from transformers import CLIPTextModel, CLIPTokenizer +from briarmbg import BriaRMBG +from enum import Enum +# from torch.hub import download_url_to_file + + +with spaces.capture_gpu_object() as gpu_object: + # 'stablediffusionapi/realistic-vision-v51' + # 'runwayml/stable-diffusion-v1-5' + sd15_name = 'stablediffusionapi/realistic-vision-v51' + tokenizer = CLIPTokenizer.from_pretrained(sd15_name, subfolder="tokenizer") + text_encoder = CLIPTextModel.from_pretrained(sd15_name, subfolder="text_encoder") + vae = AutoencoderKL.from_pretrained(sd15_name, subfolder="vae") + unet = UNet2DConditionModel.from_pretrained(sd15_name, subfolder="unet") + rmbg = BriaRMBG.from_pretrained("briaai/RMBG-1.4") + +spaces.automatically_move_to_gpu_when_forward(rmbg) + +# Change UNet + +with torch.no_grad(): + new_conv_in = torch.nn.Conv2d(8, unet.conv_in.out_channels, unet.conv_in.kernel_size, unet.conv_in.stride, unet.conv_in.padding) + new_conv_in.weight.zero_() + new_conv_in.weight[:, :4, :, :].copy_(unet.conv_in.weight) + new_conv_in.bias = unet.conv_in.bias + unet.conv_in = new_conv_in + +unet_original_forward = unet.forward + + +def hooked_unet_forward(sample, timestep, encoder_hidden_states, **kwargs): + c_concat = kwargs['cross_attention_kwargs']['concat_conds'].to(sample) + c_concat = torch.cat([c_concat] * (sample.shape[0] // c_concat.shape[0]), dim=0) + new_sample = torch.cat([sample, c_concat], dim=1) + kwargs['cross_attention_kwargs'] = {} + return unet_original_forward(new_sample, timestep, encoder_hidden_states, **kwargs) + + +unet.forward = hooked_unet_forward + +# Load + +model_path = spaces.convert_root_path() + 'models/iclight_sd15_fc.safetensors' +# download_url_to_file(url='https://huggingface.co/lllyasviel/ic-light/resolve/main/iclight_sd15_fc.safetensors', dst=model_path) +sd_offset = sf.load_file(model_path) +sd_origin = unet.state_dict() +keys = sd_origin.keys() +sd_merged = {k: sd_origin[k] + sd_offset[k] for k in sd_origin.keys()} +unet.load_state_dict(sd_merged, strict=True) +del sd_offset, sd_origin, sd_merged, keys + +# Device + +device = spaces.cpu +text_encoder = text_encoder.to(device=device, dtype=torch.float16) +vae = vae.to(device=device, dtype=torch.bfloat16) +unet = unet.to(device=device, dtype=torch.float16) +rmbg = rmbg.to(device=device, dtype=torch.float32) +device = spaces.gpu + +# SDP + +unet.set_attn_processor(AttnProcessor2_0()) +vae.set_attn_processor(AttnProcessor2_0()) + +# Samplers + +ddim_scheduler = DDIMScheduler( + num_train_timesteps=1000, + beta_start=0.00085, + beta_end=0.012, + beta_schedule="scaled_linear", + clip_sample=False, + set_alpha_to_one=False, + steps_offset=1, +) + +euler_a_scheduler = EulerAncestralDiscreteScheduler( + num_train_timesteps=1000, + beta_start=0.00085, + beta_end=0.012, + steps_offset=1 +) + +dpmpp_2m_sde_karras_scheduler = DPMSolverMultistepScheduler( + num_train_timesteps=1000, + beta_start=0.00085, + beta_end=0.012, + algorithm_type="sde-dpmsolver++", + use_karras_sigmas=True, + steps_offset=1 +) + +# Pipelines + +t2i_pipe = StableDiffusionPipeline( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + unet=unet, + scheduler=dpmpp_2m_sde_karras_scheduler, + safety_checker=None, + requires_safety_checker=False, + feature_extractor=None, + image_encoder=None +) + +i2i_pipe = StableDiffusionImg2ImgPipeline( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + unet=unet, + scheduler=dpmpp_2m_sde_karras_scheduler, + safety_checker=None, + requires_safety_checker=False, + feature_extractor=None, + image_encoder=None +) + +spaces.automatically_move_pipeline_components(t2i_pipe) + + +def overwrite_components(components): + global tokenizer, text_encoder, vae, unet, t2i_pipe, i2i_pipe + tokenizer, text_encoder, vae, unet, t2i_pipe, i2i_pipe = components + + +@torch.inference_mode() +def encode_prompt_inner(txt: str): + max_length = tokenizer.model_max_length + chunk_length = tokenizer.model_max_length - 2 + id_start = tokenizer.bos_token_id + id_end = tokenizer.eos_token_id + id_pad = id_end + + def pad(x, p, i): + return x[:i] if len(x) >= i else x + [p] * (i - len(x)) + + tokens = tokenizer(txt, truncation=False, add_special_tokens=False)["input_ids"] + chunks = [[id_start] + tokens[i: i + chunk_length] + [id_end] for i in range(0, len(tokens), chunk_length)] + chunks = [pad(ck, id_pad, max_length) for ck in chunks] + + token_ids = torch.tensor(chunks).to(device=device, dtype=torch.int64) + conds = text_encoder(token_ids).last_hidden_state + + return conds + + +@torch.inference_mode() +def encode_prompt_pair(positive_prompt, negative_prompt): + c = encode_prompt_inner(positive_prompt) + uc = encode_prompt_inner(negative_prompt) + + c_len = float(len(c)) + uc_len = float(len(uc)) + max_count = max(c_len, uc_len) + c_repeat = int(math.ceil(max_count / c_len)) + uc_repeat = int(math.ceil(max_count / uc_len)) + max_chunk = max(len(c), len(uc)) + + c = torch.cat([c] * c_repeat, dim=0)[:max_chunk] + uc = torch.cat([uc] * uc_repeat, dim=0)[:max_chunk] + + c = torch.cat([p[None, ...] for p in c], dim=1) + uc = torch.cat([p[None, ...] for p in uc], dim=1) + + return c, uc + + +@torch.inference_mode() +def pytorch2numpy(imgs, quant=True): + results = [] + for x in imgs: + y = x.movedim(0, -1) + + if quant: + y = y * 127.5 + 127.5 + y = y.detach().float().cpu().numpy().clip(0, 255).astype(np.uint8) + else: + y = y * 0.5 + 0.5 + y = y.detach().float().cpu().numpy().clip(0, 1).astype(np.float32) + + results.append(y) + return results + + +@torch.inference_mode() +def numpy2pytorch(imgs): + h = torch.from_numpy(np.stack(imgs, axis=0)).float() / 127.0 - 1.0 # so that 127 must be strictly 0.0 + h = h.movedim(-1, 1) + return h + + +def resize_and_center_crop(image, target_width, target_height): + pil_image = Image.fromarray(image) + original_width, original_height = pil_image.size + scale_factor = max(target_width / original_width, target_height / original_height) + resized_width = int(round(original_width * scale_factor)) + resized_height = int(round(original_height * scale_factor)) + resized_image = pil_image.resize((resized_width, resized_height), Image.LANCZOS) + left = (resized_width - target_width) / 2 + top = (resized_height - target_height) / 2 + right = (resized_width + target_width) / 2 + bottom = (resized_height + target_height) / 2 + cropped_image = resized_image.crop((left, top, right, bottom)) + return np.array(cropped_image) + + +def resize_without_crop(image, target_width, target_height): + pil_image = Image.fromarray(image) + resized_image = pil_image.resize((target_width, target_height), Image.LANCZOS) + return np.array(resized_image) + + +@torch.inference_mode() +def run_rmbg(img, sigma=0.0): + H, W, C = img.shape + assert C == 3 + k = (256.0 / float(H * W)) ** 0.5 + feed = resize_without_crop(img, int(64 * round(W * k)), int(64 * round(H * k))) + feed = numpy2pytorch([feed]).to(device=device, dtype=torch.float32) + alpha = rmbg(feed)[0][0] + alpha = torch.nn.functional.interpolate(alpha, size=(H, W), mode="bilinear") + alpha = alpha.movedim(1, -1)[0] + alpha = alpha.detach().float().cpu().numpy().clip(0, 1) + result = 127 + (img.astype(np.float32) - 127 + sigma) * alpha + return result.clip(0, 255).astype(np.uint8), alpha + + +external_processor = None + + +@torch.inference_mode() +def process(input_fg, prompt, image_width, image_height, num_samples, seed, steps, a_prompt, n_prompt, cfg, highres_scale, highres_denoise, lowres_denoise, bg_source): + if external_processor is not None: + return external_processor(input_fg, prompt, image_width, image_height, num_samples, seed, steps, a_prompt, n_prompt, cfg, highres_scale, highres_denoise, lowres_denoise, bg_source) + + bg_source = BGSource(bg_source) + input_bg = None + + if bg_source == BGSource.NONE: + pass + elif bg_source == BGSource.LEFT: + gradient = np.linspace(255, 0, image_width) + image = np.tile(gradient, (image_height, 1)) + input_bg = np.stack((image,) * 3, axis=-1).astype(np.uint8) + elif bg_source == BGSource.RIGHT: + gradient = np.linspace(0, 255, image_width) + image = np.tile(gradient, (image_height, 1)) + input_bg = np.stack((image,) * 3, axis=-1).astype(np.uint8) + elif bg_source == BGSource.TOP: + gradient = np.linspace(255, 0, image_height)[:, None] + image = np.tile(gradient, (1, image_width)) + input_bg = np.stack((image,) * 3, axis=-1).astype(np.uint8) + elif bg_source == BGSource.BOTTOM: + gradient = np.linspace(0, 255, image_height)[:, None] + image = np.tile(gradient, (1, image_width)) + input_bg = np.stack((image,) * 3, axis=-1).astype(np.uint8) + else: + raise 'Wrong initial latent!' + + rng = torch.Generator(device=device).manual_seed(int(seed)) + + fg = resize_and_center_crop(input_fg, image_width, image_height) + + concat_conds = numpy2pytorch([fg]).to(device=vae.device, dtype=vae.dtype) + concat_conds = vae.encode(concat_conds).latent_dist.mode() * vae.config.scaling_factor + + conds, unconds = encode_prompt_pair(positive_prompt=prompt + ', ' + a_prompt, negative_prompt=n_prompt) + + if input_bg is None: + latents = t2i_pipe( + prompt_embeds=conds, + negative_prompt_embeds=unconds, + width=image_width, + height=image_height, + num_inference_steps=steps, + num_images_per_prompt=num_samples, + generator=rng, + output_type='latent', + guidance_scale=cfg, + cross_attention_kwargs={'concat_conds': concat_conds}, + ).images.to(vae.dtype) / vae.config.scaling_factor + else: + bg = resize_and_center_crop(input_bg, image_width, image_height) + bg_latent = numpy2pytorch([bg]).to(device=vae.device, dtype=vae.dtype) + bg_latent = vae.encode(bg_latent).latent_dist.mode() * vae.config.scaling_factor + latents = i2i_pipe( + image=bg_latent, + strength=lowres_denoise, + prompt_embeds=conds, + negative_prompt_embeds=unconds, + width=image_width, + height=image_height, + num_inference_steps=int(round(steps / lowres_denoise)), + num_images_per_prompt=num_samples, + generator=rng, + output_type='latent', + guidance_scale=cfg, + cross_attention_kwargs={'concat_conds': concat_conds}, + ).images.to(vae.dtype) / vae.config.scaling_factor + + pixels = vae.decode(latents).sample + pixels = pytorch2numpy(pixels) + pixels = [resize_without_crop( + image=p, + target_width=int(round(image_width * highres_scale / 64.0) * 64), + target_height=int(round(image_height * highres_scale / 64.0) * 64)) + for p in pixels] + + pixels = numpy2pytorch(pixels).to(device=vae.device, dtype=vae.dtype) + latents = vae.encode(pixels).latent_dist.mode() * vae.config.scaling_factor + latents = latents.to(device=unet.device, dtype=unet.dtype) + + image_height, image_width = latents.shape[2] * 8, latents.shape[3] * 8 + + fg = resize_and_center_crop(input_fg, image_width, image_height) + concat_conds = numpy2pytorch([fg]).to(device=vae.device, dtype=vae.dtype) + concat_conds = vae.encode(concat_conds).latent_dist.mode() * vae.config.scaling_factor + + latents = i2i_pipe( + image=latents, + strength=highres_denoise, + prompt_embeds=conds, + negative_prompt_embeds=unconds, + width=image_width, + height=image_height, + num_inference_steps=int(round(steps / highres_denoise)), + num_images_per_prompt=num_samples, + generator=rng, + output_type='latent', + guidance_scale=cfg, + cross_attention_kwargs={'concat_conds': concat_conds}, + ).images.to(vae.dtype) / vae.config.scaling_factor + + pixels = vae.decode(latents).sample + + return pytorch2numpy(pixels) + + +@spaces.GPU(gpu_objects=[gpu_object], manual_load=True) +@torch.inference_mode() +def process_relight(input_fg, prompt, image_width, image_height, num_samples, seed, steps, a_prompt, n_prompt, cfg, highres_scale, highres_denoise, lowres_denoise, bg_source): + input_fg, matting = run_rmbg(input_fg) + results = process(input_fg, prompt, image_width, image_height, num_samples, seed, steps, a_prompt, n_prompt, cfg, highres_scale, highres_denoise, lowres_denoise, bg_source) + return input_fg, results + + +quick_prompts = [ + 'sunshine from window', + 'neon light, city', + 'sunset over sea', + 'golden time', + 'sci-fi RGB glowing, cyberpunk', + 'natural lighting', + 'warm atmosphere, at home, bedroom', + 'magic lit', + 'evil, gothic, Yharnam', + 'light and shadow', + 'shadow from window', + 'soft studio lighting', + 'home atmosphere, cozy bedroom illumination', + 'neon, Wong Kar-wai, warm' +] +quick_prompts = [[x] for x in quick_prompts] + + +quick_subjects = [ + 'beautiful woman, detailed face', + 'handsome man, detailed face', +] +quick_subjects = [[x] for x in quick_subjects] + + +class BGSource(Enum): + NONE = "None" + LEFT = "Left Light" + RIGHT = "Right Light" + TOP = "Top Light" + BOTTOM = "Bottom Light" + + +block = gr.Blocks().queue() +with block: + with gr.Row(): + gr.Markdown("## IC-Light (Relighting with Foreground Condition)") + with gr.Row(): + gr.Markdown("See also https://github.com/lllyasviel/IC-Light for background-conditioned model and normal estimation") + with gr.Row(): + with gr.Column(): + with gr.Row(): + input_fg = gr.Image(sources='upload', type="numpy", label="Image", height=480) + output_bg = gr.Image(type="numpy", label="Preprocessed Foreground", height=480) + prompt = gr.Textbox(label="Prompt") + bg_source = gr.Radio(choices=[e.value for e in BGSource], + value=BGSource.NONE.value, + label="Lighting Preference (Initial Latent)", type='value') + example_quick_subjects = gr.Dataset(samples=quick_subjects, label='Subject Quick List', samples_per_page=1000, components=[prompt]) + example_quick_prompts = gr.Dataset(samples=quick_prompts, label='Lighting Quick List', samples_per_page=1000, components=[prompt]) + relight_button = gr.Button(value="Relight") + + with gr.Group(): + with gr.Row(): + num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1) + seed = gr.Number(label="Seed", value=12345, precision=0) + + with gr.Row(): + image_width = gr.Slider(label="Image Width", minimum=256, maximum=1024, value=512, step=64) + image_height = gr.Slider(label="Image Height", minimum=256, maximum=1024, value=640, step=64) + + with gr.Accordion("Advanced options", open=False): + steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=25, step=1) + cfg = gr.Slider(label="CFG Scale", minimum=1.0, maximum=32.0, value=2, step=0.01) + lowres_denoise = gr.Slider(label="Lowres Denoise (for initial latent)", minimum=0.1, maximum=1.0, value=0.9, step=0.01) + highres_scale = gr.Slider(label="Highres Scale", minimum=1.0, maximum=3.0, value=1.5, step=0.01) + highres_denoise = gr.Slider(label="Highres Denoise", minimum=0.1, maximum=1.0, value=0.5, step=0.01) + a_prompt = gr.Textbox(label="Added Prompt", value='best quality') + n_prompt = gr.Textbox(label="Negative Prompt", value='lowres, bad anatomy, bad hands, cropped, worst quality') + with gr.Column(): + result_gallery = gr.Gallery(height=832, object_fit='contain', label='Outputs') + with gr.Row(): + dummy_image_for_outputs = gr.Image(visible=False, label='Result') + + examples = [] + + for ex in db_examples.foreground_conditioned_examples: + ex[0] = spaces.convert_root_path() + ex[0] + ex[-1] = spaces.convert_root_path() + ex[-1] + examples.append(ex) + + + gr.Examples( + fn=lambda *args: [[args[-1]], "imgs/dummy.png"], + examples=examples, + inputs=[ + input_fg, prompt, bg_source, image_width, image_height, seed, dummy_image_for_outputs + ], + outputs=[result_gallery, output_bg], + run_on_click=True, examples_per_page=1024 + ) + ips = [input_fg, prompt, image_width, image_height, num_samples, seed, steps, a_prompt, n_prompt, cfg, highres_scale, highres_denoise, lowres_denoise, bg_source] + relight_button.click(fn=process_relight, inputs=ips, outputs=[output_bg, result_gallery]) + example_quick_prompts.click(lambda x, y: ', '.join(y.split(', ')[:2] + [x[0]]), inputs=[example_quick_prompts, prompt], outputs=prompt, show_progress=False, queue=False) + example_quick_subjects.click(lambda x: x[0], inputs=example_quick_subjects, outputs=prompt, show_progress=False, queue=False) + + +demo = block + + +if __name__ == "__main__": + demo.launch() diff --git a/extensions-builtin/forge_space_iclight/space_meta.json b/extensions-builtin/forge_space_iclight/space_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..6bdf9dbe2c41661da1e185d30f89862971d9a129 --- /dev/null +++ b/extensions-builtin/forge_space_iclight/space_meta.json @@ -0,0 +1,6 @@ +{ + "tag": "Image Processing: Illumination, Shading, and Relighting", + "title": "IC-Light: Imposing Consistent Light (Foreground Model)", + "repo_id": "lllyasviel/IC-Light", + "revision": "3072485a2b69261ab332fdf2e255d0eca35b323b" +} diff --git a/extensions-builtin/forge_space_idm_vton/forge_app.py b/extensions-builtin/forge_space_idm_vton/forge_app.py new file mode 100644 index 0000000000000000000000000000000000000000..1d982a82c50a21f4047d24c70e612acc4abc1693 --- /dev/null +++ b/extensions-builtin/forge_space_idm_vton/forge_app.py @@ -0,0 +1,324 @@ +import spaces +import contextlib + +import gradio as gr +from PIL import Image +from src.tryon_pipeline import StableDiffusionXLInpaintPipeline as TryonPipeline +from src.unet_hacked_garmnet import UNet2DConditionModel as UNet2DConditionModel_ref +from src.unet_hacked_tryon import UNet2DConditionModel +from transformers import ( + CLIPImageProcessor, + CLIPVisionModelWithProjection, + CLIPTextModel, + CLIPTextModelWithProjection, +) +from diffusers import DDPMScheduler, AutoencoderKL +from typing import List + +import torch +import os +from transformers import AutoTokenizer +import numpy as np +from utils_mask import get_mask_location +from torchvision import transforms +import apply_net +from preprocess.humanparsing.run_parsing import Parsing +from preprocess.openpose.run_openpose import OpenPose +from detectron2.data.detection_utils import convert_PIL_to_numpy, _apply_exif_orientation +from torchvision.transforms.functional import to_pil_image + + +def pil_to_binary_mask(pil_image, threshold=0): + np_image = np.array(pil_image) + grayscale_image = Image.fromarray(np_image).convert("L") + binary_mask = np.array(grayscale_image) > threshold + mask = np.zeros(binary_mask.shape, dtype=np.uint8) + for i in range(binary_mask.shape[0]): + for j in range(binary_mask.shape[1]): + if binary_mask[i, j] == True: + mask[i, j] = 1 + mask = (mask * 255).astype(np.uint8) + output_mask = Image.fromarray(mask) + return output_mask + + +base_path = 'yisol/IDM-VTON' +example_path = os.path.join(spaces.convert_root_path(), 'example') + + +with spaces.capture_gpu_object() as GO: + unet = UNet2DConditionModel.from_pretrained( + base_path, + subfolder="unet", + torch_dtype=torch.float16, + ) + unet.requires_grad_(False) + tokenizer_one = AutoTokenizer.from_pretrained( + base_path, + subfolder="tokenizer", + revision=None, + use_fast=False, + ) + tokenizer_two = AutoTokenizer.from_pretrained( + base_path, + subfolder="tokenizer_2", + revision=None, + use_fast=False, + ) + noise_scheduler = DDPMScheduler.from_pretrained(base_path, subfolder="scheduler") + + text_encoder_one = CLIPTextModel.from_pretrained( + base_path, + subfolder="text_encoder", + torch_dtype=torch.float16, + ) + text_encoder_two = CLIPTextModelWithProjection.from_pretrained( + base_path, + subfolder="text_encoder_2", + torch_dtype=torch.float16, + ) + image_encoder = CLIPVisionModelWithProjection.from_pretrained( + base_path, + subfolder="image_encoder", + torch_dtype=torch.float16, + ) + vae = AutoencoderKL.from_pretrained(base_path, + subfolder="vae", + torch_dtype=torch.float16, + ) + + # "stabilityai/stable-diffusion-xl-base-1.0", + UNet_Encoder = UNet2DConditionModel_ref.from_pretrained( + base_path, + subfolder="unet_encoder", + torch_dtype=torch.float16, + ) + + parsing_model = Parsing(0) + openpose_model = OpenPose(0) + + UNet_Encoder.requires_grad_(False) + image_encoder.requires_grad_(False) + vae.requires_grad_(False) + unet.requires_grad_(False) + text_encoder_one.requires_grad_(False) + text_encoder_two.requires_grad_(False) + tensor_transfrom = transforms.Compose( + [ + transforms.ToTensor(), + transforms.Normalize([0.5], [0.5]), + ] + ) + + pipe = TryonPipeline.from_pretrained( + base_path, + unet=unet, + vae=vae, + feature_extractor=CLIPImageProcessor(), + text_encoder=text_encoder_one, + text_encoder_2=text_encoder_two, + tokenizer=tokenizer_one, + tokenizer_2=tokenizer_two, + scheduler=noise_scheduler, + image_encoder=image_encoder, + torch_dtype=torch.float16, + ) + pipe.unet_encoder = UNet_Encoder + +unet_joint = torch.nn.ModuleList([ + unet, UNet_Encoder +]) + + +spaces.automatically_move_to_gpu_when_forward(unet, target_model=unet_joint) +spaces.automatically_move_to_gpu_when_forward(UNet_Encoder, target_model=unet_joint) +spaces.automatically_move_to_gpu_when_forward(unet.encoder_hid_proj) + +spaces.automatically_move_pipeline_components(pipe=pipe) + +spaces.automatically_move_to_gpu_when_forward(openpose_model.preprocessor.body_estimation.model) +spaces.change_attention_from_diffusers_to_forge(unet) +spaces.change_attention_from_diffusers_to_forge(vae) +spaces.change_attention_from_diffusers_to_forge(UNet_Encoder) + + +@spaces.GPU(gpu_objects=GO, manual_load=True) +def start_tryon(dict, garm_img, garment_des, is_checked, is_checked_crop, denoise_steps, seed, progress=gr.Progress(track_tqdm=True)): + device = spaces.gpu + + # openpose_model.preprocessor.body_estimation.model.to(device) + # pipe.to(device) + # pipe.unet_encoder.to(device) + + garm_img = garm_img.convert("RGB").resize((768, 1024)) + human_img_orig = dict["background"].convert("RGB") + + if is_checked_crop: + width, height = human_img_orig.size + target_width = int(min(width, height * (3 / 4))) + target_height = int(min(height, width * (4 / 3))) + left = (width - target_width) / 2 + top = (height - target_height) / 2 + right = (width + target_width) / 2 + bottom = (height + target_height) / 2 + cropped_img = human_img_orig.crop((left, top, right, bottom)) + crop_size = cropped_img.size + human_img = cropped_img.resize((768, 1024)) + else: + human_img = human_img_orig.resize((768, 1024)) + + if is_checked: + keypoints = openpose_model(human_img.resize((384, 512))) + model_parse, _ = parsing_model(human_img.resize((384, 512))) + mask, mask_gray = get_mask_location('hd', "upper_body", model_parse, keypoints) + mask = mask.resize((768, 1024)) + else: + mask = pil_to_binary_mask(dict['layers'][0].convert("RGB").resize((768, 1024))) + # mask = transforms.ToTensor()(mask) + # mask = mask.unsqueeze(0) + mask_gray = (1 - transforms.ToTensor()(mask)) * tensor_transfrom(human_img) + mask_gray = to_pil_image((mask_gray + 1.0) / 2.0) + + human_img_arg = _apply_exif_orientation(human_img.resize((384, 512))) + human_img_arg = convert_PIL_to_numpy(human_img_arg, format="BGR") + + args = apply_net.create_argument_parser().parse_args(('show', spaces.convert_root_path() + 'configs/densepose_rcnn_R_50_FPN_s1x.yaml', spaces.convert_root_path() + 'ckpt/densepose/model_final_162be9.pkl', 'dp_segm', '-v', '--opts', 'MODEL.DEVICE', 'cuda')) + # verbosity = getattr(args, "verbosity", None) + pose_img = args.func(args, human_img_arg) + pose_img = pose_img[:, :, ::-1] + pose_img = Image.fromarray(pose_img).resize((768, 1024)) + + with torch.no_grad(): + # Extract the images + with torch.cuda.amp.autocast(): + with torch.no_grad(): + prompt = "model is wearing " + garment_des + negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality" + with torch.inference_mode(): + ( + prompt_embeds, + negative_prompt_embeds, + pooled_prompt_embeds, + negative_pooled_prompt_embeds, + ) = pipe.encode_prompt( + prompt, + num_images_per_prompt=1, + do_classifier_free_guidance=True, + negative_prompt=negative_prompt, + ) + + prompt = "a photo of " + garment_des + negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality" + if not isinstance(prompt, List): + prompt = [prompt] * 1 + if not isinstance(negative_prompt, List): + negative_prompt = [negative_prompt] * 1 + with torch.inference_mode(): + ( + prompt_embeds_c, + _, + _, + _, + ) = pipe.encode_prompt( + prompt, + num_images_per_prompt=1, + do_classifier_free_guidance=False, + negative_prompt=negative_prompt, + ) + + pose_img = tensor_transfrom(pose_img).unsqueeze(0).to(device, torch.float16) + garm_tensor = tensor_transfrom(garm_img).unsqueeze(0).to(device, torch.float16) + generator = torch.Generator(device).manual_seed(seed) if seed is not None else None + images = pipe( + prompt_embeds=prompt_embeds.to(device, torch.float16), + negative_prompt_embeds=negative_prompt_embeds.to(device, torch.float16), + pooled_prompt_embeds=pooled_prompt_embeds.to(device, torch.float16), + negative_pooled_prompt_embeds=negative_pooled_prompt_embeds.to(device, torch.float16), + num_inference_steps=denoise_steps, + generator=generator, + strength=1.0, + pose_img=pose_img.to(device, torch.float16), + text_embeds_cloth=prompt_embeds_c.to(device, torch.float16), + cloth=garm_tensor.to(device, torch.float16), + mask_image=mask, + image=human_img, + height=1024, + width=768, + ip_adapter_image=garm_img.resize((768, 1024)), + guidance_scale=2.0, + )[0] + + if is_checked_crop: + out_img = images[0].resize(crop_size) + human_img_orig.paste(out_img, (int(left), int(top))) + return human_img_orig, mask_gray + else: + return images[0], mask_gray + # return images[0], mask_gray + + +garm_list = os.listdir(os.path.join(example_path, "cloth")) +garm_list_path = [os.path.join(example_path, "cloth", garm) for garm in garm_list] + +human_list = os.listdir(os.path.join(example_path, "human")) +human_list_path = [os.path.join(example_path, "human", human) for human in human_list] + +human_ex_list = [] +for ex_human in human_list_path: + ex_dict = {} + ex_dict['background'] = ex_human + ex_dict['layers'] = None + ex_dict['composite'] = None + human_ex_list.append(ex_dict) + +##default human + + +image_blocks = gr.Blocks().queue() +with image_blocks as demo: + gr.Markdown("## IDM-VTON 👕👔👚") + gr.Markdown("Virtual Try-on with your image and garment image. Check out the [source codes](https://github.com/yisol/IDM-VTON) and the [model](https://huggingface.co/yisol/IDM-VTON)") + with gr.Row(): + with gr.Column(): + imgs = gr.ImageEditor(sources='upload', type="pil", label='Human. Mask with pen or use auto-masking', interactive=True) + with gr.Row(): + is_checked = gr.Checkbox(label="Yes", info="Use auto-generated mask (Takes 5 seconds)", value=True) + with gr.Row(): + is_checked_crop = gr.Checkbox(label="Yes", info="Use auto-crop & resizing", value=False) + + example = gr.Examples( + inputs=imgs, + examples_per_page=10, + examples=human_ex_list + ) + + with gr.Column(): + garm_img = gr.Image(label="Garment", sources='upload', type="pil") + with gr.Row(elem_id="prompt-container"): + with gr.Row(): + prompt = gr.Textbox(placeholder="Description of garment ex) Short Sleeve Round Neck T-shirts", show_label=False, elem_id="prompt") + example = gr.Examples( + inputs=garm_img, + examples_per_page=8, + examples=garm_list_path) + with gr.Column(): + # image_out = gr.Image(label="Output", elem_id="output-img", height=400) + masked_img = gr.Image(label="Masked image output", elem_id="masked-img", show_share_button=False) + with gr.Column(): + # image_out = gr.Image(label="Output", elem_id="output-img", height=400) + image_out = gr.Image(label="Output", elem_id="output-img", show_share_button=False) + + with gr.Column(): + try_button = gr.Button(value="Try-on") + with gr.Accordion(label="Advanced Settings", open=False): + with gr.Row(): + denoise_steps = gr.Number(label="Denoising Steps", minimum=20, maximum=40, value=30, step=1) + seed = gr.Number(label="Seed", minimum=-1, maximum=2147483647, step=1, value=42) + + try_button.click(fn=start_tryon, inputs=[imgs, garm_img, prompt, is_checked, is_checked_crop, denoise_steps, seed], outputs=[image_out, masked_img], api_name='tryon') + + +demo = image_blocks + +if __name__ == "__main__": + demo.launch() diff --git a/extensions-builtin/forge_space_idm_vton/requirements.txt b/extensions-builtin/forge_space_idm_vton/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..6cc92adb731265b0c6c51962660e2976d128afbd --- /dev/null +++ b/extensions-builtin/forge_space_idm_vton/requirements.txt @@ -0,0 +1,7 @@ +basicsr +fvcore +cloudpickle +omegaconf +pycocotools +config==0.5.1 +av diff --git a/extensions-builtin/forge_space_idm_vton/space_meta.json b/extensions-builtin/forge_space_idm_vton/space_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..172fff3b9b0cb1585fa830243b14636b7704d636 --- /dev/null +++ b/extensions-builtin/forge_space_idm_vton/space_meta.json @@ -0,0 +1,6 @@ +{ + "tag": "General Image Processing and Applications", + "title": "IDM-VTON: Virtual Try-on with your image and garment image", + "repo_id": "yisol/IDM-VTON", + "revision": "810e5908d53e4023f3dade2b8ebf10e3ae995be1" +} diff --git a/extensions-builtin/forge_space_idm_vton/src/attentionhacked_garmnet.py b/extensions-builtin/forge_space_idm_vton/src/attentionhacked_garmnet.py new file mode 100644 index 0000000000000000000000000000000000000000..66885c4778c01ae34512c752a05b537577defaec --- /dev/null +++ b/extensions-builtin/forge_space_idm_vton/src/attentionhacked_garmnet.py @@ -0,0 +1,670 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Dict, Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from diffusers.utils import USE_PEFT_BACKEND +from diffusers.utils.torch_utils import maybe_allow_in_graph +from diffusers.models.activations import GEGLU, GELU, ApproximateGELU +from diffusers.models.attention_processor import Attention +from diffusers.models.embeddings import SinusoidalPositionalEmbedding +from diffusers.models.lora import LoRACompatibleLinear +from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm + + +def _chunked_feed_forward( + ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int, lora_scale: Optional[float] = None +): + # "feed_forward_chunk_size" can be used to save memory + if hidden_states.shape[chunk_dim] % chunk_size != 0: + raise ValueError( + f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`." + ) + + num_chunks = hidden_states.shape[chunk_dim] // chunk_size + if lora_scale is None: + ff_output = torch.cat( + [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)], + dim=chunk_dim, + ) + else: + # TOOD(Patrick): LoRA scale can be removed once PEFT refactor is complete + ff_output = torch.cat( + [ff(hid_slice, scale=lora_scale) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)], + dim=chunk_dim, + ) + + return ff_output + + +@maybe_allow_in_graph +class GatedSelfAttentionDense(nn.Module): + r""" + A gated self-attention dense layer that combines visual features and object features. + + Parameters: + query_dim (`int`): The number of channels in the query. + context_dim (`int`): The number of channels in the context. + n_heads (`int`): The number of heads to use for attention. + d_head (`int`): The number of channels in each head. + """ + + def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int): + super().__init__() + + # we need a linear projection since we need cat visual feature and obj feature + self.linear = nn.Linear(context_dim, query_dim) + + self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head) + self.ff = FeedForward(query_dim, activation_fn="geglu") + + self.norm1 = nn.LayerNorm(query_dim) + self.norm2 = nn.LayerNorm(query_dim) + + self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0))) + self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0))) + + self.enabled = True + + def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor: + if not self.enabled: + return x + + n_visual = x.shape[1] + objs = self.linear(objs) + + x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :] + x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x)) + + return x + + +@maybe_allow_in_graph +class BasicTransformerBlock(nn.Module): + r""" + A basic Transformer block. + + Parameters: + dim (`int`): The number of channels in the input and output. + num_attention_heads (`int`): The number of heads to use for multi-head attention. + attention_head_dim (`int`): The number of channels in each head. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention. + activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward. + num_embeds_ada_norm (: + obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`. + attention_bias (: + obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter. + only_cross_attention (`bool`, *optional*): + Whether to use only cross-attention layers. In this case two cross attention layers are used. + double_self_attention (`bool`, *optional*): + Whether to use two self-attention layers. In this case no cross attention layers are used. + upcast_attention (`bool`, *optional*): + Whether to upcast the attention computation to float32. This is useful for mixed precision training. + norm_elementwise_affine (`bool`, *optional*, defaults to `True`): + Whether to use learnable elementwise affine parameters for normalization. + norm_type (`str`, *optional*, defaults to `"layer_norm"`): + The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`. + final_dropout (`bool` *optional*, defaults to False): + Whether to apply a final dropout after the last feed-forward layer. + attention_type (`str`, *optional*, defaults to `"default"`): + The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`. + positional_embeddings (`str`, *optional*, defaults to `None`): + The type of positional embeddings to apply to. + num_positional_embeddings (`int`, *optional*, defaults to `None`): + The maximum number of positional embeddings to apply. + """ + + def __init__( + self, + dim: int, + num_attention_heads: int, + attention_head_dim: int, + dropout=0.0, + cross_attention_dim: Optional[int] = None, + activation_fn: str = "geglu", + num_embeds_ada_norm: Optional[int] = None, + attention_bias: bool = False, + only_cross_attention: bool = False, + double_self_attention: bool = False, + upcast_attention: bool = False, + norm_elementwise_affine: bool = True, + norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single' + norm_eps: float = 1e-5, + final_dropout: bool = False, + attention_type: str = "default", + positional_embeddings: Optional[str] = None, + num_positional_embeddings: Optional[int] = None, + ada_norm_continous_conditioning_embedding_dim: Optional[int] = None, + ada_norm_bias: Optional[int] = None, + ff_inner_dim: Optional[int] = None, + ff_bias: bool = True, + attention_out_bias: bool = True, + ): + super().__init__() + self.only_cross_attention = only_cross_attention + + self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero" + self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm" + self.use_ada_layer_norm_single = norm_type == "ada_norm_single" + self.use_layer_norm = norm_type == "layer_norm" + self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous" + + if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: + raise ValueError( + f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to" + f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}." + ) + + if positional_embeddings and (num_positional_embeddings is None): + raise ValueError( + "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined." + ) + + if positional_embeddings == "sinusoidal": + self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings) + else: + self.pos_embed = None + + # Define 3 blocks. Each block has its own normalization layer. + # 1. Self-Attn + if self.use_ada_layer_norm: + self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm) + elif self.use_ada_layer_norm_zero: + self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm) + elif self.use_ada_layer_norm_continuous: + self.norm1 = AdaLayerNormContinuous( + dim, + ada_norm_continous_conditioning_embedding_dim, + norm_elementwise_affine, + norm_eps, + ada_norm_bias, + "rms_norm", + ) + else: + self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps) + + self.attn1 = Attention( + query_dim=dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + cross_attention_dim=cross_attention_dim if only_cross_attention else None, + upcast_attention=upcast_attention, + out_bias=attention_out_bias, + ) + + # 2. Cross-Attn + if cross_attention_dim is not None or double_self_attention: + # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. + # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during + # the second cross attention block. + if self.use_ada_layer_norm: + self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm) + elif self.use_ada_layer_norm_continuous: + self.norm2 = AdaLayerNormContinuous( + dim, + ada_norm_continous_conditioning_embedding_dim, + norm_elementwise_affine, + norm_eps, + ada_norm_bias, + "rms_norm", + ) + else: + self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine) + + self.attn2 = Attention( + query_dim=dim, + cross_attention_dim=cross_attention_dim if not double_self_attention else None, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + upcast_attention=upcast_attention, + out_bias=attention_out_bias, + ) # is self-attn if encoder_hidden_states is none + else: + self.norm2 = None + self.attn2 = None + + # 3. Feed-forward + if self.use_ada_layer_norm_continuous: + self.norm3 = AdaLayerNormContinuous( + dim, + ada_norm_continous_conditioning_embedding_dim, + norm_elementwise_affine, + norm_eps, + ada_norm_bias, + "layer_norm", + ) + elif not self.use_ada_layer_norm_single: + self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine) + + self.ff = FeedForward( + dim, + dropout=dropout, + activation_fn=activation_fn, + final_dropout=final_dropout, + inner_dim=ff_inner_dim, + bias=ff_bias, + ) + + # 4. Fuser + if attention_type == "gated" or attention_type == "gated-text-image": + self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim) + + # 5. Scale-shift for PixArt-Alpha. + if self.use_ada_layer_norm_single: + self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5) + + # let chunk size default to None + self._chunk_size = None + self._chunk_dim = 0 + + def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0): + # Sets chunk feed-forward + self._chunk_size = chunk_size + self._chunk_dim = dim + + def forward( + self, + hidden_states: torch.FloatTensor, + attention_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + timestep: Optional[torch.LongTensor] = None, + cross_attention_kwargs: Dict[str, Any] = None, + class_labels: Optional[torch.LongTensor] = None, + added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None, + ) -> torch.FloatTensor: + # Notice that normalization is always applied before the real computation in the following blocks. + # 0. Self-Attention + batch_size = hidden_states.shape[0] + if self.use_ada_layer_norm: + norm_hidden_states = self.norm1(hidden_states, timestep) + elif self.use_ada_layer_norm_zero: + norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1( + hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype + ) + elif self.use_layer_norm: + norm_hidden_states = self.norm1(hidden_states) + elif self.use_ada_layer_norm_continuous: + norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"]) + elif self.use_ada_layer_norm_single: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ( + self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1) + ).chunk(6, dim=1) + norm_hidden_states = self.norm1(hidden_states) + norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa + norm_hidden_states = norm_hidden_states.squeeze(1) + else: + raise ValueError("Incorrect norm used") + + if self.pos_embed is not None: + norm_hidden_states = self.pos_embed(norm_hidden_states) + + garment_features = [] + garment_features.append(norm_hidden_states) + + # 1. Retrieve lora scale. + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + + # 2. Prepare GLIGEN inputs + cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {} + gligen_kwargs = cross_attention_kwargs.pop("gligen", None) + + attn_output = self.attn1( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None, + attention_mask=attention_mask, + **cross_attention_kwargs, + ) + if self.use_ada_layer_norm_zero: + attn_output = gate_msa.unsqueeze(1) * attn_output + elif self.use_ada_layer_norm_single: + attn_output = gate_msa * attn_output + + hidden_states = attn_output + hidden_states + if hidden_states.ndim == 4: + hidden_states = hidden_states.squeeze(1) + + # 2.5 GLIGEN Control + if gligen_kwargs is not None: + hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"]) + + # 3. Cross-Attention + if self.attn2 is not None: + if self.use_ada_layer_norm: + norm_hidden_states = self.norm2(hidden_states, timestep) + elif self.use_ada_layer_norm_zero or self.use_layer_norm: + norm_hidden_states = self.norm2(hidden_states) + elif self.use_ada_layer_norm_single: + # For PixArt norm2 isn't applied here: + # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103 + norm_hidden_states = hidden_states + elif self.use_ada_layer_norm_continuous: + norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"]) + else: + raise ValueError("Incorrect norm") + + if self.pos_embed is not None and self.use_ada_layer_norm_single is False: + norm_hidden_states = self.pos_embed(norm_hidden_states) + + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=encoder_attention_mask, + **cross_attention_kwargs, + ) + hidden_states = attn_output + hidden_states + + # 4. Feed-forward + if self.use_ada_layer_norm_continuous: + norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"]) + elif not self.use_ada_layer_norm_single: + norm_hidden_states = self.norm3(hidden_states) + + if self.use_ada_layer_norm_zero: + norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] + + if self.use_ada_layer_norm_single: + norm_hidden_states = self.norm2(hidden_states) + norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp + + if self._chunk_size is not None: + # "feed_forward_chunk_size" can be used to save memory + ff_output = _chunked_feed_forward( + self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale + ) + else: + ff_output = self.ff(norm_hidden_states, scale=lora_scale) + + if self.use_ada_layer_norm_zero: + ff_output = gate_mlp.unsqueeze(1) * ff_output + elif self.use_ada_layer_norm_single: + ff_output = gate_mlp * ff_output + + hidden_states = ff_output + hidden_states + if hidden_states.ndim == 4: + hidden_states = hidden_states.squeeze(1) + + return hidden_states, garment_features + + +@maybe_allow_in_graph +class TemporalBasicTransformerBlock(nn.Module): + r""" + A basic Transformer block for video like data. + + Parameters: + dim (`int`): The number of channels in the input and output. + time_mix_inner_dim (`int`): The number of channels for temporal attention. + num_attention_heads (`int`): The number of heads to use for multi-head attention. + attention_head_dim (`int`): The number of channels in each head. + cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention. + """ + + def __init__( + self, + dim: int, + time_mix_inner_dim: int, + num_attention_heads: int, + attention_head_dim: int, + cross_attention_dim: Optional[int] = None, + ): + super().__init__() + self.is_res = dim == time_mix_inner_dim + + self.norm_in = nn.LayerNorm(dim) + + # Define 3 blocks. Each block has its own normalization layer. + # 1. Self-Attn + self.norm_in = nn.LayerNorm(dim) + self.ff_in = FeedForward( + dim, + dim_out=time_mix_inner_dim, + activation_fn="geglu", + ) + + self.norm1 = nn.LayerNorm(time_mix_inner_dim) + self.attn1 = Attention( + query_dim=time_mix_inner_dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + cross_attention_dim=None, + ) + + # 2. Cross-Attn + if cross_attention_dim is not None: + # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. + # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during + # the second cross attention block. + self.norm2 = nn.LayerNorm(time_mix_inner_dim) + self.attn2 = Attention( + query_dim=time_mix_inner_dim, + cross_attention_dim=cross_attention_dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + ) # is self-attn if encoder_hidden_states is none + else: + self.norm2 = None + self.attn2 = None + + # 3. Feed-forward + self.norm3 = nn.LayerNorm(time_mix_inner_dim) + self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu") + + # let chunk size default to None + self._chunk_size = None + self._chunk_dim = None + + def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs): + # Sets chunk feed-forward + self._chunk_size = chunk_size + # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off + self._chunk_dim = 1 + + def forward( + self, + hidden_states: torch.FloatTensor, + num_frames: int, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + # Notice that normalization is always applied before the real computation in the following blocks. + # 0. Self-Attention + batch_size = hidden_states.shape[0] + + batch_frames, seq_length, channels = hidden_states.shape + batch_size = batch_frames // num_frames + + hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels) + hidden_states = hidden_states.permute(0, 2, 1, 3) + hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels) + + residual = hidden_states + hidden_states = self.norm_in(hidden_states) + + if self._chunk_size is not None: + hidden_states = _chunked_feed_forward(self.ff_in, hidden_states, self._chunk_dim, self._chunk_size) + else: + hidden_states = self.ff_in(hidden_states) + + if self.is_res: + hidden_states = hidden_states + residual + + norm_hidden_states = self.norm1(hidden_states) + attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None) + hidden_states = attn_output + hidden_states + + # 3. Cross-Attention + if self.attn2 is not None: + norm_hidden_states = self.norm2(hidden_states) + attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states) + hidden_states = attn_output + hidden_states + + # 4. Feed-forward + norm_hidden_states = self.norm3(hidden_states) + + if self._chunk_size is not None: + ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size) + else: + ff_output = self.ff(norm_hidden_states) + + if self.is_res: + hidden_states = ff_output + hidden_states + else: + hidden_states = ff_output + + hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels) + hidden_states = hidden_states.permute(0, 2, 1, 3) + hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels) + + return hidden_states + + +class SkipFFTransformerBlock(nn.Module): + def __init__( + self, + dim: int, + num_attention_heads: int, + attention_head_dim: int, + kv_input_dim: int, + kv_input_dim_proj_use_bias: bool, + dropout=0.0, + cross_attention_dim: Optional[int] = None, + attention_bias: bool = False, + attention_out_bias: bool = True, + ): + super().__init__() + if kv_input_dim != dim: + self.kv_mapper = nn.Linear(kv_input_dim, dim, kv_input_dim_proj_use_bias) + else: + self.kv_mapper = None + + self.norm1 = RMSNorm(dim, 1e-06) + + self.attn1 = Attention( + query_dim=dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + cross_attention_dim=cross_attention_dim, + out_bias=attention_out_bias, + ) + + self.norm2 = RMSNorm(dim, 1e-06) + + self.attn2 = Attention( + query_dim=dim, + cross_attention_dim=cross_attention_dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + out_bias=attention_out_bias, + ) + + def forward(self, hidden_states, encoder_hidden_states, cross_attention_kwargs): + cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {} + + if self.kv_mapper is not None: + encoder_hidden_states = self.kv_mapper(F.silu(encoder_hidden_states)) + + norm_hidden_states = self.norm1(hidden_states) + + attn_output = self.attn1( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + **cross_attention_kwargs, + ) + + hidden_states = attn_output + hidden_states + + norm_hidden_states = self.norm2(hidden_states) + + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + **cross_attention_kwargs, + ) + + hidden_states = attn_output + hidden_states + + return hidden_states + + +class FeedForward(nn.Module): + r""" + A feed-forward layer. + + Parameters: + dim (`int`): The number of channels in the input. + dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`. + mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward. + final_dropout (`bool` *optional*, defaults to False): Apply a final dropout. + bias (`bool`, defaults to True): Whether to use a bias in the linear layer. + """ + + def __init__( + self, + dim: int, + dim_out: Optional[int] = None, + mult: int = 4, + dropout: float = 0.0, + activation_fn: str = "geglu", + final_dropout: bool = False, + inner_dim=None, + bias: bool = True, + ): + super().__init__() + if inner_dim is None: + inner_dim = int(dim * mult) + dim_out = dim_out if dim_out is not None else dim + linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear + + if activation_fn == "gelu": + act_fn = GELU(dim, inner_dim, bias=bias) + if activation_fn == "gelu-approximate": + act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias) + elif activation_fn == "geglu": + act_fn = GEGLU(dim, inner_dim, bias=bias) + elif activation_fn == "geglu-approximate": + act_fn = ApproximateGELU(dim, inner_dim, bias=bias) + + self.net = nn.ModuleList([]) + # project in + self.net.append(act_fn) + # project dropout + self.net.append(nn.Dropout(dropout)) + # project out + self.net.append(linear_cls(inner_dim, dim_out, bias=bias)) + # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout + if final_dropout: + self.net.append(nn.Dropout(dropout)) + + def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor: + compatible_cls = (GEGLU,) if USE_PEFT_BACKEND else (GEGLU, LoRACompatibleLinear) + for module in self.net: + if isinstance(module, compatible_cls): + hidden_states = module(hidden_states, scale) + else: + hidden_states = module(hidden_states) + return hidden_states diff --git a/extensions-builtin/forge_space_idm_vton/src/attentionhacked_tryon.py b/extensions-builtin/forge_space_idm_vton/src/attentionhacked_tryon.py new file mode 100644 index 0000000000000000000000000000000000000000..9947e7c878f9f1fd3701b939dfc243628fa54652 --- /dev/null +++ b/extensions-builtin/forge_space_idm_vton/src/attentionhacked_tryon.py @@ -0,0 +1,682 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Dict, Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from diffusers.utils import USE_PEFT_BACKEND +from diffusers.utils.torch_utils import maybe_allow_in_graph +from diffusers.models.activations import GEGLU, GELU, ApproximateGELU +from diffusers.models.attention_processor import Attention +from diffusers.models.embeddings import SinusoidalPositionalEmbedding +from diffusers.models.lora import LoRACompatibleLinear +from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm + + +def _chunked_feed_forward( + ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int, lora_scale: Optional[float] = None +): + # "feed_forward_chunk_size" can be used to save memory + if hidden_states.shape[chunk_dim] % chunk_size != 0: + raise ValueError( + f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`." + ) + + num_chunks = hidden_states.shape[chunk_dim] // chunk_size + if lora_scale is None: + ff_output = torch.cat( + [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)], + dim=chunk_dim, + ) + else: + # TOOD(Patrick): LoRA scale can be removed once PEFT refactor is complete + ff_output = torch.cat( + [ff(hid_slice, scale=lora_scale) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)], + dim=chunk_dim, + ) + + return ff_output + + +@maybe_allow_in_graph +class GatedSelfAttentionDense(nn.Module): + r""" + A gated self-attention dense layer that combines visual features and object features. + + Parameters: + query_dim (`int`): The number of channels in the query. + context_dim (`int`): The number of channels in the context. + n_heads (`int`): The number of heads to use for attention. + d_head (`int`): The number of channels in each head. + """ + + def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int): + super().__init__() + + # we need a linear projection since we need cat visual feature and obj feature + self.linear = nn.Linear(context_dim, query_dim) + + self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head) + self.ff = FeedForward(query_dim, activation_fn="geglu") + + self.norm1 = nn.LayerNorm(query_dim) + self.norm2 = nn.LayerNorm(query_dim) + + self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0))) + self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0))) + + self.enabled = True + + def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor: + if not self.enabled: + return x + + n_visual = x.shape[1] + objs = self.linear(objs) + + x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :] + x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x)) + + return x + + +@maybe_allow_in_graph +class BasicTransformerBlock(nn.Module): + r""" + A basic Transformer block. + + Parameters: + dim (`int`): The number of channels in the input and output. + num_attention_heads (`int`): The number of heads to use for multi-head attention. + attention_head_dim (`int`): The number of channels in each head. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention. + activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward. + num_embeds_ada_norm (: + obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`. + attention_bias (: + obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter. + only_cross_attention (`bool`, *optional*): + Whether to use only cross-attention layers. In this case two cross attention layers are used. + double_self_attention (`bool`, *optional*): + Whether to use two self-attention layers. In this case no cross attention layers are used. + upcast_attention (`bool`, *optional*): + Whether to upcast the attention computation to float32. This is useful for mixed precision training. + norm_elementwise_affine (`bool`, *optional*, defaults to `True`): + Whether to use learnable elementwise affine parameters for normalization. + norm_type (`str`, *optional*, defaults to `"layer_norm"`): + The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`. + final_dropout (`bool` *optional*, defaults to False): + Whether to apply a final dropout after the last feed-forward layer. + attention_type (`str`, *optional*, defaults to `"default"`): + The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`. + positional_embeddings (`str`, *optional*, defaults to `None`): + The type of positional embeddings to apply to. + num_positional_embeddings (`int`, *optional*, defaults to `None`): + The maximum number of positional embeddings to apply. + """ + + def __init__( + self, + dim: int, + num_attention_heads: int, + attention_head_dim: int, + dropout=0.0, + cross_attention_dim: Optional[int] = None, + activation_fn: str = "geglu", + num_embeds_ada_norm: Optional[int] = None, + attention_bias: bool = False, + only_cross_attention: bool = False, + double_self_attention: bool = False, + upcast_attention: bool = False, + norm_elementwise_affine: bool = True, + norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single' + norm_eps: float = 1e-5, + final_dropout: bool = False, + attention_type: str = "default", + positional_embeddings: Optional[str] = None, + num_positional_embeddings: Optional[int] = None, + ada_norm_continous_conditioning_embedding_dim: Optional[int] = None, + ada_norm_bias: Optional[int] = None, + ff_inner_dim: Optional[int] = None, + ff_bias: bool = True, + attention_out_bias: bool = True, + ): + super().__init__() + self.only_cross_attention = only_cross_attention + + self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero" + self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm" + self.use_ada_layer_norm_single = norm_type == "ada_norm_single" + self.use_layer_norm = norm_type == "layer_norm" + self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous" + + if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: + raise ValueError( + f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to" + f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}." + ) + + if positional_embeddings and (num_positional_embeddings is None): + raise ValueError( + "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined." + ) + + if positional_embeddings == "sinusoidal": + self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings) + else: + self.pos_embed = None + + # Define 3 blocks. Each block has its own normalization layer. + # 1. Self-Attn + if self.use_ada_layer_norm: + self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm) + elif self.use_ada_layer_norm_zero: + self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm) + elif self.use_ada_layer_norm_continuous: + self.norm1 = AdaLayerNormContinuous( + dim, + ada_norm_continous_conditioning_embedding_dim, + norm_elementwise_affine, + norm_eps, + ada_norm_bias, + "rms_norm", + ) + else: + self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps) + + self.attn1 = Attention( + query_dim=dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + cross_attention_dim=cross_attention_dim if only_cross_attention else None, + upcast_attention=upcast_attention, + out_bias=attention_out_bias, + ) + + # 2. Cross-Attn + if cross_attention_dim is not None or double_self_attention: + # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. + # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during + # the second cross attention block. + if self.use_ada_layer_norm: + self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm) + elif self.use_ada_layer_norm_continuous: + self.norm2 = AdaLayerNormContinuous( + dim, + ada_norm_continous_conditioning_embedding_dim, + norm_elementwise_affine, + norm_eps, + ada_norm_bias, + "rms_norm", + ) + else: + self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine) + + self.attn2 = Attention( + query_dim=dim, + cross_attention_dim=cross_attention_dim if not double_self_attention else None, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + upcast_attention=upcast_attention, + out_bias=attention_out_bias, + ) # is self-attn if encoder_hidden_states is none + else: + self.norm2 = None + self.attn2 = None + + # 3. Feed-forward + if self.use_ada_layer_norm_continuous: + self.norm3 = AdaLayerNormContinuous( + dim, + ada_norm_continous_conditioning_embedding_dim, + norm_elementwise_affine, + norm_eps, + ada_norm_bias, + "layer_norm", + ) + elif not self.use_ada_layer_norm_single: + self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine) + + self.ff = FeedForward( + dim, + dropout=dropout, + activation_fn=activation_fn, + final_dropout=final_dropout, + inner_dim=ff_inner_dim, + bias=ff_bias, + ) + + # 4. Fuser + if attention_type == "gated" or attention_type == "gated-text-image": + self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim) + + # 5. Scale-shift for PixArt-Alpha. + if self.use_ada_layer_norm_single: + self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5) + + # let chunk size default to None + self._chunk_size = None + self._chunk_dim = 0 + + def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0): + # Sets chunk feed-forward + self._chunk_size = chunk_size + self._chunk_dim = dim + + def forward( + self, + hidden_states: torch.FloatTensor, + attention_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + timestep: Optional[torch.LongTensor] = None, + cross_attention_kwargs: Dict[str, Any] = None, + class_labels: Optional[torch.LongTensor] = None, + garment_features=None, + curr_garment_feat_idx=0, + added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None, + ) -> torch.FloatTensor: + # Notice that normalization is always applied before the real computation in the following blocks. + # 0. Self-Attention + batch_size = hidden_states.shape[0] + + + + if self.use_ada_layer_norm: + norm_hidden_states = self.norm1(hidden_states, timestep) + elif self.use_ada_layer_norm_zero: + norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1( + hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype + ) + elif self.use_layer_norm: + norm_hidden_states = self.norm1(hidden_states) + elif self.use_ada_layer_norm_continuous: + norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"]) + elif self.use_ada_layer_norm_single: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ( + self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1) + ).chunk(6, dim=1) + norm_hidden_states = self.norm1(hidden_states) + norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa + norm_hidden_states = norm_hidden_states.squeeze(1) + else: + raise ValueError("Incorrect norm used") + + if self.pos_embed is not None: + norm_hidden_states = self.pos_embed(norm_hidden_states) + + # 1. Retrieve lora scale. + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + + # 2. Prepare GLIGEN inputs + cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {} + gligen_kwargs = cross_attention_kwargs.pop("gligen", None) + + + #type2 + modify_norm_hidden_states = torch.cat([norm_hidden_states,garment_features[curr_garment_feat_idx]], dim=1) + curr_garment_feat_idx +=1 + attn_output = self.attn1( + #norm_hidden_states, + modify_norm_hidden_states, + encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None, + attention_mask=attention_mask, + **cross_attention_kwargs, + ) + if self.use_ada_layer_norm_zero: + attn_output = gate_msa.unsqueeze(1) * attn_output + elif self.use_ada_layer_norm_single: + attn_output = gate_msa * attn_output + + + #type2 + hidden_states = attn_output[:,:hidden_states.shape[-2],:] + hidden_states + + + + + if hidden_states.ndim == 4: + hidden_states = hidden_states.squeeze(1) + + # 2.5 GLIGEN Control + if gligen_kwargs is not None: + hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"]) + + # 3. Cross-Attention + if self.attn2 is not None: + if self.use_ada_layer_norm: + norm_hidden_states = self.norm2(hidden_states, timestep) + elif self.use_ada_layer_norm_zero or self.use_layer_norm: + norm_hidden_states = self.norm2(hidden_states) + elif self.use_ada_layer_norm_single: + # For PixArt norm2 isn't applied here: + # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103 + norm_hidden_states = hidden_states + elif self.use_ada_layer_norm_continuous: + norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"]) + else: + raise ValueError("Incorrect norm") + + if self.pos_embed is not None and self.use_ada_layer_norm_single is False: + norm_hidden_states = self.pos_embed(norm_hidden_states) + + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=encoder_attention_mask, + **cross_attention_kwargs, + ) + hidden_states = attn_output + hidden_states + + # 4. Feed-forward + if self.use_ada_layer_norm_continuous: + norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"]) + elif not self.use_ada_layer_norm_single: + norm_hidden_states = self.norm3(hidden_states) + + if self.use_ada_layer_norm_zero: + norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] + + if self.use_ada_layer_norm_single: + norm_hidden_states = self.norm2(hidden_states) + norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp + + if self._chunk_size is not None: + # "feed_forward_chunk_size" can be used to save memory + ff_output = _chunked_feed_forward( + self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale + ) + else: + ff_output = self.ff(norm_hidden_states, scale=lora_scale) + + if self.use_ada_layer_norm_zero: + ff_output = gate_mlp.unsqueeze(1) * ff_output + elif self.use_ada_layer_norm_single: + ff_output = gate_mlp * ff_output + + hidden_states = ff_output + hidden_states + if hidden_states.ndim == 4: + hidden_states = hidden_states.squeeze(1) + return hidden_states,curr_garment_feat_idx + + +@maybe_allow_in_graph +class TemporalBasicTransformerBlock(nn.Module): + r""" + A basic Transformer block for video like data. + + Parameters: + dim (`int`): The number of channels in the input and output. + time_mix_inner_dim (`int`): The number of channels for temporal attention. + num_attention_heads (`int`): The number of heads to use for multi-head attention. + attention_head_dim (`int`): The number of channels in each head. + cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention. + """ + + def __init__( + self, + dim: int, + time_mix_inner_dim: int, + num_attention_heads: int, + attention_head_dim: int, + cross_attention_dim: Optional[int] = None, + ): + super().__init__() + self.is_res = dim == time_mix_inner_dim + + self.norm_in = nn.LayerNorm(dim) + + # Define 3 blocks. Each block has its own normalization layer. + # 1. Self-Attn + self.norm_in = nn.LayerNorm(dim) + self.ff_in = FeedForward( + dim, + dim_out=time_mix_inner_dim, + activation_fn="geglu", + ) + + self.norm1 = nn.LayerNorm(time_mix_inner_dim) + self.attn1 = Attention( + query_dim=time_mix_inner_dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + cross_attention_dim=None, + ) + + # 2. Cross-Attn + if cross_attention_dim is not None: + # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. + # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during + # the second cross attention block. + self.norm2 = nn.LayerNorm(time_mix_inner_dim) + self.attn2 = Attention( + query_dim=time_mix_inner_dim, + cross_attention_dim=cross_attention_dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + ) # is self-attn if encoder_hidden_states is none + else: + self.norm2 = None + self.attn2 = None + + # 3. Feed-forward + self.norm3 = nn.LayerNorm(time_mix_inner_dim) + self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu") + + # let chunk size default to None + self._chunk_size = None + self._chunk_dim = None + + def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs): + # Sets chunk feed-forward + self._chunk_size = chunk_size + # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off + self._chunk_dim = 1 + + def forward( + self, + hidden_states: torch.FloatTensor, + num_frames: int, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + # Notice that normalization is always applied before the real computation in the following blocks. + # 0. Self-Attention + batch_size = hidden_states.shape[0] + + batch_frames, seq_length, channels = hidden_states.shape + batch_size = batch_frames // num_frames + + hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels) + hidden_states = hidden_states.permute(0, 2, 1, 3) + hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels) + + residual = hidden_states + hidden_states = self.norm_in(hidden_states) + + if self._chunk_size is not None: + hidden_states = _chunked_feed_forward(self.ff_in, hidden_states, self._chunk_dim, self._chunk_size) + else: + hidden_states = self.ff_in(hidden_states) + + if self.is_res: + hidden_states = hidden_states + residual + + norm_hidden_states = self.norm1(hidden_states) + attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None) + hidden_states = attn_output + hidden_states + + # 3. Cross-Attention + if self.attn2 is not None: + norm_hidden_states = self.norm2(hidden_states) + attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states) + hidden_states = attn_output + hidden_states + + # 4. Feed-forward + norm_hidden_states = self.norm3(hidden_states) + + if self._chunk_size is not None: + ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size) + else: + ff_output = self.ff(norm_hidden_states) + + if self.is_res: + hidden_states = ff_output + hidden_states + else: + hidden_states = ff_output + + hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels) + hidden_states = hidden_states.permute(0, 2, 1, 3) + hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels) + + return hidden_states + + +class SkipFFTransformerBlock(nn.Module): + def __init__( + self, + dim: int, + num_attention_heads: int, + attention_head_dim: int, + kv_input_dim: int, + kv_input_dim_proj_use_bias: bool, + dropout=0.0, + cross_attention_dim: Optional[int] = None, + attention_bias: bool = False, + attention_out_bias: bool = True, + ): + super().__init__() + if kv_input_dim != dim: + self.kv_mapper = nn.Linear(kv_input_dim, dim, kv_input_dim_proj_use_bias) + else: + self.kv_mapper = None + + self.norm1 = RMSNorm(dim, 1e-06) + + self.attn1 = Attention( + query_dim=dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + cross_attention_dim=cross_attention_dim, + out_bias=attention_out_bias, + ) + + self.norm2 = RMSNorm(dim, 1e-06) + + self.attn2 = Attention( + query_dim=dim, + cross_attention_dim=cross_attention_dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + out_bias=attention_out_bias, + ) + + def forward(self, hidden_states, encoder_hidden_states, cross_attention_kwargs): + cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {} + + if self.kv_mapper is not None: + encoder_hidden_states = self.kv_mapper(F.silu(encoder_hidden_states)) + + norm_hidden_states = self.norm1(hidden_states) + + attn_output = self.attn1( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + **cross_attention_kwargs, + ) + + hidden_states = attn_output + hidden_states + + norm_hidden_states = self.norm2(hidden_states) + + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + **cross_attention_kwargs, + ) + + hidden_states = attn_output + hidden_states + + return hidden_states + + +class FeedForward(nn.Module): + r""" + A feed-forward layer. + + Parameters: + dim (`int`): The number of channels in the input. + dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`. + mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward. + final_dropout (`bool` *optional*, defaults to False): Apply a final dropout. + bias (`bool`, defaults to True): Whether to use a bias in the linear layer. + """ + + def __init__( + self, + dim: int, + dim_out: Optional[int] = None, + mult: int = 4, + dropout: float = 0.0, + activation_fn: str = "geglu", + final_dropout: bool = False, + inner_dim=None, + bias: bool = True, + ): + super().__init__() + if inner_dim is None: + inner_dim = int(dim * mult) + dim_out = dim_out if dim_out is not None else dim + linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear + + if activation_fn == "gelu": + act_fn = GELU(dim, inner_dim, bias=bias) + if activation_fn == "gelu-approximate": + act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias) + elif activation_fn == "geglu": + act_fn = GEGLU(dim, inner_dim, bias=bias) + elif activation_fn == "geglu-approximate": + act_fn = ApproximateGELU(dim, inner_dim, bias=bias) + + self.net = nn.ModuleList([]) + # project in + self.net.append(act_fn) + # project dropout + self.net.append(nn.Dropout(dropout)) + # project out + self.net.append(linear_cls(inner_dim, dim_out, bias=bias)) + # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout + if final_dropout: + self.net.append(nn.Dropout(dropout)) + + def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor: + compatible_cls = (GEGLU,) if USE_PEFT_BACKEND else (GEGLU, LoRACompatibleLinear) + for module in self.net: + if isinstance(module, compatible_cls): + hidden_states = module(hidden_states, scale) + else: + hidden_states = module(hidden_states) + return hidden_states diff --git a/extensions-builtin/forge_space_idm_vton/src/transformerhacked_garmnet.py b/extensions-builtin/forge_space_idm_vton/src/transformerhacked_garmnet.py new file mode 100644 index 0000000000000000000000000000000000000000..488ceb24d2d088b999641aca91383ad9d223d652 --- /dev/null +++ b/extensions-builtin/forge_space_idm_vton/src/transformerhacked_garmnet.py @@ -0,0 +1,460 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from typing import Any, Dict, Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.models.embeddings import ImagePositionalEmbeddings +from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, is_torch_version +from src.attentionhacked_garmnet import BasicTransformerBlock +from diffusers.models.embeddings import PatchEmbed, PixArtAlphaTextProjection +from diffusers.models.lora import LoRACompatibleConv, LoRACompatibleLinear +from diffusers.models.modeling_utils import ModelMixin +from diffusers.models.normalization import AdaLayerNormSingle + + +@dataclass +class Transformer2DModelOutput(BaseOutput): + """ + The output of [`Transformer2DModel`]. + + Args: + sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete): + The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability + distributions for the unnoised latent pixels. + """ + + sample: torch.FloatTensor + + +class Transformer2DModel(ModelMixin, ConfigMixin): + """ + A 2D Transformer model for image-like data. + + Parameters: + num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention. + attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head. + in_channels (`int`, *optional*): + The number of channels in the input and output (specify if the input is **continuous**). + num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use. + sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**). + This is fixed during training since it is used to learn a number of position embeddings. + num_vector_embeds (`int`, *optional*): + The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**). + Includes the class for the masked latent pixel. + activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward. + num_embeds_ada_norm ( `int`, *optional*): + The number of diffusion steps used during training. Pass if at least one of the norm_layers is + `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are + added to the hidden states. + + During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`. + attention_bias (`bool`, *optional*): + Configure if the `TransformerBlocks` attention should contain a bias parameter. + """ + + _supports_gradient_checkpointing = True + + @register_to_config + def __init__( + self, + num_attention_heads: int = 16, + attention_head_dim: int = 88, + in_channels: Optional[int] = None, + out_channels: Optional[int] = None, + num_layers: int = 1, + dropout: float = 0.0, + norm_num_groups: int = 32, + cross_attention_dim: Optional[int] = None, + attention_bias: bool = False, + sample_size: Optional[int] = None, + num_vector_embeds: Optional[int] = None, + patch_size: Optional[int] = None, + activation_fn: str = "geglu", + num_embeds_ada_norm: Optional[int] = None, + use_linear_projection: bool = False, + only_cross_attention: bool = False, + double_self_attention: bool = False, + upcast_attention: bool = False, + norm_type: str = "layer_norm", + norm_elementwise_affine: bool = True, + norm_eps: float = 1e-5, + attention_type: str = "default", + caption_channels: int = None, + ): + super().__init__() + self.use_linear_projection = use_linear_projection + self.num_attention_heads = num_attention_heads + self.attention_head_dim = attention_head_dim + inner_dim = num_attention_heads * attention_head_dim + + conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv + linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear + + # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)` + # Define whether input is continuous or discrete depending on configuration + self.is_input_continuous = (in_channels is not None) and (patch_size is None) + self.is_input_vectorized = num_vector_embeds is not None + self.is_input_patches = in_channels is not None and patch_size is not None + + if norm_type == "layer_norm" and num_embeds_ada_norm is not None: + deprecation_message = ( + f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or" + " incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config." + " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect" + " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it" + " would be very nice if you could open a Pull request for the `transformer/config.json` file" + ) + deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False) + norm_type = "ada_norm" + + if self.is_input_continuous and self.is_input_vectorized: + raise ValueError( + f"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make" + " sure that either `in_channels` or `num_vector_embeds` is None." + ) + elif self.is_input_vectorized and self.is_input_patches: + raise ValueError( + f"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make" + " sure that either `num_vector_embeds` or `num_patches` is None." + ) + elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches: + raise ValueError( + f"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:" + f" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None." + ) + + # 2. Define input layers + if self.is_input_continuous: + self.in_channels = in_channels + + self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True) + if use_linear_projection: + self.proj_in = linear_cls(in_channels, inner_dim) + else: + self.proj_in = conv_cls(in_channels, inner_dim, kernel_size=1, stride=1, padding=0) + elif self.is_input_vectorized: + assert sample_size is not None, "Transformer2DModel over discrete input must provide sample_size" + assert num_vector_embeds is not None, "Transformer2DModel over discrete input must provide num_embed" + + self.height = sample_size + self.width = sample_size + self.num_vector_embeds = num_vector_embeds + self.num_latent_pixels = self.height * self.width + + self.latent_image_embedding = ImagePositionalEmbeddings( + num_embed=num_vector_embeds, embed_dim=inner_dim, height=self.height, width=self.width + ) + elif self.is_input_patches: + assert sample_size is not None, "Transformer2DModel over patched input must provide sample_size" + + self.height = sample_size + self.width = sample_size + + self.patch_size = patch_size + interpolation_scale = self.config.sample_size // 64 # => 64 (= 512 pixart) has interpolation scale 1 + interpolation_scale = max(interpolation_scale, 1) + self.pos_embed = PatchEmbed( + height=sample_size, + width=sample_size, + patch_size=patch_size, + in_channels=in_channels, + embed_dim=inner_dim, + interpolation_scale=interpolation_scale, + ) + + # 3. Define transformers blocks + self.transformer_blocks = nn.ModuleList( + [ + BasicTransformerBlock( + inner_dim, + num_attention_heads, + attention_head_dim, + dropout=dropout, + cross_attention_dim=cross_attention_dim, + activation_fn=activation_fn, + num_embeds_ada_norm=num_embeds_ada_norm, + attention_bias=attention_bias, + only_cross_attention=only_cross_attention, + double_self_attention=double_self_attention, + upcast_attention=upcast_attention, + norm_type=norm_type, + norm_elementwise_affine=norm_elementwise_affine, + norm_eps=norm_eps, + attention_type=attention_type, + ) + for d in range(num_layers) + ] + ) + + # 4. Define output layers + self.out_channels = in_channels if out_channels is None else out_channels + if self.is_input_continuous: + # TODO: should use out_channels for continuous projections + if use_linear_projection: + self.proj_out = linear_cls(inner_dim, in_channels) + else: + self.proj_out = conv_cls(inner_dim, in_channels, kernel_size=1, stride=1, padding=0) + elif self.is_input_vectorized: + self.norm_out = nn.LayerNorm(inner_dim) + self.out = nn.Linear(inner_dim, self.num_vector_embeds - 1) + elif self.is_input_patches and norm_type != "ada_norm_single": + self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6) + self.proj_out_1 = nn.Linear(inner_dim, 2 * inner_dim) + self.proj_out_2 = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels) + elif self.is_input_patches and norm_type == "ada_norm_single": + self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6) + self.scale_shift_table = nn.Parameter(torch.randn(2, inner_dim) / inner_dim**0.5) + self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels) + + # 5. PixArt-Alpha blocks. + self.adaln_single = None + self.use_additional_conditions = False + if norm_type == "ada_norm_single": + self.use_additional_conditions = self.config.sample_size == 128 + # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use + # additional conditions until we find better name + self.adaln_single = AdaLayerNormSingle(inner_dim, use_additional_conditions=self.use_additional_conditions) + + self.caption_projection = None + if caption_channels is not None: + self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim) + + self.gradient_checkpointing = False + + def _set_gradient_checkpointing(self, module, value=False): + if hasattr(module, "gradient_checkpointing"): + module.gradient_checkpointing = value + + def forward( + self, + hidden_states: torch.Tensor, + encoder_hidden_states: Optional[torch.Tensor] = None, + timestep: Optional[torch.LongTensor] = None, + added_cond_kwargs: Dict[str, torch.Tensor] = None, + class_labels: Optional[torch.LongTensor] = None, + cross_attention_kwargs: Dict[str, Any] = None, + attention_mask: Optional[torch.Tensor] = None, + encoder_attention_mask: Optional[torch.Tensor] = None, + return_dict: bool = True, + ): + """ + The [`Transformer2DModel`] forward method. + + Args: + hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous): + Input `hidden_states`. + encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*): + Conditional embeddings for cross attention layer. If not given, cross-attention defaults to + self-attention. + timestep ( `torch.LongTensor`, *optional*): + Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`. + class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*): + Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in + `AdaLayerZeroNorm`. + cross_attention_kwargs ( `Dict[str, Any]`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + attention_mask ( `torch.Tensor`, *optional*): + An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask + is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large + negative values to the attention scores corresponding to "discard" tokens. + encoder_attention_mask ( `torch.Tensor`, *optional*): + Cross-attention mask applied to `encoder_hidden_states`. Two formats supported: + + * Mask `(batch, sequence_length)` True = keep, False = discard. + * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard. + + If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format + above. This bias will be added to the cross-attention scores. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain + tuple. + + Returns: + If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a + `tuple` where the first element is the sample tensor. + """ + # ensure attention_mask is a bias, and give it a singleton query_tokens dimension. + # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward. + # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias. + # expects mask of shape: + # [batch, key_tokens] + # adds singleton query_tokens dimension: + # [batch, 1, key_tokens] + # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes: + # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn) + # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn) + if attention_mask is not None and attention_mask.ndim == 2: + # assume that mask is expressed as: + # (1 = keep, 0 = discard) + # convert mask into a bias that can be added to attention scores: + # (keep = +0, discard = -10000.0) + attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0 + attention_mask = attention_mask.unsqueeze(1) + + # convert encoder_attention_mask to a bias the same way we do for attention_mask + if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2: + encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0 + encoder_attention_mask = encoder_attention_mask.unsqueeze(1) + + # Retrieve lora scale. + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + + # 1. Input + if self.is_input_continuous: + batch, _, height, width = hidden_states.shape + residual = hidden_states + + hidden_states = self.norm(hidden_states) + if not self.use_linear_projection: + hidden_states = ( + self.proj_in(hidden_states, scale=lora_scale) + if not USE_PEFT_BACKEND + else self.proj_in(hidden_states) + ) + inner_dim = hidden_states.shape[1] + hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim) + else: + inner_dim = hidden_states.shape[1] + hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim) + hidden_states = ( + self.proj_in(hidden_states, scale=lora_scale) + if not USE_PEFT_BACKEND + else self.proj_in(hidden_states) + ) + + elif self.is_input_vectorized: + hidden_states = self.latent_image_embedding(hidden_states) + elif self.is_input_patches: + height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size + hidden_states = self.pos_embed(hidden_states) + + if self.adaln_single is not None: + if self.use_additional_conditions and added_cond_kwargs is None: + raise ValueError( + "`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`." + ) + batch_size = hidden_states.shape[0] + timestep, embedded_timestep = self.adaln_single( + timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype + ) + + # 2. Blocks + if self.caption_projection is not None: + batch_size = hidden_states.shape[0] + encoder_hidden_states = self.caption_projection(encoder_hidden_states) + encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1]) + + garment_features = [] + for block in self.transformer_blocks: + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + hidden_states,out_garment_feat = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + hidden_states, + attention_mask, + encoder_hidden_states, + encoder_attention_mask, + timestep, + cross_attention_kwargs, + class_labels, + **ckpt_kwargs, + ) + else: + hidden_states,out_garment_feat = block( + hidden_states, + attention_mask=attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + timestep=timestep, + cross_attention_kwargs=cross_attention_kwargs, + class_labels=class_labels, + ) + garment_features += out_garment_feat + # 3. Output + if self.is_input_continuous: + if not self.use_linear_projection: + hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous() + hidden_states = ( + self.proj_out(hidden_states, scale=lora_scale) + if not USE_PEFT_BACKEND + else self.proj_out(hidden_states) + ) + else: + hidden_states = ( + self.proj_out(hidden_states, scale=lora_scale) + if not USE_PEFT_BACKEND + else self.proj_out(hidden_states) + ) + hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous() + + output = hidden_states + residual + elif self.is_input_vectorized: + hidden_states = self.norm_out(hidden_states) + logits = self.out(hidden_states) + # (batch, self.num_vector_embeds - 1, self.num_latent_pixels) + logits = logits.permute(0, 2, 1) + + # log(p(x_0)) + output = F.log_softmax(logits.double(), dim=1).float() + + if self.is_input_patches: + if self.config.norm_type != "ada_norm_single": + conditioning = self.transformer_blocks[0].norm1.emb( + timestep, class_labels, hidden_dtype=hidden_states.dtype + ) + shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1) + hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None] + hidden_states = self.proj_out_2(hidden_states) + elif self.config.norm_type == "ada_norm_single": + shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1) + hidden_states = self.norm_out(hidden_states) + # Modulation + hidden_states = hidden_states * (1 + scale) + shift + hidden_states = self.proj_out(hidden_states) + hidden_states = hidden_states.squeeze(1) + + # unpatchify + if self.adaln_single is None: + height = width = int(hidden_states.shape[1] ** 0.5) + hidden_states = hidden_states.reshape( + shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels) + ) + hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states) + output = hidden_states.reshape( + shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size) + ) + + if not return_dict: + return (output,) ,garment_features + + return Transformer2DModelOutput(sample=output),garment_features diff --git a/extensions-builtin/forge_space_idm_vton/src/transformerhacked_tryon.py b/extensions-builtin/forge_space_idm_vton/src/transformerhacked_tryon.py new file mode 100644 index 0000000000000000000000000000000000000000..9a4ac5daf7c5e2f894b2ca0763d5950bd4845aae --- /dev/null +++ b/extensions-builtin/forge_space_idm_vton/src/transformerhacked_tryon.py @@ -0,0 +1,467 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from typing import Any, Dict, Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.models.embeddings import ImagePositionalEmbeddings +from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, is_torch_version +from src.attentionhacked_tryon import BasicTransformerBlock +from diffusers.models.embeddings import PatchEmbed, PixArtAlphaTextProjection +from diffusers.models.lora import LoRACompatibleConv, LoRACompatibleLinear +from diffusers.models.modeling_utils import ModelMixin +from diffusers.models.normalization import AdaLayerNormSingle + + +@dataclass +class Transformer2DModelOutput(BaseOutput): + """ + The output of [`Transformer2DModel`]. + + Args: + sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete): + The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability + distributions for the unnoised latent pixels. + """ + + sample: torch.FloatTensor + + +class Transformer2DModel(ModelMixin, ConfigMixin): + """ + A 2D Transformer model for image-like data. + + Parameters: + num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention. + attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head. + in_channels (`int`, *optional*): + The number of channels in the input and output (specify if the input is **continuous**). + num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use. + sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**). + This is fixed during training since it is used to learn a number of position embeddings. + num_vector_embeds (`int`, *optional*): + The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**). + Includes the class for the masked latent pixel. + activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward. + num_embeds_ada_norm ( `int`, *optional*): + The number of diffusion steps used during training. Pass if at least one of the norm_layers is + `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are + added to the hidden states. + + During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`. + attention_bias (`bool`, *optional*): + Configure if the `TransformerBlocks` attention should contain a bias parameter. + """ + + _supports_gradient_checkpointing = True + + @register_to_config + def __init__( + self, + num_attention_heads: int = 16, + attention_head_dim: int = 88, + in_channels: Optional[int] = None, + out_channels: Optional[int] = None, + num_layers: int = 1, + dropout: float = 0.0, + norm_num_groups: int = 32, + cross_attention_dim: Optional[int] = None, + attention_bias: bool = False, + sample_size: Optional[int] = None, + num_vector_embeds: Optional[int] = None, + patch_size: Optional[int] = None, + activation_fn: str = "geglu", + num_embeds_ada_norm: Optional[int] = None, + use_linear_projection: bool = False, + only_cross_attention: bool = False, + double_self_attention: bool = False, + upcast_attention: bool = False, + norm_type: str = "layer_norm", + norm_elementwise_affine: bool = True, + norm_eps: float = 1e-5, + attention_type: str = "default", + caption_channels: int = None, + ): + super().__init__() + self.use_linear_projection = use_linear_projection + self.num_attention_heads = num_attention_heads + self.attention_head_dim = attention_head_dim + inner_dim = num_attention_heads * attention_head_dim + + conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv + linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear + + # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)` + # Define whether input is continuous or discrete depending on configuration + self.is_input_continuous = (in_channels is not None) and (patch_size is None) + self.is_input_vectorized = num_vector_embeds is not None + self.is_input_patches = in_channels is not None and patch_size is not None + + if norm_type == "layer_norm" and num_embeds_ada_norm is not None: + deprecation_message = ( + f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or" + " incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config." + " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect" + " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it" + " would be very nice if you could open a Pull request for the `transformer/config.json` file" + ) + deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False) + norm_type = "ada_norm" + + if self.is_input_continuous and self.is_input_vectorized: + raise ValueError( + f"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make" + " sure that either `in_channels` or `num_vector_embeds` is None." + ) + elif self.is_input_vectorized and self.is_input_patches: + raise ValueError( + f"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make" + " sure that either `num_vector_embeds` or `num_patches` is None." + ) + elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches: + raise ValueError( + f"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:" + f" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None." + ) + + # 2. Define input layers + if self.is_input_continuous: + self.in_channels = in_channels + + self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True) + if use_linear_projection: + self.proj_in = linear_cls(in_channels, inner_dim) + else: + self.proj_in = conv_cls(in_channels, inner_dim, kernel_size=1, stride=1, padding=0) + elif self.is_input_vectorized: + assert sample_size is not None, "Transformer2DModel over discrete input must provide sample_size" + assert num_vector_embeds is not None, "Transformer2DModel over discrete input must provide num_embed" + + self.height = sample_size + self.width = sample_size + self.num_vector_embeds = num_vector_embeds + self.num_latent_pixels = self.height * self.width + + self.latent_image_embedding = ImagePositionalEmbeddings( + num_embed=num_vector_embeds, embed_dim=inner_dim, height=self.height, width=self.width + ) + elif self.is_input_patches: + assert sample_size is not None, "Transformer2DModel over patched input must provide sample_size" + + self.height = sample_size + self.width = sample_size + + self.patch_size = patch_size + interpolation_scale = self.config.sample_size // 64 # => 64 (= 512 pixart) has interpolation scale 1 + interpolation_scale = max(interpolation_scale, 1) + self.pos_embed = PatchEmbed( + height=sample_size, + width=sample_size, + patch_size=patch_size, + in_channels=in_channels, + embed_dim=inner_dim, + interpolation_scale=interpolation_scale, + ) + + # 3. Define transformers blocks + self.transformer_blocks = nn.ModuleList( + [ + BasicTransformerBlock( + inner_dim, + num_attention_heads, + attention_head_dim, + dropout=dropout, + cross_attention_dim=cross_attention_dim, + activation_fn=activation_fn, + num_embeds_ada_norm=num_embeds_ada_norm, + attention_bias=attention_bias, + only_cross_attention=only_cross_attention, + double_self_attention=double_self_attention, + upcast_attention=upcast_attention, + norm_type=norm_type, + norm_elementwise_affine=norm_elementwise_affine, + norm_eps=norm_eps, + attention_type=attention_type, + ) + for d in range(num_layers) + ] + ) + + # 4. Define output layers + self.out_channels = in_channels if out_channels is None else out_channels + if self.is_input_continuous: + # TODO: should use out_channels for continuous projections + if use_linear_projection: + self.proj_out = linear_cls(inner_dim, in_channels) + else: + self.proj_out = conv_cls(inner_dim, in_channels, kernel_size=1, stride=1, padding=0) + elif self.is_input_vectorized: + self.norm_out = nn.LayerNorm(inner_dim) + self.out = nn.Linear(inner_dim, self.num_vector_embeds - 1) + elif self.is_input_patches and norm_type != "ada_norm_single": + self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6) + self.proj_out_1 = nn.Linear(inner_dim, 2 * inner_dim) + self.proj_out_2 = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels) + elif self.is_input_patches and norm_type == "ada_norm_single": + self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6) + self.scale_shift_table = nn.Parameter(torch.randn(2, inner_dim) / inner_dim**0.5) + self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels) + + # 5. PixArt-Alpha blocks. + self.adaln_single = None + self.use_additional_conditions = False + if norm_type == "ada_norm_single": + self.use_additional_conditions = self.config.sample_size == 128 + # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use + # additional conditions until we find better name + self.adaln_single = AdaLayerNormSingle(inner_dim, use_additional_conditions=self.use_additional_conditions) + + self.caption_projection = None + if caption_channels is not None: + self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim) + + self.gradient_checkpointing = False + + def _set_gradient_checkpointing(self, module, value=False): + if hasattr(module, "gradient_checkpointing"): + module.gradient_checkpointing = value + + def forward( + self, + hidden_states: torch.Tensor, + encoder_hidden_states: Optional[torch.Tensor] = None, + timestep: Optional[torch.LongTensor] = None, + added_cond_kwargs: Dict[str, torch.Tensor] = None, + class_labels: Optional[torch.LongTensor] = None, + cross_attention_kwargs: Dict[str, Any] = None, + attention_mask: Optional[torch.Tensor] = None, + encoder_attention_mask: Optional[torch.Tensor] = None, + garment_features=None, + curr_garment_feat_idx=0, + return_dict: bool = True, + ): + """ + The [`Transformer2DModel`] forward method. + + Args: + hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous): + Input `hidden_states`. + encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*): + Conditional embeddings for cross attention layer. If not given, cross-attention defaults to + self-attention. + timestep ( `torch.LongTensor`, *optional*): + Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`. + class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*): + Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in + `AdaLayerZeroNorm`. + cross_attention_kwargs ( `Dict[str, Any]`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + attention_mask ( `torch.Tensor`, *optional*): + An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask + is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large + negative values to the attention scores corresponding to "discard" tokens. + encoder_attention_mask ( `torch.Tensor`, *optional*): + Cross-attention mask applied to `encoder_hidden_states`. Two formats supported: + + * Mask `(batch, sequence_length)` True = keep, False = discard. + * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard. + + If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format + above. This bias will be added to the cross-attention scores. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain + tuple. + + Returns: + If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a + `tuple` where the first element is the sample tensor. + """ + # ensure attention_mask is a bias, and give it a singleton query_tokens dimension. + # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward. + # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias. + # expects mask of shape: + # [batch, key_tokens] + # adds singleton query_tokens dimension: + # [batch, 1, key_tokens] + # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes: + # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn) + # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn) + if attention_mask is not None and attention_mask.ndim == 2: + # assume that mask is expressed as: + # (1 = keep, 0 = discard) + # convert mask into a bias that can be added to attention scores: + # (keep = +0, discard = -10000.0) + attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0 + attention_mask = attention_mask.unsqueeze(1) + + # convert encoder_attention_mask to a bias the same way we do for attention_mask + if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2: + encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0 + encoder_attention_mask = encoder_attention_mask.unsqueeze(1) + + # Retrieve lora scale. + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + + # 1. Input + if self.is_input_continuous: + batch, _, height, width = hidden_states.shape + residual = hidden_states + + hidden_states = self.norm(hidden_states) + if not self.use_linear_projection: + hidden_states = ( + self.proj_in(hidden_states, scale=lora_scale) + if not USE_PEFT_BACKEND + else self.proj_in(hidden_states) + ) + inner_dim = hidden_states.shape[1] + hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim) + else: + inner_dim = hidden_states.shape[1] + hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim) + hidden_states = ( + self.proj_in(hidden_states, scale=lora_scale) + if not USE_PEFT_BACKEND + else self.proj_in(hidden_states) + ) + + elif self.is_input_vectorized: + hidden_states = self.latent_image_embedding(hidden_states) + elif self.is_input_patches: + height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size + hidden_states = self.pos_embed(hidden_states) + + if self.adaln_single is not None: + if self.use_additional_conditions and added_cond_kwargs is None: + raise ValueError( + "`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`." + ) + batch_size = hidden_states.shape[0] + timestep, embedded_timestep = self.adaln_single( + timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype + ) + + # 2. Blocks + if self.caption_projection is not None: + batch_size = hidden_states.shape[0] + encoder_hidden_states = self.caption_projection(encoder_hidden_states) + encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1]) + + + for block in self.transformer_blocks: + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + hidden_states,curr_garment_feat_idx = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + hidden_states, + attention_mask, + encoder_hidden_states, + encoder_attention_mask, + timestep, + cross_attention_kwargs, + class_labels, + garment_features, + curr_garment_feat_idx, + **ckpt_kwargs, + ) + else: + hidden_states,curr_garment_feat_idx = block( + hidden_states, + attention_mask=attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + timestep=timestep, + cross_attention_kwargs=cross_attention_kwargs, + class_labels=class_labels, + garment_features=garment_features, + curr_garment_feat_idx=curr_garment_feat_idx, + ) + + + # 3. Output + if self.is_input_continuous: + if not self.use_linear_projection: + hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous() + hidden_states = ( + self.proj_out(hidden_states, scale=lora_scale) + if not USE_PEFT_BACKEND + else self.proj_out(hidden_states) + ) + else: + hidden_states = ( + self.proj_out(hidden_states, scale=lora_scale) + if not USE_PEFT_BACKEND + else self.proj_out(hidden_states) + ) + hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous() + + output = hidden_states + residual + elif self.is_input_vectorized: + hidden_states = self.norm_out(hidden_states) + logits = self.out(hidden_states) + # (batch, self.num_vector_embeds - 1, self.num_latent_pixels) + logits = logits.permute(0, 2, 1) + + # log(p(x_0)) + output = F.log_softmax(logits.double(), dim=1).float() + + if self.is_input_patches: + if self.config.norm_type != "ada_norm_single": + conditioning = self.transformer_blocks[0].norm1.emb( + timestep, class_labels, hidden_dtype=hidden_states.dtype + ) + shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1) + hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None] + hidden_states = self.proj_out_2(hidden_states) + elif self.config.norm_type == "ada_norm_single": + shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1) + hidden_states = self.norm_out(hidden_states) + # Modulation + hidden_states = hidden_states * (1 + scale) + shift + hidden_states = self.proj_out(hidden_states) + hidden_states = hidden_states.squeeze(1) + + # unpatchify + if self.adaln_single is None: + height = width = int(hidden_states.shape[1] ** 0.5) + hidden_states = hidden_states.reshape( + shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels) + ) + hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states) + output = hidden_states.reshape( + shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size) + ) + + if not return_dict: + return (output,),curr_garment_feat_idx + + return Transformer2DModelOutput(sample=output),curr_garment_feat_idx diff --git a/extensions-builtin/forge_space_idm_vton/src/tryon_pipeline.py b/extensions-builtin/forge_space_idm_vton/src/tryon_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..78f22375101a3312a6e3f992126f92fa91839ed4 --- /dev/null +++ b/extensions-builtin/forge_space_idm_vton/src/tryon_pipeline.py @@ -0,0 +1,1893 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import numpy as np +import PIL.Image +import torch +from transformers import ( + CLIPImageProcessor, + CLIPTextModel, + CLIPTextModelWithProjection, + CLIPTokenizer, + CLIPVisionModelWithProjection, +) + +from diffusers.image_processor import PipelineImageInput, VaeImageProcessor +from diffusers.loaders import ( + FromSingleFileMixin, + IPAdapterMixin, + StableDiffusionXLLoraLoaderMixin, + TextualInversionLoaderMixin, +) +from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel +from diffusers.models.attention_processor import ( + AttnProcessor2_0, + FusedAttnProcessor2_0, + LoRAAttnProcessor2_0, + LoRAXFormersAttnProcessor, + XFormersAttnProcessor, +) +from diffusers.models.lora import adjust_lora_scale_text_encoder +from diffusers.schedulers import KarrasDiffusionSchedulers +from diffusers.utils import ( + USE_PEFT_BACKEND, + deprecate, + is_invisible_watermark_available, + is_torch_xla_available, + logging, + replace_example_docstring, + scale_lora_layers, + unscale_lora_layers, +) +from diffusers.utils.torch_utils import randn_tensor +from diffusers.pipelines.pipeline_utils import DiffusionPipeline + + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + XLA_AVAILABLE = True +else: + XLA_AVAILABLE = False + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +EXAMPLE_DOC_STRING = """ + Examples: + ```py + >>> import torch + >>> from diffusers import StableDiffusionXLInpaintPipeline + >>> from diffusers.utils import load_image + + >>> pipe = StableDiffusionXLInpaintPipeline.from_pretrained( + ... "stabilityai/stable-diffusion-xl-base-1.0", + ... torch_dtype=torch.float16, + ... variant="fp16", + ... use_safetensors=True, + ... ) + >>> pipe.to("cuda") + + >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png" + >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png" + + >>> init_image = load_image(img_url).convert("RGB") + >>> mask_image = load_image(mask_url).convert("RGB") + + >>> prompt = "A majestic tiger sitting on a bench" + >>> image = pipe( + ... prompt=prompt, image=init_image, mask_image=mask_image, num_inference_steps=50, strength=0.80 + ... ).images[0] + ``` +""" + + +# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg +def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0): + """ + Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and + Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4 + """ + std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True) + std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True) + # rescale the results from guidance (fixes overexposure) + noise_pred_rescaled = noise_cfg * (std_text / std_cfg) + # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images + noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg + return noise_cfg + + +def mask_pil_to_torch(mask, height, width): + # preprocess mask + if isinstance(mask, (PIL.Image.Image, np.ndarray)): + mask = [mask] + + if isinstance(mask, list) and isinstance(mask[0], PIL.Image.Image): + mask = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in mask] + mask = np.concatenate([np.array(m.convert("L"))[None, None, :] for m in mask], axis=0) + mask = mask.astype(np.float32) / 255.0 + elif isinstance(mask, list) and isinstance(mask[0], np.ndarray): + mask = np.concatenate([m[None, None, :] for m in mask], axis=0) + + mask = torch.from_numpy(mask) + return mask + + +def prepare_mask_and_masked_image(image, mask, height, width, return_image: bool = False): + """ + Prepares a pair (image, mask) to be consumed by the Stable Diffusion pipeline. This means that those inputs will be + converted to ``torch.Tensor`` with shapes ``batch x channels x height x width`` where ``channels`` is ``3`` for the + ``image`` and ``1`` for the ``mask``. + + The ``image`` will be converted to ``torch.float32`` and normalized to be in ``[-1, 1]``. The ``mask`` will be + binarized (``mask > 0.5``) and cast to ``torch.float32`` too. + + Args: + image (Union[np.array, PIL.Image, torch.Tensor]): The image to inpaint. + It can be a ``PIL.Image``, or a ``height x width x 3`` ``np.array`` or a ``channels x height x width`` + ``torch.Tensor`` or a ``batch x channels x height x width`` ``torch.Tensor``. + mask (_type_): The mask to apply to the image, i.e. regions to inpaint. + It can be a ``PIL.Image``, or a ``height x width`` ``np.array`` or a ``1 x height x width`` + ``torch.Tensor`` or a ``batch x 1 x height x width`` ``torch.Tensor``. + + + Raises: + ValueError: ``torch.Tensor`` images should be in the ``[-1, 1]`` range. ValueError: ``torch.Tensor`` mask + should be in the ``[0, 1]`` range. ValueError: ``mask`` and ``image`` should have the same spatial dimensions. + TypeError: ``mask`` is a ``torch.Tensor`` but ``image`` is not + (ot the other way around). + + Returns: + tuple[torch.Tensor]: The pair (mask, masked_image) as ``torch.Tensor`` with 4 + dimensions: ``batch x channels x height x width``. + """ + + # checkpoint. TOD(Yiyi) - need to clean this up later + deprecation_message = "The prepare_mask_and_masked_image method is deprecated and will be removed in a future version. Please use VaeImageProcessor.preprocess instead" + deprecate( + "prepare_mask_and_masked_image", + "0.30.0", + deprecation_message, + ) + if image is None: + raise ValueError("`image` input cannot be undefined.") + + if mask is None: + raise ValueError("`mask_image` input cannot be undefined.") + + if isinstance(image, torch.Tensor): + if not isinstance(mask, torch.Tensor): + mask = mask_pil_to_torch(mask, height, width) + + if image.ndim == 3: + image = image.unsqueeze(0) + + # Batch and add channel dim for single mask + if mask.ndim == 2: + mask = mask.unsqueeze(0).unsqueeze(0) + + # Batch single mask or add channel dim + if mask.ndim == 3: + # Single batched mask, no channel dim or single mask not batched but channel dim + if mask.shape[0] == 1: + mask = mask.unsqueeze(0) + + # Batched masks no channel dim + else: + mask = mask.unsqueeze(1) + + assert image.ndim == 4 and mask.ndim == 4, "Image and Mask must have 4 dimensions" + # assert image.shape[-2:] == mask.shape[-2:], "Image and Mask must have the same spatial dimensions" + assert image.shape[0] == mask.shape[0], "Image and Mask must have the same batch size" + + # Check image is in [-1, 1] + # if image.min() < -1 or image.max() > 1: + # raise ValueError("Image should be in [-1, 1] range") + + # Check mask is in [0, 1] + if mask.min() < 0 or mask.max() > 1: + raise ValueError("Mask should be in [0, 1] range") + + # Binarize mask + mask[mask < 0.5] = 0 + mask[mask >= 0.5] = 1 + + # Image as float32 + image = image.to(dtype=torch.float32) + elif isinstance(mask, torch.Tensor): + raise TypeError(f"`mask` is a torch.Tensor but `image` (type: {type(image)} is not") + else: + # preprocess image + if isinstance(image, (PIL.Image.Image, np.ndarray)): + image = [image] + if isinstance(image, list) and isinstance(image[0], PIL.Image.Image): + # resize all images w.r.t passed height an width + image = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in image] + image = [np.array(i.convert("RGB"))[None, :] for i in image] + image = np.concatenate(image, axis=0) + elif isinstance(image, list) and isinstance(image[0], np.ndarray): + image = np.concatenate([i[None, :] for i in image], axis=0) + + image = image.transpose(0, 3, 1, 2) + image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0 + + mask = mask_pil_to_torch(mask, height, width) + mask[mask < 0.5] = 0 + mask[mask >= 0.5] = 1 + + if image.shape[1] == 4: + # images are in latent space and thus can't + # be masked set masked_image to None + # we assume that the checkpoint is not an inpainting + # checkpoint. TOD(Yiyi) - need to clean this up later + masked_image = None + else: + masked_image = image * (mask < 0.5) + + # n.b. ensure backwards compatibility as old function does not return image + if return_image: + return mask, masked_image, image + + return mask, masked_image + + +# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents +def retrieve_latents( + encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample" +): + if hasattr(encoder_output, "latent_dist") and sample_mode == "sample": + return encoder_output.latent_dist.sample(generator) + elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax": + return encoder_output.latent_dist.mode() + elif hasattr(encoder_output, "latents"): + return encoder_output.latents + else: + raise AttributeError("Could not access latents of provided encoder_output") + + +# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps +def retrieve_timesteps( + scheduler, + num_inference_steps: Optional[int] = None, + device: Optional[Union[str, torch.device]] = None, + timesteps: Optional[List[int]] = None, + **kwargs, +): + """ + Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles + custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`. + + Args: + scheduler (`SchedulerMixin`): + The scheduler to get timesteps from. + num_inference_steps (`int`): + The number of diffusion steps used when generating samples with a pre-trained model. If used, + `timesteps` must be `None`. + device (`str` or `torch.device`, *optional*): + The device to which the timesteps should be moved to. If `None`, the timesteps are not moved. + timesteps (`List[int]`, *optional*): + Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default + timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps` + must be `None`. + + Returns: + `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the + second element is the number of inference steps. + """ + if timesteps is not None: + accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys()) + if not accepts_timesteps: + raise ValueError( + f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" + f" timestep schedules. Please check whether you are using the correct scheduler." + ) + scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs) + timesteps = scheduler.timesteps + num_inference_steps = len(timesteps) + else: + scheduler.set_timesteps(num_inference_steps, device=device, **kwargs) + timesteps = scheduler.timesteps + return timesteps, num_inference_steps + + +class StableDiffusionXLInpaintPipeline( + DiffusionPipeline, + TextualInversionLoaderMixin, + StableDiffusionXLLoraLoaderMixin, + FromSingleFileMixin, + IPAdapterMixin, +): + r""" + Pipeline for text-to-image generation using Stable Diffusion XL. + + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the + library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) + + The pipeline also inherits the following loading methods: + - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings + - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files + - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights + - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights + - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters + + Args: + vae ([`AutoencoderKL`]): + Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. + text_encoder ([`CLIPTextModel`]): + Frozen text-encoder. Stable Diffusion XL uses the text portion of + [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically + the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. + text_encoder_2 ([` CLIPTextModelWithProjection`]): + Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of + [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), + specifically the + [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k) + variant. + tokenizer (`CLIPTokenizer`): + Tokenizer of class + [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). + tokenizer_2 (`CLIPTokenizer`): + Second Tokenizer of class + [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). + unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents. + scheduler ([`SchedulerMixin`]): + A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of + [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. + requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`): + Whether the `unet` requires a aesthetic_score condition to be passed during inference. Also see the config + of `stabilityai/stable-diffusion-xl-refiner-1-0`. + force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`): + Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of + `stabilityai/stable-diffusion-xl-base-1-0`. + add_watermarker (`bool`, *optional*): + Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to + watermark output images. If not defined, it will default to True if the package is installed, otherwise no + watermarker will be used. + """ + + model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae" + + _optional_components = [ + "tokenizer", + "tokenizer_2", + "text_encoder", + "text_encoder_2", + "image_encoder", + "feature_extractor", + ] + _callback_tensor_inputs = [ + "latents", + "prompt_embeds", + "negative_prompt_embeds", + "add_text_embeds", + "add_time_ids", + "negative_pooled_prompt_embeds", + "add_neg_time_ids", + "mask", + "masked_image_latents", + ] + + def __init__( + self, + vae: AutoencoderKL, + text_encoder: CLIPTextModel, + text_encoder_2: CLIPTextModelWithProjection, + tokenizer: CLIPTokenizer, + tokenizer_2: CLIPTokenizer, + unet: UNet2DConditionModel, + scheduler: KarrasDiffusionSchedulers, + image_encoder: CLIPVisionModelWithProjection = None, + feature_extractor: CLIPImageProcessor = None, + requires_aesthetics_score: bool = False, + force_zeros_for_empty_prompt: bool = True, + ): + super().__init__() + + self.register_modules( + vae=vae, + text_encoder=text_encoder, + text_encoder_2=text_encoder_2, + tokenizer=tokenizer, + tokenizer_2=tokenizer_2, + unet=unet, + image_encoder=image_encoder, + feature_extractor=feature_extractor, + scheduler=scheduler, + ) + self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt) + self.register_to_config(requires_aesthetics_score=requires_aesthetics_score) + self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) + self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor) + self.mask_processor = VaeImageProcessor( + vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_binarize=True, do_convert_grayscale=True + ) + + + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing + def enable_vae_slicing(self): + r""" + Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to + compute decoding in several steps. This is useful to save some memory and allow larger batch sizes. + """ + self.vae.enable_slicing() + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing + def disable_vae_slicing(self): + r""" + Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to + computing decoding in one step. + """ + self.vae.disable_slicing() + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling + def enable_vae_tiling(self): + r""" + Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to + compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow + processing larger images. + """ + self.vae.enable_tiling() + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling + def disable_vae_tiling(self): + r""" + Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to + computing decoding in one step. + """ + self.vae.disable_tiling() + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image + def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None): + dtype = next(self.image_encoder.parameters()).dtype + # print(image.shape) + if not isinstance(image, torch.Tensor): + image = self.feature_extractor(image, return_tensors="pt").pixel_values + + image = image.to(device=device, dtype=dtype) + if output_hidden_states: + image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2] + image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0) + uncond_image_enc_hidden_states = self.image_encoder( + torch.zeros_like(image), output_hidden_states=True + ).hidden_states[-2] + uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave( + num_images_per_prompt, dim=0 + ) + return image_enc_hidden_states, uncond_image_enc_hidden_states + else: + image_embeds = self.image_encoder(image).image_embeds + image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0) + uncond_image_embeds = torch.zeros_like(image_embeds) + + return image_embeds, uncond_image_embeds + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds + def prepare_ip_adapter_image_embeds(self, ip_adapter_image, device, num_images_per_prompt): + # if not isinstance(ip_adapter_image, list): + # ip_adapter_image = [ip_adapter_image] + + # if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers): + # raise ValueError( + # f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters." + # ) + output_hidden_state = not isinstance(self.unet.encoder_hid_proj, ImageProjection) + # print(output_hidden_state) + image_embeds, negative_image_embeds = self.encode_image( + ip_adapter_image, device, 1, output_hidden_state + ) + # print(single_image_embeds.shape) + # single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0) + # single_negative_image_embeds = torch.stack([single_negative_image_embeds] * num_images_per_prompt, dim=0) + # print(single_image_embeds.shape) + if self.do_classifier_free_guidance: + image_embeds = torch.cat([negative_image_embeds, image_embeds]) + image_embeds = image_embeds.to(device) + + + return image_embeds + + + # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt + def encode_prompt( + self, + prompt: str, + prompt_2: Optional[str] = None, + device: Optional[torch.device] = None, + num_images_per_prompt: int = 1, + do_classifier_free_guidance: bool = True, + negative_prompt: Optional[str] = None, + negative_prompt_2: Optional[str] = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + pooled_prompt_embeds: Optional[torch.FloatTensor] = None, + negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None, + lora_scale: Optional[float] = None, + clip_skip: Optional[int] = None, + ): + r""" + Encodes the prompt into text encoder hidden states. + + Args: + prompt (`str` or `List[str]`, *optional*): + prompt to be encoded + prompt_2 (`str` or `List[str]`, *optional*): + The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is + used in both text-encoders + device: (`torch.device`): + torch device + num_images_per_prompt (`int`): + number of images that should be generated per prompt + do_classifier_free_guidance (`bool`): + whether to use classifier free guidance or not + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + negative_prompt_2 (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and + `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + pooled_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. + If not provided, pooled text embeddings will be generated from `prompt` input argument. + negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt` + input argument. + lora_scale (`float`, *optional*): + A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded. + clip_skip (`int`, *optional*): + Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that + the output of the pre-final layer will be used for computing the prompt embeddings. + """ + device = device or self._execution_device + + # set lora scale so that monkey patched LoRA + # function of text encoder can correctly access it + if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin): + self._lora_scale = lora_scale + + # dynamically adjust the LoRA scale + if self.text_encoder is not None: + if not USE_PEFT_BACKEND: + adjust_lora_scale_text_encoder(self.text_encoder, lora_scale) + else: + scale_lora_layers(self.text_encoder, lora_scale) + + if self.text_encoder_2 is not None: + if not USE_PEFT_BACKEND: + adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale) + else: + scale_lora_layers(self.text_encoder_2, lora_scale) + + prompt = [prompt] if isinstance(prompt, str) else prompt + + if prompt is not None: + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + # Define tokenizers and text encoders + tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2] + text_encoders = ( + [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2] + ) + + if prompt_embeds is None: + prompt_2 = prompt_2 or prompt + prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2 + + # textual inversion: procecss multi-vector tokens if necessary + prompt_embeds_list = [] + prompts = [prompt, prompt_2] + for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders): + if isinstance(self, TextualInversionLoaderMixin): + prompt = self.maybe_convert_prompt(prompt, tokenizer) + + text_inputs = tokenizer( + prompt, + padding="max_length", + max_length=tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + + text_input_ids = text_inputs.input_ids + untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids + + if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal( + text_input_ids, untruncated_ids + ): + removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1]) + logger.warning( + "The following part of your input was truncated because CLIP can only handle sequences up to" + f" {tokenizer.model_max_length} tokens: {removed_text}" + ) + + prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True) + + # We are only ALWAYS interested in the pooled output of the final text encoder + pooled_prompt_embeds = prompt_embeds[0] + if clip_skip is None: + prompt_embeds = prompt_embeds.hidden_states[-2] + else: + # "2" because SDXL always indexes from the penultimate layer. + prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)] + + prompt_embeds_list.append(prompt_embeds) + + prompt_embeds = torch.concat(prompt_embeds_list, dim=-1) + + # get unconditional embeddings for classifier free guidance + zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt + if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt: + negative_prompt_embeds = torch.zeros_like(prompt_embeds) + negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds) + elif do_classifier_free_guidance and negative_prompt_embeds is None: + negative_prompt = negative_prompt or "" + negative_prompt_2 = negative_prompt_2 or negative_prompt + + # normalize str to list + negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt + negative_prompt_2 = ( + batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2 + ) + + uncond_tokens: List[str] + if prompt is not None and type(prompt) is not type(negative_prompt): + raise TypeError( + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + else: + uncond_tokens = [negative_prompt, negative_prompt_2] + + negative_prompt_embeds_list = [] + for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders): + if isinstance(self, TextualInversionLoaderMixin): + negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer) + + max_length = prompt_embeds.shape[1] + uncond_input = tokenizer( + negative_prompt, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="pt", + ) + + negative_prompt_embeds = text_encoder( + uncond_input.input_ids.to(device), + output_hidden_states=True, + ) + # We are only ALWAYS interested in the pooled output of the final text encoder + negative_pooled_prompt_embeds = negative_prompt_embeds[0] + negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2] + + negative_prompt_embeds_list.append(negative_prompt_embeds) + + negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1) + + if self.text_encoder_2 is not None: + prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device) + else: + prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device) + + bs_embed, seq_len, _ = prompt_embeds.shape + # duplicate text embeddings for each generation per prompt, using mps friendly method + prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) + prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1) + + if do_classifier_free_guidance: + # duplicate unconditional embeddings for each generation per prompt, using mps friendly method + seq_len = negative_prompt_embeds.shape[1] + + if self.text_encoder_2 is not None: + negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device) + else: + negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device) + + negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1) + negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1) + + pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view( + bs_embed * num_images_per_prompt, -1 + ) + if do_classifier_free_guidance: + negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view( + bs_embed * num_images_per_prompt, -1 + ) + + if self.text_encoder is not None: + if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND: + # Retrieve the original scale by scaling back the LoRA layers + unscale_lora_layers(self.text_encoder, lora_scale) + + if self.text_encoder_2 is not None: + if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND: + # Retrieve the original scale by scaling back the LoRA layers + unscale_lora_layers(self.text_encoder_2, lora_scale) + + return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs + def prepare_extra_step_kwargs(self, generator, eta): + # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature + # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. + # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 + # and should be between [0, 1] + + accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) + extra_step_kwargs = {} + if accepts_eta: + extra_step_kwargs["eta"] = eta + + # check if the scheduler accepts generator + accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) + if accepts_generator: + extra_step_kwargs["generator"] = generator + return extra_step_kwargs + + def check_inputs( + self, + prompt, + prompt_2, + image, + mask_image, + height, + width, + strength, + callback_steps, + output_type, + negative_prompt=None, + negative_prompt_2=None, + prompt_embeds=None, + negative_prompt_embeds=None, + callback_on_step_end_tensor_inputs=None, + padding_mask_crop=None, + ): + if strength < 0 or strength > 1: + raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}") + + if height % 8 != 0 or width % 8 != 0: + raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") + + if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0): + raise ValueError( + f"`callback_steps` has to be a positive integer but is {callback_steps} of type" + f" {type(callback_steps)}." + ) + + if callback_on_step_end_tensor_inputs is not None and not all( + k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs + ): + raise ValueError( + f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}" + ) + + if prompt is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif prompt_2 is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif prompt is None and prompt_embeds is None: + raise ValueError( + "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." + ) + elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)): + raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}") + + if negative_prompt is not None and negative_prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" + f" {negative_prompt_embeds}. Please make sure to only forward one of the two." + ) + elif negative_prompt_2 is not None and negative_prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:" + f" {negative_prompt_embeds}. Please make sure to only forward one of the two." + ) + + if prompt_embeds is not None and negative_prompt_embeds is not None: + if prompt_embeds.shape != negative_prompt_embeds.shape: + raise ValueError( + "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" + f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" + f" {negative_prompt_embeds.shape}." + ) + if padding_mask_crop is not None: + if not isinstance(image, PIL.Image.Image): + raise ValueError( + f"The image should be a PIL image when inpainting mask crop, but is of type" f" {type(image)}." + ) + if not isinstance(mask_image, PIL.Image.Image): + raise ValueError( + f"The mask image should be a PIL image when inpainting mask crop, but is of type" + f" {type(mask_image)}." + ) + if output_type != "pil": + raise ValueError(f"The output type should be PIL when inpainting mask crop, but is" f" {output_type}.") + + def prepare_latents( + self, + batch_size, + num_channels_latents, + height, + width, + dtype, + device, + generator, + latents=None, + image=None, + timestep=None, + is_strength_max=True, + add_noise=True, + return_noise=False, + return_image_latents=False, + ): + shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor) + if isinstance(generator, list) and len(generator) != batch_size: + raise ValueError( + f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" + f" size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + + if (image is None or timestep is None) and not is_strength_max: + raise ValueError( + "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise." + "However, either the image or the noise timestep has not been provided." + ) + + if image.shape[1] == 4: + image_latents = image.to(device=device, dtype=dtype) + image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1) + elif return_image_latents or (latents is None and not is_strength_max): + image = image.to(device=device, dtype=dtype) + image_latents = self._encode_vae_image(image=image, generator=generator) + image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1) + + if latents is None and add_noise: + noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype) + # if strength is 1. then initialise the latents to noise, else initial to image + noise + latents = noise if is_strength_max else self.scheduler.add_noise(image_latents, noise, timestep) + # if pure noise then scale the initial latents by the Scheduler's init sigma + latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents + elif add_noise: + noise = latents.to(device) + latents = noise * self.scheduler.init_noise_sigma + else: + noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype) + latents = image_latents.to(device) + + outputs = (latents,) + + if return_noise: + outputs += (noise,) + + if return_image_latents: + outputs += (image_latents,) + + return outputs + + def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator): + dtype = image.dtype + if self.vae.config.force_upcast: + image = image.float() + self.vae.to(dtype=torch.float32) + + if isinstance(generator, list): + image_latents = [ + retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i]) + for i in range(image.shape[0]) + ] + image_latents = torch.cat(image_latents, dim=0) + else: + image_latents = retrieve_latents(self.vae.encode(image), generator=generator) + + if self.vae.config.force_upcast: + self.vae.to(dtype) + + image_latents = image_latents.to(dtype) + image_latents = self.vae.config.scaling_factor * image_latents + + return image_latents + + def prepare_mask_latents( + self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance + ): + # resize the mask to latents shape as we concatenate the mask to the latents + # we do that before converting to dtype to avoid breaking in case we're using cpu_offload + # and half precision + mask = torch.nn.functional.interpolate( + mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor) + ) + mask = mask.to(device=device, dtype=dtype) + + # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method + if mask.shape[0] < batch_size: + if not batch_size % mask.shape[0] == 0: + raise ValueError( + "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to" + f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number" + " of masks that you pass is divisible by the total requested batch size." + ) + mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1) + + mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask + if masked_image is not None and masked_image.shape[1] == 4: + masked_image_latents = masked_image + else: + masked_image_latents = None + + if masked_image is not None: + if masked_image_latents is None: + masked_image = masked_image.to(device=device, dtype=dtype) + masked_image_latents = self._encode_vae_image(masked_image, generator=generator) + + if masked_image_latents.shape[0] < batch_size: + if not batch_size % masked_image_latents.shape[0] == 0: + raise ValueError( + "The passed images and the required batch size don't match. Images are supposed to be duplicated" + f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed." + " Make sure the number of images that you pass is divisible by the total requested batch size." + ) + masked_image_latents = masked_image_latents.repeat( + batch_size // masked_image_latents.shape[0], 1, 1, 1 + ) + + masked_image_latents = ( + torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents + ) + + # aligning device to prevent device errors when concating it with the latent model input + masked_image_latents = masked_image_latents.to(device=device, dtype=dtype) + + return mask, masked_image_latents + + # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.get_timesteps + def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None): + # get the original timestep using init_timestep + if denoising_start is None: + init_timestep = min(int(num_inference_steps * strength), num_inference_steps) + t_start = max(num_inference_steps - init_timestep, 0) + else: + t_start = 0 + + timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :] + + # Strength is irrelevant if we directly request a timestep to start at; + # that is, strength is determined by the denoising_start instead. + if denoising_start is not None: + discrete_timestep_cutoff = int( + round( + self.scheduler.config.num_train_timesteps + - (denoising_start * self.scheduler.config.num_train_timesteps) + ) + ) + + num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item() + if self.scheduler.order == 2 and num_inference_steps % 2 == 0: + # if the scheduler is a 2nd order scheduler we might have to do +1 + # because `num_inference_steps` might be even given that every timestep + # (except the highest one) is duplicated. If `num_inference_steps` is even it would + # mean that we cut the timesteps in the middle of the denoising step + # (between 1st and 2nd devirative) which leads to incorrect results. By adding 1 + # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler + num_inference_steps = num_inference_steps + 1 + + # because t_n+1 >= t_n, we slice the timesteps starting from the end + timesteps = timesteps[-num_inference_steps:] + return timesteps, num_inference_steps + + return timesteps, num_inference_steps - t_start + + # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline._get_add_time_ids + def _get_add_time_ids( + self, + original_size, + crops_coords_top_left, + target_size, + aesthetic_score, + negative_aesthetic_score, + negative_original_size, + negative_crops_coords_top_left, + negative_target_size, + dtype, + text_encoder_projection_dim=None, + ): + if self.config.requires_aesthetics_score: + add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,)) + add_neg_time_ids = list( + negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,) + ) + else: + add_time_ids = list(original_size + crops_coords_top_left + target_size) + add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size) + + passed_add_embed_dim = ( + self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim + ) + expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features + + if ( + expected_add_embed_dim > passed_add_embed_dim + and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim + ): + raise ValueError( + f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model." + ) + elif ( + expected_add_embed_dim < passed_add_embed_dim + and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim + ): + raise ValueError( + f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model." + ) + elif expected_add_embed_dim != passed_add_embed_dim: + raise ValueError( + f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`." + ) + + add_time_ids = torch.tensor([add_time_ids], dtype=dtype) + add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype) + + return add_time_ids, add_neg_time_ids + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae + def upcast_vae(self): + dtype = self.vae.dtype + self.vae.to(dtype=torch.float32) + use_torch_2_0_or_xformers = isinstance( + self.vae.decoder.mid_block.attentions[0].processor, + ( + AttnProcessor2_0, + XFormersAttnProcessor, + LoRAXFormersAttnProcessor, + LoRAAttnProcessor2_0, + ), + ) + # if xformers or torch_2_0 is used attention block does not need + # to be in float32 which can save lots of memory + if use_torch_2_0_or_xformers: + self.vae.post_quant_conv.to(dtype) + self.vae.decoder.conv_in.to(dtype) + self.vae.decoder.mid_block.to(dtype) + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_freeu + def enable_freeu(self, s1: float, s2: float, b1: float, b2: float): + r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497. + + The suffixes after the scaling factors represent the stages where they are being applied. + + Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values + that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL. + + Args: + s1 (`float`): + Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to + mitigate "oversmoothing effect" in the enhanced denoising process. + s2 (`float`): + Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to + mitigate "oversmoothing effect" in the enhanced denoising process. + b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features. + b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features. + """ + if not hasattr(self, "unet"): + raise ValueError("The pipeline must have `unet` for using FreeU.") + self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2) + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_freeu + def disable_freeu(self): + """Disables the FreeU mechanism if enabled.""" + self.unet.disable_freeu() + + # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.fuse_qkv_projections + def fuse_qkv_projections(self, unet: bool = True, vae: bool = True): + """ + Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, + key, value) are fused. For cross-attention modules, key and value projection matrices are fused. + + + + This API is 🧪 experimental. + + + + Args: + unet (`bool`, defaults to `True`): To apply fusion on the UNet. + vae (`bool`, defaults to `True`): To apply fusion on the VAE. + """ + self.fusing_unet = False + self.fusing_vae = False + + if unet: + self.fusing_unet = True + self.unet.fuse_qkv_projections() + self.unet.set_attn_processor(FusedAttnProcessor2_0()) + + if vae: + if not isinstance(self.vae, AutoencoderKL): + raise ValueError("`fuse_qkv_projections()` is only supported for the VAE of type `AutoencoderKL`.") + + self.fusing_vae = True + self.vae.fuse_qkv_projections() + self.vae.set_attn_processor(FusedAttnProcessor2_0()) + + # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.unfuse_qkv_projections + def unfuse_qkv_projections(self, unet: bool = True, vae: bool = True): + """Disable QKV projection fusion if enabled. + + + + This API is 🧪 experimental. + + + + Args: + unet (`bool`, defaults to `True`): To apply fusion on the UNet. + vae (`bool`, defaults to `True`): To apply fusion on the VAE. + + """ + if unet: + if not self.fusing_unet: + logger.warning("The UNet was not initially fused for QKV projections. Doing nothing.") + else: + self.unet.unfuse_qkv_projections() + self.fusing_unet = False + + if vae: + if not self.fusing_vae: + logger.warning("The VAE was not initially fused for QKV projections. Doing nothing.") + else: + self.vae.unfuse_qkv_projections() + self.fusing_vae = False + + # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding + def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32): + """ + See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 + + Args: + timesteps (`torch.Tensor`): + generate embedding vectors at these timesteps + embedding_dim (`int`, *optional*, defaults to 512): + dimension of the embeddings to generate + dtype: + data type of the generated embeddings + + Returns: + `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)` + """ + assert len(w.shape) == 1 + w = w * 1000.0 + + half_dim = embedding_dim // 2 + emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1) + emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb) + emb = w.to(dtype)[:, None] * emb[None, :] + emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1) + if embedding_dim % 2 == 1: # zero pad + emb = torch.nn.functional.pad(emb, (0, 1)) + assert emb.shape == (w.shape[0], embedding_dim) + return emb + + @property + def guidance_scale(self): + return self._guidance_scale + + @property + def guidance_rescale(self): + return self._guidance_rescale + + @property + def clip_skip(self): + return self._clip_skip + + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + @property + def do_classifier_free_guidance(self): + return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None + + @property + def cross_attention_kwargs(self): + return self._cross_attention_kwargs + + @property + def denoising_end(self): + return self._denoising_end + + @property + def denoising_start(self): + return self._denoising_start + + @property + def num_timesteps(self): + return self._num_timesteps + + @property + def interrupt(self): + return self._interrupt + + @torch.no_grad() + @replace_example_docstring(EXAMPLE_DOC_STRING) + def __call__( + self, + prompt: Union[str, List[str]] = None, + prompt_2: Optional[Union[str, List[str]]] = None, + image: PipelineImageInput = None, + mask_image: PipelineImageInput = None, + masked_image_latents: torch.FloatTensor = None, + height: Optional[int] = None, + width: Optional[int] = None, + padding_mask_crop: Optional[int] = None, + strength: float = 0.9999, + num_inference_steps: int = 50, + timesteps: List[int] = None, + denoising_start: Optional[float] = None, + denoising_end: Optional[float] = None, + guidance_scale: float = 7.5, + negative_prompt: Optional[Union[str, List[str]]] = None, + negative_prompt_2: Optional[Union[str, List[str]]] = None, + num_images_per_prompt: Optional[int] = 1, + eta: float = 0.0, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.FloatTensor] = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + pooled_prompt_embeds: Optional[torch.FloatTensor] = None, + negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None, + ip_adapter_image: Optional[PipelineImageInput] = None, + output_type: Optional[str] = "pil", + cloth =None, + pose_img = None, + text_embeds_cloth=None, + return_dict: bool = True, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + guidance_rescale: float = 0.0, + original_size: Tuple[int, int] = None, + crops_coords_top_left: Tuple[int, int] = (0, 0), + target_size: Tuple[int, int] = None, + negative_original_size: Optional[Tuple[int, int]] = None, + negative_crops_coords_top_left: Tuple[int, int] = (0, 0), + negative_target_size: Optional[Tuple[int, int]] = None, + aesthetic_score: float = 6.0, + negative_aesthetic_score: float = 2.5, + clip_skip: Optional[int] = None, + pooled_prompt_embeds_c=None, + callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None, + callback_on_step_end_tensor_inputs: List[str] = ["latents"], + **kwargs, + ): + r""" + Function invoked when calling the pipeline for generation. + + Args: + prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. + instead. + prompt_2 (`str` or `List[str]`, *optional*): + The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is + used in both text-encoders + image (`PIL.Image.Image`): + `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will + be masked out with `mask_image` and repainted according to `prompt`. + mask_image (`PIL.Image.Image`): + `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be + repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted + to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L) + instead of 3, so the expected shape would be `(B, H, W, 1)`. + height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): + The height in pixels of the generated image. This is set to 1024 by default for the best results. + Anything below 512 pixels won't work well for + [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) + and checkpoints that are not specifically fine-tuned on low resolutions. + width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): + The width in pixels of the generated image. This is set to 1024 by default for the best results. + Anything below 512 pixels won't work well for + [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) + and checkpoints that are not specifically fine-tuned on low resolutions. + padding_mask_crop (`int`, *optional*, defaults to `None`): + The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to image and mask_image. If + `padding_mask_crop` is not `None`, it will first find a rectangular region with the same aspect ration of the image and + contains all masked area, and then expand that area based on `padding_mask_crop`. The image and mask_image will then be cropped based on + the expanded area before resizing to the original image size for inpainting. This is useful when the masked area is small while the image is large + and contain information inreleant for inpainging, such as background. + strength (`float`, *optional*, defaults to 0.9999): + Conceptually, indicates how much to transform the masked portion of the reference `image`. Must be + between 0 and 1. `image` will be used as a starting point, adding more noise to it the larger the + `strength`. The number of denoising steps depends on the amount of noise initially added. When + `strength` is 1, added noise will be maximum and the denoising process will run for the full number of + iterations specified in `num_inference_steps`. A value of 1, therefore, essentially ignores the masked + portion of the reference `image`. Note that in the case of `denoising_start` being declared as an + integer, the value of `strength` will be ignored. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + timesteps (`List[int]`, *optional*): + Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument + in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is + passed will be used. Must be in descending order. + denoising_start (`float`, *optional*): + When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be + bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and + it is assumed that the passed `image` is a partly denoised image. Note that when this is specified, + strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline + is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refining the Image + Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output). + denoising_end (`float`, *optional*): + When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be + completed before it is intentionally prematurely terminated. As a result, the returned sample will + still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be + denoised by a successor pipeline that has `denoising_start` set to 0.8 so that it only denoises the + final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline + forms a part of a "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image + Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output). + guidance_scale (`float`, *optional*, defaults to 7.5): + Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). + `guidance_scale` is defined as `w` of equation 2. of [Imagen + Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > + 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + negative_prompt_2 (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and + `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + pooled_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. + If not provided, pooled text embeddings will be generated from `prompt` input argument. + negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt` + input argument. + ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters. + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to + [`schedulers.DDIMScheduler`], will be ignored for others. + generator (`torch.Generator`, *optional*): + One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) + to make generation deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor will ge generated by sampling using the supplied random `generator`. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generate image. Choose between + [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)): + If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled. + `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as + explained in section 2.2 of + [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). + crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)): + `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position + `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting + `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of + [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). + target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)): + For most cases, `target_size` should be set to the desired height and width of the generated image. If + not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in + section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). + negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)): + To negatively condition the generation process based on a specific image resolution. Part of SDXL's + micro-conditioning as explained in section 2.2 of + [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more + information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. + negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)): + To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's + micro-conditioning as explained in section 2.2 of + [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more + information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. + negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)): + To negatively condition the generation process based on a target image resolution. It should be as same + as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of + [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more + information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. + aesthetic_score (`float`, *optional*, defaults to 6.0): + Used to simulate an aesthetic score of the generated image by influencing the positive text condition. + Part of SDXL's micro-conditioning as explained in section 2.2 of + [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). + negative_aesthetic_score (`float`, *optional*, defaults to 2.5): + Part of SDXL's micro-conditioning as explained in section 2.2 of + [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to + simulate an aesthetic score of the generated image by influencing the negative text condition. + clip_skip (`int`, *optional*): + Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that + the output of the pre-final layer will be used for computing the prompt embeddings. + callback_on_step_end (`Callable`, *optional*): + A function that calls at the end of each denoising steps during the inference. The function is called + with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, + callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by + `callback_on_step_end_tensor_inputs`. + callback_on_step_end_tensor_inputs (`List`, *optional*): + The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list + will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the + `._callback_tensor_inputs` attribute of your pipeline class. + + Examples: + + Returns: + [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`: + [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a + `tuple. `tuple. When returning a tuple, the first element is a list with the generated images. + """ + + callback = kwargs.pop("callback", None) + callback_steps = kwargs.pop("callback_steps", None) + + if callback is not None: + deprecate( + "callback", + "1.0.0", + "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`", + ) + if callback_steps is not None: + deprecate( + "callback_steps", + "1.0.0", + "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`", + ) + + # 0. Default height and width to unet + height = height or self.unet.config.sample_size * self.vae_scale_factor + width = width or self.unet.config.sample_size * self.vae_scale_factor + + # 1. Check inputs + self.check_inputs( + prompt, + prompt_2, + image, + mask_image, + height, + width, + strength, + callback_steps, + output_type, + negative_prompt, + negative_prompt_2, + prompt_embeds, + negative_prompt_embeds, + callback_on_step_end_tensor_inputs, + padding_mask_crop, + ) + + self._guidance_scale = guidance_scale + self._guidance_rescale = guidance_rescale + self._clip_skip = clip_skip + self._cross_attention_kwargs = cross_attention_kwargs + self._denoising_end = denoising_end + self._denoising_start = denoising_start + self._interrupt = False + + # 2. Define call parameters + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = self._execution_device + + # 3. Encode input prompt + text_encoder_lora_scale = ( + self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None + ) + + ( + prompt_embeds, + negative_prompt_embeds, + pooled_prompt_embeds, + negative_pooled_prompt_embeds, + ) = self.encode_prompt( + prompt=prompt, + prompt_2=prompt_2, + device=device, + num_images_per_prompt=num_images_per_prompt, + do_classifier_free_guidance=self.do_classifier_free_guidance, + negative_prompt=negative_prompt, + negative_prompt_2=negative_prompt_2, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + pooled_prompt_embeds=pooled_prompt_embeds, + negative_pooled_prompt_embeds=negative_pooled_prompt_embeds, + lora_scale=text_encoder_lora_scale, + clip_skip=self.clip_skip, + ) + + # 4. set timesteps + def denoising_value_valid(dnv): + return isinstance(self.denoising_end, float) and 0 < dnv < 1 + + timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps) + timesteps, num_inference_steps = self.get_timesteps( + num_inference_steps, + strength, + device, + denoising_start=self.denoising_start if denoising_value_valid else None, + ) + # check that number of inference steps is not < 1 - as this doesn't make sense + if num_inference_steps < 1: + raise ValueError( + f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline" + f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline." + ) + # at which timestep to set the initial noise (n.b. 50% if strength is 0.5) + latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt) + # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise + is_strength_max = strength == 1.0 + + # 5. Preprocess mask and image + if padding_mask_crop is not None: + crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop) + resize_mode = "fill" + else: + crops_coords = None + resize_mode = "default" + + original_image = image + init_image = self.image_processor.preprocess( + image, height=height, width=width, crops_coords=crops_coords, resize_mode=resize_mode + ) + init_image = init_image.to(dtype=torch.float32) + + mask = self.mask_processor.preprocess( + mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords + ) + if masked_image_latents is not None: + masked_image = masked_image_latents + elif init_image.shape[1] == 4: + # if images are in latent space, we can't mask it + masked_image = None + else: + masked_image = init_image * (mask < 0.5) + + # 6. Prepare latent variables + num_channels_latents = self.vae.config.latent_channels + num_channels_unet = self.unet.config.in_channels + return_image_latents = num_channels_unet == 4 + + add_noise = True if self.denoising_start is None else False + latents_outputs = self.prepare_latents( + batch_size * num_images_per_prompt, + num_channels_latents, + height, + width, + prompt_embeds.dtype, + device, + generator, + latents, + image=init_image, + timestep=latent_timestep, + is_strength_max=is_strength_max, + add_noise=add_noise, + return_noise=True, + return_image_latents=return_image_latents, + ) + + if return_image_latents: + latents, noise, image_latents = latents_outputs + else: + latents, noise = latents_outputs + + # 7. Prepare mask latent variables + mask, masked_image_latents = self.prepare_mask_latents( + mask, + masked_image, + batch_size * num_images_per_prompt, + height, + width, + prompt_embeds.dtype, + device, + generator, + self.do_classifier_free_guidance, + ) + pose_img = pose_img.to(device=device, dtype=prompt_embeds.dtype) + + pose_img = self.vae.encode(pose_img).latent_dist.sample() + pose_img = pose_img * self.vae.config.scaling_factor + + # pose_img = self._encode_vae_image(pose_img, generator=generator) + + pose_img = ( + torch.cat([pose_img] * 2) if self.do_classifier_free_guidance else pose_img + ) + cloth = self._encode_vae_image(cloth, generator=generator) + + # # 8. Check that sizes of mask, masked image and latents match + # if num_channels_unet == 9: + # # default case for runwayml/stable-diffusion-inpainting + # num_channels_mask = mask.shape[1] + # num_channels_masked_image = masked_image_latents.shape[1] + # if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels: + # raise ValueError( + # f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects" + # f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +" + # f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}" + # f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of" + # " `pipeline.unet` or your `mask_image` or `image` input." + # ) + # elif num_channels_unet != 4: + # raise ValueError( + # f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}." + # ) + # 8.1 Prepare extra step kwargs. + extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) + + # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline + height, width = latents.shape[-2:] + height = height * self.vae_scale_factor + width = width * self.vae_scale_factor + + original_size = original_size or (height, width) + target_size = target_size or (height, width) + + # 10. Prepare added time ids & embeddings + if negative_original_size is None: + negative_original_size = original_size + if negative_target_size is None: + negative_target_size = target_size + + add_text_embeds = pooled_prompt_embeds + if self.text_encoder_2 is None: + text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1]) + else: + text_encoder_projection_dim = self.text_encoder_2.config.projection_dim + + add_time_ids, add_neg_time_ids = self._get_add_time_ids( + original_size, + crops_coords_top_left, + target_size, + aesthetic_score, + negative_aesthetic_score, + negative_original_size, + negative_crops_coords_top_left, + negative_target_size, + dtype=prompt_embeds.dtype, + text_encoder_projection_dim=text_encoder_projection_dim, + ) + add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1) + + if self.do_classifier_free_guidance: + prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0) + add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0) + add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1) + add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0) + + prompt_embeds = prompt_embeds.to(device) + add_text_embeds = add_text_embeds.to(device) + add_time_ids = add_time_ids.to(device) + + if ip_adapter_image is not None: + image_embeds = self.prepare_ip_adapter_image_embeds( + ip_adapter_image, device, batch_size * num_images_per_prompt + ) + + #project outside for loop + image_embeds = self.unet.encoder_hid_proj(image_embeds).to(prompt_embeds.dtype) + + + # 11. Denoising loop + num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0) + + if ( + self.denoising_end is not None + and self.denoising_start is not None + and denoising_value_valid(self.denoising_end) + and denoising_value_valid(self.denoising_start) + and self.denoising_start >= self.denoising_end + ): + raise ValueError( + f"`denoising_start`: {self.denoising_start} cannot be larger than or equal to `denoising_end`: " + + f" {self.denoising_end} when using type float." + ) + elif self.denoising_end is not None and denoising_value_valid(self.denoising_end): + discrete_timestep_cutoff = int( + round( + self.scheduler.config.num_train_timesteps + - (self.denoising_end * self.scheduler.config.num_train_timesteps) + ) + ) + num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps))) + timesteps = timesteps[:num_inference_steps] + + # 11.1 Optionally get Guidance Scale Embedding + timestep_cond = None + if self.unet.config.time_cond_proj_dim is not None: + guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt) + timestep_cond = self.get_guidance_scale_embedding( + guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim + ).to(device=device, dtype=latents.dtype) + + + + self._num_timesteps = len(timesteps) + with self.progress_bar(total=num_inference_steps) as progress_bar: + for i, t in enumerate(timesteps): + if self.interrupt: + continue + # expand the latents if we are doing classifier free guidance + latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents + + # concat latents, mask, masked_image_latents in the channel dimension + latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) + + + # bsz = mask.shape[0] + if num_channels_unet == 13: + latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents,pose_img], dim=1) + + # if num_channels_unet == 9: + # latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1) + + # predict the noise residual + added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids} + if ip_adapter_image is not None: + added_cond_kwargs["image_embeds"] = image_embeds + # down,reference_features = self.UNet_Encoder(cloth,t, text_embeds_cloth,added_cond_kwargs= {"text_embeds": pooled_prompt_embeds_c, "time_ids": add_time_ids},return_dict=False) + down,reference_features = self.unet_encoder(cloth,t, text_embeds_cloth,return_dict=False) + # print(type(reference_features)) + # print(reference_features) + reference_features = list(reference_features) + # print(len(reference_features)) + # for elem in reference_features: + # print(elem.shape) + # exit(1) + if self.do_classifier_free_guidance: + reference_features = [torch.cat([torch.zeros_like(d), d]) for d in reference_features] + + + noise_pred = self.unet( + latent_model_input, + t, + encoder_hidden_states=prompt_embeds, + timestep_cond=timestep_cond, + cross_attention_kwargs=self.cross_attention_kwargs, + added_cond_kwargs=added_cond_kwargs, + return_dict=False, + garment_features=reference_features, + )[0] + # noise_pred = self.unet(latent_model_input, t, + # prompt_embeds,timestep_cond=timestep_cond,cross_attention_kwargs=self.cross_attention_kwargs,added_cond_kwargs=added_cond_kwargs,down_block_additional_attn=down ).sample + + + # perform guidance + if self.do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond) + + if self.do_classifier_free_guidance and self.guidance_rescale > 0.0: + # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf + noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale) + + # compute the previous noisy sample x_t -> x_t-1 + latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] + + if num_channels_unet == 4: + init_latents_proper = image_latents + if self.do_classifier_free_guidance: + init_mask, _ = mask.chunk(2) + else: + init_mask = mask + + if i < len(timesteps) - 1: + noise_timestep = timesteps[i + 1] + init_latents_proper = self.scheduler.add_noise( + init_latents_proper, noise, torch.tensor([noise_timestep]) + ) + + latents = (1 - init_mask) * init_latents_proper + init_mask * latents + + if callback_on_step_end is not None: + callback_kwargs = {} + for k in callback_on_step_end_tensor_inputs: + callback_kwargs[k] = locals()[k] + callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) + + latents = callback_outputs.pop("latents", latents) + prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) + negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) + add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds) + negative_pooled_prompt_embeds = callback_outputs.pop( + "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds + ) + add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids) + add_neg_time_ids = callback_outputs.pop("add_neg_time_ids", add_neg_time_ids) + mask = callback_outputs.pop("mask", mask) + masked_image_latents = callback_outputs.pop("masked_image_latents", masked_image_latents) + + # call the callback, if provided + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + progress_bar.update() + if callback is not None and i % callback_steps == 0: + step_idx = i // getattr(self.scheduler, "order", 1) + callback(step_idx, t, latents) + + if XLA_AVAILABLE: + xm.mark_step() + + if not output_type == "latent": + # make sure the VAE is in float32 mode, as it overflows in float16 + needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast + + if needs_upcasting: + self.upcast_vae() + latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype) + + image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0] + + # cast back to fp16 if needed + if needs_upcasting: + self.vae.to(dtype=torch.float16) + # else: + # return StableDiffusionXLPipelineOutput(images=latents) + + + image = self.image_processor.postprocess(image, output_type=output_type) + + if padding_mask_crop is not None: + image = [self.image_processor.apply_overlay(mask_image, original_image, i, crops_coords) for i in image] + + # Offload all models + self.maybe_free_model_hooks() + + # if not return_dict: + return (image,) + + # return StableDiffusionXLPipelineOutput(images=image) \ No newline at end of file diff --git a/extensions-builtin/forge_space_idm_vton/src/unet_block_hacked_garmnet.py b/extensions-builtin/forge_space_idm_vton/src/unet_block_hacked_garmnet.py new file mode 100644 index 0000000000000000000000000000000000000000..a6e80c058014b83617fa3fd4e26daeb5a0a11ec3 --- /dev/null +++ b/extensions-builtin/forge_space_idm_vton/src/unet_block_hacked_garmnet.py @@ -0,0 +1,3579 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Dict, Optional, Tuple, Union + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +from diffusers.utils import is_torch_version, logging +from diffusers.utils.torch_utils import apply_freeu +from diffusers.models.activations import get_activation +from diffusers.models.attention_processor import Attention, AttnAddedKVProcessor, AttnAddedKVProcessor2_0 +from diffusers.models.dual_transformer_2d import DualTransformer2DModel +from diffusers.models.normalization import AdaGroupNorm +from diffusers.models.resnet import Downsample2D, FirDownsample2D, FirUpsample2D, KDownsample2D, KUpsample2D, ResnetBlock2D, Upsample2D +from src.transformerhacked_garmnet import Transformer2DModel +from einops import rearrange + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +def get_down_block( + down_block_type: str, + num_layers: int, + in_channels: int, + out_channels: int, + temb_channels: int, + add_downsample: bool, + resnet_eps: float, + resnet_act_fn: str, + transformer_layers_per_block: int = 1, + num_attention_heads: Optional[int] = None, + resnet_groups: Optional[int] = None, + cross_attention_dim: Optional[int] = None, + downsample_padding: Optional[int] = None, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + only_cross_attention: bool = False, + upcast_attention: bool = False, + resnet_time_scale_shift: str = "default", + attention_type: str = "default", + resnet_skip_time_act: bool = False, + resnet_out_scale_factor: float = 1.0, + cross_attention_norm: Optional[str] = None, + attention_head_dim: Optional[int] = None, + downsample_type: Optional[str] = None, + dropout: float = 0.0, +): + # If attn head dim is not defined, we default it to the number of heads + if attention_head_dim is None: + logger.warn( + f"It is recommended to provide `attention_head_dim` when calling `get_down_block`. Defaulting `attention_head_dim` to {num_attention_heads}." + ) + attention_head_dim = num_attention_heads + + down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_type + if down_block_type == "DownBlock2D": + return DownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + downsample_padding=downsample_padding, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif down_block_type == "ResnetDownsampleBlock2D": + return ResnetDownsampleBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + skip_time_act=resnet_skip_time_act, + output_scale_factor=resnet_out_scale_factor, + ) + elif down_block_type == "AttnDownBlock2D": + if add_downsample is False: + downsample_type = None + else: + downsample_type = downsample_type or "conv" # default to 'conv' + return AttnDownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + downsample_padding=downsample_padding, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + downsample_type=downsample_type, + ) + elif down_block_type == "CrossAttnDownBlock2D": + if cross_attention_dim is None: + raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock2D") + return CrossAttnDownBlock2D( + num_layers=num_layers, + transformer_layers_per_block=transformer_layers_per_block, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + downsample_padding=downsample_padding, + cross_attention_dim=cross_attention_dim, + num_attention_heads=num_attention_heads, + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + resnet_time_scale_shift=resnet_time_scale_shift, + attention_type=attention_type, + ) + elif down_block_type == "SimpleCrossAttnDownBlock2D": + if cross_attention_dim is None: + raise ValueError("cross_attention_dim must be specified for SimpleCrossAttnDownBlock2D") + return SimpleCrossAttnDownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + cross_attention_dim=cross_attention_dim, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + skip_time_act=resnet_skip_time_act, + output_scale_factor=resnet_out_scale_factor, + only_cross_attention=only_cross_attention, + cross_attention_norm=cross_attention_norm, + ) + elif down_block_type == "SkipDownBlock2D": + return SkipDownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + downsample_padding=downsample_padding, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif down_block_type == "AttnSkipDownBlock2D": + return AttnSkipDownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif down_block_type == "DownEncoderBlock2D": + return DownEncoderBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + downsample_padding=downsample_padding, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif down_block_type == "AttnDownEncoderBlock2D": + return AttnDownEncoderBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + downsample_padding=downsample_padding, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif down_block_type == "KDownBlock2D": + return KDownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + ) + elif down_block_type == "KCrossAttnDownBlock2D": + return KCrossAttnDownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + cross_attention_dim=cross_attention_dim, + attention_head_dim=attention_head_dim, + add_self_attention=True if not add_downsample else False, + ) + raise ValueError(f"{down_block_type} does not exist.") + + +def get_up_block( + up_block_type: str, + num_layers: int, + in_channels: int, + out_channels: int, + prev_output_channel: int, + temb_channels: int, + add_upsample: bool, + resnet_eps: float, + resnet_act_fn: str, + resolution_idx: Optional[int] = None, + transformer_layers_per_block: int = 1, + num_attention_heads: Optional[int] = None, + resnet_groups: Optional[int] = None, + cross_attention_dim: Optional[int] = None, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + only_cross_attention: bool = False, + upcast_attention: bool = False, + resnet_time_scale_shift: str = "default", + attention_type: str = "default", + resnet_skip_time_act: bool = False, + resnet_out_scale_factor: float = 1.0, + cross_attention_norm: Optional[str] = None, + attention_head_dim: Optional[int] = None, + upsample_type: Optional[str] = None, + dropout: float = 0.0, +) -> nn.Module: + # If attn head dim is not defined, we default it to the number of heads + if attention_head_dim is None: + logger.warn( + f"It is recommended to provide `attention_head_dim` when calling `get_up_block`. Defaulting `attention_head_dim` to {num_attention_heads}." + ) + attention_head_dim = num_attention_heads + + up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type + if up_block_type == "UpBlock2D": + return UpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif up_block_type == "ResnetUpsampleBlock2D": + return ResnetUpsampleBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + skip_time_act=resnet_skip_time_act, + output_scale_factor=resnet_out_scale_factor, + ) + elif up_block_type == "CrossAttnUpBlock2D": + if cross_attention_dim is None: + raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock2D") + return CrossAttnUpBlock2D( + num_layers=num_layers, + transformer_layers_per_block=transformer_layers_per_block, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + cross_attention_dim=cross_attention_dim, + num_attention_heads=num_attention_heads, + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + resnet_time_scale_shift=resnet_time_scale_shift, + attention_type=attention_type, + ) + elif up_block_type == "SimpleCrossAttnUpBlock2D": + if cross_attention_dim is None: + raise ValueError("cross_attention_dim must be specified for SimpleCrossAttnUpBlock2D") + return SimpleCrossAttnUpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + cross_attention_dim=cross_attention_dim, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + skip_time_act=resnet_skip_time_act, + output_scale_factor=resnet_out_scale_factor, + only_cross_attention=only_cross_attention, + cross_attention_norm=cross_attention_norm, + ) + elif up_block_type == "AttnUpBlock2D": + if add_upsample is False: + upsample_type = None + else: + upsample_type = upsample_type or "conv" # default to 'conv' + + return AttnUpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + upsample_type=upsample_type, + ) + elif up_block_type == "SkipUpBlock2D": + return SkipUpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif up_block_type == "AttnSkipUpBlock2D": + return AttnSkipUpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif up_block_type == "UpDecoderBlock2D": + return UpDecoderBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + temb_channels=temb_channels, + ) + elif up_block_type == "AttnUpDecoderBlock2D": + return AttnUpDecoderBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + temb_channels=temb_channels, + ) + elif up_block_type == "KUpBlock2D": + return KUpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + ) + elif up_block_type == "KCrossAttnUpBlock2D": + return KCrossAttnUpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + cross_attention_dim=cross_attention_dim, + attention_head_dim=attention_head_dim, + ) + + raise ValueError(f"{up_block_type} does not exist.") + + +class AutoencoderTinyBlock(nn.Module): + """ + Tiny Autoencoder block used in [`AutoencoderTiny`]. It is a mini residual module consisting of plain conv + ReLU + blocks. + + Args: + in_channels (`int`): The number of input channels. + out_channels (`int`): The number of output channels. + act_fn (`str`): + ` The activation function to use. Supported values are `"swish"`, `"mish"`, `"gelu"`, and `"relu"`. + + Returns: + `torch.FloatTensor`: A tensor with the same shape as the input tensor, but with the number of channels equal to + `out_channels`. + """ + + def __init__(self, in_channels: int, out_channels: int, act_fn: str): + super().__init__() + act_fn = get_activation(act_fn) + self.conv = nn.Sequential( + nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), + act_fn, + nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1), + act_fn, + nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1), + ) + self.skip = ( + nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) + if in_channels != out_channels + else nn.Identity() + ) + self.fuse = nn.ReLU() + + def forward(self, x: torch.FloatTensor) -> torch.FloatTensor: + return self.fuse(self.conv(x) + self.skip(x)) + + +class UNetMidBlock2D(nn.Module): + """ + A 2D UNet mid-block [`UNetMidBlock2D`] with multiple residual blocks and optional attention blocks. + + Args: + in_channels (`int`): The number of input channels. + temb_channels (`int`): The number of temporal embedding channels. + dropout (`float`, *optional*, defaults to 0.0): The dropout rate. + num_layers (`int`, *optional*, defaults to 1): The number of residual blocks. + resnet_eps (`float`, *optional*, 1e-6 ): The epsilon value for the resnet blocks. + resnet_time_scale_shift (`str`, *optional*, defaults to `default`): + The type of normalization to apply to the time embeddings. This can help to improve the performance of the + model on tasks with long-range temporal dependencies. + resnet_act_fn (`str`, *optional*, defaults to `swish`): The activation function for the resnet blocks. + resnet_groups (`int`, *optional*, defaults to 32): + The number of groups to use in the group normalization layers of the resnet blocks. + attn_groups (`Optional[int]`, *optional*, defaults to None): The number of groups for the attention blocks. + resnet_pre_norm (`bool`, *optional*, defaults to `True`): + Whether to use pre-normalization for the resnet blocks. + add_attention (`bool`, *optional*, defaults to `True`): Whether to add attention blocks. + attention_head_dim (`int`, *optional*, defaults to 1): + Dimension of a single attention head. The number of attention heads is determined based on this value and + the number of input channels. + output_scale_factor (`float`, *optional*, defaults to 1.0): The output scale factor. + + Returns: + `torch.FloatTensor`: The output of the last residual block, which is a tensor of shape `(batch_size, + in_channels, height, width)`. + + """ + + def __init__( + self, + in_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", # default, spatial + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + attn_groups: Optional[int] = None, + resnet_pre_norm: bool = True, + add_attention: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = 1.0, + ): + super().__init__() + resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32) + self.add_attention = add_attention + + if attn_groups is None: + attn_groups = resnet_groups if resnet_time_scale_shift == "default" else None + + # there is always at least one resnet + resnets = [ + ResnetBlock2D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ] + attentions = [] + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {in_channels}." + ) + attention_head_dim = in_channels + + for _ in range(num_layers): + if self.add_attention: + attentions.append( + Attention( + in_channels, + heads=in_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=attn_groups, + spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + else: + attentions.append(None) + + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + def forward(self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None) -> torch.FloatTensor: + hidden_states = self.resnets[0](hidden_states, temb) + for attn, resnet in zip(self.attentions, self.resnets[1:]): + if attn is not None: + hidden_states = attn(hidden_states, temb=temb) + hidden_states = resnet(hidden_states, temb) + + return hidden_states + + +class UNetMidBlock2DCrossAttn(nn.Module): + def __init__( + self, + in_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + transformer_layers_per_block: Union[int, Tuple[int]] = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + num_attention_heads: int = 1, + output_scale_factor: float = 1.0, + cross_attention_dim: int = 1280, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + upcast_attention: bool = False, + attention_type: str = "default", + ): + super().__init__() + + self.has_cross_attention = True + self.num_attention_heads = num_attention_heads + resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32) + + # support for variable transformer layers per block + if isinstance(transformer_layers_per_block, int): + transformer_layers_per_block = [transformer_layers_per_block] * num_layers + + # there is always at least one resnet + resnets = [ + ResnetBlock2D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ] + attentions = [] + + for i in range(num_layers): + if not dual_cross_attention: + attentions.append( + Transformer2DModel( + num_attention_heads, + in_channels // num_attention_heads, + in_channels=in_channels, + num_layers=transformer_layers_per_block[i], + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + use_linear_projection=use_linear_projection, + upcast_attention=upcast_attention, + attention_type=attention_type, + ) + ) + else: + attentions.append( + DualTransformer2DModel( + num_attention_heads, + in_channels // num_attention_heads, + in_channels=in_channels, + num_layers=1, + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + ) + ) + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + hidden_states = self.resnets[0](hidden_states, temb, scale=lora_scale) + garment_features = [] + for attn, resnet in zip(self.attentions, self.resnets[1:]): + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + # hidden_states = attn( + hidden_states,out_garment_feat = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + return_dict=False, + ) + hidden_states=hidden_states[0] + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), + hidden_states, + temb, + **ckpt_kwargs, + ) + else: + # hidden_states= attn( + hidden_states,out_garment_feat = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + return_dict=False, + ) + hidden_states=hidden_states[0] + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + garment_features += out_garment_feat + return hidden_states,garment_features + # return hidden_states + + +class UNetMidBlock2DSimpleCrossAttn(nn.Module): + def __init__( + self, + in_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = 1.0, + cross_attention_dim: int = 1280, + skip_time_act: bool = False, + only_cross_attention: bool = False, + cross_attention_norm: Optional[str] = None, + ): + super().__init__() + + self.has_cross_attention = True + + self.attention_head_dim = attention_head_dim + resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32) + + self.num_heads = in_channels // self.attention_head_dim + + # there is always at least one resnet + resnets = [ + ResnetBlock2D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + ) + ] + attentions = [] + + for _ in range(num_layers): + processor = ( + AttnAddedKVProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnAddedKVProcessor() + ) + + attentions.append( + Attention( + query_dim=in_channels, + cross_attention_dim=in_channels, + heads=self.num_heads, + dim_head=self.attention_head_dim, + added_kv_proj_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + bias=True, + upcast_softmax=True, + only_cross_attention=only_cross_attention, + cross_attention_norm=cross_attention_norm, + processor=processor, + ) + ) + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {} + lora_scale = cross_attention_kwargs.get("scale", 1.0) + + if attention_mask is None: + # if encoder_hidden_states is defined: we are doing cross-attn, so we should use cross-attn mask. + mask = None if encoder_hidden_states is None else encoder_attention_mask + else: + # when attention_mask is defined: we don't even check for encoder_attention_mask. + # this is to maintain compatibility with UnCLIP, which uses 'attention_mask' param for cross-attn masks. + # TODO: UnCLIP should express cross-attn mask via encoder_attention_mask param instead of via attention_mask. + # then we can simplify this whole if/else block to: + # mask = attention_mask if encoder_hidden_states is None else encoder_attention_mask + mask = attention_mask + + hidden_states = self.resnets[0](hidden_states, temb, scale=lora_scale) + for attn, resnet in zip(self.attentions, self.resnets[1:]): + # attn + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=mask, + **cross_attention_kwargs, + ) + + # resnet + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + + return hidden_states + + +class AttnDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = 1.0, + downsample_padding: int = 1, + downsample_type: str = "conv", + ): + super().__init__() + resnets = [] + attentions = [] + self.downsample_type = downsample_type + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {out_channels}." + ) + attention_head_dim = out_channels + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + attentions.append( + Attention( + out_channels, + heads=out_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=resnet_groups, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if downsample_type == "conv": + self.downsamplers = nn.ModuleList( + [ + Downsample2D( + out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op" + ) + ] + ) + elif downsample_type == "resnet": + self.downsamplers = nn.ModuleList( + [ + ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + down=True, + ) + ] + ) + else: + self.downsamplers = None + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + upsample_size: Optional[int] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {} + + lora_scale = cross_attention_kwargs.get("scale", 1.0) + + output_states = () + + for resnet, attn in zip(self.resnets, self.attentions): + cross_attention_kwargs.update({"scale": lora_scale}) + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + hidden_states = attn(hidden_states, **cross_attention_kwargs) + output_states = output_states + (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + if self.downsample_type == "resnet": + hidden_states = downsampler(hidden_states, temb=temb, scale=lora_scale) + else: + hidden_states = downsampler(hidden_states, scale=lora_scale) + + output_states += (hidden_states,) + + return hidden_states, output_states + + +class CrossAttnDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + transformer_layers_per_block: Union[int, Tuple[int]] = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + num_attention_heads: int = 1, + cross_attention_dim: int = 1280, + output_scale_factor: float = 1.0, + downsample_padding: int = 1, + add_downsample: bool = True, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + only_cross_attention: bool = False, + upcast_attention: bool = False, + attention_type: str = "default", + ): + super().__init__() + resnets = [] + attentions = [] + + self.has_cross_attention = True + self.num_attention_heads = num_attention_heads + if isinstance(transformer_layers_per_block, int): + transformer_layers_per_block = [transformer_layers_per_block] * num_layers + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + if not dual_cross_attention: + attentions.append( + Transformer2DModel( + num_attention_heads, + out_channels // num_attention_heads, + in_channels=out_channels, + num_layers=transformer_layers_per_block[i], + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + attention_type=attention_type, + ) + ) + else: + attentions.append( + DualTransformer2DModel( + num_attention_heads, + out_channels // num_attention_heads, + in_channels=out_channels, + num_layers=1, + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + ) + ) + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + Downsample2D( + out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op" + ) + ] + ) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + additional_residuals: Optional[torch.FloatTensor] = None, + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + output_states = () + + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + + blocks = list(zip(self.resnets, self.attentions)) + garment_features = [] + for i, (resnet, attn) in enumerate(blocks): + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), + hidden_states, + temb, + **ckpt_kwargs, + ) + hidden_states,out_garment_feat = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + return_dict=False, + ) + hidden_states=hidden_states[0] + else: + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + hidden_states,out_garment_feat = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + return_dict=False, + ) + hidden_states=hidden_states[0] + garment_features += out_garment_feat + # apply additional residuals to the output of the last pair of resnet and attention blocks + if i == len(blocks) - 1 and additional_residuals is not None: + hidden_states = hidden_states + additional_residuals + + output_states = output_states + (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states, scale=lora_scale) + + output_states = output_states + (hidden_states,) + + return hidden_states, output_states,garment_features + + +class DownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor: float = 1.0, + add_downsample: bool = True, + downsample_padding: int = 1, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + Downsample2D( + out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op" + ) + ] + ) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0 + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + output_states = () + + for resnet in self.resnets: + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + if is_torch_version(">=", "1.11.0"): + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + ) + else: + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb, scale=scale) + + output_states = output_states + (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states, scale=scale) + + output_states = output_states + (hidden_states,) + + return hidden_states, output_states + + +class DownEncoderBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor: float = 1.0, + add_downsample: bool = True, + downsample_padding: int = 1, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=None, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + Downsample2D( + out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op" + ) + ] + ) + else: + self.downsamplers = None + + def forward(self, hidden_states: torch.FloatTensor, scale: float = 1.0) -> torch.FloatTensor: + for resnet in self.resnets: + hidden_states = resnet(hidden_states, temb=None, scale=scale) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states, scale) + + return hidden_states + + +class AttnDownEncoderBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = 1.0, + add_downsample: bool = True, + downsample_padding: int = 1, + ): + super().__init__() + resnets = [] + attentions = [] + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {out_channels}." + ) + attention_head_dim = out_channels + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=None, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + attentions.append( + Attention( + out_channels, + heads=out_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=resnet_groups, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + Downsample2D( + out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op" + ) + ] + ) + else: + self.downsamplers = None + + def forward(self, hidden_states: torch.FloatTensor, scale: float = 1.0) -> torch.FloatTensor: + for resnet, attn in zip(self.resnets, self.attentions): + hidden_states = resnet(hidden_states, temb=None, scale=scale) + cross_attention_kwargs = {"scale": scale} + hidden_states = attn(hidden_states, **cross_attention_kwargs) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states, scale) + + return hidden_states + + +class AttnSkipDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = np.sqrt(2.0), + add_downsample: bool = True, + ): + super().__init__() + self.attentions = nn.ModuleList([]) + self.resnets = nn.ModuleList([]) + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {out_channels}." + ) + attention_head_dim = out_channels + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + self.resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(in_channels // 4, 32), + groups_out=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + self.attentions.append( + Attention( + out_channels, + heads=out_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=32, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + + if add_downsample: + self.resnet_down = ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + use_in_shortcut=True, + down=True, + kernel="fir", + ) + self.downsamplers = nn.ModuleList([FirDownsample2D(out_channels, out_channels=out_channels)]) + self.skip_conv = nn.Conv2d(3, out_channels, kernel_size=(1, 1), stride=(1, 1)) + else: + self.resnet_down = None + self.downsamplers = None + self.skip_conv = None + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + skip_sample: Optional[torch.FloatTensor] = None, + scale: float = 1.0, + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...], torch.FloatTensor]: + output_states = () + + for resnet, attn in zip(self.resnets, self.attentions): + hidden_states = resnet(hidden_states, temb, scale=scale) + cross_attention_kwargs = {"scale": scale} + hidden_states = attn(hidden_states, **cross_attention_kwargs) + output_states += (hidden_states,) + + if self.downsamplers is not None: + hidden_states = self.resnet_down(hidden_states, temb, scale=scale) + for downsampler in self.downsamplers: + skip_sample = downsampler(skip_sample) + + hidden_states = self.skip_conv(skip_sample) + hidden_states + + output_states += (hidden_states,) + + return hidden_states, output_states, skip_sample + + +class SkipDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_pre_norm: bool = True, + output_scale_factor: float = np.sqrt(2.0), + add_downsample: bool = True, + downsample_padding: int = 1, + ): + super().__init__() + self.resnets = nn.ModuleList([]) + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + self.resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(in_channels // 4, 32), + groups_out=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + if add_downsample: + self.resnet_down = ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + use_in_shortcut=True, + down=True, + kernel="fir", + ) + self.downsamplers = nn.ModuleList([FirDownsample2D(out_channels, out_channels=out_channels)]) + self.skip_conv = nn.Conv2d(3, out_channels, kernel_size=(1, 1), stride=(1, 1)) + else: + self.resnet_down = None + self.downsamplers = None + self.skip_conv = None + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + skip_sample: Optional[torch.FloatTensor] = None, + scale: float = 1.0, + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...], torch.FloatTensor]: + output_states = () + + for resnet in self.resnets: + hidden_states = resnet(hidden_states, temb, scale) + output_states += (hidden_states,) + + if self.downsamplers is not None: + hidden_states = self.resnet_down(hidden_states, temb, scale) + for downsampler in self.downsamplers: + skip_sample = downsampler(skip_sample) + + hidden_states = self.skip_conv(skip_sample) + hidden_states + + output_states += (hidden_states,) + + return hidden_states, output_states, skip_sample + + +class ResnetDownsampleBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor: float = 1.0, + add_downsample: bool = True, + skip_time_act: bool = False, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + down=True, + ) + ] + ) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0 + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + output_states = () + + for resnet in self.resnets: + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + if is_torch_version(">=", "1.11.0"): + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + ) + else: + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb, scale) + + output_states = output_states + (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states, temb, scale) + + output_states = output_states + (hidden_states,) + + return hidden_states, output_states + + +class SimpleCrossAttnDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + cross_attention_dim: int = 1280, + output_scale_factor: float = 1.0, + add_downsample: bool = True, + skip_time_act: bool = False, + only_cross_attention: bool = False, + cross_attention_norm: Optional[str] = None, + ): + super().__init__() + + self.has_cross_attention = True + + resnets = [] + attentions = [] + + self.attention_head_dim = attention_head_dim + self.num_heads = out_channels // self.attention_head_dim + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + ) + ) + + processor = ( + AttnAddedKVProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnAddedKVProcessor() + ) + + attentions.append( + Attention( + query_dim=out_channels, + cross_attention_dim=out_channels, + heads=self.num_heads, + dim_head=attention_head_dim, + added_kv_proj_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + bias=True, + upcast_softmax=True, + only_cross_attention=only_cross_attention, + cross_attention_norm=cross_attention_norm, + processor=processor, + ) + ) + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + down=True, + ) + ] + ) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + output_states = () + cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {} + + lora_scale = cross_attention_kwargs.get("scale", 1.0) + + if attention_mask is None: + # if encoder_hidden_states is defined: we are doing cross-attn, so we should use cross-attn mask. + mask = None if encoder_hidden_states is None else encoder_attention_mask + else: + # when attention_mask is defined: we don't even check for encoder_attention_mask. + # this is to maintain compatibility with UnCLIP, which uses 'attention_mask' param for cross-attn masks. + # TODO: UnCLIP should express cross-attn mask via encoder_attention_mask param instead of via attention_mask. + # then we can simplify this whole if/else block to: + # mask = attention_mask if encoder_hidden_states is None else encoder_attention_mask + mask = attention_mask + + for resnet, attn in zip(self.resnets, self.attentions): + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb) + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=mask, + **cross_attention_kwargs, + ) + else: + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=mask, + **cross_attention_kwargs, + ) + + output_states = output_states + (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states, temb, scale=lora_scale) + + output_states = output_states + (hidden_states,) + + return hidden_states, output_states + + +class KDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 4, + resnet_eps: float = 1e-5, + resnet_act_fn: str = "gelu", + resnet_group_size: int = 32, + add_downsample: bool = False, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + groups = in_channels // resnet_group_size + groups_out = out_channels // resnet_group_size + + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + dropout=dropout, + temb_channels=temb_channels, + groups=groups, + groups_out=groups_out, + eps=resnet_eps, + non_linearity=resnet_act_fn, + time_embedding_norm="ada_group", + conv_shortcut_bias=False, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + # YiYi's comments- might be able to use FirDownsample2D, look into details later + self.downsamplers = nn.ModuleList([KDownsample2D()]) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0 + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + output_states = () + + for resnet in self.resnets: + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + if is_torch_version(">=", "1.11.0"): + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + ) + else: + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb, scale) + + output_states += (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states) + + return hidden_states, output_states + + +class KCrossAttnDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + cross_attention_dim: int, + dropout: float = 0.0, + num_layers: int = 4, + resnet_group_size: int = 32, + add_downsample: bool = True, + attention_head_dim: int = 64, + add_self_attention: bool = False, + resnet_eps: float = 1e-5, + resnet_act_fn: str = "gelu", + ): + super().__init__() + resnets = [] + attentions = [] + + self.has_cross_attention = True + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + groups = in_channels // resnet_group_size + groups_out = out_channels // resnet_group_size + + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + dropout=dropout, + temb_channels=temb_channels, + groups=groups, + groups_out=groups_out, + eps=resnet_eps, + non_linearity=resnet_act_fn, + time_embedding_norm="ada_group", + conv_shortcut_bias=False, + ) + ) + attentions.append( + KAttentionBlock( + out_channels, + out_channels // attention_head_dim, + attention_head_dim, + cross_attention_dim=cross_attention_dim, + temb_channels=temb_channels, + attention_bias=True, + add_self_attention=add_self_attention, + cross_attention_norm="layer_norm", + group_size=resnet_group_size, + ) + ) + + self.resnets = nn.ModuleList(resnets) + self.attentions = nn.ModuleList(attentions) + + if add_downsample: + self.downsamplers = nn.ModuleList([KDownsample2D()]) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + output_states = () + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + + for resnet, attn in zip(self.resnets, self.attentions): + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), + hidden_states, + temb, + **ckpt_kwargs, + ) + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + emb=temb, + attention_mask=attention_mask, + cross_attention_kwargs=cross_attention_kwargs, + encoder_attention_mask=encoder_attention_mask, + ) + else: + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + emb=temb, + attention_mask=attention_mask, + cross_attention_kwargs=cross_attention_kwargs, + encoder_attention_mask=encoder_attention_mask, + ) + + if self.downsamplers is None: + output_states += (None,) + else: + output_states += (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states) + + return hidden_states, output_states + + +class AttnUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + prev_output_channel: int, + out_channels: int, + temb_channels: int, + resolution_idx: int = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = 1.0, + upsample_type: str = "conv", + ): + super().__init__() + resnets = [] + attentions = [] + + self.upsample_type = upsample_type + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {out_channels}." + ) + attention_head_dim = out_channels + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + attentions.append( + Attention( + out_channels, + heads=out_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=resnet_groups, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if upsample_type == "conv": + self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]) + elif upsample_type == "resnet": + self.upsamplers = nn.ModuleList( + [ + ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + up=True, + ) + ] + ) + else: + self.upsamplers = None + + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + upsample_size: Optional[int] = None, + scale: float = 1.0, + ) -> torch.FloatTensor: + for resnet, attn in zip(self.resnets, self.attentions): + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + hidden_states = resnet(hidden_states, temb, scale=scale) + cross_attention_kwargs = {"scale": scale} + hidden_states = attn(hidden_states, **cross_attention_kwargs) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + if self.upsample_type == "resnet": + hidden_states = upsampler(hidden_states, temb=temb, scale=scale) + else: + hidden_states = upsampler(hidden_states, scale=scale) + + return hidden_states + + +class CrossAttnUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + prev_output_channel: int, + temb_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + transformer_layers_per_block: Union[int, Tuple[int]] = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + num_attention_heads: int = 1, + cross_attention_dim: int = 1280, + output_scale_factor: float = 1.0, + add_upsample: bool = True, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + only_cross_attention: bool = False, + upcast_attention: bool = False, + attention_type: str = "default", + ): + super().__init__() + resnets = [] + attentions = [] + + self.has_cross_attention = True + self.num_attention_heads = num_attention_heads + + if isinstance(transformer_layers_per_block, int): + transformer_layers_per_block = [transformer_layers_per_block] * num_layers + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + if not dual_cross_attention: + attentions.append( + Transformer2DModel( + num_attention_heads, + out_channels // num_attention_heads, + in_channels=out_channels, + num_layers=transformer_layers_per_block[i], + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + attention_type=attention_type, + ) + ) + else: + attentions.append( + DualTransformer2DModel( + num_attention_heads, + out_channels // num_attention_heads, + in_channels=out_channels, + num_layers=1, + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + ) + ) + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + upsample_size: Optional[int] = None, + attention_mask: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + is_freeu_enabled = ( + getattr(self, "s1", None) + and getattr(self, "s2", None) + and getattr(self, "b1", None) + and getattr(self, "b2", None) + ) + garment_features = [] + for resnet, attn in zip(self.resnets, self.attentions): + # pop res hidden states + # print("h.shape") + # print(h.shape) + # print("hidden_states.shape) + # print(hidden_states.shape) + # print("attn_block") + # print(attn) + + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + + # FreeU: Only operate on the first two stages + if is_freeu_enabled: + hidden_states, res_hidden_states = apply_freeu( + self.resolution_idx, + hidden_states, + res_hidden_states, + s1=self.s1, + s2=self.s2, + b1=self.b1, + b2=self.b2, + ) + + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + # print(hidden_states.shape) + # print(encoder_hidden_states.shape) + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), + hidden_states, + temb, + **ckpt_kwargs, + ) + hidden_states,out_garment_feat = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + return_dict=False, + ) + hidden_states=hidden_states[0] + else: + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + hidden_states,out_garment_feat = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + return_dict=False, + ) + hidden_states=hidden_states[0] + garment_features += out_garment_feat + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states, upsample_size, scale=lora_scale) + + return hidden_states,garment_features + + +class UpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + prev_output_channel: int, + out_channels: int, + temb_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor: float = 1.0, + add_upsample: bool = True, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + upsample_size: Optional[int] = None, + scale: float = 1.0, + ) -> torch.FloatTensor: + is_freeu_enabled = ( + getattr(self, "s1", None) + and getattr(self, "s2", None) + and getattr(self, "b1", None) + and getattr(self, "b2", None) + ) + + for resnet in self.resnets: + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + + # FreeU: Only operate on the first two stages + if is_freeu_enabled: + hidden_states, res_hidden_states = apply_freeu( + self.resolution_idx, + hidden_states, + res_hidden_states, + s1=self.s1, + s2=self.s2, + b1=self.b1, + b2=self.b2, + ) + + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + if is_torch_version(">=", "1.11.0"): + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + ) + else: + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb, scale=scale) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states, upsample_size, scale=scale) + + return hidden_states + # def forward( + # self, + # hidden_states: torch.FloatTensor, + # res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + # temb: Optional[torch.FloatTensor] = None, + # upsample_size: Optional[int] = None, + # scale: float = 1.0, + # zero_block=None, + # hint=None, + # ) -> torch.FloatTensor: + # is_freeu_enabled = ( + # getattr(self, "s1", None) + # and getattr(self, "s2", None) + # and getattr(self, "b1", None) + # and getattr(self, "b2", None) + # ) + + # # print(len(self.resnets)) + # # print(len(zero_block)) + # # print(len(hint)) + # # for resnet in self.resnets: + # for resnet, zero,h in zip(self.resnets,zero_block,hint): + + # # pop res hidden states + # res_hidden_states = res_hidden_states_tuple[-1] + # res_hidden_states_tuple = res_hidden_states_tuple[:-1] + + # res_hidden_states = res_hidden_states + zero(h) + # # FreeU: Only operate on the first two stages + # if is_freeu_enabled: + # hidden_states, res_hidden_states = apply_freeu( + # self.resolution_idx, + # hidden_states, + # res_hidden_states, + # s1=self.s1, + # s2=self.s2, + # b1=self.b1, + # b2=self.b2, + # ) + + # # print(hidden_states.shape) + # # # print(h.shape) + # # print(res_hidden_states.shape) + # hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + # # print(hidden_states.shape) + + # if self.training and self.gradient_checkpointing: + + # def create_custom_forward(module): + # def custom_forward(*inputs): + # return module(*inputs) + + # return custom_forward + + # if is_torch_version(">=", "1.11.0"): + # hidden_states = torch.utils.checkpoint.checkpoint( + # create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + # ) + # else: + # hidden_states = torch.utils.checkpoint.checkpoint( + # create_custom_forward(resnet), hidden_states, temb + # ) + # else: + # hidden_states = resnet(hidden_states, temb, scale=scale) + + # if self.upsamplers is not None: + # for upsampler in self.upsamplers: + # hidden_states = upsampler(hidden_states, upsample_size, scale=scale) + + # return hidden_states + + +class UpDecoderBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", # default, spatial + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor: float = 1.0, + add_upsample: bool = True, + temb_channels: Optional[int] = None, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + input_channels = in_channels if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=input_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]) + else: + self.upsamplers = None + + self.resolution_idx = resolution_idx + + def forward( + self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0 + ) -> torch.FloatTensor: + for resnet in self.resnets: + hidden_states = resnet(hidden_states, temb=temb, scale=scale) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states) + + return hidden_states + + +class AttnUpDecoderBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = 1.0, + add_upsample: bool = True, + temb_channels: Optional[int] = None, + ): + super().__init__() + resnets = [] + attentions = [] + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `out_channels`: {out_channels}." + ) + attention_head_dim = out_channels + + for i in range(num_layers): + input_channels = in_channels if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=input_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + attentions.append( + Attention( + out_channels, + heads=out_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=resnet_groups if resnet_time_scale_shift != "spatial" else None, + spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]) + else: + self.upsamplers = None + + self.resolution_idx = resolution_idx + + def forward( + self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0 + ) -> torch.FloatTensor: + for resnet, attn in zip(self.resnets, self.attentions): + hidden_states = resnet(hidden_states, temb=temb, scale=scale) + cross_attention_kwargs = {"scale": scale} + hidden_states = attn(hidden_states, temb=temb, **cross_attention_kwargs) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states, scale=scale) + + return hidden_states + + +class AttnSkipUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + prev_output_channel: int, + out_channels: int, + temb_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = np.sqrt(2.0), + add_upsample: bool = True, + ): + super().__init__() + self.attentions = nn.ModuleList([]) + self.resnets = nn.ModuleList([]) + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + self.resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(resnet_in_channels + res_skip_channels // 4, 32), + groups_out=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `out_channels`: {out_channels}." + ) + attention_head_dim = out_channels + + self.attentions.append( + Attention( + out_channels, + heads=out_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=32, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + + self.upsampler = FirUpsample2D(in_channels, out_channels=out_channels) + if add_upsample: + self.resnet_up = ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(out_channels // 4, 32), + groups_out=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + use_in_shortcut=True, + up=True, + kernel="fir", + ) + self.skip_conv = nn.Conv2d(out_channels, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) + self.skip_norm = torch.nn.GroupNorm( + num_groups=min(out_channels // 4, 32), num_channels=out_channels, eps=resnet_eps, affine=True + ) + self.act = nn.SiLU() + else: + self.resnet_up = None + self.skip_conv = None + self.skip_norm = None + self.act = None + + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + skip_sample=None, + scale: float = 1.0, + ) -> Tuple[torch.FloatTensor, torch.FloatTensor]: + for resnet in self.resnets: + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + hidden_states = resnet(hidden_states, temb, scale=scale) + + cross_attention_kwargs = {"scale": scale} + hidden_states = self.attentions[0](hidden_states, **cross_attention_kwargs) + + if skip_sample is not None: + skip_sample = self.upsampler(skip_sample) + else: + skip_sample = 0 + + if self.resnet_up is not None: + skip_sample_states = self.skip_norm(hidden_states) + skip_sample_states = self.act(skip_sample_states) + skip_sample_states = self.skip_conv(skip_sample_states) + + skip_sample = skip_sample + skip_sample_states + + hidden_states = self.resnet_up(hidden_states, temb, scale=scale) + + return hidden_states, skip_sample + + +class SkipUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + prev_output_channel: int, + out_channels: int, + temb_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_pre_norm: bool = True, + output_scale_factor: float = np.sqrt(2.0), + add_upsample: bool = True, + upsample_padding: int = 1, + ): + super().__init__() + self.resnets = nn.ModuleList([]) + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + self.resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min((resnet_in_channels + res_skip_channels) // 4, 32), + groups_out=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.upsampler = FirUpsample2D(in_channels, out_channels=out_channels) + if add_upsample: + self.resnet_up = ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(out_channels // 4, 32), + groups_out=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + use_in_shortcut=True, + up=True, + kernel="fir", + ) + self.skip_conv = nn.Conv2d(out_channels, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) + self.skip_norm = torch.nn.GroupNorm( + num_groups=min(out_channels // 4, 32), num_channels=out_channels, eps=resnet_eps, affine=True + ) + self.act = nn.SiLU() + else: + self.resnet_up = None + self.skip_conv = None + self.skip_norm = None + self.act = None + + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + skip_sample=None, + scale: float = 1.0, + ) -> Tuple[torch.FloatTensor, torch.FloatTensor]: + for resnet in self.resnets: + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + hidden_states = resnet(hidden_states, temb, scale=scale) + + if skip_sample is not None: + skip_sample = self.upsampler(skip_sample) + else: + skip_sample = 0 + + if self.resnet_up is not None: + skip_sample_states = self.skip_norm(hidden_states) + skip_sample_states = self.act(skip_sample_states) + skip_sample_states = self.skip_conv(skip_sample_states) + + skip_sample = skip_sample + skip_sample_states + + hidden_states = self.resnet_up(hidden_states, temb, scale=scale) + + return hidden_states, skip_sample + + +class ResnetUpsampleBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + prev_output_channel: int, + out_channels: int, + temb_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor: float = 1.0, + add_upsample: bool = True, + skip_time_act: bool = False, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList( + [ + ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + up=True, + ) + ] + ) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + upsample_size: Optional[int] = None, + scale: float = 1.0, + ) -> torch.FloatTensor: + for resnet in self.resnets: + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + if is_torch_version(">=", "1.11.0"): + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + ) + else: + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb, scale=scale) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states, temb, scale=scale) + + return hidden_states + + +class SimpleCrossAttnUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + prev_output_channel: int, + temb_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + cross_attention_dim: int = 1280, + output_scale_factor: float = 1.0, + add_upsample: bool = True, + skip_time_act: bool = False, + only_cross_attention: bool = False, + cross_attention_norm: Optional[str] = None, + ): + super().__init__() + resnets = [] + attentions = [] + + self.has_cross_attention = True + self.attention_head_dim = attention_head_dim + + self.num_heads = out_channels // self.attention_head_dim + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + ) + ) + + processor = ( + AttnAddedKVProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnAddedKVProcessor() + ) + + attentions.append( + Attention( + query_dim=out_channels, + cross_attention_dim=out_channels, + heads=self.num_heads, + dim_head=self.attention_head_dim, + added_kv_proj_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + bias=True, + upcast_softmax=True, + only_cross_attention=only_cross_attention, + cross_attention_norm=cross_attention_norm, + processor=processor, + ) + ) + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList( + [ + ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + up=True, + ) + ] + ) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + upsample_size: Optional[int] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {} + + lora_scale = cross_attention_kwargs.get("scale", 1.0) + if attention_mask is None: + # if encoder_hidden_states is defined: we are doing cross-attn, so we should use cross-attn mask. + mask = None if encoder_hidden_states is None else encoder_attention_mask + else: + # when attention_mask is defined: we don't even check for encoder_attention_mask. + # this is to maintain compatibility with UnCLIP, which uses 'attention_mask' param for cross-attn masks. + # TODO: UnCLIP should express cross-attn mask via encoder_attention_mask param instead of via attention_mask. + # then we can simplify this whole if/else block to: + # mask = attention_mask if encoder_hidden_states is None else encoder_attention_mask + mask = attention_mask + + for resnet, attn in zip(self.resnets, self.attentions): + # resnet + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb) + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=mask, + **cross_attention_kwargs, + ) + else: + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=mask, + **cross_attention_kwargs, + ) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states, temb, scale=lora_scale) + + return hidden_states + + +class KUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + resolution_idx: int, + dropout: float = 0.0, + num_layers: int = 5, + resnet_eps: float = 1e-5, + resnet_act_fn: str = "gelu", + resnet_group_size: Optional[int] = 32, + add_upsample: bool = True, + ): + super().__init__() + resnets = [] + k_in_channels = 2 * out_channels + k_out_channels = in_channels + num_layers = num_layers - 1 + + for i in range(num_layers): + in_channels = k_in_channels if i == 0 else out_channels + groups = in_channels // resnet_group_size + groups_out = out_channels // resnet_group_size + + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=k_out_channels if (i == num_layers - 1) else out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=groups, + groups_out=groups_out, + dropout=dropout, + non_linearity=resnet_act_fn, + time_embedding_norm="ada_group", + conv_shortcut_bias=False, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList([KUpsample2D()]) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + upsample_size: Optional[int] = None, + scale: float = 1.0, + ) -> torch.FloatTensor: + res_hidden_states_tuple = res_hidden_states_tuple[-1] + if res_hidden_states_tuple is not None: + hidden_states = torch.cat([hidden_states, res_hidden_states_tuple], dim=1) + + for resnet in self.resnets: + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + if is_torch_version(">=", "1.11.0"): + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + ) + else: + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb, scale=scale) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states) + + return hidden_states + + +class KCrossAttnUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + resolution_idx: int, + dropout: float = 0.0, + num_layers: int = 4, + resnet_eps: float = 1e-5, + resnet_act_fn: str = "gelu", + resnet_group_size: int = 32, + attention_head_dim: int = 1, # attention dim_head + cross_attention_dim: int = 768, + add_upsample: bool = True, + upcast_attention: bool = False, + ): + super().__init__() + resnets = [] + attentions = [] + + is_first_block = in_channels == out_channels == temb_channels + is_middle_block = in_channels != out_channels + add_self_attention = True if is_first_block else False + + self.has_cross_attention = True + self.attention_head_dim = attention_head_dim + + # in_channels, and out_channels for the block (k-unet) + k_in_channels = out_channels if is_first_block else 2 * out_channels + k_out_channels = in_channels + + num_layers = num_layers - 1 + + for i in range(num_layers): + in_channels = k_in_channels if i == 0 else out_channels + groups = in_channels // resnet_group_size + groups_out = out_channels // resnet_group_size + + if is_middle_block and (i == num_layers - 1): + conv_2d_out_channels = k_out_channels + else: + conv_2d_out_channels = None + + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + conv_2d_out_channels=conv_2d_out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=groups, + groups_out=groups_out, + dropout=dropout, + non_linearity=resnet_act_fn, + time_embedding_norm="ada_group", + conv_shortcut_bias=False, + ) + ) + attentions.append( + KAttentionBlock( + k_out_channels if (i == num_layers - 1) else out_channels, + k_out_channels // attention_head_dim + if (i == num_layers - 1) + else out_channels // attention_head_dim, + attention_head_dim, + cross_attention_dim=cross_attention_dim, + temb_channels=temb_channels, + attention_bias=True, + add_self_attention=add_self_attention, + cross_attention_norm="layer_norm", + upcast_attention=upcast_attention, + ) + ) + + self.resnets = nn.ModuleList(resnets) + self.attentions = nn.ModuleList(attentions) + + if add_upsample: + self.upsamplers = nn.ModuleList([KUpsample2D()]) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + upsample_size: Optional[int] = None, + attention_mask: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + res_hidden_states_tuple = res_hidden_states_tuple[-1] + if res_hidden_states_tuple is not None: + hidden_states = torch.cat([hidden_states, res_hidden_states_tuple], dim=1) + + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + for resnet, attn in zip(self.resnets, self.attentions): + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), + hidden_states, + temb, + **ckpt_kwargs, + ) + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + emb=temb, + attention_mask=attention_mask, + cross_attention_kwargs=cross_attention_kwargs, + encoder_attention_mask=encoder_attention_mask, + ) + else: + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + emb=temb, + attention_mask=attention_mask, + cross_attention_kwargs=cross_attention_kwargs, + encoder_attention_mask=encoder_attention_mask, + ) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states) + + return hidden_states + + +# can potentially later be renamed to `No-feed-forward` attention +class KAttentionBlock(nn.Module): + r""" + A basic Transformer block. + + Parameters: + dim (`int`): The number of channels in the input and output. + num_attention_heads (`int`): The number of heads to use for multi-head attention. + attention_head_dim (`int`): The number of channels in each head. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention. + attention_bias (`bool`, *optional*, defaults to `False`): + Configure if the attention layers should contain a bias parameter. + upcast_attention (`bool`, *optional*, defaults to `False`): + Set to `True` to upcast the attention computation to `float32`. + temb_channels (`int`, *optional*, defaults to 768): + The number of channels in the token embedding. + add_self_attention (`bool`, *optional*, defaults to `False`): + Set to `True` to add self-attention to the block. + cross_attention_norm (`str`, *optional*, defaults to `None`): + The type of normalization to use for the cross attention. Can be `None`, `layer_norm`, or `group_norm`. + group_size (`int`, *optional*, defaults to 32): + The number of groups to separate the channels into for group normalization. + """ + + def __init__( + self, + dim: int, + num_attention_heads: int, + attention_head_dim: int, + dropout: float = 0.0, + cross_attention_dim: Optional[int] = None, + attention_bias: bool = False, + upcast_attention: bool = False, + temb_channels: int = 768, # for ada_group_norm + add_self_attention: bool = False, + cross_attention_norm: Optional[str] = None, + group_size: int = 32, + ): + super().__init__() + self.add_self_attention = add_self_attention + + # 1. Self-Attn + if add_self_attention: + self.norm1 = AdaGroupNorm(temb_channels, dim, max(1, dim // group_size)) + self.attn1 = Attention( + query_dim=dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + cross_attention_dim=None, + cross_attention_norm=None, + ) + + # 2. Cross-Attn + self.norm2 = AdaGroupNorm(temb_channels, dim, max(1, dim // group_size)) + self.attn2 = Attention( + query_dim=dim, + cross_attention_dim=cross_attention_dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + upcast_attention=upcast_attention, + cross_attention_norm=cross_attention_norm, + ) + + def _to_3d(self, hidden_states: torch.FloatTensor, height: int, weight: int) -> torch.FloatTensor: + return hidden_states.permute(0, 2, 3, 1).reshape(hidden_states.shape[0], height * weight, -1) + + def _to_4d(self, hidden_states: torch.FloatTensor, height: int, weight: int) -> torch.FloatTensor: + return hidden_states.permute(0, 2, 1).reshape(hidden_states.shape[0], -1, height, weight) + + def forward( + self, + hidden_states: torch.FloatTensor, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + # TODO: mark emb as non-optional (self.norm2 requires it). + # requires assessing impact of change to positional param interface. + emb: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {} + + # 1. Self-Attention + if self.add_self_attention: + norm_hidden_states = self.norm1(hidden_states, emb) + + height, weight = norm_hidden_states.shape[2:] + norm_hidden_states = self._to_3d(norm_hidden_states, height, weight) + + attn_output = self.attn1( + norm_hidden_states, + encoder_hidden_states=None, + attention_mask=attention_mask, + **cross_attention_kwargs, + ) + attn_output = self._to_4d(attn_output, height, weight) + + hidden_states = attn_output + hidden_states + + # 2. Cross-Attention/None + norm_hidden_states = self.norm2(hidden_states, emb) + + height, weight = norm_hidden_states.shape[2:] + norm_hidden_states = self._to_3d(norm_hidden_states, height, weight) + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=attention_mask if encoder_hidden_states is None else encoder_attention_mask, + **cross_attention_kwargs, + ) + attn_output = self._to_4d(attn_output, height, weight) + + hidden_states = attn_output + hidden_states + + return hidden_states diff --git a/extensions-builtin/forge_space_idm_vton/src/unet_block_hacked_tryon.py b/extensions-builtin/forge_space_idm_vton/src/unet_block_hacked_tryon.py new file mode 100644 index 0000000000000000000000000000000000000000..d46728a7501764dbb710ba04c43e63e8b5b84146 --- /dev/null +++ b/extensions-builtin/forge_space_idm_vton/src/unet_block_hacked_tryon.py @@ -0,0 +1,3522 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Dict, Optional, Tuple, Union + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +from diffusers.utils import is_torch_version, logging +from diffusers.utils.torch_utils import apply_freeu +from diffusers.models.activations import get_activation +from diffusers.models.attention_processor import Attention, AttnAddedKVProcessor, AttnAddedKVProcessor2_0 +from diffusers.models.dual_transformer_2d import DualTransformer2DModel +from diffusers.models.normalization import AdaGroupNorm +from diffusers.models.resnet import Downsample2D, FirDownsample2D, FirUpsample2D, KDownsample2D, KUpsample2D, ResnetBlock2D, Upsample2D +from src.transformerhacked_tryon import Transformer2DModel +from einops import rearrange + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +def get_down_block( + down_block_type: str, + num_layers: int, + in_channels: int, + out_channels: int, + temb_channels: int, + add_downsample: bool, + resnet_eps: float, + resnet_act_fn: str, + transformer_layers_per_block: int = 1, + num_attention_heads: Optional[int] = None, + resnet_groups: Optional[int] = None, + cross_attention_dim: Optional[int] = None, + downsample_padding: Optional[int] = None, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + only_cross_attention: bool = False, + upcast_attention: bool = False, + resnet_time_scale_shift: str = "default", + attention_type: str = "default", + resnet_skip_time_act: bool = False, + resnet_out_scale_factor: float = 1.0, + cross_attention_norm: Optional[str] = None, + attention_head_dim: Optional[int] = None, + downsample_type: Optional[str] = None, + dropout: float = 0.0, +): + # If attn head dim is not defined, we default it to the number of heads + if attention_head_dim is None: + logger.warn( + f"It is recommended to provide `attention_head_dim` when calling `get_down_block`. Defaulting `attention_head_dim` to {num_attention_heads}." + ) + attention_head_dim = num_attention_heads + + down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_type + if down_block_type == "DownBlock2D": + return DownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + downsample_padding=downsample_padding, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif down_block_type == "ResnetDownsampleBlock2D": + return ResnetDownsampleBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + skip_time_act=resnet_skip_time_act, + output_scale_factor=resnet_out_scale_factor, + ) + elif down_block_type == "AttnDownBlock2D": + if add_downsample is False: + downsample_type = None + else: + downsample_type = downsample_type or "conv" # default to 'conv' + return AttnDownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + downsample_padding=downsample_padding, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + downsample_type=downsample_type, + ) + elif down_block_type == "CrossAttnDownBlock2D": + if cross_attention_dim is None: + raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock2D") + return CrossAttnDownBlock2D( + num_layers=num_layers, + transformer_layers_per_block=transformer_layers_per_block, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + downsample_padding=downsample_padding, + cross_attention_dim=cross_attention_dim, + num_attention_heads=num_attention_heads, + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + resnet_time_scale_shift=resnet_time_scale_shift, + attention_type=attention_type, + ) + elif down_block_type == "SimpleCrossAttnDownBlock2D": + if cross_attention_dim is None: + raise ValueError("cross_attention_dim must be specified for SimpleCrossAttnDownBlock2D") + return SimpleCrossAttnDownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + cross_attention_dim=cross_attention_dim, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + skip_time_act=resnet_skip_time_act, + output_scale_factor=resnet_out_scale_factor, + only_cross_attention=only_cross_attention, + cross_attention_norm=cross_attention_norm, + ) + elif down_block_type == "SkipDownBlock2D": + return SkipDownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + downsample_padding=downsample_padding, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif down_block_type == "AttnSkipDownBlock2D": + return AttnSkipDownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif down_block_type == "DownEncoderBlock2D": + return DownEncoderBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + downsample_padding=downsample_padding, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif down_block_type == "AttnDownEncoderBlock2D": + return AttnDownEncoderBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + downsample_padding=downsample_padding, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif down_block_type == "KDownBlock2D": + return KDownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + ) + elif down_block_type == "KCrossAttnDownBlock2D": + return KCrossAttnDownBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + dropout=dropout, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + cross_attention_dim=cross_attention_dim, + attention_head_dim=attention_head_dim, + add_self_attention=True if not add_downsample else False, + ) + raise ValueError(f"{down_block_type} does not exist.") + + +def get_up_block( + up_block_type: str, + num_layers: int, + in_channels: int, + out_channels: int, + prev_output_channel: int, + temb_channels: int, + add_upsample: bool, + resnet_eps: float, + resnet_act_fn: str, + resolution_idx: Optional[int] = None, + transformer_layers_per_block: int = 1, + num_attention_heads: Optional[int] = None, + resnet_groups: Optional[int] = None, + cross_attention_dim: Optional[int] = None, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + only_cross_attention: bool = False, + upcast_attention: bool = False, + resnet_time_scale_shift: str = "default", + attention_type: str = "default", + resnet_skip_time_act: bool = False, + resnet_out_scale_factor: float = 1.0, + cross_attention_norm: Optional[str] = None, + attention_head_dim: Optional[int] = None, + upsample_type: Optional[str] = None, + dropout: float = 0.0, +) -> nn.Module: + # If attn head dim is not defined, we default it to the number of heads + if attention_head_dim is None: + logger.warn( + f"It is recommended to provide `attention_head_dim` when calling `get_up_block`. Defaulting `attention_head_dim` to {num_attention_heads}." + ) + attention_head_dim = num_attention_heads + + up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type + if up_block_type == "UpBlock2D": + return UpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif up_block_type == "ResnetUpsampleBlock2D": + return ResnetUpsampleBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + skip_time_act=resnet_skip_time_act, + output_scale_factor=resnet_out_scale_factor, + ) + elif up_block_type == "CrossAttnUpBlock2D": + if cross_attention_dim is None: + raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock2D") + return CrossAttnUpBlock2D( + num_layers=num_layers, + transformer_layers_per_block=transformer_layers_per_block, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + cross_attention_dim=cross_attention_dim, + num_attention_heads=num_attention_heads, + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + resnet_time_scale_shift=resnet_time_scale_shift, + attention_type=attention_type, + ) + elif up_block_type == "SimpleCrossAttnUpBlock2D": + if cross_attention_dim is None: + raise ValueError("cross_attention_dim must be specified for SimpleCrossAttnUpBlock2D") + return SimpleCrossAttnUpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + cross_attention_dim=cross_attention_dim, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + skip_time_act=resnet_skip_time_act, + output_scale_factor=resnet_out_scale_factor, + only_cross_attention=only_cross_attention, + cross_attention_norm=cross_attention_norm, + ) + elif up_block_type == "AttnUpBlock2D": + if add_upsample is False: + upsample_type = None + else: + upsample_type = upsample_type or "conv" # default to 'conv' + + return AttnUpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + upsample_type=upsample_type, + ) + elif up_block_type == "SkipUpBlock2D": + return SkipUpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif up_block_type == "AttnSkipUpBlock2D": + return AttnSkipUpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif up_block_type == "UpDecoderBlock2D": + return UpDecoderBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + temb_channels=temb_channels, + ) + elif up_block_type == "AttnUpDecoderBlock2D": + return AttnUpDecoderBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + attention_head_dim=attention_head_dim, + resnet_time_scale_shift=resnet_time_scale_shift, + temb_channels=temb_channels, + ) + elif up_block_type == "KUpBlock2D": + return KUpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + ) + elif up_block_type == "KCrossAttnUpBlock2D": + return KCrossAttnUpBlock2D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + resolution_idx=resolution_idx, + dropout=dropout, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + cross_attention_dim=cross_attention_dim, + attention_head_dim=attention_head_dim, + ) + + raise ValueError(f"{up_block_type} does not exist.") + + +class AutoencoderTinyBlock(nn.Module): + """ + Tiny Autoencoder block used in [`AutoencoderTiny`]. It is a mini residual module consisting of plain conv + ReLU + blocks. + + Args: + in_channels (`int`): The number of input channels. + out_channels (`int`): The number of output channels. + act_fn (`str`): + ` The activation function to use. Supported values are `"swish"`, `"mish"`, `"gelu"`, and `"relu"`. + + Returns: + `torch.FloatTensor`: A tensor with the same shape as the input tensor, but with the number of channels equal to + `out_channels`. + """ + + def __init__(self, in_channels: int, out_channels: int, act_fn: str): + super().__init__() + act_fn = get_activation(act_fn) + self.conv = nn.Sequential( + nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), + act_fn, + nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1), + act_fn, + nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1), + ) + self.skip = ( + nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) + if in_channels != out_channels + else nn.Identity() + ) + self.fuse = nn.ReLU() + + def forward(self, x: torch.FloatTensor) -> torch.FloatTensor: + return self.fuse(self.conv(x) + self.skip(x)) + + +class UNetMidBlock2D(nn.Module): + """ + A 2D UNet mid-block [`UNetMidBlock2D`] with multiple residual blocks and optional attention blocks. + + Args: + in_channels (`int`): The number of input channels. + temb_channels (`int`): The number of temporal embedding channels. + dropout (`float`, *optional*, defaults to 0.0): The dropout rate. + num_layers (`int`, *optional*, defaults to 1): The number of residual blocks. + resnet_eps (`float`, *optional*, 1e-6 ): The epsilon value for the resnet blocks. + resnet_time_scale_shift (`str`, *optional*, defaults to `default`): + The type of normalization to apply to the time embeddings. This can help to improve the performance of the + model on tasks with long-range temporal dependencies. + resnet_act_fn (`str`, *optional*, defaults to `swish`): The activation function for the resnet blocks. + resnet_groups (`int`, *optional*, defaults to 32): + The number of groups to use in the group normalization layers of the resnet blocks. + attn_groups (`Optional[int]`, *optional*, defaults to None): The number of groups for the attention blocks. + resnet_pre_norm (`bool`, *optional*, defaults to `True`): + Whether to use pre-normalization for the resnet blocks. + add_attention (`bool`, *optional*, defaults to `True`): Whether to add attention blocks. + attention_head_dim (`int`, *optional*, defaults to 1): + Dimension of a single attention head. The number of attention heads is determined based on this value and + the number of input channels. + output_scale_factor (`float`, *optional*, defaults to 1.0): The output scale factor. + + Returns: + `torch.FloatTensor`: The output of the last residual block, which is a tensor of shape `(batch_size, + in_channels, height, width)`. + + """ + + def __init__( + self, + in_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", # default, spatial + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + attn_groups: Optional[int] = None, + resnet_pre_norm: bool = True, + add_attention: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = 1.0, + ): + super().__init__() + resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32) + self.add_attention = add_attention + + if attn_groups is None: + attn_groups = resnet_groups if resnet_time_scale_shift == "default" else None + + # there is always at least one resnet + resnets = [ + ResnetBlock2D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ] + attentions = [] + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {in_channels}." + ) + attention_head_dim = in_channels + + for _ in range(num_layers): + if self.add_attention: + attentions.append( + Attention( + in_channels, + heads=in_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=attn_groups, + spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + else: + attentions.append(None) + + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + def forward(self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None) -> torch.FloatTensor: + hidden_states = self.resnets[0](hidden_states, temb) + for attn, resnet in zip(self.attentions, self.resnets[1:]): + if attn is not None: + hidden_states = attn(hidden_states, temb=temb) + hidden_states = resnet(hidden_states, temb) + + return hidden_states + + +class UNetMidBlock2DCrossAttn(nn.Module): + def __init__( + self, + in_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + transformer_layers_per_block: Union[int, Tuple[int]] = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + num_attention_heads: int = 1, + output_scale_factor: float = 1.0, + cross_attention_dim: int = 1280, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + upcast_attention: bool = False, + attention_type: str = "default", + ): + super().__init__() + + self.has_cross_attention = True + self.num_attention_heads = num_attention_heads + resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32) + + # support for variable transformer layers per block + if isinstance(transformer_layers_per_block, int): + transformer_layers_per_block = [transformer_layers_per_block] * num_layers + + # there is always at least one resnet + resnets = [ + ResnetBlock2D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ] + attentions = [] + + for i in range(num_layers): + if not dual_cross_attention: + attentions.append( + Transformer2DModel( + num_attention_heads, + in_channels // num_attention_heads, + in_channels=in_channels, + num_layers=transformer_layers_per_block[i], + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + use_linear_projection=use_linear_projection, + upcast_attention=upcast_attention, + attention_type=attention_type, + ) + ) + else: + attentions.append( + DualTransformer2DModel( + num_attention_heads, + in_channels // num_attention_heads, + in_channels=in_channels, + num_layers=1, + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + ) + ) + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + garment_features=None, + curr_garment_feat_idx=0, + ) -> torch.FloatTensor: + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + hidden_states = self.resnets[0](hidden_states, temb, scale=lora_scale) + for attn, resnet in zip(self.attentions, self.resnets[1:]): + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + hidden_states,curr_garment_feat_idx = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + return_dict=False, + garment_features=garment_features, + curr_garment_feat_idx=curr_garment_feat_idx, + ) + hidden_states=hidden_states[0] + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), + hidden_states, + temb, + **ckpt_kwargs, + ) + else: + hidden_states,curr_garment_feat_idx = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + return_dict=False, + garment_features=garment_features, + curr_garment_feat_idx=curr_garment_feat_idx, + ) + hidden_states=hidden_states[0] + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + + return hidden_states,curr_garment_feat_idx + + +class UNetMidBlock2DSimpleCrossAttn(nn.Module): + def __init__( + self, + in_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = 1.0, + cross_attention_dim: int = 1280, + skip_time_act: bool = False, + only_cross_attention: bool = False, + cross_attention_norm: Optional[str] = None, + ): + super().__init__() + + self.has_cross_attention = True + + self.attention_head_dim = attention_head_dim + resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32) + + self.num_heads = in_channels // self.attention_head_dim + + # there is always at least one resnet + resnets = [ + ResnetBlock2D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + ) + ] + attentions = [] + + for _ in range(num_layers): + processor = ( + AttnAddedKVProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnAddedKVProcessor() + ) + + attentions.append( + Attention( + query_dim=in_channels, + cross_attention_dim=in_channels, + heads=self.num_heads, + dim_head=self.attention_head_dim, + added_kv_proj_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + bias=True, + upcast_softmax=True, + only_cross_attention=only_cross_attention, + cross_attention_norm=cross_attention_norm, + processor=processor, + ) + ) + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {} + lora_scale = cross_attention_kwargs.get("scale", 1.0) + + if attention_mask is None: + # if encoder_hidden_states is defined: we are doing cross-attn, so we should use cross-attn mask. + mask = None if encoder_hidden_states is None else encoder_attention_mask + else: + # when attention_mask is defined: we don't even check for encoder_attention_mask. + # this is to maintain compatibility with UnCLIP, which uses 'attention_mask' param for cross-attn masks. + # TODO: UnCLIP should express cross-attn mask via encoder_attention_mask param instead of via attention_mask. + # then we can simplify this whole if/else block to: + # mask = attention_mask if encoder_hidden_states is None else encoder_attention_mask + mask = attention_mask + + hidden_states = self.resnets[0](hidden_states, temb, scale=lora_scale) + for attn, resnet in zip(self.attentions, self.resnets[1:]): + # attn + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=mask, + **cross_attention_kwargs, + ) + + # resnet + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + + return hidden_states + + +class AttnDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = 1.0, + downsample_padding: int = 1, + downsample_type: str = "conv", + ): + super().__init__() + resnets = [] + attentions = [] + self.downsample_type = downsample_type + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {out_channels}." + ) + attention_head_dim = out_channels + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + attentions.append( + Attention( + out_channels, + heads=out_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=resnet_groups, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if downsample_type == "conv": + self.downsamplers = nn.ModuleList( + [ + Downsample2D( + out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op" + ) + ] + ) + elif downsample_type == "resnet": + self.downsamplers = nn.ModuleList( + [ + ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + down=True, + ) + ] + ) + else: + self.downsamplers = None + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + upsample_size: Optional[int] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {} + + lora_scale = cross_attention_kwargs.get("scale", 1.0) + + output_states = () + + for resnet, attn in zip(self.resnets, self.attentions): + cross_attention_kwargs.update({"scale": lora_scale}) + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + hidden_states = attn(hidden_states, **cross_attention_kwargs) + output_states = output_states + (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + if self.downsample_type == "resnet": + hidden_states = downsampler(hidden_states, temb=temb, scale=lora_scale) + else: + hidden_states = downsampler(hidden_states, scale=lora_scale) + + output_states += (hidden_states,) + + return hidden_states, output_states + + +class CrossAttnDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + transformer_layers_per_block: Union[int, Tuple[int]] = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + num_attention_heads: int = 1, + cross_attention_dim: int = 1280, + output_scale_factor: float = 1.0, + downsample_padding: int = 1, + add_downsample: bool = True, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + only_cross_attention: bool = False, + upcast_attention: bool = False, + attention_type: str = "default", + ): + super().__init__() + resnets = [] + attentions = [] + + self.has_cross_attention = True + self.num_attention_heads = num_attention_heads + if isinstance(transformer_layers_per_block, int): + transformer_layers_per_block = [transformer_layers_per_block] * num_layers + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + if not dual_cross_attention: + attentions.append( + Transformer2DModel( + num_attention_heads, + out_channels // num_attention_heads, + in_channels=out_channels, + num_layers=transformer_layers_per_block[i], + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + attention_type=attention_type, + ) + ) + else: + attentions.append( + DualTransformer2DModel( + num_attention_heads, + out_channels // num_attention_heads, + in_channels=out_channels, + num_layers=1, + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + ) + ) + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + Downsample2D( + out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op" + ) + ] + ) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + additional_residuals: Optional[torch.FloatTensor] = None, + garment_features=None, + curr_garment_feat_idx=0, + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + output_states = () + + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + + blocks = list(zip(self.resnets, self.attentions)) + # print("len(self.resnets)") + # print(len(self.resnets)) + # print("len(self.attentions)") + # print(len(self.attentions)) + for i, (resnet, attn) in enumerate(blocks): + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), + hidden_states, + temb, + **ckpt_kwargs, + ) + hidden_states,curr_garment_feat_idx = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + return_dict=False, + garment_features=garment_features, + curr_garment_feat_idx=curr_garment_feat_idx, + ) + hidden_states=hidden_states[0] + else: + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + hidden_states,curr_garment_feat_idx = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + return_dict=False, + garment_features=garment_features, + curr_garment_feat_idx=curr_garment_feat_idx, + ) + hidden_states=hidden_states[0] + + + # apply additional residuals to the output of the last pair of resnet and attention blocks + if i == len(blocks) - 1 and additional_residuals is not None: + hidden_states = hidden_states + additional_residuals + + output_states = output_states + (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states, scale=lora_scale) + + output_states = output_states + (hidden_states,) + + return hidden_states, output_states,curr_garment_feat_idx + + +class DownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor: float = 1.0, + add_downsample: bool = True, + downsample_padding: int = 1, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + Downsample2D( + out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op" + ) + ] + ) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0 + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + output_states = () + + for resnet in self.resnets: + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + if is_torch_version(">=", "1.11.0"): + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + ) + else: + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb, scale=scale) + + output_states = output_states + (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states, scale=scale) + + output_states = output_states + (hidden_states,) + + return hidden_states, output_states + + +class DownEncoderBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor: float = 1.0, + add_downsample: bool = True, + downsample_padding: int = 1, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=None, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + Downsample2D( + out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op" + ) + ] + ) + else: + self.downsamplers = None + + def forward(self, hidden_states: torch.FloatTensor, scale: float = 1.0) -> torch.FloatTensor: + for resnet in self.resnets: + hidden_states = resnet(hidden_states, temb=None, scale=scale) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states, scale) + + return hidden_states + + +class AttnDownEncoderBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = 1.0, + add_downsample: bool = True, + downsample_padding: int = 1, + ): + super().__init__() + resnets = [] + attentions = [] + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {out_channels}." + ) + attention_head_dim = out_channels + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=None, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + attentions.append( + Attention( + out_channels, + heads=out_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=resnet_groups, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + Downsample2D( + out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op" + ) + ] + ) + else: + self.downsamplers = None + + def forward(self, hidden_states: torch.FloatTensor, scale: float = 1.0) -> torch.FloatTensor: + for resnet, attn in zip(self.resnets, self.attentions): + hidden_states = resnet(hidden_states, temb=None, scale=scale) + cross_attention_kwargs = {"scale": scale} + hidden_states = attn(hidden_states, **cross_attention_kwargs) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states, scale) + + return hidden_states + + +class AttnSkipDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = np.sqrt(2.0), + add_downsample: bool = True, + ): + super().__init__() + self.attentions = nn.ModuleList([]) + self.resnets = nn.ModuleList([]) + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {out_channels}." + ) + attention_head_dim = out_channels + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + self.resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(in_channels // 4, 32), + groups_out=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + self.attentions.append( + Attention( + out_channels, + heads=out_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=32, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + + if add_downsample: + self.resnet_down = ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + use_in_shortcut=True, + down=True, + kernel="fir", + ) + self.downsamplers = nn.ModuleList([FirDownsample2D(out_channels, out_channels=out_channels)]) + self.skip_conv = nn.Conv2d(3, out_channels, kernel_size=(1, 1), stride=(1, 1)) + else: + self.resnet_down = None + self.downsamplers = None + self.skip_conv = None + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + skip_sample: Optional[torch.FloatTensor] = None, + scale: float = 1.0, + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...], torch.FloatTensor]: + output_states = () + + for resnet, attn in zip(self.resnets, self.attentions): + hidden_states = resnet(hidden_states, temb, scale=scale) + cross_attention_kwargs = {"scale": scale} + hidden_states = attn(hidden_states, **cross_attention_kwargs) + output_states += (hidden_states,) + + if self.downsamplers is not None: + hidden_states = self.resnet_down(hidden_states, temb, scale=scale) + for downsampler in self.downsamplers: + skip_sample = downsampler(skip_sample) + + hidden_states = self.skip_conv(skip_sample) + hidden_states + + output_states += (hidden_states,) + + return hidden_states, output_states, skip_sample + + +class SkipDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_pre_norm: bool = True, + output_scale_factor: float = np.sqrt(2.0), + add_downsample: bool = True, + downsample_padding: int = 1, + ): + super().__init__() + self.resnets = nn.ModuleList([]) + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + self.resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(in_channels // 4, 32), + groups_out=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + if add_downsample: + self.resnet_down = ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + use_in_shortcut=True, + down=True, + kernel="fir", + ) + self.downsamplers = nn.ModuleList([FirDownsample2D(out_channels, out_channels=out_channels)]) + self.skip_conv = nn.Conv2d(3, out_channels, kernel_size=(1, 1), stride=(1, 1)) + else: + self.resnet_down = None + self.downsamplers = None + self.skip_conv = None + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + skip_sample: Optional[torch.FloatTensor] = None, + scale: float = 1.0, + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...], torch.FloatTensor]: + output_states = () + + for resnet in self.resnets: + hidden_states = resnet(hidden_states, temb, scale) + output_states += (hidden_states,) + + if self.downsamplers is not None: + hidden_states = self.resnet_down(hidden_states, temb, scale) + for downsampler in self.downsamplers: + skip_sample = downsampler(skip_sample) + + hidden_states = self.skip_conv(skip_sample) + hidden_states + + output_states += (hidden_states,) + + return hidden_states, output_states, skip_sample + + +class ResnetDownsampleBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor: float = 1.0, + add_downsample: bool = True, + skip_time_act: bool = False, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + down=True, + ) + ] + ) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0 + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + output_states = () + + for resnet in self.resnets: + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + if is_torch_version(">=", "1.11.0"): + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + ) + else: + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb, scale) + + output_states = output_states + (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states, temb, scale) + + output_states = output_states + (hidden_states,) + + return hidden_states, output_states + + +class SimpleCrossAttnDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + cross_attention_dim: int = 1280, + output_scale_factor: float = 1.0, + add_downsample: bool = True, + skip_time_act: bool = False, + only_cross_attention: bool = False, + cross_attention_norm: Optional[str] = None, + ): + super().__init__() + + self.has_cross_attention = True + + resnets = [] + attentions = [] + + self.attention_head_dim = attention_head_dim + self.num_heads = out_channels // self.attention_head_dim + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + ) + ) + + processor = ( + AttnAddedKVProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnAddedKVProcessor() + ) + + attentions.append( + Attention( + query_dim=out_channels, + cross_attention_dim=out_channels, + heads=self.num_heads, + dim_head=attention_head_dim, + added_kv_proj_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + bias=True, + upcast_softmax=True, + only_cross_attention=only_cross_attention, + cross_attention_norm=cross_attention_norm, + processor=processor, + ) + ) + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + down=True, + ) + ] + ) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + output_states = () + cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {} + + lora_scale = cross_attention_kwargs.get("scale", 1.0) + + if attention_mask is None: + # if encoder_hidden_states is defined: we are doing cross-attn, so we should use cross-attn mask. + mask = None if encoder_hidden_states is None else encoder_attention_mask + else: + # when attention_mask is defined: we don't even check for encoder_attention_mask. + # this is to maintain compatibility with UnCLIP, which uses 'attention_mask' param for cross-attn masks. + # TODO: UnCLIP should express cross-attn mask via encoder_attention_mask param instead of via attention_mask. + # then we can simplify this whole if/else block to: + # mask = attention_mask if encoder_hidden_states is None else encoder_attention_mask + mask = attention_mask + + for resnet, attn in zip(self.resnets, self.attentions): + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb) + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=mask, + **cross_attention_kwargs, + ) + else: + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=mask, + **cross_attention_kwargs, + ) + + output_states = output_states + (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states, temb, scale=lora_scale) + + output_states = output_states + (hidden_states,) + + return hidden_states, output_states + + +class KDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 4, + resnet_eps: float = 1e-5, + resnet_act_fn: str = "gelu", + resnet_group_size: int = 32, + add_downsample: bool = False, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + groups = in_channels // resnet_group_size + groups_out = out_channels // resnet_group_size + + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + dropout=dropout, + temb_channels=temb_channels, + groups=groups, + groups_out=groups_out, + eps=resnet_eps, + non_linearity=resnet_act_fn, + time_embedding_norm="ada_group", + conv_shortcut_bias=False, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + # YiYi's comments- might be able to use FirDownsample2D, look into details later + self.downsamplers = nn.ModuleList([KDownsample2D()]) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0 + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + output_states = () + + for resnet in self.resnets: + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + if is_torch_version(">=", "1.11.0"): + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + ) + else: + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb, scale) + + output_states += (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states) + + return hidden_states, output_states + + +class KCrossAttnDownBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + cross_attention_dim: int, + dropout: float = 0.0, + num_layers: int = 4, + resnet_group_size: int = 32, + add_downsample: bool = True, + attention_head_dim: int = 64, + add_self_attention: bool = False, + resnet_eps: float = 1e-5, + resnet_act_fn: str = "gelu", + ): + super().__init__() + resnets = [] + attentions = [] + + self.has_cross_attention = True + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + groups = in_channels // resnet_group_size + groups_out = out_channels // resnet_group_size + + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + dropout=dropout, + temb_channels=temb_channels, + groups=groups, + groups_out=groups_out, + eps=resnet_eps, + non_linearity=resnet_act_fn, + time_embedding_norm="ada_group", + conv_shortcut_bias=False, + ) + ) + attentions.append( + KAttentionBlock( + out_channels, + out_channels // attention_head_dim, + attention_head_dim, + cross_attention_dim=cross_attention_dim, + temb_channels=temb_channels, + attention_bias=True, + add_self_attention=add_self_attention, + cross_attention_norm="layer_norm", + group_size=resnet_group_size, + ) + ) + + self.resnets = nn.ModuleList(resnets) + self.attentions = nn.ModuleList(attentions) + + if add_downsample: + self.downsamplers = nn.ModuleList([KDownsample2D()]) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.FloatTensor, + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]: + output_states = () + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + + for resnet, attn in zip(self.resnets, self.attentions): + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), + hidden_states, + temb, + **ckpt_kwargs, + ) + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + emb=temb, + attention_mask=attention_mask, + cross_attention_kwargs=cross_attention_kwargs, + encoder_attention_mask=encoder_attention_mask, + ) + else: + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + emb=temb, + attention_mask=attention_mask, + cross_attention_kwargs=cross_attention_kwargs, + encoder_attention_mask=encoder_attention_mask, + ) + + if self.downsamplers is None: + output_states += (None,) + else: + output_states += (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states) + + return hidden_states, output_states + + +class AttnUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + prev_output_channel: int, + out_channels: int, + temb_channels: int, + resolution_idx: int = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = 1.0, + upsample_type: str = "conv", + ): + super().__init__() + resnets = [] + attentions = [] + + self.upsample_type = upsample_type + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {out_channels}." + ) + attention_head_dim = out_channels + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + attentions.append( + Attention( + out_channels, + heads=out_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=resnet_groups, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if upsample_type == "conv": + self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]) + elif upsample_type == "resnet": + self.upsamplers = nn.ModuleList( + [ + ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + up=True, + ) + ] + ) + else: + self.upsamplers = None + + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + upsample_size: Optional[int] = None, + scale: float = 1.0, + ) -> torch.FloatTensor: + for resnet, attn in zip(self.resnets, self.attentions): + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + hidden_states = resnet(hidden_states, temb, scale=scale) + cross_attention_kwargs = {"scale": scale} + hidden_states = attn(hidden_states, **cross_attention_kwargs) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + if self.upsample_type == "resnet": + hidden_states = upsampler(hidden_states, temb=temb, scale=scale) + else: + hidden_states = upsampler(hidden_states, scale=scale) + + return hidden_states + + +class CrossAttnUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + prev_output_channel: int, + temb_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + transformer_layers_per_block: Union[int, Tuple[int]] = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + num_attention_heads: int = 1, + cross_attention_dim: int = 1280, + output_scale_factor: float = 1.0, + add_upsample: bool = True, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + only_cross_attention: bool = False, + upcast_attention: bool = False, + attention_type: str = "default", + ): + super().__init__() + resnets = [] + attentions = [] + + self.has_cross_attention = True + self.num_attention_heads = num_attention_heads + + if isinstance(transformer_layers_per_block, int): + transformer_layers_per_block = [transformer_layers_per_block] * num_layers + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + if not dual_cross_attention: + attentions.append( + Transformer2DModel( + num_attention_heads, + out_channels // num_attention_heads, + in_channels=out_channels, + num_layers=transformer_layers_per_block[i], + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + attention_type=attention_type, + ) + ) + else: + attentions.append( + DualTransformer2DModel( + num_attention_heads, + out_channels // num_attention_heads, + in_channels=out_channels, + num_layers=1, + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + ) + ) + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + upsample_size: Optional[int] = None, + attention_mask: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + garment_features=None, + curr_garment_feat_idx=0, + ) -> torch.FloatTensor: + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + is_freeu_enabled = ( + getattr(self, "s1", None) + and getattr(self, "s2", None) + and getattr(self, "b1", None) + and getattr(self, "b2", None) + ) + + for resnet, attn in zip(self.resnets, self.attentions): + + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + + # FreeU: Only operate on the first two stages + if is_freeu_enabled: + hidden_states, res_hidden_states = apply_freeu( + self.resolution_idx, + hidden_states, + res_hidden_states, + s1=self.s1, + s2=self.s2, + b1=self.b1, + b2=self.b2, + ) + + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + # print(hidden_states.shape) + # print(encoder_hidden_states.shape) + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), + hidden_states, + temb, + **ckpt_kwargs, + ) + hidden_states,curr_garment_feat_idx = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + return_dict=False, + garment_features=garment_features, + curr_garment_feat_idx=curr_garment_feat_idx, + ) + hidden_states=hidden_states[0] + else: + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + hidden_states,curr_garment_feat_idx = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + return_dict=False, + garment_features=garment_features, + curr_garment_feat_idx=curr_garment_feat_idx, + ) + hidden_states=hidden_states[0] + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states, upsample_size, scale=lora_scale) + + + + return hidden_states,curr_garment_feat_idx + + +class UpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + prev_output_channel: int, + out_channels: int, + temb_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor: float = 1.0, + add_upsample: bool = True, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + upsample_size: Optional[int] = None, + scale: float = 1.0, + ) -> torch.FloatTensor: + is_freeu_enabled = ( + getattr(self, "s1", None) + and getattr(self, "s2", None) + and getattr(self, "b1", None) + and getattr(self, "b2", None) + ) + + for resnet in self.resnets: + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + + # FreeU: Only operate on the first two stages + if is_freeu_enabled: + hidden_states, res_hidden_states = apply_freeu( + self.resolution_idx, + hidden_states, + res_hidden_states, + s1=self.s1, + s2=self.s2, + b1=self.b1, + b2=self.b2, + ) + + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + if is_torch_version(">=", "1.11.0"): + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + ) + else: + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb, scale=scale) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states, upsample_size, scale=scale) + + return hidden_states + + + +class UpDecoderBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", # default, spatial + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor: float = 1.0, + add_upsample: bool = True, + temb_channels: Optional[int] = None, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + input_channels = in_channels if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=input_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]) + else: + self.upsamplers = None + + self.resolution_idx = resolution_idx + + def forward( + self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0 + ) -> torch.FloatTensor: + for resnet in self.resnets: + hidden_states = resnet(hidden_states, temb=temb, scale=scale) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states) + + return hidden_states + + +class AttnUpDecoderBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = 1.0, + add_upsample: bool = True, + temb_channels: Optional[int] = None, + ): + super().__init__() + resnets = [] + attentions = [] + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `out_channels`: {out_channels}." + ) + attention_head_dim = out_channels + + for i in range(num_layers): + input_channels = in_channels if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=input_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + attentions.append( + Attention( + out_channels, + heads=out_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=resnet_groups if resnet_time_scale_shift != "spatial" else None, + spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]) + else: + self.upsamplers = None + + self.resolution_idx = resolution_idx + + def forward( + self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0 + ) -> torch.FloatTensor: + for resnet, attn in zip(self.resnets, self.attentions): + hidden_states = resnet(hidden_states, temb=temb, scale=scale) + cross_attention_kwargs = {"scale": scale} + hidden_states = attn(hidden_states, temb=temb, **cross_attention_kwargs) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states, scale=scale) + + return hidden_states + + +class AttnSkipUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + prev_output_channel: int, + out_channels: int, + temb_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + output_scale_factor: float = np.sqrt(2.0), + add_upsample: bool = True, + ): + super().__init__() + self.attentions = nn.ModuleList([]) + self.resnets = nn.ModuleList([]) + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + self.resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(resnet_in_channels + res_skip_channels // 4, 32), + groups_out=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + if attention_head_dim is None: + logger.warn( + f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `out_channels`: {out_channels}." + ) + attention_head_dim = out_channels + + self.attentions.append( + Attention( + out_channels, + heads=out_channels // attention_head_dim, + dim_head=attention_head_dim, + rescale_output_factor=output_scale_factor, + eps=resnet_eps, + norm_num_groups=32, + residual_connection=True, + bias=True, + upcast_softmax=True, + _from_deprecated_attn_block=True, + ) + ) + + self.upsampler = FirUpsample2D(in_channels, out_channels=out_channels) + if add_upsample: + self.resnet_up = ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(out_channels // 4, 32), + groups_out=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + use_in_shortcut=True, + up=True, + kernel="fir", + ) + self.skip_conv = nn.Conv2d(out_channels, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) + self.skip_norm = torch.nn.GroupNorm( + num_groups=min(out_channels // 4, 32), num_channels=out_channels, eps=resnet_eps, affine=True + ) + self.act = nn.SiLU() + else: + self.resnet_up = None + self.skip_conv = None + self.skip_norm = None + self.act = None + + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + skip_sample=None, + scale: float = 1.0, + ) -> Tuple[torch.FloatTensor, torch.FloatTensor]: + for resnet in self.resnets: + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + hidden_states = resnet(hidden_states, temb, scale=scale) + + cross_attention_kwargs = {"scale": scale} + hidden_states = self.attentions[0](hidden_states, **cross_attention_kwargs) + + if skip_sample is not None: + skip_sample = self.upsampler(skip_sample) + else: + skip_sample = 0 + + if self.resnet_up is not None: + skip_sample_states = self.skip_norm(hidden_states) + skip_sample_states = self.act(skip_sample_states) + skip_sample_states = self.skip_conv(skip_sample_states) + + skip_sample = skip_sample + skip_sample_states + + hidden_states = self.resnet_up(hidden_states, temb, scale=scale) + + return hidden_states, skip_sample + + +class SkipUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + prev_output_channel: int, + out_channels: int, + temb_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_pre_norm: bool = True, + output_scale_factor: float = np.sqrt(2.0), + add_upsample: bool = True, + upsample_padding: int = 1, + ): + super().__init__() + self.resnets = nn.ModuleList([]) + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + self.resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min((resnet_in_channels + res_skip_channels) // 4, 32), + groups_out=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.upsampler = FirUpsample2D(in_channels, out_channels=out_channels) + if add_upsample: + self.resnet_up = ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=min(out_channels // 4, 32), + groups_out=min(out_channels // 4, 32), + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + use_in_shortcut=True, + up=True, + kernel="fir", + ) + self.skip_conv = nn.Conv2d(out_channels, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) + self.skip_norm = torch.nn.GroupNorm( + num_groups=min(out_channels // 4, 32), num_channels=out_channels, eps=resnet_eps, affine=True + ) + self.act = nn.SiLU() + else: + self.resnet_up = None + self.skip_conv = None + self.skip_norm = None + self.act = None + + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + skip_sample=None, + scale: float = 1.0, + ) -> Tuple[torch.FloatTensor, torch.FloatTensor]: + for resnet in self.resnets: + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + hidden_states = resnet(hidden_states, temb, scale=scale) + + if skip_sample is not None: + skip_sample = self.upsampler(skip_sample) + else: + skip_sample = 0 + + if self.resnet_up is not None: + skip_sample_states = self.skip_norm(hidden_states) + skip_sample_states = self.act(skip_sample_states) + skip_sample_states = self.skip_conv(skip_sample_states) + + skip_sample = skip_sample + skip_sample_states + + hidden_states = self.resnet_up(hidden_states, temb, scale=scale) + + return hidden_states, skip_sample + + +class ResnetUpsampleBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + prev_output_channel: int, + out_channels: int, + temb_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor: float = 1.0, + add_upsample: bool = True, + skip_time_act: bool = False, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList( + [ + ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + up=True, + ) + ] + ) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + upsample_size: Optional[int] = None, + scale: float = 1.0, + ) -> torch.FloatTensor: + for resnet in self.resnets: + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + if is_torch_version(">=", "1.11.0"): + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + ) + else: + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb, scale=scale) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states, temb, scale=scale) + + return hidden_states + + +class SimpleCrossAttnUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + prev_output_channel: int, + temb_channels: int, + resolution_idx: Optional[int] = None, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attention_head_dim: int = 1, + cross_attention_dim: int = 1280, + output_scale_factor: float = 1.0, + add_upsample: bool = True, + skip_time_act: bool = False, + only_cross_attention: bool = False, + cross_attention_norm: Optional[str] = None, + ): + super().__init__() + resnets = [] + attentions = [] + + self.has_cross_attention = True + self.attention_head_dim = attention_head_dim + + self.num_heads = out_channels // self.attention_head_dim + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + resnets.append( + ResnetBlock2D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + ) + ) + + processor = ( + AttnAddedKVProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnAddedKVProcessor() + ) + + attentions.append( + Attention( + query_dim=out_channels, + cross_attention_dim=out_channels, + heads=self.num_heads, + dim_head=self.attention_head_dim, + added_kv_proj_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + bias=True, + upcast_softmax=True, + only_cross_attention=only_cross_attention, + cross_attention_norm=cross_attention_norm, + processor=processor, + ) + ) + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList( + [ + ResnetBlock2D( + in_channels=out_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + skip_time_act=skip_time_act, + up=True, + ) + ] + ) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + upsample_size: Optional[int] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {} + + lora_scale = cross_attention_kwargs.get("scale", 1.0) + if attention_mask is None: + # if encoder_hidden_states is defined: we are doing cross-attn, so we should use cross-attn mask. + mask = None if encoder_hidden_states is None else encoder_attention_mask + else: + # when attention_mask is defined: we don't even check for encoder_attention_mask. + # this is to maintain compatibility with UnCLIP, which uses 'attention_mask' param for cross-attn masks. + # TODO: UnCLIP should express cross-attn mask via encoder_attention_mask param instead of via attention_mask. + # then we can simplify this whole if/else block to: + # mask = attention_mask if encoder_hidden_states is None else encoder_attention_mask + mask = attention_mask + + for resnet, attn in zip(self.resnets, self.attentions): + # resnet + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb) + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=mask, + **cross_attention_kwargs, + ) + else: + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=mask, + **cross_attention_kwargs, + ) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states, temb, scale=lora_scale) + + return hidden_states + + +class KUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + resolution_idx: int, + dropout: float = 0.0, + num_layers: int = 5, + resnet_eps: float = 1e-5, + resnet_act_fn: str = "gelu", + resnet_group_size: Optional[int] = 32, + add_upsample: bool = True, + ): + super().__init__() + resnets = [] + k_in_channels = 2 * out_channels + k_out_channels = in_channels + num_layers = num_layers - 1 + + for i in range(num_layers): + in_channels = k_in_channels if i == 0 else out_channels + groups = in_channels // resnet_group_size + groups_out = out_channels // resnet_group_size + + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=k_out_channels if (i == num_layers - 1) else out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=groups, + groups_out=groups_out, + dropout=dropout, + non_linearity=resnet_act_fn, + time_embedding_norm="ada_group", + conv_shortcut_bias=False, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList([KUpsample2D()]) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + upsample_size: Optional[int] = None, + scale: float = 1.0, + ) -> torch.FloatTensor: + res_hidden_states_tuple = res_hidden_states_tuple[-1] + if res_hidden_states_tuple is not None: + hidden_states = torch.cat([hidden_states, res_hidden_states_tuple], dim=1) + + for resnet in self.resnets: + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + if is_torch_version(">=", "1.11.0"): + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb, use_reentrant=False + ) + else: + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb, scale=scale) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states) + + return hidden_states + + +class KCrossAttnUpBlock2D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + resolution_idx: int, + dropout: float = 0.0, + num_layers: int = 4, + resnet_eps: float = 1e-5, + resnet_act_fn: str = "gelu", + resnet_group_size: int = 32, + attention_head_dim: int = 1, # attention dim_head + cross_attention_dim: int = 768, + add_upsample: bool = True, + upcast_attention: bool = False, + ): + super().__init__() + resnets = [] + attentions = [] + + is_first_block = in_channels == out_channels == temb_channels + is_middle_block = in_channels != out_channels + add_self_attention = True if is_first_block else False + + self.has_cross_attention = True + self.attention_head_dim = attention_head_dim + + # in_channels, and out_channels for the block (k-unet) + k_in_channels = out_channels if is_first_block else 2 * out_channels + k_out_channels = in_channels + + num_layers = num_layers - 1 + + for i in range(num_layers): + in_channels = k_in_channels if i == 0 else out_channels + groups = in_channels // resnet_group_size + groups_out = out_channels // resnet_group_size + + if is_middle_block and (i == num_layers - 1): + conv_2d_out_channels = k_out_channels + else: + conv_2d_out_channels = None + + resnets.append( + ResnetBlock2D( + in_channels=in_channels, + out_channels=out_channels, + conv_2d_out_channels=conv_2d_out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=groups, + groups_out=groups_out, + dropout=dropout, + non_linearity=resnet_act_fn, + time_embedding_norm="ada_group", + conv_shortcut_bias=False, + ) + ) + attentions.append( + KAttentionBlock( + k_out_channels if (i == num_layers - 1) else out_channels, + k_out_channels // attention_head_dim + if (i == num_layers - 1) + else out_channels // attention_head_dim, + attention_head_dim, + cross_attention_dim=cross_attention_dim, + temb_channels=temb_channels, + attention_bias=True, + add_self_attention=add_self_attention, + cross_attention_norm="layer_norm", + upcast_attention=upcast_attention, + ) + ) + + self.resnets = nn.ModuleList(resnets) + self.attentions = nn.ModuleList(attentions) + + if add_upsample: + self.upsamplers = nn.ModuleList([KUpsample2D()]) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + self.resolution_idx = resolution_idx + + def forward( + self, + hidden_states: torch.FloatTensor, + res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], + temb: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + upsample_size: Optional[int] = None, + attention_mask: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + res_hidden_states_tuple = res_hidden_states_tuple[-1] + if res_hidden_states_tuple is not None: + hidden_states = torch.cat([hidden_states, res_hidden_states_tuple], dim=1) + + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + for resnet, attn in zip(self.resnets, self.attentions): + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), + hidden_states, + temb, + **ckpt_kwargs, + ) + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + emb=temb, + attention_mask=attention_mask, + cross_attention_kwargs=cross_attention_kwargs, + encoder_attention_mask=encoder_attention_mask, + ) + else: + hidden_states = resnet(hidden_states, temb, scale=lora_scale) + hidden_states = attn( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + emb=temb, + attention_mask=attention_mask, + cross_attention_kwargs=cross_attention_kwargs, + encoder_attention_mask=encoder_attention_mask, + ) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states) + + return hidden_states + + +# can potentially later be renamed to `No-feed-forward` attention +class KAttentionBlock(nn.Module): + r""" + A basic Transformer block. + + Parameters: + dim (`int`): The number of channels in the input and output. + num_attention_heads (`int`): The number of heads to use for multi-head attention. + attention_head_dim (`int`): The number of channels in each head. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention. + attention_bias (`bool`, *optional*, defaults to `False`): + Configure if the attention layers should contain a bias parameter. + upcast_attention (`bool`, *optional*, defaults to `False`): + Set to `True` to upcast the attention computation to `float32`. + temb_channels (`int`, *optional*, defaults to 768): + The number of channels in the token embedding. + add_self_attention (`bool`, *optional*, defaults to `False`): + Set to `True` to add self-attention to the block. + cross_attention_norm (`str`, *optional*, defaults to `None`): + The type of normalization to use for the cross attention. Can be `None`, `layer_norm`, or `group_norm`. + group_size (`int`, *optional*, defaults to 32): + The number of groups to separate the channels into for group normalization. + """ + + def __init__( + self, + dim: int, + num_attention_heads: int, + attention_head_dim: int, + dropout: float = 0.0, + cross_attention_dim: Optional[int] = None, + attention_bias: bool = False, + upcast_attention: bool = False, + temb_channels: int = 768, # for ada_group_norm + add_self_attention: bool = False, + cross_attention_norm: Optional[str] = None, + group_size: int = 32, + ): + super().__init__() + self.add_self_attention = add_self_attention + + # 1. Self-Attn + if add_self_attention: + self.norm1 = AdaGroupNorm(temb_channels, dim, max(1, dim // group_size)) + self.attn1 = Attention( + query_dim=dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + cross_attention_dim=None, + cross_attention_norm=None, + ) + + # 2. Cross-Attn + self.norm2 = AdaGroupNorm(temb_channels, dim, max(1, dim // group_size)) + self.attn2 = Attention( + query_dim=dim, + cross_attention_dim=cross_attention_dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + upcast_attention=upcast_attention, + cross_attention_norm=cross_attention_norm, + ) + + def _to_3d(self, hidden_states: torch.FloatTensor, height: int, weight: int) -> torch.FloatTensor: + return hidden_states.permute(0, 2, 3, 1).reshape(hidden_states.shape[0], height * weight, -1) + + def _to_4d(self, hidden_states: torch.FloatTensor, height: int, weight: int) -> torch.FloatTensor: + return hidden_states.permute(0, 2, 1).reshape(hidden_states.shape[0], -1, height, weight) + + def forward( + self, + hidden_states: torch.FloatTensor, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + # TODO: mark emb as non-optional (self.norm2 requires it). + # requires assessing impact of change to positional param interface. + emb: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + ) -> torch.FloatTensor: + cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {} + + # 1. Self-Attention + if self.add_self_attention: + norm_hidden_states = self.norm1(hidden_states, emb) + + height, weight = norm_hidden_states.shape[2:] + norm_hidden_states = self._to_3d(norm_hidden_states, height, weight) + + attn_output = self.attn1( + norm_hidden_states, + encoder_hidden_states=None, + attention_mask=attention_mask, + **cross_attention_kwargs, + ) + attn_output = self._to_4d(attn_output, height, weight) + + hidden_states = attn_output + hidden_states + + # 2. Cross-Attention/None + norm_hidden_states = self.norm2(hidden_states, emb) + + height, weight = norm_hidden_states.shape[2:] + norm_hidden_states = self._to_3d(norm_hidden_states, height, weight) + attn_output = self.attn2( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=attention_mask if encoder_hidden_states is None else encoder_attention_mask, + **cross_attention_kwargs, + ) + attn_output = self._to_4d(attn_output, height, weight) + + hidden_states = attn_output + hidden_states + + return hidden_states diff --git a/extensions-builtin/forge_space_idm_vton/src/unet_hacked_garmnet.py b/extensions-builtin/forge_space_idm_vton/src/unet_hacked_garmnet.py new file mode 100644 index 0000000000000000000000000000000000000000..53b1f8575c97ce6c26170b34481de6c5ac94a62b --- /dev/null +++ b/extensions-builtin/forge_space_idm_vton/src/unet_hacked_garmnet.py @@ -0,0 +1,1284 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Tuple, Union + +import torch +import torch.nn as nn +import torch.utils.checkpoint + +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.loaders import UNet2DConditionLoadersMixin +from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers +from diffusers.models.activations import get_activation +from diffusers.models.attention_processor import ( + ADDED_KV_ATTENTION_PROCESSORS, + CROSS_ATTENTION_PROCESSORS, + Attention, + AttentionProcessor, + AttnAddedKVProcessor, + AttnProcessor, +) +from einops import rearrange + +from diffusers.models.embeddings import ( + GaussianFourierProjection, + ImageHintTimeEmbedding, + ImageProjection, + ImageTimeEmbedding, + PositionNet, + TextImageProjection, + TextImageTimeEmbedding, + TextTimeEmbedding, + TimestepEmbedding, + Timesteps, +) +from diffusers.models.modeling_utils import ModelMixin +from src.unet_block_hacked_garmnet import ( + UNetMidBlock2D, + UNetMidBlock2DCrossAttn, + UNetMidBlock2DSimpleCrossAttn, + get_down_block, + get_up_block, +) +from diffusers.models.resnet import Downsample2D, FirDownsample2D, FirUpsample2D, KDownsample2D, KUpsample2D, ResnetBlock2D, Upsample2D +from diffusers.models.transformer_2d import Transformer2DModel + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +def zero_module(module): + for p in module.parameters(): + nn.init.zeros_(p) + return module + +@dataclass +class UNet2DConditionOutput(BaseOutput): + """ + The output of [`UNet2DConditionModel`]. + + Args: + sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): + The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model. + """ + + sample: torch.FloatTensor = None + + +class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin): + r""" + A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample + shaped output. + + This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented + for all models (such as downloading or saving). + + Parameters: + sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`): + Height and width of input/output sample. + in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample. + out_channels (`int`, *optional*, defaults to 4): Number of channels in the output. + center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample. + flip_sin_to_cos (`bool`, *optional*, defaults to `False`): + Whether to flip the sin to cos in the time embedding. + freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding. + down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`): + The tuple of downsample blocks to use. + mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`): + Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or + `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped. + up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`): + The tuple of upsample blocks to use. + only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`): + Whether to include self-attention in the basic transformer blocks, see + [`~models.attention.BasicTransformerBlock`]. + block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`): + The tuple of output channels for each block. + layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. + downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution. + mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use. + norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization. + If `None`, normalization and activation layers is skipped in post-processing. + norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization. + cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280): + The dimension of the cross attention features. + transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1): + The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for + [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`], + [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`]. + reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None): + The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling + blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for + [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`], + [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`]. + encoder_hid_dim (`int`, *optional*, defaults to None): + If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim` + dimension to `cross_attention_dim`. + encoder_hid_dim_type (`str`, *optional*, defaults to `None`): + If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text + embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`. + attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads. + num_attention_heads (`int`, *optional*): + The number of attention heads. If not defined, defaults to `attention_head_dim` + resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config + for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`. + class_embed_type (`str`, *optional*, defaults to `None`): + The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`, + `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`. + addition_embed_type (`str`, *optional*, defaults to `None`): + Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or + "text". "text" will use the `TextTimeEmbedding` layer. + addition_time_embed_dim: (`int`, *optional*, defaults to `None`): + Dimension for the timestep embeddings. + num_class_embeds (`int`, *optional*, defaults to `None`): + Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing + class conditioning with `class_embed_type` equal to `None`. + time_embedding_type (`str`, *optional*, defaults to `positional`): + The type of position embedding to use for timesteps. Choose from `positional` or `fourier`. + time_embedding_dim (`int`, *optional*, defaults to `None`): + An optional override for the dimension of the projected time embedding. + time_embedding_act_fn (`str`, *optional*, defaults to `None`): + Optional activation function to use only once on the time embeddings before they are passed to the rest of + the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`. + timestep_post_act (`str`, *optional*, defaults to `None`): + The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`. + time_cond_proj_dim (`int`, *optional*, defaults to `None`): + The dimension of `cond_proj` layer in the timestep embedding. + conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer. conv_out_kernel (`int`, + *optional*, default to `3`): The kernel size of `conv_out` layer. projection_class_embeddings_input_dim (`int`, + *optional*): The dimension of the `class_labels` input when + `class_embed_type="projection"`. Required when `class_embed_type="projection"`. + class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time + embeddings with the class embeddings. + mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`): + Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If + `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the + `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False` + otherwise. + """ + + _supports_gradient_checkpointing = True + + @register_to_config + def __init__( + self, + sample_size: Optional[int] = None, + in_channels: int = 4, + out_channels: int = 4, + center_input_sample: bool = False, + flip_sin_to_cos: bool = True, + freq_shift: int = 0, + down_block_types: Tuple[str] = ( + "CrossAttnDownBlock2D", + "CrossAttnDownBlock2D", + "CrossAttnDownBlock2D", + "DownBlock2D", + ), + mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn", + up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"), + only_cross_attention: Union[bool, Tuple[bool]] = False, + block_out_channels: Tuple[int] = (320, 640, 1280, 1280), + layers_per_block: Union[int, Tuple[int]] = 2, + downsample_padding: int = 1, + mid_block_scale_factor: float = 1, + dropout: float = 0.0, + act_fn: str = "silu", + norm_num_groups: Optional[int] = 32, + norm_eps: float = 1e-5, + cross_attention_dim: Union[int, Tuple[int]] = 1280, + transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1, + reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None, + encoder_hid_dim: Optional[int] = None, + encoder_hid_dim_type: Optional[str] = None, + attention_head_dim: Union[int, Tuple[int]] = 8, + num_attention_heads: Optional[Union[int, Tuple[int]]] = None, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + class_embed_type: Optional[str] = None, + addition_embed_type: Optional[str] = None, + addition_time_embed_dim: Optional[int] = None, + num_class_embeds: Optional[int] = None, + upcast_attention: bool = False, + resnet_time_scale_shift: str = "default", + resnet_skip_time_act: bool = False, + resnet_out_scale_factor: int = 1.0, + time_embedding_type: str = "positional", + time_embedding_dim: Optional[int] = None, + time_embedding_act_fn: Optional[str] = None, + timestep_post_act: Optional[str] = None, + time_cond_proj_dim: Optional[int] = None, + conv_in_kernel: int = 3, + conv_out_kernel: int = 3, + projection_class_embeddings_input_dim: Optional[int] = None, + attention_type: str = "default", + class_embeddings_concat: bool = False, + mid_block_only_cross_attention: Optional[bool] = None, + cross_attention_norm: Optional[str] = None, + addition_embed_type_num_heads=64, + ): + super().__init__() + + self.sample_size = sample_size + + if num_attention_heads is not None: + raise ValueError( + "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19." + ) + + # If `num_attention_heads` is not defined (which is the case for most models) + # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. + # The reason for this behavior is to correct for incorrectly named variables that were introduced + # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 + # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking + # which is why we correct for the naming here. + num_attention_heads = num_attention_heads or attention_head_dim + + # Check inputs + if len(down_block_types) != len(up_block_types): + raise ValueError( + f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}." + ) + + if len(block_out_channels) != len(down_block_types): + raise ValueError( + f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}." + ) + + if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types): + raise ValueError( + f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}." + ) + + if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types): + raise ValueError( + f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}." + ) + + if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types): + raise ValueError( + f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}." + ) + + if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types): + raise ValueError( + f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}." + ) + + if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types): + raise ValueError( + f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}." + ) + if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None: + for layer_number_per_block in transformer_layers_per_block: + if isinstance(layer_number_per_block, list): + raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.") + + # input + conv_in_padding = (conv_in_kernel - 1) // 2 + self.conv_in = nn.Conv2d( + in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding + ) + + # time + if time_embedding_type == "fourier": + time_embed_dim = time_embedding_dim or block_out_channels[0] * 2 + if time_embed_dim % 2 != 0: + raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.") + self.time_proj = GaussianFourierProjection( + time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos + ) + timestep_input_dim = time_embed_dim + elif time_embedding_type == "positional": + time_embed_dim = time_embedding_dim or block_out_channels[0] * 4 + + self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) + timestep_input_dim = block_out_channels[0] + else: + raise ValueError( + f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`." + ) + + self.time_embedding = TimestepEmbedding( + timestep_input_dim, + time_embed_dim, + act_fn=act_fn, + post_act_fn=timestep_post_act, + cond_proj_dim=time_cond_proj_dim, + ) + + if encoder_hid_dim_type is None and encoder_hid_dim is not None: + encoder_hid_dim_type = "text_proj" + self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type) + logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.") + + if encoder_hid_dim is None and encoder_hid_dim_type is not None: + raise ValueError( + f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}." + ) + + if encoder_hid_dim_type == "text_proj": + self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim) + elif encoder_hid_dim_type == "text_image_proj": + # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much + # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use + # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)` + self.encoder_hid_proj = TextImageProjection( + text_embed_dim=encoder_hid_dim, + image_embed_dim=cross_attention_dim, + cross_attention_dim=cross_attention_dim, + ) + elif encoder_hid_dim_type == "image_proj": + # Kandinsky 2.2 + self.encoder_hid_proj = ImageProjection( + image_embed_dim=encoder_hid_dim, + cross_attention_dim=cross_attention_dim, + ) + elif encoder_hid_dim_type is not None: + raise ValueError( + f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'." + ) + else: + self.encoder_hid_proj = None + + # class embedding + if class_embed_type is None and num_class_embeds is not None: + self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) + elif class_embed_type == "timestep": + self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn) + elif class_embed_type == "identity": + self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) + elif class_embed_type == "projection": + if projection_class_embeddings_input_dim is None: + raise ValueError( + "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set" + ) + # The projection `class_embed_type` is the same as the timestep `class_embed_type` except + # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings + # 2. it projects from an arbitrary input dimension. + # + # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations. + # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings. + # As a result, `TimestepEmbedding` can be passed arbitrary vectors. + self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) + elif class_embed_type == "simple_projection": + if projection_class_embeddings_input_dim is None: + raise ValueError( + "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set" + ) + self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim) + else: + self.class_embedding = None + + if addition_embed_type == "text": + if encoder_hid_dim is not None: + text_time_embedding_from_dim = encoder_hid_dim + else: + text_time_embedding_from_dim = cross_attention_dim + + self.add_embedding = TextTimeEmbedding( + text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads + ) + elif addition_embed_type == "text_image": + # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much + # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use + # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)` + self.add_embedding = TextImageTimeEmbedding( + text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim + ) + elif addition_embed_type == "text_time": + self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift) + self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) + elif addition_embed_type == "image": + # Kandinsky 2.2 + self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) + elif addition_embed_type == "image_hint": + # Kandinsky 2.2 ControlNet + self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) + elif addition_embed_type is not None: + raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.") + + if time_embedding_act_fn is None: + self.time_embed_act = None + else: + self.time_embed_act = get_activation(time_embedding_act_fn) + + self.down_blocks = nn.ModuleList([]) + self.up_blocks = nn.ModuleList([]) + + if isinstance(only_cross_attention, bool): + if mid_block_only_cross_attention is None: + mid_block_only_cross_attention = only_cross_attention + + only_cross_attention = [only_cross_attention] * len(down_block_types) + + if mid_block_only_cross_attention is None: + mid_block_only_cross_attention = False + + if isinstance(num_attention_heads, int): + num_attention_heads = (num_attention_heads,) * len(down_block_types) + + if isinstance(attention_head_dim, int): + attention_head_dim = (attention_head_dim,) * len(down_block_types) + + if isinstance(cross_attention_dim, int): + cross_attention_dim = (cross_attention_dim,) * len(down_block_types) + + if isinstance(layers_per_block, int): + layers_per_block = [layers_per_block] * len(down_block_types) + + if isinstance(transformer_layers_per_block, int): + transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types) + if class_embeddings_concat: + # The time embeddings are concatenated with the class embeddings. The dimension of the + # time embeddings passed to the down, middle, and up blocks is twice the dimension of the + # regular time embeddings + blocks_time_embed_dim = time_embed_dim * 2 + else: + blocks_time_embed_dim = time_embed_dim + + # down + output_channel = block_out_channels[0] + for i, down_block_type in enumerate(down_block_types): + input_channel = output_channel + output_channel = block_out_channels[i] + is_final_block = i == len(block_out_channels) - 1 + + down_block = get_down_block( + down_block_type, + num_layers=layers_per_block[i], + transformer_layers_per_block=transformer_layers_per_block[i], + in_channels=input_channel, + out_channels=output_channel, + temb_channels=blocks_time_embed_dim, + add_downsample=not is_final_block, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + resnet_groups=norm_num_groups, + cross_attention_dim=cross_attention_dim[i], + num_attention_heads=num_attention_heads[i], + downsample_padding=downsample_padding, + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention[i], + upcast_attention=upcast_attention, + resnet_time_scale_shift=resnet_time_scale_shift, + attention_type=attention_type, + resnet_skip_time_act=resnet_skip_time_act, + resnet_out_scale_factor=resnet_out_scale_factor, + cross_attention_norm=cross_attention_norm, + attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel, + dropout=dropout, + ) + self.down_blocks.append(down_block) + + # mid + if mid_block_type == "UNetMidBlock2DCrossAttn": + self.mid_block = UNetMidBlock2DCrossAttn( + transformer_layers_per_block=transformer_layers_per_block[-1], + in_channels=block_out_channels[-1], + temb_channels=blocks_time_embed_dim, + dropout=dropout, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + output_scale_factor=mid_block_scale_factor, + resnet_time_scale_shift=resnet_time_scale_shift, + cross_attention_dim=cross_attention_dim[-1], + num_attention_heads=num_attention_heads[-1], + resnet_groups=norm_num_groups, + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + upcast_attention=upcast_attention, + attention_type=attention_type, + ) + elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn": + self.mid_block = UNetMidBlock2DSimpleCrossAttn( + in_channels=block_out_channels[-1], + temb_channels=blocks_time_embed_dim, + dropout=dropout, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + output_scale_factor=mid_block_scale_factor, + cross_attention_dim=cross_attention_dim[-1], + attention_head_dim=attention_head_dim[-1], + resnet_groups=norm_num_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + skip_time_act=resnet_skip_time_act, + only_cross_attention=mid_block_only_cross_attention, + cross_attention_norm=cross_attention_norm, + ) + elif mid_block_type == "UNetMidBlock2D": + self.mid_block = UNetMidBlock2D( + in_channels=block_out_channels[-1], + temb_channels=blocks_time_embed_dim, + dropout=dropout, + num_layers=0, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + output_scale_factor=mid_block_scale_factor, + resnet_groups=norm_num_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + add_attention=False, + ) + elif mid_block_type is None: + self.mid_block = None + else: + raise ValueError(f"unknown mid_block_type : {mid_block_type}") + + # count how many layers upsample the images + self.num_upsamplers = 0 + + # up + reversed_block_out_channels = list(reversed(block_out_channels)) + reversed_num_attention_heads = list(reversed(num_attention_heads)) + reversed_layers_per_block = list(reversed(layers_per_block)) + reversed_cross_attention_dim = list(reversed(cross_attention_dim)) + reversed_transformer_layers_per_block = ( + list(reversed(transformer_layers_per_block)) + if reverse_transformer_layers_per_block is None + else reverse_transformer_layers_per_block + ) + only_cross_attention = list(reversed(only_cross_attention)) + + output_channel = reversed_block_out_channels[0] + for i, up_block_type in enumerate(up_block_types): + is_final_block = i == len(block_out_channels) - 1 + + prev_output_channel = output_channel + output_channel = reversed_block_out_channels[i] + input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] + + # add upsample block for all BUT final layer + if not is_final_block: + add_upsample = True + self.num_upsamplers += 1 + else: + add_upsample = False + up_block = get_up_block( + up_block_type, + num_layers=reversed_layers_per_block[i] + 1, + transformer_layers_per_block=reversed_transformer_layers_per_block[i], + in_channels=input_channel, + out_channels=output_channel, + prev_output_channel=prev_output_channel, + temb_channels=blocks_time_embed_dim, + add_upsample=add_upsample, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + resolution_idx=i, + resnet_groups=norm_num_groups, + cross_attention_dim=reversed_cross_attention_dim[i], + num_attention_heads=reversed_num_attention_heads[i], + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention[i], + upcast_attention=upcast_attention, + resnet_time_scale_shift=resnet_time_scale_shift, + attention_type=attention_type, + resnet_skip_time_act=resnet_skip_time_act, + resnet_out_scale_factor=resnet_out_scale_factor, + cross_attention_norm=cross_attention_norm, + attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel, + dropout=dropout, + ) + + self.up_blocks.append(up_block) + prev_output_channel = output_channel + + + + + # encode_output_chs = [ + # # 320, + # # 320, + # # 320, + # 1280, + # 1280, + # 1280, + # 1280, + # 640, + # 640 + # ] + + # encode_output_chs2 = [ + # # 320, + # # 320, + # # 320, + # 1280, + # 1280, + # 640, + # 640, + # 640, + # 320 + # ] + + # encode_num_head_chs3 = [ + # # 5, + # # 5, + # # 10, + # 20, + # 20, + # 20, + # 10, + # 10, + # 10 + # ] + + + # encode_num_layers_chs4 = [ + # # 1, + # # 1, + # # 2, + # 10, + # 10, + # 10, + # 2, + # 2, + # 2 + # ] + + + # self.warp_blks = nn.ModuleList([]) + # self.warp_zeros = nn.ModuleList([]) + + # for in_ch, cont_ch,num_head,num_layers in zip(encode_output_chs, encode_output_chs2,encode_num_head_chs3,encode_num_layers_chs4): + # # dim_head = in_ch // self.num_heads + # # dim_head = dim_head // dim_head_denorm + + # self.warp_blks.append(Transformer2DModel( + # num_attention_heads=num_head, + # attention_head_dim=64, + # in_channels=in_ch, + # num_layers = num_layers, + # cross_attention_dim = cont_ch, + # )) + + # self.warp_zeros.append(zero_module(nn.Conv2d(in_ch, in_ch, 1, padding=0))) + + + + # out + if norm_num_groups is not None: + self.conv_norm_out = nn.GroupNorm( + num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps + ) + + self.conv_act = get_activation(act_fn) + + else: + self.conv_norm_out = None + self.conv_act = None + + conv_out_padding = (conv_out_kernel - 1) // 2 + self.conv_out = nn.Conv2d( + block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding + ) + + if attention_type in ["gated", "gated-text-image"]: + positive_len = 768 + if isinstance(cross_attention_dim, int): + positive_len = cross_attention_dim + elif isinstance(cross_attention_dim, tuple) or isinstance(cross_attention_dim, list): + positive_len = cross_attention_dim[0] + + feature_type = "text-only" if attention_type == "gated" else "text-image" + self.position_net = PositionNet( + positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type + ) + + + + + @property + def attn_processors(self) -> Dict[str, AttentionProcessor]: + r""" + Returns: + `dict` of attention processors: A dictionary containing all attention processors used in the model with + indexed by its weight name. + """ + # set recursively + processors = {} + + def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]): + if hasattr(module, "get_processor"): + processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True) + + for sub_name, child in module.named_children(): + fn_recursive_add_processors(f"{name}.{sub_name}", child, processors) + + return processors + + for name, module in self.named_children(): + fn_recursive_add_processors(name, module, processors) + + return processors + + def set_attn_processor( + self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False + ): + r""" + Sets the attention processor to use to compute attention. + + Parameters: + processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`): + The instantiated processor class or a dictionary of processor classes that will be set as the processor + for **all** `Attention` layers. + + If `processor` is a dict, the key needs to define the path to the corresponding cross attention + processor. This is strongly recommended when setting trainable attention processors. + + """ + count = len(self.attn_processors.keys()) + + if isinstance(processor, dict) and len(processor) != count: + raise ValueError( + f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" + f" number of attention layers: {count}. Please make sure to pass {count} processor classes." + ) + + def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor): + if hasattr(module, "set_processor"): + if not isinstance(processor, dict): + module.set_processor(processor) + else: + module.set_processor(processor.pop(f"{name}.processor")) + + for sub_name, child in module.named_children(): + fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor) + + for name, module in self.named_children(): + fn_recursive_attn_processor(name, module, processor) + + def set_default_attn_processor(self): + """ + Disables custom attention processors and sets the default attention implementation. + """ + if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()): + processor = AttnAddedKVProcessor() + elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()): + processor = AttnProcessor() + else: + raise ValueError( + f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}" + ) + + self.set_attn_processor(processor, _remove_lora=True) + + def set_attention_slice(self, slice_size): + r""" + Enable sliced attention computation. + + When this option is enabled, the attention module splits the input tensor in slices to compute attention in + several steps. This is useful for saving some memory in exchange for a small decrease in speed. + + Args: + slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): + When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If + `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is + provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim` + must be a multiple of `slice_size`. + """ + sliceable_head_dims = [] + + def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module): + if hasattr(module, "set_attention_slice"): + sliceable_head_dims.append(module.sliceable_head_dim) + + for child in module.children(): + fn_recursive_retrieve_sliceable_dims(child) + + # retrieve number of attention layers + for module in self.children(): + fn_recursive_retrieve_sliceable_dims(module) + + num_sliceable_layers = len(sliceable_head_dims) + + if slice_size == "auto": + # half the attention head size is usually a good trade-off between + # speed and memory + slice_size = [dim // 2 for dim in sliceable_head_dims] + elif slice_size == "max": + # make smallest slice possible + slice_size = num_sliceable_layers * [1] + + slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size + + if len(slice_size) != len(sliceable_head_dims): + raise ValueError( + f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different" + f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}." + ) + + for i in range(len(slice_size)): + size = slice_size[i] + dim = sliceable_head_dims[i] + if size is not None and size > dim: + raise ValueError(f"size {size} has to be smaller or equal to {dim}.") + + # Recursively walk through all the children. + # Any children which exposes the set_attention_slice method + # gets the message + def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]): + if hasattr(module, "set_attention_slice"): + module.set_attention_slice(slice_size.pop()) + + for child in module.children(): + fn_recursive_set_attention_slice(child, slice_size) + + reversed_slice_size = list(reversed(slice_size)) + for module in self.children(): + fn_recursive_set_attention_slice(module, reversed_slice_size) + + def _set_gradient_checkpointing(self, module, value=False): + if hasattr(module, "gradient_checkpointing"): + module.gradient_checkpointing = value + + def enable_freeu(self, s1, s2, b1, b2): + r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497. + + The suffixes after the scaling factors represent the stage blocks where they are being applied. + + Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that + are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL. + + Args: + s1 (`float`): + Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to + mitigate the "oversmoothing effect" in the enhanced denoising process. + s2 (`float`): + Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to + mitigate the "oversmoothing effect" in the enhanced denoising process. + b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features. + b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features. + """ + for i, upsample_block in enumerate(self.up_blocks): + setattr(upsample_block, "s1", s1) + setattr(upsample_block, "s2", s2) + setattr(upsample_block, "b1", b1) + setattr(upsample_block, "b2", b2) + + def disable_freeu(self): + """Disables the FreeU mechanism.""" + freeu_keys = {"s1", "s2", "b1", "b2"} + for i, upsample_block in enumerate(self.up_blocks): + for k in freeu_keys: + if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None: + setattr(upsample_block, k, None) + + def fuse_qkv_projections(self): + """ + Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, + key, value) are fused. For cross-attention modules, key and value projection matrices are fused. + + + + This API is 🧪 experimental. + + + """ + self.original_attn_processors = None + + for _, attn_processor in self.attn_processors.items(): + if "Added" in str(attn_processor.__class__.__name__): + raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.") + + self.original_attn_processors = self.attn_processors + + for module in self.modules(): + if isinstance(module, Attention): + module.fuse_projections(fuse=True) + + def unfuse_qkv_projections(self): + """Disables the fused QKV projection if enabled. + + + + This API is 🧪 experimental. + + + + """ + if self.original_attn_processors is not None: + self.set_attn_processor(self.original_attn_processors) + + def forward( + self, + sample: torch.FloatTensor, + timestep: Union[torch.Tensor, float, int], + encoder_hidden_states: torch.Tensor, + class_labels: Optional[torch.Tensor] = None, + timestep_cond: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None, + down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None, + mid_block_additional_residual: Optional[torch.Tensor] = None, + down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None, + encoder_attention_mask: Optional[torch.Tensor] = None, + return_dict: bool = True, + ) -> Union[UNet2DConditionOutput, Tuple]: + r""" + The [`UNet2DConditionModel`] forward method. + + Args: + sample (`torch.FloatTensor`): + The noisy input tensor with the following shape `(batch, channel, height, width)`. + timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input. + encoder_hidden_states (`torch.FloatTensor`): + The encoder hidden states with shape `(batch, sequence_length, feature_dim)`. + class_labels (`torch.Tensor`, *optional*, defaults to `None`): + Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings. + timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`): + Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed + through the `self.time_embedding` layer to obtain the timestep embeddings. + attention_mask (`torch.Tensor`, *optional*, defaults to `None`): + An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask + is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large + negative values to the attention scores corresponding to "discard" tokens. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + added_cond_kwargs: (`dict`, *optional*): + A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that + are passed along to the UNet blocks. + down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*): + A tuple of tensors that if specified are added to the residuals of down unet blocks. + mid_block_additional_residual: (`torch.Tensor`, *optional*): + A tensor that if specified is added to the residual of the middle unet block. + encoder_attention_mask (`torch.Tensor`): + A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If + `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias, + which adds large negative values to the attention scores corresponding to "discard" tokens. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain + tuple. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the [`AttnProcessor`]. + added_cond_kwargs: (`dict`, *optional*): + A kwargs dictionary containin additional embeddings that if specified are added to the embeddings that + are passed along to the UNet blocks. + down_block_additional_residuals (`tuple` of `torch.Tensor`, *optional*): + additional residuals to be added to UNet long skip connections from down blocks to up blocks for + example from ControlNet side model(s) + mid_block_additional_residual (`torch.Tensor`, *optional*): + additional residual to be added to UNet mid block output, for example from ControlNet side model + down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*): + additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s) + + Returns: + [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`: + If `return_dict` is True, an [`~models.unet_2d_condition.UNet2DConditionOutput`] is returned, otherwise + a `tuple` is returned where the first element is the sample tensor. + """ + # By default samples have to be AT least a multiple of the overall upsampling factor. + # The overall upsampling factor is equal to 2 ** (# num of upsampling layers). + # However, the upsampling interpolation output size can be forced to fit any upsampling size + # on the fly if necessary. + default_overall_up_factor = 2**self.num_upsamplers + + # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor` + forward_upsample_size = False + upsample_size = None + + for dim in sample.shape[-2:]: + if dim % default_overall_up_factor != 0: + # Forward upsample size to force interpolation output size. + forward_upsample_size = True + break + + # ensure attention_mask is a bias, and give it a singleton query_tokens dimension + # expects mask of shape: + # [batch, key_tokens] + # adds singleton query_tokens dimension: + # [batch, 1, key_tokens] + # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes: + # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn) + # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn) + if attention_mask is not None: + # assume that mask is expressed as: + # (1 = keep, 0 = discard) + # convert mask into a bias that can be added to attention scores: + # (keep = +0, discard = -10000.0) + attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0 + attention_mask = attention_mask.unsqueeze(1) + + # convert encoder_attention_mask to a bias the same way we do for attention_mask + if encoder_attention_mask is not None: + encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0 + encoder_attention_mask = encoder_attention_mask.unsqueeze(1) + + # 0. center input if necessary + if self.config.center_input_sample: + sample = 2 * sample - 1.0 + + # 1. time + timesteps = timestep + if not torch.is_tensor(timesteps): + # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can + # This would be a good case for the `match` statement (Python 3.10+) + is_mps = sample.device.type == "mps" + if isinstance(timestep, float): + dtype = torch.float32 if is_mps else torch.float64 + else: + dtype = torch.int32 if is_mps else torch.int64 + timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device) + elif len(timesteps.shape) == 0: + timesteps = timesteps[None].to(sample.device) + + # broadcast to batch dimension in a way that's compatible with ONNX/Core ML + timesteps = timesteps.expand(sample.shape[0]) + + t_emb = self.time_proj(timesteps) + + # `Timesteps` does not contain any weights and will always return f32 tensors + # but time_embedding might actually be running in fp16. so we need to cast here. + # there might be better ways to encapsulate this. + t_emb = t_emb.to(dtype=sample.dtype) + + emb = self.time_embedding(t_emb, timestep_cond) + aug_emb = None + + if self.class_embedding is not None: + if class_labels is None: + raise ValueError("class_labels should be provided when num_class_embeds > 0") + + if self.config.class_embed_type == "timestep": + class_labels = self.time_proj(class_labels) + + # `Timesteps` does not contain any weights and will always return f32 tensors + # there might be better ways to encapsulate this. + class_labels = class_labels.to(dtype=sample.dtype) + + class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype) + + if self.config.class_embeddings_concat: + emb = torch.cat([emb, class_emb], dim=-1) + else: + emb = emb + class_emb + + if self.config.addition_embed_type == "text": + aug_emb = self.add_embedding(encoder_hidden_states) + elif self.config.addition_embed_type == "text_image": + # Kandinsky 2.1 - style + if "image_embeds" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `addition_embed_type` set to 'text_image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`" + ) + + image_embs = added_cond_kwargs.get("image_embeds") + text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states) + aug_emb = self.add_embedding(text_embs, image_embs) + elif self.config.addition_embed_type == "text_time": + # SDXL - style + if "text_embeds" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`" + ) + text_embeds = added_cond_kwargs.get("text_embeds") + if "time_ids" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`" + ) + time_ids = added_cond_kwargs.get("time_ids") + time_embeds = self.add_time_proj(time_ids.flatten()) + time_embeds = time_embeds.reshape((text_embeds.shape[0], -1)) + add_embeds = torch.concat([text_embeds, time_embeds], dim=-1) + add_embeds = add_embeds.to(emb.dtype) + aug_emb = self.add_embedding(add_embeds) + elif self.config.addition_embed_type == "image": + # Kandinsky 2.2 - style + if "image_embeds" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `addition_embed_type` set to 'image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`" + ) + image_embs = added_cond_kwargs.get("image_embeds") + aug_emb = self.add_embedding(image_embs) + elif self.config.addition_embed_type == "image_hint": + # Kandinsky 2.2 - style + if "image_embeds" not in added_cond_kwargs or "hint" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `addition_embed_type` set to 'image_hint' which requires the keyword arguments `image_embeds` and `hint` to be passed in `added_cond_kwargs`" + ) + image_embs = added_cond_kwargs.get("image_embeds") + hint = added_cond_kwargs.get("hint") + aug_emb, hint = self.add_embedding(image_embs, hint) + sample = torch.cat([sample, hint], dim=1) + + emb = emb + aug_emb if aug_emb is not None else emb + + if self.time_embed_act is not None: + emb = self.time_embed_act(emb) + + if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj": + encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states) + elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj": + # Kadinsky 2.1 - style + if "image_embeds" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'text_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`" + ) + + image_embeds = added_cond_kwargs.get("image_embeds") + encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds) + elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj": + # Kandinsky 2.2 - style + if "image_embeds" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`" + ) + image_embeds = added_cond_kwargs.get("image_embeds") + encoder_hidden_states = self.encoder_hid_proj(image_embeds) + elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj": + if "image_embeds" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'ip_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`" + ) + image_embeds = added_cond_kwargs.get("image_embeds") + image_embeds = self.encoder_hid_proj(image_embeds).to(encoder_hidden_states.dtype) + encoder_hidden_states = torch.cat([encoder_hidden_states, image_embeds], dim=1) + + # 2. pre-process + sample = self.conv_in(sample) + garment_features=[] + + # 2.5 GLIGEN position net + if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None: + cross_attention_kwargs = cross_attention_kwargs.copy() + gligen_args = cross_attention_kwargs.pop("gligen") + cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)} + + + # 3. down + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + if USE_PEFT_BACKEND: + # weight the lora layers by setting `lora_scale` for each PEFT layer + scale_lora_layers(self, lora_scale) + + is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None + # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets + is_adapter = down_intrablock_additional_residuals is not None + # maintain backward compatibility for legacy usage, where + # T2I-Adapter and ControlNet both use down_block_additional_residuals arg + # but can only use one or the other + if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None: + deprecate( + "T2I should not use down_block_additional_residuals", + "1.3.0", + "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \ + and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \ + for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ", + standard_warn=False, + ) + down_intrablock_additional_residuals = down_block_additional_residuals + is_adapter = True + + down_block_res_samples = (sample,) + for downsample_block in self.down_blocks: + if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention: + # For t2i-adapter CrossAttnDownBlock2D + additional_residuals = {} + if is_adapter and len(down_intrablock_additional_residuals) > 0: + additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0) + + sample, res_samples,out_garment_feat = downsample_block( + hidden_states=sample, + temb=emb, + encoder_hidden_states=encoder_hidden_states, + attention_mask=attention_mask, + cross_attention_kwargs=cross_attention_kwargs, + encoder_attention_mask=encoder_attention_mask, + **additional_residuals, + ) + garment_features += out_garment_feat + else: + sample, res_samples = downsample_block(hidden_states=sample, temb=emb, scale=lora_scale) + if is_adapter and len(down_intrablock_additional_residuals) > 0: + sample += down_intrablock_additional_residuals.pop(0) + + down_block_res_samples += res_samples + + + if is_controlnet: + new_down_block_res_samples = () + + for down_block_res_sample, down_block_additional_residual in zip( + down_block_res_samples, down_block_additional_residuals + ): + down_block_res_sample = down_block_res_sample + down_block_additional_residual + new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,) + + down_block_res_samples = new_down_block_res_samples + + # 4. mid + if self.mid_block is not None: + if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention: + sample,out_garment_feat = self.mid_block( + sample, + emb, + encoder_hidden_states=encoder_hidden_states, + attention_mask=attention_mask, + cross_attention_kwargs=cross_attention_kwargs, + encoder_attention_mask=encoder_attention_mask, + ) + garment_features += out_garment_feat + + else: + sample = self.mid_block(sample, emb) + + # To support T2I-Adapter-XL + if ( + is_adapter + and len(down_intrablock_additional_residuals) > 0 + and sample.shape == down_intrablock_additional_residuals[0].shape + ): + sample += down_intrablock_additional_residuals.pop(0) + + if is_controlnet: + sample = sample + mid_block_additional_residual + + + + # 5. up + for i, upsample_block in enumerate(self.up_blocks): + is_final_block = i == len(self.up_blocks) - 1 + + res_samples = down_block_res_samples[-len(upsample_block.resnets) :] + down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)] + + # if we have not reached the final block and need to forward the + # upsample size, we do it here + if not is_final_block and forward_upsample_size: + upsample_size = down_block_res_samples[-1].shape[2:] + + if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention: + sample,out_garment_feat = upsample_block( + hidden_states=sample, + temb=emb, + res_hidden_states_tuple=res_samples, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + upsample_size=upsample_size, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + ) + garment_features += out_garment_feat + + + if not return_dict: + return (sample,),garment_features + + return UNet2DConditionOutput(sample=sample),garment_features diff --git a/extensions-builtin/forge_space_idm_vton/src/unet_hacked_tryon.py b/extensions-builtin/forge_space_idm_vton/src/unet_hacked_tryon.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c795ce2187f6d6708f24e4c20db94486114432 --- /dev/null +++ b/extensions-builtin/forge_space_idm_vton/src/unet_hacked_tryon.py @@ -0,0 +1,1395 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Tuple, Union + +import torch +import torch.nn as nn +import torch.utils.checkpoint + +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.loaders import UNet2DConditionLoadersMixin +from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers +from diffusers.models.activations import get_activation +from diffusers.models.attention_processor import ( + ADDED_KV_ATTENTION_PROCESSORS, + CROSS_ATTENTION_PROCESSORS, + Attention, + AttentionProcessor, + AttnAddedKVProcessor, + AttnProcessor, +) +from einops import rearrange + +from diffusers.models.embeddings import ( + GaussianFourierProjection, + ImageHintTimeEmbedding, + ImageProjection, + ImageTimeEmbedding, + PositionNet, + TextImageProjection, + TextImageTimeEmbedding, + TextTimeEmbedding, + TimestepEmbedding, + Timesteps, +) + + +from diffusers.models.modeling_utils import ModelMixin +from src.unet_block_hacked_tryon import ( + UNetMidBlock2D, + UNetMidBlock2DCrossAttn, + UNetMidBlock2DSimpleCrossAttn, + get_down_block, + get_up_block, +) +from diffusers.models.resnet import Downsample2D, FirDownsample2D, FirUpsample2D, KDownsample2D, KUpsample2D, ResnetBlock2D, Upsample2D +from diffusers.models.transformer_2d import Transformer2DModel +import math + +from ip_adapter.ip_adapter import Resampler + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +# def FeedForward(dim, mult=4): +# inner_dim = int(dim * mult) +# return nn.Sequential( +# nn.LayerNorm(dim), +# nn.Linear(dim, inner_dim, bias=False), +# nn.GELU(), +# nn.Linear(inner_dim, dim, bias=False), +# ) + + + +# def reshape_tensor(x, heads): +# bs, length, width = x.shape +# # (bs, length, width) --> (bs, length, n_heads, dim_per_head) +# x = x.view(bs, length, heads, -1) +# # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head) +# x = x.transpose(1, 2) +# # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head) +# x = x.reshape(bs, heads, length, -1) +# return x + + +# class PerceiverAttention(nn.Module): +# def __init__(self, *, dim, dim_head=64, heads=8): +# super().__init__() +# self.scale = dim_head**-0.5 +# self.dim_head = dim_head +# self.heads = heads +# inner_dim = dim_head * heads + +# self.norm1 = nn.LayerNorm(dim) +# self.norm2 = nn.LayerNorm(dim) + +# self.to_q = nn.Linear(dim, inner_dim, bias=False) +# self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False) +# self.to_out = nn.Linear(inner_dim, dim, bias=False) + +# def forward(self, x, latents): +# """ +# Args: +# x (torch.Tensor): image features +# shape (b, n1, D) +# latent (torch.Tensor): latent features +# shape (b, n2, D) +# """ +# x = self.norm1(x) +# latents = self.norm2(latents) + +# b, l, _ = latents.shape + +# q = self.to_q(latents) +# kv_input = torch.cat((x, latents), dim=-2) +# k, v = self.to_kv(kv_input).chunk(2, dim=-1) + +# q = reshape_tensor(q, self.heads) +# k = reshape_tensor(k, self.heads) +# v = reshape_tensor(v, self.heads) + +# # attention +# scale = 1 / math.sqrt(math.sqrt(self.dim_head)) +# weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards +# weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype) +# out = weight @ v + +# out = out.permute(0, 2, 1, 3).reshape(b, l, -1) + +# return self.to_out(out) + + +# class Resampler(nn.Module): +# def __init__( +# self, +# dim=1024, +# depth=8, +# dim_head=64, +# heads=16, +# num_queries=8, +# embedding_dim=768, +# output_dim=1024, +# ff_mult=4, +# max_seq_len: int = 257, # CLIP tokens + CLS token +# apply_pos_emb: bool = False, +# num_latents_mean_pooled: int = 0, # number of latents derived from mean pooled representation of the sequence +# ): +# super().__init__() + +# self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5) + +# self.proj_in = nn.Linear(embedding_dim, dim) + +# self.proj_out = nn.Linear(dim, output_dim) +# self.norm_out = nn.LayerNorm(output_dim) + +# self.layers = nn.ModuleList([]) +# for _ in range(depth): +# self.layers.append( +# nn.ModuleList( +# [ +# PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads), +# FeedForward(dim=dim, mult=ff_mult), +# ] +# ) +# ) + +# def forward(self, x): + +# latents = self.latents.repeat(x.size(0), 1, 1) + +# x = self.proj_in(x) + + +# for attn, ff in self.layers: +# latents = attn(x, latents) + latents +# latents = ff(latents) + latents + +# latents = self.proj_out(latents) +# return self.norm_out(latents) + + +def zero_module(module): + for p in module.parameters(): + nn.init.zeros_(p) + return module + +@dataclass +class UNet2DConditionOutput(BaseOutput): + """ + The output of [`UNet2DConditionModel`]. + + Args: + sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): + The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model. + """ + + sample: torch.FloatTensor = None + + +class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin): + r""" + A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample + shaped output. + + This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented + for all models (such as downloading or saving). + + Parameters: + sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`): + Height and width of input/output sample. + in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample. + out_channels (`int`, *optional*, defaults to 4): Number of channels in the output. + center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample. + flip_sin_to_cos (`bool`, *optional*, defaults to `False`): + Whether to flip the sin to cos in the time embedding. + freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding. + down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`): + The tuple of downsample blocks to use. + mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`): + Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or + `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped. + up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`): + The tuple of upsample blocks to use. + only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`): + Whether to include self-attention in the basic transformer blocks, see + [`~models.attention.BasicTransformerBlock`]. + block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`): + The tuple of output channels for each block. + layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. + downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution. + mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use. + norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization. + If `None`, normalization and activation layers is skipped in post-processing. + norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization. + cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280): + The dimension of the cross attention features. + transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1): + The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for + [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`], + [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`]. + reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None): + The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling + blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for + [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`], + [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`]. + encoder_hid_dim (`int`, *optional*, defaults to None): + If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim` + dimension to `cross_attention_dim`. + encoder_hid_dim_type (`str`, *optional*, defaults to `None`): + If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text + embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`. + attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads. + num_attention_heads (`int`, *optional*): + The number of attention heads. If not defined, defaults to `attention_head_dim` + resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config + for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`. + class_embed_type (`str`, *optional*, defaults to `None`): + The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`, + `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`. + addition_embed_type (`str`, *optional*, defaults to `None`): + Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or + "text". "text" will use the `TextTimeEmbedding` layer. + addition_time_embed_dim: (`int`, *optional*, defaults to `None`): + Dimension for the timestep embeddings. + num_class_embeds (`int`, *optional*, defaults to `None`): + Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing + class conditioning with `class_embed_type` equal to `None`. + time_embedding_type (`str`, *optional*, defaults to `positional`): + The type of position embedding to use for timesteps. Choose from `positional` or `fourier`. + time_embedding_dim (`int`, *optional*, defaults to `None`): + An optional override for the dimension of the projected time embedding. + time_embedding_act_fn (`str`, *optional*, defaults to `None`): + Optional activation function to use only once on the time embeddings before they are passed to the rest of + the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`. + timestep_post_act (`str`, *optional*, defaults to `None`): + The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`. + time_cond_proj_dim (`int`, *optional*, defaults to `None`): + The dimension of `cond_proj` layer in the timestep embedding. + conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer. conv_out_kernel (`int`, + *optional*, default to `3`): The kernel size of `conv_out` layer. projection_class_embeddings_input_dim (`int`, + *optional*): The dimension of the `class_labels` input when + `class_embed_type="projection"`. Required when `class_embed_type="projection"`. + class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time + embeddings with the class embeddings. + mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`): + Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If + `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the + `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False` + otherwise. + """ + + _supports_gradient_checkpointing = True + + @register_to_config + def __init__( + self, + sample_size: Optional[int] = None, + in_channels: int = 4, + out_channels: int = 4, + center_input_sample: bool = False, + flip_sin_to_cos: bool = True, + freq_shift: int = 0, + down_block_types: Tuple[str] = ( + "CrossAttnDownBlock2D", + "CrossAttnDownBlock2D", + "CrossAttnDownBlock2D", + "DownBlock2D", + ), + mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn", + up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"), + only_cross_attention: Union[bool, Tuple[bool]] = False, + block_out_channels: Tuple[int] = (320, 640, 1280, 1280), + layers_per_block: Union[int, Tuple[int]] = 2, + downsample_padding: int = 1, + mid_block_scale_factor: float = 1, + dropout: float = 0.0, + act_fn: str = "silu", + norm_num_groups: Optional[int] = 32, + norm_eps: float = 1e-5, + cross_attention_dim: Union[int, Tuple[int]] = 1280, + transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1, + reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None, + encoder_hid_dim: Optional[int] = None, + encoder_hid_dim_type: Optional[str] = None, + attention_head_dim: Union[int, Tuple[int]] = 8, + num_attention_heads: Optional[Union[int, Tuple[int]]] = None, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + class_embed_type: Optional[str] = None, + addition_embed_type: Optional[str] = None, + addition_time_embed_dim: Optional[int] = None, + num_class_embeds: Optional[int] = None, + upcast_attention: bool = False, + resnet_time_scale_shift: str = "default", + resnet_skip_time_act: bool = False, + resnet_out_scale_factor: int = 1.0, + time_embedding_type: str = "positional", + time_embedding_dim: Optional[int] = None, + time_embedding_act_fn: Optional[str] = None, + timestep_post_act: Optional[str] = None, + time_cond_proj_dim: Optional[int] = None, + conv_in_kernel: int = 3, + conv_out_kernel: int = 3, + projection_class_embeddings_input_dim: Optional[int] = None, + attention_type: str = "default", + class_embeddings_concat: bool = False, + mid_block_only_cross_attention: Optional[bool] = None, + cross_attention_norm: Optional[str] = None, + addition_embed_type_num_heads=64, + ): + super().__init__() + + self.sample_size = sample_size + + if num_attention_heads is not None: + raise ValueError( + "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19." + ) + + # If `num_attention_heads` is not defined (which is the case for most models) + # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. + # The reason for this behavior is to correct for incorrectly named variables that were introduced + # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 + # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking + # which is why we correct for the naming here. + num_attention_heads = num_attention_heads or attention_head_dim + + # Check inputs + if len(down_block_types) != len(up_block_types): + raise ValueError( + f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}." + ) + + if len(block_out_channels) != len(down_block_types): + raise ValueError( + f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}." + ) + + if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types): + raise ValueError( + f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}." + ) + + if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types): + raise ValueError( + f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}." + ) + + if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types): + raise ValueError( + f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}." + ) + + if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types): + raise ValueError( + f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}." + ) + + if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types): + raise ValueError( + f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}." + ) + if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None: + for layer_number_per_block in transformer_layers_per_block: + if isinstance(layer_number_per_block, list): + raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.") + + # input + conv_in_padding = (conv_in_kernel - 1) // 2 + self.conv_in = nn.Conv2d( + in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding + ) + + # time + if time_embedding_type == "fourier": + time_embed_dim = time_embedding_dim or block_out_channels[0] * 2 + if time_embed_dim % 2 != 0: + raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.") + self.time_proj = GaussianFourierProjection( + time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos + ) + timestep_input_dim = time_embed_dim + elif time_embedding_type == "positional": + time_embed_dim = time_embedding_dim or block_out_channels[0] * 4 + + self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) + timestep_input_dim = block_out_channels[0] + else: + raise ValueError( + f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`." + ) + + self.time_embedding = TimestepEmbedding( + timestep_input_dim, + time_embed_dim, + act_fn=act_fn, + post_act_fn=timestep_post_act, + cond_proj_dim=time_cond_proj_dim, + ) + + if encoder_hid_dim_type is None and encoder_hid_dim is not None: + encoder_hid_dim_type = "text_proj" + self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type) + logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.") + + if encoder_hid_dim is None and encoder_hid_dim_type is not None: + raise ValueError( + f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}." + ) + + if encoder_hid_dim_type == "text_proj": + self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim) + elif encoder_hid_dim_type == "text_image_proj": + # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much + # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use + # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)` + self.encoder_hid_proj = TextImageProjection( + text_embed_dim=encoder_hid_dim, + image_embed_dim=cross_attention_dim, + cross_attention_dim=cross_attention_dim, + ) + elif encoder_hid_dim_type == "image_proj": + # Kandinsky 2.2 + self.encoder_hid_proj = ImageProjection( + image_embed_dim=encoder_hid_dim, + cross_attention_dim=cross_attention_dim, + ) + elif encoder_hid_dim_type == "ip_image_proj": + # Kandinsky 2.2 + self.encoder_hid_proj = Resampler( + dim=1280, + depth=4, + dim_head=64, + heads=20, + num_queries=16, + embedding_dim=encoder_hid_dim, + output_dim=self.config.cross_attention_dim, + ff_mult=4, + ) + + + elif encoder_hid_dim_type is not None: + raise ValueError( + f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'." + ) + else: + self.encoder_hid_proj = None + + # class embedding + if class_embed_type is None and num_class_embeds is not None: + self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) + elif class_embed_type == "timestep": + self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn) + elif class_embed_type == "identity": + self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) + elif class_embed_type == "projection": + if projection_class_embeddings_input_dim is None: + raise ValueError( + "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set" + ) + # The projection `class_embed_type` is the same as the timestep `class_embed_type` except + # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings + # 2. it projects from an arbitrary input dimension. + # + # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations. + # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings. + # As a result, `TimestepEmbedding` can be passed arbitrary vectors. + self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) + elif class_embed_type == "simple_projection": + if projection_class_embeddings_input_dim is None: + raise ValueError( + "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set" + ) + self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim) + else: + self.class_embedding = None + + if addition_embed_type == "text": + if encoder_hid_dim is not None: + text_time_embedding_from_dim = encoder_hid_dim + else: + text_time_embedding_from_dim = cross_attention_dim + + self.add_embedding = TextTimeEmbedding( + text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads + ) + elif addition_embed_type == "text_image": + # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much + # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use + # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)` + self.add_embedding = TextImageTimeEmbedding( + text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim + ) + elif addition_embed_type == "text_time": + self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift) + self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) + elif addition_embed_type == "image": + # Kandinsky 2.2 + self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) + elif addition_embed_type == "image_hint": + # Kandinsky 2.2 ControlNet + self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) + elif addition_embed_type is not None: + raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.") + + if time_embedding_act_fn is None: + self.time_embed_act = None + else: + self.time_embed_act = get_activation(time_embedding_act_fn) + + self.down_blocks = nn.ModuleList([]) + self.up_blocks = nn.ModuleList([]) + + if isinstance(only_cross_attention, bool): + if mid_block_only_cross_attention is None: + mid_block_only_cross_attention = only_cross_attention + + only_cross_attention = [only_cross_attention] * len(down_block_types) + + if mid_block_only_cross_attention is None: + mid_block_only_cross_attention = False + + if isinstance(num_attention_heads, int): + num_attention_heads = (num_attention_heads,) * len(down_block_types) + + if isinstance(attention_head_dim, int): + attention_head_dim = (attention_head_dim,) * len(down_block_types) + + if isinstance(cross_attention_dim, int): + cross_attention_dim = (cross_attention_dim,) * len(down_block_types) + + if isinstance(layers_per_block, int): + layers_per_block = [layers_per_block] * len(down_block_types) + + if isinstance(transformer_layers_per_block, int): + transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types) + if class_embeddings_concat: + # The time embeddings are concatenated with the class embeddings. The dimension of the + # time embeddings passed to the down, middle, and up blocks is twice the dimension of the + # regular time embeddings + blocks_time_embed_dim = time_embed_dim * 2 + else: + blocks_time_embed_dim = time_embed_dim + + # down + output_channel = block_out_channels[0] + for i, down_block_type in enumerate(down_block_types): + input_channel = output_channel + output_channel = block_out_channels[i] + is_final_block = i == len(block_out_channels) - 1 + + down_block = get_down_block( + down_block_type, + num_layers=layers_per_block[i], + transformer_layers_per_block=transformer_layers_per_block[i], + in_channels=input_channel, + out_channels=output_channel, + temb_channels=blocks_time_embed_dim, + add_downsample=not is_final_block, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + resnet_groups=norm_num_groups, + cross_attention_dim=cross_attention_dim[i], + num_attention_heads=num_attention_heads[i], + downsample_padding=downsample_padding, + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention[i], + upcast_attention=upcast_attention, + resnet_time_scale_shift=resnet_time_scale_shift, + attention_type=attention_type, + resnet_skip_time_act=resnet_skip_time_act, + resnet_out_scale_factor=resnet_out_scale_factor, + cross_attention_norm=cross_attention_norm, + attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel, + dropout=dropout, + ) + self.down_blocks.append(down_block) + + # mid + if mid_block_type == "UNetMidBlock2DCrossAttn": + self.mid_block = UNetMidBlock2DCrossAttn( + transformer_layers_per_block=transformer_layers_per_block[-1], + in_channels=block_out_channels[-1], + temb_channels=blocks_time_embed_dim, + dropout=dropout, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + output_scale_factor=mid_block_scale_factor, + resnet_time_scale_shift=resnet_time_scale_shift, + cross_attention_dim=cross_attention_dim[-1], + num_attention_heads=num_attention_heads[-1], + resnet_groups=norm_num_groups, + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + upcast_attention=upcast_attention, + attention_type=attention_type, + ) + elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn": + self.mid_block = UNetMidBlock2DSimpleCrossAttn( + in_channels=block_out_channels[-1], + temb_channels=blocks_time_embed_dim, + dropout=dropout, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + output_scale_factor=mid_block_scale_factor, + cross_attention_dim=cross_attention_dim[-1], + attention_head_dim=attention_head_dim[-1], + resnet_groups=norm_num_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + skip_time_act=resnet_skip_time_act, + only_cross_attention=mid_block_only_cross_attention, + cross_attention_norm=cross_attention_norm, + ) + elif mid_block_type == "UNetMidBlock2D": + self.mid_block = UNetMidBlock2D( + in_channels=block_out_channels[-1], + temb_channels=blocks_time_embed_dim, + dropout=dropout, + num_layers=0, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + output_scale_factor=mid_block_scale_factor, + resnet_groups=norm_num_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + add_attention=False, + ) + elif mid_block_type is None: + self.mid_block = None + else: + raise ValueError(f"unknown mid_block_type : {mid_block_type}") + + # count how many layers upsample the images + self.num_upsamplers = 0 + + # up + reversed_block_out_channels = list(reversed(block_out_channels)) + reversed_num_attention_heads = list(reversed(num_attention_heads)) + reversed_layers_per_block = list(reversed(layers_per_block)) + reversed_cross_attention_dim = list(reversed(cross_attention_dim)) + reversed_transformer_layers_per_block = ( + list(reversed(transformer_layers_per_block)) + if reverse_transformer_layers_per_block is None + else reverse_transformer_layers_per_block + ) + only_cross_attention = list(reversed(only_cross_attention)) + + output_channel = reversed_block_out_channels[0] + for i, up_block_type in enumerate(up_block_types): + is_final_block = i == len(block_out_channels) - 1 + + prev_output_channel = output_channel + output_channel = reversed_block_out_channels[i] + input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] + + # add upsample block for all BUT final layer + if not is_final_block: + add_upsample = True + self.num_upsamplers += 1 + else: + add_upsample = False + up_block = get_up_block( + up_block_type, + num_layers=reversed_layers_per_block[i] + 1, + transformer_layers_per_block=reversed_transformer_layers_per_block[i], + in_channels=input_channel, + out_channels=output_channel, + prev_output_channel=prev_output_channel, + temb_channels=blocks_time_embed_dim, + add_upsample=add_upsample, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + resolution_idx=i, + resnet_groups=norm_num_groups, + cross_attention_dim=reversed_cross_attention_dim[i], + num_attention_heads=reversed_num_attention_heads[i], + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention[i], + upcast_attention=upcast_attention, + resnet_time_scale_shift=resnet_time_scale_shift, + attention_type=attention_type, + resnet_skip_time_act=resnet_skip_time_act, + resnet_out_scale_factor=resnet_out_scale_factor, + cross_attention_norm=cross_attention_norm, + attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel, + dropout=dropout, + ) + + self.up_blocks.append(up_block) + prev_output_channel = output_channel + + + + + # out + if norm_num_groups is not None: + self.conv_norm_out = nn.GroupNorm( + num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps + ) + + self.conv_act = get_activation(act_fn) + + else: + self.conv_norm_out = None + self.conv_act = None + + conv_out_padding = (conv_out_kernel - 1) // 2 + self.conv_out = nn.Conv2d( + block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding + ) + + if attention_type in ["gated", "gated-text-image"]: + positive_len = 768 + if isinstance(cross_attention_dim, int): + positive_len = cross_attention_dim + elif isinstance(cross_attention_dim, tuple) or isinstance(cross_attention_dim, list): + positive_len = cross_attention_dim[0] + + feature_type = "text-only" if attention_type == "gated" else "text-image" + self.position_net = PositionNet( + positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type + ) + + + + from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor, AttnProcessor2_0 as AttnProcessor + + attn_procs = {} + for name in self.attn_processors.keys(): + cross_attention_dim = None if name.endswith("attn1.processor") else self.config.cross_attention_dim + if name.startswith("mid_block"): + hidden_size = self.config.block_out_channels[-1] + elif name.startswith("up_blocks"): + block_id = int(name[len("up_blocks.")]) + hidden_size = list(reversed(self.config.block_out_channels))[block_id] + elif name.startswith("down_blocks"): + block_id = int(name[len("down_blocks.")]) + hidden_size = self.config.block_out_channels[block_id] + if cross_attention_dim is None: + attn_procs[name] = AttnProcessor() + else: + layer_name = name.split(".processor")[0] + attn_procs[name] = IPAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, num_tokens=16) + self.set_attn_processor(attn_procs) + + + @property + def attn_processors(self) -> Dict[str, AttentionProcessor]: + r""" + Returns: + `dict` of attention processors: A dictionary containing all attention processors used in the model with + indexed by its weight name. + """ + # set recursively + processors = {} + + def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]): + if hasattr(module, "get_processor"): + processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True) + + for sub_name, child in module.named_children(): + fn_recursive_add_processors(f"{name}.{sub_name}", child, processors) + + return processors + + for name, module in self.named_children(): + fn_recursive_add_processors(name, module, processors) + + return processors + + def set_attn_processor( + self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False + ): + r""" + Sets the attention processor to use to compute attention. + + Parameters: + processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`): + The instantiated processor class or a dictionary of processor classes that will be set as the processor + for **all** `Attention` layers. + + If `processor` is a dict, the key needs to define the path to the corresponding cross attention + processor. This is strongly recommended when setting trainable attention processors. + + """ + count = len(self.attn_processors.keys()) + + if isinstance(processor, dict) and len(processor) != count: + raise ValueError( + f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" + f" number of attention layers: {count}. Please make sure to pass {count} processor classes." + ) + + def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor): + if hasattr(module, "set_processor"): + if not isinstance(processor, dict): + module.set_processor(processor) + else: + module.set_processor(processor.pop(f"{name}.processor")) + + for sub_name, child in module.named_children(): + fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor) + + for name, module in self.named_children(): + fn_recursive_attn_processor(name, module, processor) + + def set_default_attn_processor(self): + """ + Disables custom attention processors and sets the default attention implementation. + """ + if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()): + processor = AttnAddedKVProcessor() + elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()): + processor = AttnProcessor() + else: + raise ValueError( + f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}" + ) + + self.set_attn_processor(processor, _remove_lora=True) + + def set_attention_slice(self, slice_size): + r""" + Enable sliced attention computation. + + When this option is enabled, the attention module splits the input tensor in slices to compute attention in + several steps. This is useful for saving some memory in exchange for a small decrease in speed. + + Args: + slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): + When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If + `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is + provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim` + must be a multiple of `slice_size`. + """ + sliceable_head_dims = [] + + def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module): + if hasattr(module, "set_attention_slice"): + sliceable_head_dims.append(module.sliceable_head_dim) + + for child in module.children(): + fn_recursive_retrieve_sliceable_dims(child) + + # retrieve number of attention layers + for module in self.children(): + fn_recursive_retrieve_sliceable_dims(module) + + num_sliceable_layers = len(sliceable_head_dims) + + if slice_size == "auto": + # half the attention head size is usually a good trade-off between + # speed and memory + slice_size = [dim // 2 for dim in sliceable_head_dims] + elif slice_size == "max": + # make smallest slice possible + slice_size = num_sliceable_layers * [1] + + slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size + + if len(slice_size) != len(sliceable_head_dims): + raise ValueError( + f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different" + f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}." + ) + + for i in range(len(slice_size)): + size = slice_size[i] + dim = sliceable_head_dims[i] + if size is not None and size > dim: + raise ValueError(f"size {size} has to be smaller or equal to {dim}.") + + # Recursively walk through all the children. + # Any children which exposes the set_attention_slice method + # gets the message + def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]): + if hasattr(module, "set_attention_slice"): + module.set_attention_slice(slice_size.pop()) + + for child in module.children(): + fn_recursive_set_attention_slice(child, slice_size) + + reversed_slice_size = list(reversed(slice_size)) + for module in self.children(): + fn_recursive_set_attention_slice(module, reversed_slice_size) + + def _set_gradient_checkpointing(self, module, value=False): + if hasattr(module, "gradient_checkpointing"): + module.gradient_checkpointing = value + + def enable_freeu(self, s1, s2, b1, b2): + r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497. + + The suffixes after the scaling factors represent the stage blocks where they are being applied. + + Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that + are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL. + + Args: + s1 (`float`): + Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to + mitigate the "oversmoothing effect" in the enhanced denoising process. + s2 (`float`): + Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to + mitigate the "oversmoothing effect" in the enhanced denoising process. + b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features. + b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features. + """ + for i, upsample_block in enumerate(self.up_blocks): + setattr(upsample_block, "s1", s1) + setattr(upsample_block, "s2", s2) + setattr(upsample_block, "b1", b1) + setattr(upsample_block, "b2", b2) + + def disable_freeu(self): + """Disables the FreeU mechanism.""" + freeu_keys = {"s1", "s2", "b1", "b2"} + for i, upsample_block in enumerate(self.up_blocks): + for k in freeu_keys: + if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None: + setattr(upsample_block, k, None) + + def fuse_qkv_projections(self): + """ + Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, + key, value) are fused. For cross-attention modules, key and value projection matrices are fused. + + + + This API is 🧪 experimental. + + + """ + self.original_attn_processors = None + + for _, attn_processor in self.attn_processors.items(): + if "Added" in str(attn_processor.__class__.__name__): + raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.") + + self.original_attn_processors = self.attn_processors + + for module in self.modules(): + if isinstance(module, Attention): + module.fuse_projections(fuse=True) + + def unfuse_qkv_projections(self): + """Disables the fused QKV projection if enabled. + + + + This API is 🧪 experimental. + + + + """ + if self.original_attn_processors is not None: + self.set_attn_processor(self.original_attn_processors) + + def forward( + self, + sample: torch.FloatTensor, + timestep: Union[torch.Tensor, float, int], + encoder_hidden_states: torch.Tensor, + class_labels: Optional[torch.Tensor] = None, + timestep_cond: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None, + down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None, + mid_block_additional_residual: Optional[torch.Tensor] = None, + down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None, + encoder_attention_mask: Optional[torch.Tensor] = None, + return_dict: bool = True, + garment_features: Optional[Tuple[torch.Tensor]] = None, + ) -> Union[UNet2DConditionOutput, Tuple]: + r""" + The [`UNet2DConditionModel`] forward method. + + Args: + sample (`torch.FloatTensor`): + The noisy input tensor with the following shape `(batch, channel, height, width)`. + timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input. + encoder_hidden_states (`torch.FloatTensor`): + The encoder hidden states with shape `(batch, sequence_length, feature_dim)`. + class_labels (`torch.Tensor`, *optional*, defaults to `None`): + Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings. + timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`): + Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed + through the `self.time_embedding` layer to obtain the timestep embeddings. + attention_mask (`torch.Tensor`, *optional*, defaults to `None`): + An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask + is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large + negative values to the attention scores corresponding to "discard" tokens. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + added_cond_kwargs: (`dict`, *optional*): + A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that + are passed along to the UNet blocks. + down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*): + A tuple of tensors that if specified are added to the residuals of down unet blocks. + mid_block_additional_residual: (`torch.Tensor`, *optional*): + A tensor that if specified is added to the residual of the middle unet block. + encoder_attention_mask (`torch.Tensor`): + A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If + `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias, + which adds large negative values to the attention scores corresponding to "discard" tokens. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain + tuple. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the [`AttnProcessor`]. + added_cond_kwargs: (`dict`, *optional*): + A kwargs dictionary containin additional embeddings that if specified are added to the embeddings that + are passed along to the UNet blocks. + down_block_additional_residuals (`tuple` of `torch.Tensor`, *optional*): + additional residuals to be added to UNet long skip connections from down blocks to up blocks for + example from ControlNet side model(s) + mid_block_additional_residual (`torch.Tensor`, *optional*): + additional residual to be added to UNet mid block output, for example from ControlNet side model + down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*): + additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s) + + Returns: + [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`: + If `return_dict` is True, an [`~models.unet_2d_condition.UNet2DConditionOutput`] is returned, otherwise + a `tuple` is returned where the first element is the sample tensor. + """ + # By default samples have to be AT least a multiple of the overall upsampling factor. + # The overall upsampling factor is equal to 2 ** (# num of upsampling layers). + # However, the upsampling interpolation output size can be forced to fit any upsampling size + # on the fly if necessary. + default_overall_up_factor = 2**self.num_upsamplers + + # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor` + forward_upsample_size = False + upsample_size = None + + for dim in sample.shape[-2:]: + if dim % default_overall_up_factor != 0: + # Forward upsample size to force interpolation output size. + forward_upsample_size = True + break + # ensure attention_mask is a bias, and give it a singleton query_tokens dimension + # expects mask of shape: + # [batch, key_tokens] + # adds singleton query_tokens dimension: + # [batch, 1, key_tokens] + # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes: + # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn) + # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn) + if attention_mask is not None: + # assume that mask is expressed as: + # (1 = keep, 0 = discard) + # convert mask into a bias that can be added to attention scores: + # (keep = +0, discard = -10000.0) + attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0 + attention_mask = attention_mask.unsqueeze(1) + + # convert encoder_attention_mask to a bias the same way we do for attention_mask + if encoder_attention_mask is not None: + encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0 + encoder_attention_mask = encoder_attention_mask.unsqueeze(1) + + # 0. center input if necessary + if self.config.center_input_sample: + sample = 2 * sample - 1.0 + + # 1. time + timesteps = timestep + if not torch.is_tensor(timesteps): + # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can + # This would be a good case for the `match` statement (Python 3.10+) + is_mps = sample.device.type == "mps" + if isinstance(timestep, float): + dtype = torch.float32 if is_mps else torch.float64 + else: + dtype = torch.int32 if is_mps else torch.int64 + timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device) + elif len(timesteps.shape) == 0: + timesteps = timesteps[None].to(sample.device) + + # broadcast to batch dimension in a way that's compatible with ONNX/Core ML + timesteps = timesteps.expand(sample.shape[0]) + + t_emb = self.time_proj(timesteps) + + # `Timesteps` does not contain any weights and will always return f32 tensors + # but time_embedding might actually be running in fp16. so we need to cast here. + # there might be better ways to encapsulate this. + t_emb = t_emb.to(dtype=sample.dtype) + + emb = self.time_embedding(t_emb, timestep_cond) + aug_emb = None + + if self.class_embedding is not None: + if class_labels is None: + raise ValueError("class_labels should be provided when num_class_embeds > 0") + + if self.config.class_embed_type == "timestep": + class_labels = self.time_proj(class_labels) + + # `Timesteps` does not contain any weights and will always return f32 tensors + # there might be better ways to encapsulate this. + class_labels = class_labels.to(dtype=sample.dtype) + + class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype) + + if self.config.class_embeddings_concat: + emb = torch.cat([emb, class_emb], dim=-1) + else: + emb = emb + class_emb + + if self.config.addition_embed_type == "text": + aug_emb = self.add_embedding(encoder_hidden_states) + elif self.config.addition_embed_type == "text_image": + # Kandinsky 2.1 - style + if "image_embeds" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `addition_embed_type` set to 'text_image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`" + ) + + image_embs = added_cond_kwargs.get("image_embeds") + text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states) + aug_emb = self.add_embedding(text_embs, image_embs) + elif self.config.addition_embed_type == "text_time": + # SDXL - style + if "text_embeds" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`" + ) + text_embeds = added_cond_kwargs.get("text_embeds") + if "time_ids" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`" + ) + time_ids = added_cond_kwargs.get("time_ids") + time_embeds = self.add_time_proj(time_ids.flatten()) + time_embeds = time_embeds.reshape((text_embeds.shape[0], -1)) + add_embeds = torch.concat([text_embeds, time_embeds], dim=-1) + add_embeds = add_embeds.to(emb.dtype) + aug_emb = self.add_embedding(add_embeds) + elif self.config.addition_embed_type == "image": + # Kandinsky 2.2 - style + if "image_embeds" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `addition_embed_type` set to 'image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`" + ) + image_embs = added_cond_kwargs.get("image_embeds") + aug_emb = self.add_embedding(image_embs) + elif self.config.addition_embed_type == "image_hint": + # Kandinsky 2.2 - style + if "image_embeds" not in added_cond_kwargs or "hint" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `addition_embed_type` set to 'image_hint' which requires the keyword arguments `image_embeds` and `hint` to be passed in `added_cond_kwargs`" + ) + image_embs = added_cond_kwargs.get("image_embeds") + hint = added_cond_kwargs.get("hint") + aug_emb, hint = self.add_embedding(image_embs, hint) + sample = torch.cat([sample, hint], dim=1) + + emb = emb + aug_emb if aug_emb is not None else emb + + if self.time_embed_act is not None: + emb = self.time_embed_act(emb) + + if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj": + encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states) + elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj": + # Kadinsky 2.1 - style + if "image_embeds" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'text_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`" + ) + + image_embeds = added_cond_kwargs.get("image_embeds") + encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds) + elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj": + # Kandinsky 2.2 - style + if "image_embeds" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`" + ) + image_embeds = added_cond_kwargs.get("image_embeds") + encoder_hidden_states = self.encoder_hid_proj(image_embeds) + elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj": + if "image_embeds" not in added_cond_kwargs: + raise ValueError( + f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'ip_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`" + ) + image_embeds = added_cond_kwargs.get("image_embeds") + # print(image_embeds.shape) + # image_embeds = self.encoder_hid_proj(image_embeds).to(encoder_hidden_states.dtype) + encoder_hidden_states = torch.cat([encoder_hidden_states, image_embeds], dim=1) + + # 2. pre-process + sample = self.conv_in(sample) + + # 2.5 GLIGEN position net + if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None: + cross_attention_kwargs = cross_attention_kwargs.copy() + gligen_args = cross_attention_kwargs.pop("gligen") + cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)} + + + curr_garment_feat_idx = 0 + + + # 3. down + lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 + if USE_PEFT_BACKEND: + # weight the lora layers by setting `lora_scale` for each PEFT layer + scale_lora_layers(self, lora_scale) + + is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None + # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets + is_adapter = down_intrablock_additional_residuals is not None + # maintain backward compatibility for legacy usage, where + # T2I-Adapter and ControlNet both use down_block_additional_residuals arg + # but can only use one or the other + if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None: + deprecate( + "T2I should not use down_block_additional_residuals", + "1.3.0", + "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \ + and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \ + for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ", + standard_warn=False, + ) + down_intrablock_additional_residuals = down_block_additional_residuals + is_adapter = True + + down_block_res_samples = (sample,) + for downsample_block in self.down_blocks: + if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention: + # For t2i-adapter CrossAttnDownBlock2D + additional_residuals = {} + if is_adapter and len(down_intrablock_additional_residuals) > 0: + additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0) + + sample, res_samples,curr_garment_feat_idx = downsample_block( + hidden_states=sample, + temb=emb, + encoder_hidden_states=encoder_hidden_states, + attention_mask=attention_mask, + cross_attention_kwargs=cross_attention_kwargs, + encoder_attention_mask=encoder_attention_mask, + garment_features=garment_features, + curr_garment_feat_idx=curr_garment_feat_idx, + **additional_residuals, + ) + else: + sample, res_samples = downsample_block(hidden_states=sample, temb=emb, scale=lora_scale) + if is_adapter and len(down_intrablock_additional_residuals) > 0: + sample += down_intrablock_additional_residuals.pop(0) + + down_block_res_samples += res_samples + + + if is_controlnet: + new_down_block_res_samples = () + + for down_block_res_sample, down_block_additional_residual in zip( + down_block_res_samples, down_block_additional_residuals + ): + down_block_res_sample = down_block_res_sample + down_block_additional_residual + new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,) + + down_block_res_samples = new_down_block_res_samples + + # 4. mid + if self.mid_block is not None: + if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention: + sample ,curr_garment_feat_idx= self.mid_block( + sample, + emb, + encoder_hidden_states=encoder_hidden_states, + attention_mask=attention_mask, + cross_attention_kwargs=cross_attention_kwargs, + encoder_attention_mask=encoder_attention_mask, + garment_features=garment_features, + curr_garment_feat_idx=curr_garment_feat_idx, + ) + else: + sample = self.mid_block(sample, emb) + + # To support T2I-Adapter-XL + if ( + is_adapter + and len(down_intrablock_additional_residuals) > 0 + and sample.shape == down_intrablock_additional_residuals[0].shape + ): + sample += down_intrablock_additional_residuals.pop(0) + + if is_controlnet: + sample = sample + mid_block_additional_residual + + + + # 5. up + for i, upsample_block in enumerate(self.up_blocks): + is_final_block = i == len(self.up_blocks) - 1 + + res_samples = down_block_res_samples[-len(upsample_block.resnets) :] + down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)] + + # if we have not reached the final block and need to forward the + # upsample size, we do it here + if not is_final_block and forward_upsample_size: + upsample_size = down_block_res_samples[-1].shape[2:] + + if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention: + sample ,curr_garment_feat_idx= upsample_block( + hidden_states=sample, + temb=emb, + res_hidden_states_tuple=res_samples, + encoder_hidden_states=encoder_hidden_states, + cross_attention_kwargs=cross_attention_kwargs, + upsample_size=upsample_size, + attention_mask=attention_mask, + encoder_attention_mask=encoder_attention_mask, + garment_features=garment_features, + curr_garment_feat_idx=curr_garment_feat_idx, + ) + + else: + sample = upsample_block( + hidden_states=sample, + temb=emb, + res_hidden_states_tuple=res_samples, + upsample_size=upsample_size, + scale=lora_scale, + ) + # 6. post-process + if self.conv_norm_out: + sample = self.conv_norm_out(sample) + sample = self.conv_act(sample) + sample = self.conv_out(sample) + + if USE_PEFT_BACKEND: + # remove `lora_scale` from each PEFT layer + unscale_lora_layers(self, lora_scale) + + if not return_dict: + return (sample,) + + return UNet2DConditionOutput(sample=sample) diff --git a/extensions-builtin/forge_space_illusion_diffusion/forge_app.py b/extensions-builtin/forge_space_illusion_diffusion/forge_app.py new file mode 100644 index 0000000000000000000000000000000000000000..2804d29cda89351244b307b0a12d3cedeb205fec --- /dev/null +++ b/extensions-builtin/forge_space_illusion_diffusion/forge_app.py @@ -0,0 +1,305 @@ +import spaces +import torch +import gradio as gr +from gradio import processing_utils, utils +from PIL import Image +import random + +from diffusers import ( + DiffusionPipeline, + AutoencoderKL, + StableDiffusionControlNetPipeline, + ControlNetModel, + StableDiffusionLatentUpscalePipeline, + StableDiffusionImg2ImgPipeline, + StableDiffusionControlNetImg2ImgPipeline, + DPMSolverMultistepScheduler, + EulerDiscreteScheduler +) +import tempfile +import time +from share_btn import community_icon_html, loading_icon_html, share_js +import user_history +from illusion_style import css +import os +from transformers import CLIPImageProcessor +from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker + +BASE_MODEL = "SG161222/Realistic_Vision_V5.1_noVAE" + + +with spaces.capture_gpu_object() as gpu_object: + # Initialize both pipelines + vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=torch.float16) + controlnet = ControlNetModel.from_pretrained("monster-labs/control_v1p_sd15_qrcode_monster", torch_dtype=torch.float16) + + # Initialize the safety checker conditionally + SAFETY_CHECKER_ENABLED = os.environ.get("SAFETY_CHECKER", "0") == "1" + safety_checker = None + feature_extractor = None + if SAFETY_CHECKER_ENABLED: + safety_checker = StableDiffusionSafetyChecker.from_pretrained("CompVis/stable-diffusion-safety-checker").to("cuda") + feature_extractor = CLIPImageProcessor.from_pretrained("openai/clip-vit-base-patch32") + + main_pipe = StableDiffusionControlNetPipeline.from_pretrained( + BASE_MODEL, + controlnet=controlnet, + vae=vae, + safety_checker=safety_checker, + feature_extractor=feature_extractor, + torch_dtype=torch.float16, + ) + +cn_and_unet = torch.nn.ModuleList([main_pipe.unet, main_pipe.controlnet]) + +spaces.automatically_move_to_gpu_when_forward(main_pipe.unet, target_model=cn_and_unet) +spaces.automatically_move_to_gpu_when_forward(main_pipe.controlnet, target_model=cn_and_unet) +spaces.automatically_move_to_gpu_when_forward(main_pipe.vae) +spaces.automatically_move_to_gpu_when_forward(main_pipe.text_encoder) +spaces.change_attention_from_diffusers_to_forge(main_pipe.unet) +spaces.change_attention_from_diffusers_to_forge(main_pipe.vae) + +# Function to check NSFW images +# def check_nsfw_images(images: list[Image.Image]) -> tuple[list[Image.Image], list[bool]]: +# if SAFETY_CHECKER_ENABLED: +# safety_checker_input = feature_extractor(images, return_tensors="pt").to("cuda") +# has_nsfw_concepts = safety_checker( +# images=[images], +# clip_input=safety_checker_input.pixel_values.to("cuda") +# ) +# return images, has_nsfw_concepts +# else: +# return images, [False] * len(images) + +# main_pipe.unet = torch.compile(main_pipe.unet, mode="reduce-overhead", fullgraph=True) +# main_pipe.unet.to(memory_format=torch.channels_last) +# main_pipe.unet = torch.compile(main_pipe.unet, mode="reduce-overhead", fullgraph=True) +# model_id = "stabilityai/sd-x2-latent-upscaler" +image_pipe = StableDiffusionControlNetImg2ImgPipeline(**main_pipe.components) + +# image_pipe.unet = torch.compile(image_pipe.unet, mode="reduce-overhead", fullgraph=True) +# upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16) +# upscaler.to("cuda") + + +# Sampler map +SAMPLER_MAP = { + "DPM++ Karras SDE": lambda config: DPMSolverMultistepScheduler.from_config(config, use_karras=True, algorithm_type="sde-dpmsolver++"), + "Euler": lambda config: EulerDiscreteScheduler.from_config(config), +} + + +def center_crop_resize(img, output_size=(512, 512)): + width, height = img.size + + # Calculate dimensions to crop to the center + new_dimension = min(width, height) + left = (width - new_dimension) / 2 + top = (height - new_dimension) / 2 + right = (width + new_dimension) / 2 + bottom = (height + new_dimension) / 2 + + # Crop and resize + img = img.crop((left, top, right, bottom)) + img = img.resize(output_size) + + return img + + +def common_upscale(samples, width, height, upscale_method, crop=False): + if crop == "center": + old_width = samples.shape[3] + old_height = samples.shape[2] + old_aspect = old_width / old_height + new_aspect = width / height + x = 0 + y = 0 + if old_aspect > new_aspect: + x = round((old_width - old_width * (new_aspect / old_aspect)) / 2) + elif old_aspect < new_aspect: + y = round((old_height - old_height * (old_aspect / new_aspect)) / 2) + s = samples[:, :, y:old_height - y, x:old_width - x] + else: + s = samples + + return torch.nn.functional.interpolate(s, size=(height, width), mode=upscale_method) + + +def upscale(samples, upscale_method, scale_by): + # s = samples.copy() + width = round(samples["images"].shape[3] * scale_by) + height = round(samples["images"].shape[2] * scale_by) + s = common_upscale(samples["images"], width, height, upscale_method, "disabled") + return (s) + + +def check_inputs(prompt: str, control_image: Image.Image): + if control_image is None: + raise gr.Error("Please select or upload an Input Illusion") + if prompt is None or prompt == "": + raise gr.Error("Prompt is required") + + +def convert_to_pil(base64_image): + pil_image = Image.open(base64_image) + return pil_image + + +def convert_to_base64(pil_image): + with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as temp_file: + image.save(temp_file.name) + return temp_file.name + + +# Inference function +@spaces.GPU(gpu_objects=[gpu_object], manual_load=True) +def inference( + control_image: Image.Image, + prompt: str, + negative_prompt: str, + guidance_scale: float = 8.0, + controlnet_conditioning_scale: float = 1, + control_guidance_start: float = 1, + control_guidance_end: float = 1, + upscaler_strength: float = 0.5, + seed: int = -1, + sampler="DPM++ Karras SDE", + progress=gr.Progress(track_tqdm=True), + profile=None, +): + start_time = time.time() + start_time_struct = time.localtime(start_time) + start_time_formatted = time.strftime("%H:%M:%S", start_time_struct) + print(f"Inference started at {start_time_formatted}") + + # Generate the initial image + # init_image = init_pipe(prompt).images[0] + + # Rest of your existing code + control_image_small = center_crop_resize(control_image) + control_image_large = center_crop_resize(control_image, (1024, 1024)) + + main_pipe.scheduler = SAMPLER_MAP[sampler](main_pipe.scheduler.config) + my_seed = random.randint(0, 2 ** 32 - 1) if seed == -1 else seed + generator = torch.Generator(device="cuda").manual_seed(my_seed) + + out = main_pipe( + prompt=prompt, + negative_prompt=negative_prompt, + image=control_image_small, + guidance_scale=float(guidance_scale), + controlnet_conditioning_scale=float(controlnet_conditioning_scale), + generator=generator, + control_guidance_start=float(control_guidance_start), + control_guidance_end=float(control_guidance_end), + num_inference_steps=15, + output_type="latent" + ) + upscaled_latents = upscale(out, "nearest-exact", 2) + out_image = image_pipe( + prompt=prompt, + negative_prompt=negative_prompt, + control_image=control_image_large, + image=upscaled_latents, + guidance_scale=float(guidance_scale), + generator=generator, + num_inference_steps=20, + strength=upscaler_strength, + control_guidance_start=float(control_guidance_start), + control_guidance_end=float(control_guidance_end), + controlnet_conditioning_scale=float(controlnet_conditioning_scale) + ) + end_time = time.time() + end_time_struct = time.localtime(end_time) + end_time_formatted = time.strftime("%H:%M:%S", end_time_struct) + print(f"Inference ended at {end_time_formatted}, taking {end_time - start_time}s") + + # Save image + metadata + user_history.save_image( + label=prompt, + image=out_image["images"][0], + profile=profile, + metadata={ + "prompt": prompt, + "negative_prompt": negative_prompt, + "guidance_scale": guidance_scale, + "controlnet_conditioning_scale": controlnet_conditioning_scale, + "control_guidance_start": control_guidance_start, + "control_guidance_end": control_guidance_end, + "upscaler_strength": upscaler_strength, + "seed": seed, + "sampler": sampler, + }, + ) + + return out_image["images"][0], gr.update(visible=True), gr.update(visible=True), my_seed + + +with gr.Blocks() as app: + gr.Markdown( + ''' +
+

Illusion Diffusion HQ 🌀

+

Generate stunning high quality illusion artwork with Stable Diffusion

+

Illusion Diffusion is back up with a safety checker! Because I have been asked, if you would like to support me, consider using deforum.studio

+

A space by AP Follow me on Twitter with big contributions from multimodalart

+

This project works by using Monster Labs QR Control Net. Given a prompt and your pattern, we use a QR code conditioned controlnet to create a stunning illusion! Credit to: MrUgleh for discovering the workflow :)

+
+ ''' + ) + + state_img_input = gr.State() + state_img_output = gr.State() + with gr.Row(): + with gr.Column(): + control_image = gr.Image(label="Input Illusion", type="pil", elem_id="control_image") + controlnet_conditioning_scale = gr.Slider(minimum=0.0, maximum=5.0, step=0.01, value=0.8, label="Illusion strength", elem_id="illusion_strength", info="ControlNet conditioning scale") + examples = ["checkers.png", "checkers_mid.jpg", "pattern.png", "ultra_checkers.png", "spiral.jpeg", "funky.jpeg"] + examples = [spaces.convert_root_path() + y for y in examples] + gr.Examples(examples=examples, inputs=control_image) + prompt = gr.Textbox(label="Prompt", elem_id="prompt", info="Type what you want to generate", placeholder="Medieval village scene with busy streets and castle in the distance") + negative_prompt = gr.Textbox(label="Negative Prompt", info="Type what you don't want to see", value="low quality", elem_id="negative_prompt") + with gr.Accordion(label="Advanced Options", open=False): + guidance_scale = gr.Slider(minimum=0.0, maximum=50.0, step=0.25, value=7.5, label="Guidance Scale") + sampler = gr.Dropdown(choices=list(SAMPLER_MAP.keys()), value="Euler") + control_start = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0, label="Start of ControlNet") + control_end = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=1, label="End of ControlNet") + strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=1, label="Strength of the upscaler") + seed = gr.Slider(minimum=-1, maximum=9999999999, step=1, value=-1, label="Seed", info="-1 means random seed") + used_seed = gr.Number(label="Last seed used", interactive=False) + run_btn = gr.Button("Run") + with gr.Column(): + result_image = gr.Image(label="Illusion Diffusion Output", interactive=False, elem_id="output") + with gr.Group(elem_id="share-btn-container", visible=False) as share_group: + community_icon = gr.HTML(community_icon_html) + loading_icon = gr.HTML(loading_icon_html) + share_button = gr.Button("Share to community", elem_id="share-btn") + + prompt.submit( + check_inputs, + inputs=[prompt, control_image], + queue=False + ).success( + inference, + inputs=[control_image, prompt, negative_prompt, guidance_scale, controlnet_conditioning_scale, control_start, control_end, strength, seed, sampler], + outputs=[result_image, result_image, share_group, used_seed]) + + run_btn.click( + check_inputs, + inputs=[prompt, control_image], + queue=False + ).success( + inference, + inputs=[control_image, prompt, negative_prompt, guidance_scale, controlnet_conditioning_scale, control_start, control_end, strength, seed, sampler], + outputs=[result_image, result_image, share_group, used_seed]) + + share_button.click(None, [], [], js=share_js) + +with gr.Blocks(css=css) as demo: + with gr.Tab("Demo"): + app.render() + with gr.Tab("Past generations"): + user_history.render() + +if __name__ == "__main__": + demo.launch() diff --git a/extensions-builtin/forge_space_illusion_diffusion/space_meta.json b/extensions-builtin/forge_space_illusion_diffusion/space_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..ce85768aaad4ec4c544aa170fd51e1a68b549d18 --- /dev/null +++ b/extensions-builtin/forge_space_illusion_diffusion/space_meta.json @@ -0,0 +1,6 @@ +{ + "tag": "General Image Processing and Applications", + "title": "IllusionDiffusion (Monster Labs QR Control Net)", + "repo_id": "AP123/IllusionDiffusion", + "revision": "7a874d15dccd7b8c6c30d3440f07ddedb54ec454" +} diff --git a/extensions-builtin/forge_space_sapiens_normal/forge_app.py b/extensions-builtin/forge_space_sapiens_normal/forge_app.py new file mode 100644 index 0000000000000000000000000000000000000000..1cf541aa80d78180b060ec40d94247341aefee35 --- /dev/null +++ b/extensions-builtin/forge_space_sapiens_normal/forge_app.py @@ -0,0 +1,142 @@ +import os +import cv2 +import gradio as gr +import numpy as np +import spaces +import torch +import torch.nn.functional as F +from gradio.themes.utils import sizes +from PIL import Image +from torchvision import transforms + + +# if torch.cuda.is_available() and torch.cuda.get_device_properties(0).major >= 8: +# torch.backends.cuda.matmul.allow_tf32 = True +# torch.backends.cudnn.allow_tf32 = True + +ASSETS_DIR = os.path.join(spaces.convert_root_path(), 'assets') +CHECKPOINTS_DIR = os.path.join(ASSETS_DIR, "checkpoints") +CHECKPOINTS = { + "0.3b": "sapiens_0.3b_normal_render_people_epoch_66_torchscript.pt2", + "0.6b": "sapiens_0.6b_normal_render_people_epoch_200_torchscript.pt2", + "1b": "sapiens_1b_normal_render_people_epoch_115_torchscript.pt2", + "2b": "sapiens_2b_normal_render_people_epoch_70_torchscript.pt2", +} +SEG_CHECKPOINT = 'sapiens_1b_goliath_best_goliath_mIoU_7994_epoch_151_torchscript.pt2' + +GO = spaces.capture_gpu_object() + + +def load_model(checkpoint_name: str): + with GO: + remote_url = 'https://huggingface.co/spaces/facebook/sapiens_normal/resolve/main/assets/checkpoints/' + checkpoint_name + checkpoint_path = os.path.join(CHECKPOINTS_DIR, checkpoint_name) + spaces.download_single_file(remote_url, model_dir=CHECKPOINTS_DIR, file_name=checkpoint_name) + model = torch.jit.load(checkpoint_path) + model.eval() + spaces.automatically_move_to_gpu_when_forward(model) + # model.to("cuda") + return model + + +# MODELS = {name: load_model(CHECKPOINTS[name]) for name in CHECKPOINTS.keys()} +MODELS = {name: None for name in CHECKPOINTS.keys()} +SEG_MODEL = load_model(SEG_CHECKPOINT) + + +@torch.inference_mode() +def run_model(model, input_tensor, height, width): + output = model(input_tensor) + output = F.interpolate(output, size=(height, width), mode="bilinear", align_corners=False) + return output + + +transform_fn = transforms.Compose([ + transforms.Resize((1024, 768)), + transforms.ToTensor(), + transforms.Normalize(mean=[123.5 / 255, 116.5 / 255, 103.5 / 255], std=[58.5 / 255, 57.0 / 255, 57.5 / 255]), +]) + + +@spaces.GPU(gpu_objects=GO, manual_load=True) +def process_image(image: Image.Image, model_name: str) -> Image.Image: + input_tensor = transform_fn(image).unsqueeze(0).to("cuda") + + # Run segmentation + seg_output = run_model(SEG_MODEL, input_tensor, image.height, image.width) + seg_mask = (seg_output.argmax(dim=1) > 0).float().cpu().numpy()[0] + + # Run normal estimation + + if MODELS[model_name] is None: + MODELS[model_name] = load_model(CHECKPOINTS[model_name]) + + normal_model = MODELS[model_name] + normal_output = run_model(normal_model, input_tensor, image.height, image.width) + normal_map = normal_output.squeeze().cpu().numpy().transpose(1, 2, 0) + + # Apply segmentation mask to normal map + normal_map[seg_mask == 0] = -1 # Set background to -1 + + # Normalize and visualize normal map + normal_map_norm = np.linalg.norm(normal_map, axis=-1, keepdims=True) + normal_map_normalized = normal_map / (normal_map_norm + 1e-5) + normal_map_vis = ((normal_map_normalized + 1) / 2 * 255).astype(np.uint8) + # normal_map_vis = normal_map_vis[:, :, ::-1] # Convert to BGR for OpenCV + + return Image.fromarray(normal_map_vis) + + +with open(spaces.convert_root_path() + "header.html", "r") as file: + header = file.read() + +CUSTOM_CSS = """ +.image-container img { + max-width: 1024px; + max-height: 512px; + margin: 0 auto; + border-radius: 0px; +} +.gradio-container {background-color: #000000} +""" + +js_func = """ +function refresh() { + const url = new URL(window.location); + if (url.searchParams.get('__theme') !== 'dark') { + url.searchParams.set('__theme', 'dark'); + window.location.href = url.href; + } +} +""" + +with gr.Blocks(js=js_func, css=CUSTOM_CSS, theme=gr.themes.Monochrome(radius_size=sizes.radius_md)) as demo: + gr.HTML(header) + with gr.Row(): + with gr.Column(): + input_image = gr.Image(label="Input Image", type="pil", format="png") + model_name = gr.Dropdown( + label="Model Size", + choices=list(CHECKPOINTS.keys()), + value="0.3b", + ) + example_model = gr.Examples( + inputs=input_image, + examples_per_page=14, + examples=[ + os.path.join(ASSETS_DIR, "images", img) + for img in os.listdir(os.path.join(ASSETS_DIR, "images")) + ], + ) + with gr.Column(): + result_image = gr.Image(label="Normal Estimation Result", format="png") + run_button = gr.Button("Run") + + run_button.click( + fn=process_image, + inputs=[input_image, model_name], + outputs=[result_image], + ) + +if __name__ == "__main__": + demo.launch(share=False) diff --git a/extensions-builtin/forge_space_sapiens_normal/space_meta.json b/extensions-builtin/forge_space_sapiens_normal/space_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..fe269d7180db098b6bfe13cbc9e4811344eefd3a --- /dev/null +++ b/extensions-builtin/forge_space_sapiens_normal/space_meta.json @@ -0,0 +1,7 @@ +{ + "tag": "Computer Vision: Depth, Normal, and Geometry", + "title": "Sapiens: Normal Estimation", + "repo_id": "facebook/sapiens_normal", + "revision": "9c0e1ffc14c59f658197200fc599672675014dc6", + "ignore_patterns": "*.pt2" +} diff --git a/extensions-builtin/prompt-bracket-checker/javascript/prompt-bracket-checker.js b/extensions-builtin/prompt-bracket-checker/javascript/prompt-bracket-checker.js new file mode 100644 index 0000000000000000000000000000000000000000..114cf94ccbf69b473757f2fc46443a39723a9269 --- /dev/null +++ b/extensions-builtin/prompt-bracket-checker/javascript/prompt-bracket-checker.js @@ -0,0 +1,42 @@ +// Stable Diffusion WebUI - Bracket checker +// By Hingashi no Florin/Bwin4L & @akx +// Counts open and closed brackets (round, square, curly) in the prompt and negative prompt text boxes in the txt2img and img2img tabs. +// If there's a mismatch, the keyword counter turns red and if you hover on it, a tooltip tells you what's wrong. + +function checkBrackets(textArea, counterElt) { + var counts = {}; + (textArea.value.match(/[(){}[\]]/g) || []).forEach(bracket => { + counts[bracket] = (counts[bracket] || 0) + 1; + }); + var errors = []; + + function checkPair(open, close, kind) { + if (counts[open] !== counts[close]) { + errors.push( + `${open}...${close} - Detected ${counts[open] || 0} opening and ${counts[close] || 0} closing ${kind}.` + ); + } + } + + checkPair('(', ')', 'round brackets'); + checkPair('[', ']', 'square brackets'); + checkPair('{', '}', 'curly brackets'); + counterElt.title = errors.join('\n'); + counterElt.classList.toggle('error', errors.length !== 0); +} + +function setupBracketChecking(id_prompt, id_counter) { + var textarea = gradioApp().querySelector("#" + id_prompt + " > label > textarea"); + var counter = gradioApp().getElementById(id_counter); + + if (textarea && counter) { + textarea.addEventListener("input", () => checkBrackets(textarea, counter)); + } +} + +onUiLoaded(function() { + setupBracketChecking('txt2img_prompt', 'txt2img_token_counter'); + setupBracketChecking('txt2img_neg_prompt', 'txt2img_negative_token_counter'); + setupBracketChecking('img2img_prompt', 'img2img_token_counter'); + setupBracketChecking('img2img_neg_prompt', 'img2img_negative_token_counter'); +}); diff --git a/extensions-builtin/sd-civitai-browser-plus-main/.github/FUNDING.yml b/extensions-builtin/sd-civitai-browser-plus-main/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..6d0af7885427407541e59b781dc19c2872b6915b --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +custom: ["https://www.paypal.me/JeJongen"] diff --git a/extensions-builtin/sd-civitai-browser-plus-main/.github/ISSUE_TEMPLATE/bug_report.yml b/extensions-builtin/sd-civitai-browser-plus-main/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000000000000000000000000000000000..d55765a7a1a78d703c7a031830029fab0dfafd15 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,60 @@ +name: 🐛 Bug report +description: If something isn't working as expected, please report a bug here. +title: "[Bug]: " +labels: ["bug"] + +body: + - type: markdown + attributes: + value: | + *Please fill this form with as much information as possible!* + - type: textarea + id: what-did + attributes: + label: Describe the bug. + description: A clear and concise description of what the bug is. + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce the problem. + description: Precise step by step instructions on how to reproduce the bug. + value: | + 1. Go to .... + 2. Press .... + 3. ... + validations: + required: true + - type: textarea + id: what-should + attributes: + label: Expected behavior + description: A clear and concise description of what you expected to happen. + validations: + required: true + - type: textarea + id: sysinfo + attributes: + label: System info + description: Information about your system and the versions that were used. + value: | + * Extension version: + * OS: + * SD-WebUI version: + * Python: + validations: + required: true + - type: textarea + id: logs + attributes: + label: Console logs + description: Please share the complete cmd/terminal logs from the time the error occurred, ensuring you include all associated error messages. + render: Shell + validations: + required: true + - type: textarea + id: misc + attributes: + label: Additional information + description: Please provide any relevant additional info or context. diff --git a/extensions-builtin/sd-civitai-browser-plus-main/.github/ISSUE_TEMPLATE/config.yml b/extensions-builtin/sd-civitai-browser-plus-main/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..95d64503d645d008eaac35b1985cfe4c6dbb2a02 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: "🌟 Feature Request" + url: "https://github.com/BlafKing/sd-civitai-browser-plus/discussions/new?category=ideas" + about: "Feature requests are handled in the Discussions tab under 'Ideas'." + - name: "❓ Question" + url: "https://github.com/BlafKing/sd-civitai-browser-plus/discussions/new?category=q-a" + about: "If you have questions, please ask them in the Discussions tab under 'Q&A'." diff --git a/extensions-builtin/sd-civitai-browser-plus-main/.gitignore b/extensions-builtin/sd-civitai-browser-plus-main/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..d0683b4e1f5027ec96118b222cb330c864c5a0d6 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/.gitignore @@ -0,0 +1,3 @@ +__pycache__ +.vscode +running \ No newline at end of file diff --git a/extensions-builtin/sd-civitai-browser-plus-main/LICENSE b/extensions-builtin/sd-civitai-browser-plus-main/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0ad25db4bd1d86c452db3f9602ccdbe172438f52 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/extensions-builtin/sd-civitai-browser-plus-main/README.md b/extensions-builtin/sd-civitai-browser-plus-main/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1b9ef0d04bca30c8851b4d8f839617c034bb43be --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/README.md @@ -0,0 +1,693 @@ + +![CivitAI Browser-05+](https://github.com/BlafKing/sd-civitai-browser-plus/assets/9644716/95afcc41-56f0-4398-8779-51cb2a9e2f55) + +--- +### Extension for [Automatic1111's Stable Diffusion Web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) + + +

Features 🚀

+

Browse all models from CivitAI 🧩

+ +* Explore a wide range of models at your fingertips. + +

Check for updates and installed models 🔄

+ +* Easily spot new updates and identify already installed models while browsing. +* Ability to scan all installed models for available updates. + +

Download any Model, any version, and any file 📥

+ +* Get the specific model version and file you need hassle-free. +* Download queue to avoid waiting for finished downloads. + +

Automatically assign tags to installed models 🏷️

+ +* Assign tags by scanning all installed models for automatic use in image generation. + +

Quick Model Info Access 📊

+ +* A button for each model card in txt2img and img2img to load it into the extension. +* A button under each image in model info to send its generation info to txt2img. + +

High-speed downloads with Aria2 🚄

+ +* Maximize your bandwidth for lightning-fast downloads. + +

Sleek and Intuitive User Interface 🖌️

+ +* Enjoy a clutter-free, user-friendly interface, designed to enhance your experience. + +

Actively maintained with feature requests welcome 🛠️

+ +* Feel free to send me your feature requests, and I'll do my best to implement them! + +

+ +
+

Known Issues 🐛

+ +

Unable to download / Frozen download:

+ +**If you're experiencing issues with broken or frozen downloads, there are two possible solutions you can try:** + +1. **Revert to the old download method**: + A solution could be to disable the "Download models using Aria2" feature. +This will switch back to the old download method, which may resolve the issue. + + ![Revert to old download method](https://github.com/BlafKing/sd-civitai-browser-plus/assets/9644716/982b0ebb-0cac-4053-8060-285533e0e176) + +2. **Disable Async DNS for Aria2**: + If you're using a DNS manager program like PortMaster, try turning on the "Disable Async DNS for Aria2" option. + + ![Disable Async DNS for Aria2](https://github.com/BlafKing/sd-civitai-browser-plus/assets/9644716/3cf7fab3-0df5-4995-9543-d9824b7931ff) + +These settings can be found under the "Settings" tab in Web-UI and then under the "CivitAI Browser+" tile. + +
+ +

+ +# How to install 📘 + +

Automatic Installation:

+ +![HowTo](https://github.com/BlafKing/sd-civitai-browser-plus/assets/9644716/91a8f636-0fd5-4964-8fb4-830a5c22254a) + + +

Manual Installation:

+ +1. Download the latest version from this site and unpack the .zip +![2023-09-25 13_06_31](https://github.com/BlafKing/sd-civitai-browser-plus/assets/9644716/12e46c6b-74b5-4ed5-bf55-cb76c5f75c62) + +2. Navigate to your extensions folder (Your SD folder/webui/extensions) +3. Place the unpacked folder inside the extensions folder +4. Restart SD-WebUI + +# Preview 👀 + +https://github.com/BlafKing/sd-civitai-browser-plus/assets/9644716/44c5c7a0-4854-4043-bfbb-f32fa9df5a74 + + +# Star History 🌟 + + + + + + Star History Chart + + + +# Changelog 📋 + +

v3.6.0

+ +* Feature: Ability to set custom default sub folders. +* Feature: Automatically fetches latest available Basemodels. +* Bug fix: Lag fixed on SD-WebUI Forge/Gradio 4+, thanks to [@BenjaminSymons](https://github.com/BenjaminSymons) and [@channelcat](https://github.com/channelcat)! +* Bug fix: Version ID has been suffixed to filename to avoid detecting different models as installed. +* Bug fix: Filename comparing to detect installed models is no longer case sensitive. +* Bug fix: CivitAI button on model cards correctly works again. +* Bug fix: Correct image path now gets used when local images in HTML are used. +* Bug fix: Any trailing or leading spaces get removed from model/version names now. + +--- +

v3.5.4

+ +* Feature: Added support for DoRA (Requires SD-WebUI v1.9) +* Bug fix: No longer rescans models that were previously not found on CivitAI +* Bug fix: Fixed placement of HTML & api_info files when custom images location was used. +* Bug fix: Fixed incorrect json naming. + +--- +

v3.5.3

+ +* New Setting: Send model from the cards CivitAI button to the browser, instead of showing a popup. +* Bug fix: No longer fetch HTML info when the file already exists and overwrite is off. +* Bug fix: Fix NSFW models update functions. +* Bug fix: Fixed CivitAI button on NSFW model cards. + +--- +

v3.5.2

+ +* Bug fix: NSFW filtering fixed. + +--- +

v3.5.1

+ +* Temp fix: Quick fix for the new NSFW system. + - NSFW models may be returned when NSFW is disabled, this is an issue with the public CivitAI API. + - Search results currently do not get influenced by the NSFW setting, also an issue with the API. +* Bug fix: Better automatic coloring for white theme. + +--- +

v3.5.0

+ +* Bug fix: Extension now works again with the latest CivitAI API version! +* Cleanup: Re-wrote backend API handling code. + +--- +

v3.4.3

+ +* Bug fix: Hotfix for a change in the public API which broke searching. +* Bug fix: Fixed incorrect permission display on model page. + +--- +

v3.4.2

+ +* Feature: Ability to set-up a custom proxy for API requests and downloads. +* Feature: Use image API for prompt info, should speed up loading. +* Feature: Optimized javascript code, improved webpage speed for some users. +* New setting: Proxy settings to set-up custom proxy. +* New setting: Toggle for saving description to model json file. (this displays description on the cards) +* Bug fix: Broken default sub folder option fixed [#217](https://github.com/BlafKing/sd-civitai-browser-plus/issues/217) + +--- +

v3.4.1

+ +* Feature: Local images now work in HTML files as preview. (credit: [mx](https://github.com/mx)) +* Feature: Updated available base models. +* Bug fix: Fixed prompt info and model selection after CivitAI API update. +* Bug fix: Fixed "/" missing from default path/sub-folder. + +--- +

v3.4.0

+ +* Feature: (BETA) Download queue! rearrange download order and remove models from queue + - Will likely contain bugs, still not completely finished. +* Feature: Customizable sub folder insertion options, choose what sub folder options you want! +* New setting: Toggle per prompt example image buttons +* New setting: Insert sub folder options +* Bug fix: Add to queue fixed, now properly gets enabled. +* Bug fix: Symlinks now get correctly recognized and used. +* Bug fix: No longer creates accidental sub folder when bulk downloading. + +--- +

v3.3.1

+ +* Feature: Ability to send individual parts of image generation data to txt2img. +* Feature: Added compatibility for [stable-diffusion-webui-forge](https://github.com/lllyasviel/stable-diffusion-webui-forge) fork. +* New setting: Use local images in the HTML + - Does not work in combination with the "Use local HTML file for model info" option! +* New setting: Store the HTML and api_info in the custom images location +* Bug fix: New HTML model info now scales with width so it should always fit. +* Bug fix: Various bug fixes to the "Update model info & tags" function. +* Bug fix: Auto save all images now uses correctly uses custom image path if set. +* Bug fix: "Save model info" button should no longer return errors. +* Bug fix: Old download method (non Aria2) should now work again. + +--- +

v3.3.0

+ +* Feature: New txt2img and img2img model info overlay on CivitAI button press. +* Feature: Base Model as sub folder option. +* Feature: Ability to multi-download to selected folder. +* Feature: Use the same folder as older versions when updating using multi-download. +* Feature: txt2img and img2img CivitAI buttons can use local HTML file, toggle in settings. +* Note: Save images no longer saves .html and API info, save model info does this instead now. +* New setting: Save API info of model when saving model info. +* New setting: Automatically save all images after download. +* New setting: Use local HTML file for model info. +* Bug fix: better JSON decode, now forces UTF-8 +* Bug fix: Now uses the proper default file when using multi-download +* Bug fix: Hide early access models fix, now works when published_at does not exist in API. +* Bug fix: Fix attempt for queue clearing upon download fail. + +--- +

v3.2.5

+ +* Bug fix: Removed default API Key since it gets blocked after many downloads. + - Because of this it's now required for some downloads to use a personal CivitAI key, this can be set in the the settings tab of SD-WebUI under the CivitAI Browser+ tab. +* Bug fix: Fixed bug when selecting a model from txt2img/img2img that doesn't exist on CivitAI. +* Bug fix: Changed model selection to Model ID instead of model name + - This previously caused issues when 2 models were named the same. +* Bug fix: Fixed an issue where the default file was not properly used by default. +* Bug fix: Fixed some tiles not being selectable due to having "'" in its title +* Bug fix: Now automatically removes residual Aria2 files. + +--- +

v3.2.4

+ +* Bug fix: Fix version detection for non standard SD-WebUI versions. +* Bug fix: Retry to fetch ModelID if previously not found in update functions. +* Bug fix: Style fix for when the Lobe theme is used in SD-WebUI +* Bug fix: Better required packages import error catching. +* Bug fix: Fixed CivitAI button scaling in txt2img and img2img tabs. +* Bug fix: Added ability to handle models that have no hashes saved. + +--- +

v3.2.3

+ +* Bug fix: Generate hash toggle in update models was inverted (silly mistake, sry bout that) +* Bug fix: Better error detection if no model IDs were retrieved during update functions. +* Bug fix: Better error handling if a local model does not exist on CivitAI + +--- +

v3.2.2

+ +* Bug fix: Fixed an `api_response` issue in the update model functions +* Bug fix: Reverted automatically retrieving base models to fix startup issues +* Bug fix: Better error description if a model no longer exists on CivitAI +* Bug fix: Primary file is now used as default file. +* Bug fix: Search after updating models no longer returns errors. + +--- +

v3.2.1

+ +* Feature: Extension now automatically retrieves latest base models from CivitAI. +* Bug fix: Hotfix for functionality with SD.Next + +--- +

v3.2.0

+ +* Feature: A toggle for One-Time hash generation for externally downloaded models. +* Feature: Updated extension settings layout for SD-WebUI 1.7.0 and higher. +* Bug fix: Set default value of Lora & LoCON combination based on SD-WebUI version. +* Bug fix: LORA models with embedding files now get placed inside embeddings folder. +* Bug fix: Better tile count handling to avoid issues with incorrect tile count. +* Bug fix: Better settings saving/loading to prevent writing issues. + +--- +

v3.1.1

+ +* Bug fix: Early Access models now get correctly hidden/detected. +* Bug fix: Better timeout/offline server detection for options in "Update Models" tab. +* Bug fix: Better error detection if required packages were not installed/imported. +* Bug fix: Download button now displays as "Add to queue" during active download. + +--- +

v3.1.0

+ +* Feature: Send to txt2img, Send any image in the model info to txt2img. +* Feature: Added new Base model filters: + - SD 1.5 LCM, SDXL 1.0 LCM, SDXL Distilled, SDXL Turbo, SVD, SVD XT +* Feature: Hide installed models filter toggle. +* Feature: Better display of permissions and tags in model info. +* New setting: Append sub folders to custom image path. +* New setting: Toggle gif/video playback, Disable if videos are causing high CPU usage. +* Bug fix: Better handling if hash is not found. + +--- +

v3.0

+ +* Feature: Download queue! Ability to add downloads to a queue. (Finally!) +* Feature: Checkboxes to download multiple models at once. + - This will automatically use the first version and first file of the selected model(s). + - Will use the default sub folders per content type defined in sub folder settings. +* Feature: "Select all" button to select all downloadable models at once. +* Feature: "Open on CivitAI" button when viewing a models metadata in txt2img or img2img. + - Will only display if the model's info has been saved to the .json after v3.0 +* Feature: Ability to rename model filename + - Note that it's not recommended to change the filename since some checks rely on it. +* Bug fix: Fixed display of saved .html files. +* Bug fix: Removed potential illegal characters from file name/path name. +* Bug fix: Fixed case sensitive sorting of sub folders. + +--- +

v2.1.0

+ +* Feature: "Overwrite any existing previews, tags or descriptions" Toggle in Update tab. +* Feature: Added content type "All" to model scanning to select all content types. + +--- +

v2.0.1

+ +* Bug fix: Folders starting with "." now no longer show sub folders. +* Bug fix: Added headers to simulate browser request. (May fix issues for users from Russia) + +--- +

v2.0

+ +* Feature: New button on each model card in txt2img and img2img to view it in the extension. +
+ Preview + +![ezgif-3-b1f0de4dd2](https://github.com/BlafKing/sd-civitai-browser-plus/assets/9644716/536a693a-c30c-438e-a34f-1aec54e4e7ee) + +
+ +* Feature: NSFW toggle now properly impacts search results. +* Feature: Ability to set [\Model Name] & [\Model Name\Version Name] as default sub folders. +* New setting: Hide sub folders that start with a '.' +* Bug fix: Preview HTML is now emptied when loading a new page. +* Bug fix: Buttons now correctly display when loading new page. +* Bug fix: Fixed compatibility with SD.Next. (again) +* Bug fix: Emptied tags, base model, and filename upon loading new page. +* Bug fix: Filter change detection fixed + +--- +

v1.16

+ +* Feature: Ability to download/update model preview images in Update Models tab. +* Feature: "Update model tags" changed to "Update model info & tags". + - The option now saves tags, description and base model version. + - This also applies to the browser, saved tags is changed to save model info. +* Bug fix: Archived models are now hidden since they cannot be used. + +--- +

v1.15.2

+ +* New setting: Custom save images location +* New setting: Default sub folders + - Any sub folders you have will be able to be selected as default, per content type. + - If a content type doesn't appear, then it means there are no subfolders in that type. +* Bug fix: Unreleased models caused a crash, now hidden by default since they can't be used. + +--- +

v1.15.1

+ +* New setting: Show console logs during update scanning. +* Bug fix: Scan for update no longer prints incorrect info about outdated models. +* Bug fix: Removed bad logic which triggered the same function multiple times. +* Cleanup: Optimized functions and improved the speed of selecting models. + +--- +

v1.15

+ +* Feature: Filter option to show favorited models. (requires personal API key) +* Feature: Back to top button when viewing model details. +* New setting: Page navigation as header. (keeps page navigation always visible at the top) +* Bug fix: Aria2 now restarts when UI is reloaded. +* Bug fix: SHA256 error fixed if .json files don't contain it. +* Bug fix: Cleaned up javascript code. + +--- +

v1.14.7

+ +* New setting: Hide early access models (EA models are only downloadable by supporters) +* New setting: Personal CivitAI API key (Text field to insert personal API key) + - Useful for CivitAI supporters, you can use your own API Key to allow downloading Early Access models +* Bug fix: Extension now works with `no gradio queue` flag. +* Bug fix: Auto disable Aria2 on MacOS due to incompatibility. +* Bug fix: Now properly works on SD.Next again. +* Bug fix: Download progression and cancelling is no longer broken on old download method. +* Bug fix: Extension now correctly downloads models where it is required to be logged in. +* Bug fix: Extension no longer attempts to install already installed requirements. + +--- +

v1.14.6

+ +* Bug fix: Removed pre-load of default page, caused issues for some users. +* Bug fix: Fixed internal model naming, caused issues when model names included ' +* Bug fix: Different host for .svg icons, caused issues with MalwareBytes. +* Bug fix: Preview saving was broken due to passing the wrong file path. + +--- +

v1.14.5

+ +* Feature: Base Model filter now impacts search results. +* Feature: Ability to input model URL into search bar to find corresponding model. +* Bug fix: Adetailer models now get placed in the correct folder + +--- +

v1.14.4

+ +* Bug fix: Page slider broke the Next Page button when loaded from "Update Models". +* Bug fix: "Save settings as default" button inserted broken .json data. +* Bug fix: Triggering "Scan for available updates" twice resulted in an error. + +--- +

v1.14.3

+ +* Bug fix: LORA content type was broken when "Treat LoCon as LORA" was turned on. + +--- +

v1.14.2

+ +* Feature: Custom page handling when scanning models. +* Bug fix: Model scan feature now works for large model count (+900) +* Bug fix: Better broken .json error handling + +--- +

v1.14.1

+ +* Bug fix: Gifs did not display properly. +* Bug fix: Video's no longer save as preview since they cannot be used. +* Bug fix: Filter window was not hidden by default. + +--- +

v1.14

+ +* Feature: Redesign of UI. +* Feature: New dropdown with filter settings. +* Feature: Button to save current filter settings as default. (requires restart) +* Feature: Tag box can now be typed in to save custom tags. +* Feature: Delete function removes any unpacked files. + +--- +

v1.13

+ +* Feature: Updated available content types: + - Upscaler + - MotionModule + - Wildcards + - Workflows + - Other +* Feature: Videos can now also be displayed on preview cards and in the model info. +* Feature: Automatically scans upscaler type by looking through model's description. +* Feature: Automatically identify correct folder for wildcards based on extension. +* Bug fix: Version ID got saved instead of correct Model ID after download. + +--- +

v1.12.5

+ +* Bug fix: [Installed] tag was only assigned to latest installed version. +* Bug fix: Folder location didn't update when selecting different version/file. +* Bug fix: Version scanning didn't properly scan sha256 in uppercase. + +--- +

v1.12.4

+ +* Feature: You can now refresh by pressing Ctrl+Enter and Alt+Enter. +* Bug fix: Auto unpack feature was unpacking unintended archives, now only unpacks .zip. + +--- +

v1.12.3

+ +* New setting: Option to toggle automatically unpacking .zip models. +* Bug fix: Error wasn't catched when file path was incorrect. + +--- +

v1.12.2

+ +* Feature: Able to download multiple files from each version. +* Bug fix: Models did not get deleted properly when in nested folders. +* Bug fix: Wrong sha256 was being saved after downloading. +* Bug fix: Wrong default folder was used when installed model got selected. + +--- +

v1.12.1

+ +* Feature: File deletion now uses both SHA256 and file name to detect correct file. +* New setting: Option to toggle automatically inserting 2 default sub folders. +* New setting: Option to toggle installing LoCON's in LORA folder. +* Bug fix: Default file was incorrect when selecting a model. +* Bug fix: Next Page caused an error when changing content type. + +--- +

v1.12

+ +* Feature: Ability to load all selected installed models into browser in Update Models tab. +* Feature: Installed/outdated models check is now done using SHA256 + file name. +* Feature: Ability to select multiple content Types when searching and scanning. +* Feature: Greatly improved speed of model scanning if model ID is saved in .json + +--- +

v1.11.2

+ +* Feature: Redesign of model page by [ManOrMonster](https://github.com/ManOrMonster) +*
Model page changes (https://github.com/BlafKing/sd-civitai-browser-plus/pull/33) + + - Redesigned the look of the model page. + - Added link to model page on CivitAI. Click on model name to open. + - Added link to uploader/creator page on CivitAI. Click creator name to open. + - Added CivitAI avatar display. + - Separate description section. + - First sample image is marked with data attribute and downloaded as preview image instead of grabbing first in model HTML. This guarantees that the first sample image (not avatar or image in description) is used when downloading the model. + - Sample images are marked with data attribute so that only they are downloaded when using "Save Images" (no description images or avatar). + - Removed trained tags from info since they are displayed above. + - Each sample image has its own section. + - Sample images zoom in when clicked, zoom out when clicking anywhere. + - Forced width is removed from sample image URLs so that nice big images can be viewed. + - Metadata is arranged so that the most commonly used data is at the top, no more searching for prompts. + - Extra metadata is in accordion labeled "More details...". This is especially useful to hide insanely large ComfyUI JSON. + +
+ +--- +

v1.11.1

+ +* Feature: Error detection during Aria2 downloads. +* Bug fix: Avoid starting Aria2 RPC multiple times with better port check. +* Bug fix: Fixed dynamic tile status updates after deleting/downloading. +--- + +

v1.11

+ +* Feature: Ability to scan all installed models for available updates. +* Feature: Model ID and sha256 get saved to .json after scanning or downloading a model. +* Bug fix: Fixed crash when base model is not found. +* Bug fix: No longer overwrite sha256 and model ID in existing .json. +--- + +

v1.10.1

+ +* Bug fix: Fixed pathing for Unix systems +* Bug fix: Extra checks to prevent deleting unintentional files. +* Feature: Models get moved to trash instead of fully deleted. +--- +

v1.10

+ +* Feature: Update tags for all installed models! +* Feature: Tabs for Browsing and updating Tags. +* Feature: Buttons to select which folders to update tags in. +--- +

v1.9.4

+ +* Feature: Added Civit AI settings tab + - New setting: Disable downloading with Aria2. (will use old download method instead) + - New setting: Disable using Async DNS. (can fix issues for some users who use DNS managing programs) + - New setting: Show Aria2 logs in the CMD. + - New setting: Set the amount of connections when downloading a model with Aria2. + (The optimal connection count is different per user, try to find the lowest option which still gives you full bandwidth speed) +--- +

v1.9.3

+ +* Feature: Included Motrix Aria2 version. +* Feature: Max connections per server set to 64 and split file set 64. +* Feature: Aria2 is now shipped with this extension for Linux as well. +--- + +

v1.9.2

+ +* Cleanup: Split up script into multiple files for improved oversight/readability. +* Cleanup: Centered model icons +--- + +

v1.9.1

+ +* Bug fix: Added back old download function if aria2 fails. +--- + +

v1.9

+ +* Feature: Faster downloads by using Aria2. +* Feature: More info about current download: Speed, ETA, File Size and % completion. +--- + +

v1.8.1

+ +* Feature: Sub Folder list now contains 2 default options: `/{Model name}` & `/{Model name}/{Version name}` +--- + +

v1.8

+ +* Feature: Ability to download different file types per version. +* Feature: NSFW Toggle is now dynamic. +* Feature: Version list now dynamically updates after download. +* Cleanup: Rearranged/Resized UI elements. +* Bug fix: Downloading models now uses file ID instead of names. +* Bug fix: NSFW Toggle no longer hides images tagged as "Soft". +* Bug fix: Fixed each model load running twice. +--- + +

v1.7.2

+ +* Bug fix: Download button did not get re-enabled properly. +* Bug fix: Tile status did not get updated properly when download failed. +--- + +

v1.7.1

+ +* Feature: Base Model filtering dims tiles instead of hiding. +* Bug fix: NSFW Blur increases with tile size. +* Bug fix: Dynamic tile status after installation & deletion now correctly detects other versions. +--- + +

v1.7

+ +* Feature: Introduced seperate download progress bar, browse while downloading. +* Feature: no more force refresh after installing, cancelling and deleting. +* Feature: Added toggle to sort Tiles by date. +* Feature: Dynamic changing of tile borders after installation & deletion. +* Removal: 'Auto delete old version' removed since it relied on a reload. +--- + +

v1.6

+ +* Bug fix: Page count is now always correclty read when refreshing. +(You can fill in the page number you'd like to visit and press refresh to go to that page) +* Feature: 'Filter Base Model' to dynamically hide any unselected Base models. +(Please note: This does not impact search results, since the CivitAI API does not yet support this) +--- + +

v1.5

+ +* Feature: Slider to change tile size. +* Feature: Download Folder textbox which can be used to define a custom download path. +* Feature: Sub Folder Dropdown to select any available subfolder(s) as download location. +* Feature: Display a timed out message instead of an error icon. +* Bug fix: Nested files can now be detected as installed or outdated. +* Bug fix: Auto selects corresponding folder of any installed models. +* Bug fix: Better cancellation logic to prevent downloads from continuing. +--- + +

v1.4

+ +* Feature: Download progress bar is now on web page instead of CMD. +* Feature: Added Cancel and Delete buttons. +* Feature: Download button will now change according to circumstances: + - Cancel button if there's a current download. + - Delete button if the selected version is installed. +* Cleanup: Better margin fixes with theme detection. +* Bug fix: Delete option now also removes .json files. +* Bug fix: Buttons are now disabled during download. (except cancel button) +--- + +

v1.3.1

+ +* Bug fix: Fixed tag saving bugs/oversights. +* Bug fix: Trained tags display now do not include the model itself. +--- + +

v1.3

+ +* Feature: 'Save Tags' button saves tags to a .json file which gets used in image creaton. + (If a LORA with saved tags is used it will automatically input all tags into the txt box in image creation) +* Feature: 'Save tags after download' toggle to automatically save .json tags. +* Cleanup: Removed "Get model info" button. +* Cleanup: Removed download link box. +* Cleanup: Removed "No" from search options. +* Cleanup: Added border radius to cards. +* Cleanup: Improved padding based on if Lobe theme is being used. +--- + +

v1.2

+ +* Feature: Automatically saves preview image when downloading a model. +* Feature: Added [installed] text suffix for any versions that are installed in the 'Version' tab. +* Cleanup: Changed 'Model Filename' from a dropbox to a textbox. +* Cleanup: Made bottom textboxes non typeable. +* Cleanup: Disabled bottom buttons when no model is selected. +* Bug fix: Margin error on the latest tile. +* Bug fix: Version checking is now case sensitive. +* Bug fix: Default verison in version tab shows installed version. +--- + +

v1.1

+ +* Feature: Dropdown box which can filter by time period. +* Cleanup: 'Content type' changed from buttons to a dropdown box. +* Bug fix: Fixed tiles not reloading when already pressed. +--- + +

v1.0

+ +* Feature: 'Refresh' now reloads the current page unless any options have been changed. +* Feature: Made the page refresh after a download and made it load during one. +* Feature: Orange glow for any outdated installed packages. +* Feature: 'Delete old version after download' option. +* Feature: Ability to manually fill in a page number to load the corresponding page. +* Cleanup: Removed new folder option. +* Cleanup: Made the glow around frames always visible without hovering. +* Pulled fork from: [SignalFlagZ's Fork](https://github.com/SignalFlagZ/sd-civitai-browser) [v1.1.0](https://github.com/SignalFlagZ/sd-civitai-browser/releases/tag/1.1.0) diff --git a/extensions-builtin/sd-civitai-browser-plus-main/aria2/lin/aria2 b/extensions-builtin/sd-civitai-browser-plus-main/aria2/lin/aria2 new file mode 100644 index 0000000000000000000000000000000000000000..b93f84f39353b2784d18c91d1525d8f12f904aa6 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/aria2/lin/aria2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f50816471fbd5e91c04df6cf6f995c6279d295b70187f313e6d3b04f65769fc +size 9926088 diff --git a/extensions-builtin/sd-civitai-browser-plus-main/aria2/win/aria2.exe b/extensions-builtin/sd-civitai-browser-plus-main/aria2/win/aria2.exe new file mode 100644 index 0000000000000000000000000000000000000000..5485d42b9ba6f54ef5dfa6c71150ea725737d493 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/aria2/win/aria2.exe @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:098a065ab71f639bf7048e790c870756fd6e83de9cc678915bbd07077d473fa2 +size 8136704 diff --git a/extensions-builtin/sd-civitai-browser-plus-main/install.py b/extensions-builtin/sd-civitai-browser-plus-main/install.py new file mode 100644 index 0000000000000000000000000000000000000000..8e0287ccd04497e40b84f58bc619d0fb434ded43 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/install.py @@ -0,0 +1,20 @@ +import launch +from pathlib import Path + +aria2path = Path(__file__).resolve().parents[0] / "aria2" + +for item in aria2path.iterdir(): + if item.is_file(): + item.unlink() + +def install_req(check_name, install_name=None): + if not install_name: install_name = check_name + if not launch.is_installed(f"{check_name}"): + print("") + launch.run_pip(f"install {install_name}", f"Installing missing requirement \"{check_name}\" for CivitAI Browser") + +install_req("send2trash", "send2trash==1.8.2") +install_req("zip_unicode", "ZipUnicode==1.1.1") +install_req("bs4", "beautifulsoup4==4.12.3") +install_req("packaging","packaging==23.2") +install_req("pysocks","pysocks==1.7.1") \ No newline at end of file diff --git a/extensions-builtin/sd-civitai-browser-plus-main/javascript/Sortable.min.js b/extensions-builtin/sd-civitai-browser-plus-main/javascript/Sortable.min.js new file mode 100644 index 0000000000000000000000000000000000000000..bb9953355480571864d048d1b4070237af5027d6 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/javascript/Sortable.min.js @@ -0,0 +1,2 @@ +/*! Sortable 1.15.2 - MIT | git://github.com/SortableJS/Sortable.git */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).Sortable=e()}(this,function(){"use strict";function e(e,t){var n,o=Object.keys(e);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(e),t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),o.push.apply(o,n)),o}function I(o){for(var t=1;tt.length)&&(e=t.length);for(var n=0,o=new Array(e);n"===e[0]&&(e=e.substring(1)),t))try{if(t.matches)return t.matches(e);if(t.msMatchesSelector)return t.msMatchesSelector(e);if(t.webkitMatchesSelector)return t.webkitMatchesSelector(e)}catch(t){return}}function P(t,e,n,o){if(t){n=n||document;do{if(null!=e&&(">"!==e[0]||t.parentNode===n)&&p(t,e)||o&&t===n)return t}while(t!==n&&(t=(i=t).host&&i!==document&&i.host.nodeType?i.host:i.parentNode))}var i;return null}var g,m=/\s+/g;function k(t,e,n){var o;t&&e&&(t.classList?t.classList[n?"add":"remove"](e):(o=(" "+t.className+" ").replace(m," ").replace(" "+e+" "," "),t.className=(o+(n?" "+e:"")).replace(m," ")))}function R(t,e,n){var o=t&&t.style;if(o){if(void 0===n)return document.defaultView&&document.defaultView.getComputedStyle?n=document.defaultView.getComputedStyle(t,""):t.currentStyle&&(n=t.currentStyle),void 0===e?n:n[e];o[e=!(e in o||-1!==e.indexOf("webkit"))?"-webkit-"+e:e]=n+("string"==typeof n?"":"px")}}function v(t,e){var n="";if("string"==typeof t)n=t;else do{var o=R(t,"transform")}while(o&&"none"!==o&&(n=o+" "+n),!e&&(t=t.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return i&&new i(n)}function b(t,e,n){if(t){var o=t.getElementsByTagName(e),i=0,r=o.length;if(n)for(;i=n.left-e&&i<=n.right+e,e=r>=n.top-e&&r<=n.bottom+e;return o&&e?a=t:void 0}}),a);if(e){var n,o={};for(n in t)t.hasOwnProperty(n)&&(o[n]=t[n]);o.target=o.rootEl=e,o.preventDefault=void 0,o.stopPropagation=void 0,e[K]._onDragOver(o)}}var i,r,a}function Bt(t){V&&V.parentNode[K]._isOutsideThisEl(t.target)}function Ft(t,e){if(!t||!t.nodeType||1!==t.nodeType)throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(t));this.el=t,this.options=e=a({},e),t[K]=this;var n,o,i={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(t.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return Pt(t,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(t,e){t.setData("Text",e.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:!1!==Ft.supportPointer&&"PointerEvent"in window&&!u,emptyInsertThreshold:5};for(n in W.initializePlugins(this,t,i),i)n in e||(e[n]=i[n]);for(o in kt(e),this)"_"===o.charAt(0)&&"function"==typeof this[o]&&(this[o]=this[o].bind(this));this.nativeDraggable=!e.forceFallback&&Nt,this.nativeDraggable&&(this.options.touchStartThreshold=1),e.supportPointer?h(t,"pointerdown",this._onTapStart):(h(t,"mousedown",this._onTapStart),h(t,"touchstart",this._onTapStart)),this.nativeDraggable&&(h(t,"dragover",this),h(t,"dragenter",this)),Dt.push(this.el),e.store&&e.store.get&&this.sort(e.store.get(this)||[]),a(this,x())}function jt(t,e,n,o,i,r,a,l){var s,c,u=t[K],d=u.options.onMove;return!window.CustomEvent||y||w?(s=document.createEvent("Event")).initEvent("move",!0,!0):s=new CustomEvent("move",{bubbles:!0,cancelable:!0}),s.to=e,s.from=t,s.dragged=n,s.draggedRect=o,s.related=i||e,s.relatedRect=r||X(e),s.willInsertAfter=l,s.originalEvent=a,t.dispatchEvent(s),c=d?d.call(u,s,a):c}function Ht(t){t.draggable=!1}function Lt(){Tt=!1}function Kt(t){return setTimeout(t,0)}function Wt(t){return clearTimeout(t)}Ft.prototype={constructor:Ft,_isOutsideThisEl:function(t){this.el.contains(t)||t===this.el||(mt=null)},_getDirection:function(t,e){return"function"==typeof this.options.direction?this.options.direction.call(this,t,e,V):this.options.direction},_onTapStart:function(e){if(e.cancelable){var n=this,o=this.el,t=this.options,i=t.preventOnFilter,r=e.type,a=e.touches&&e.touches[0]||e.pointerType&&"touch"===e.pointerType&&e,l=(a||e).target,s=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||l,c=t.filter;if(!function(t){xt.length=0;var e=t.getElementsByTagName("input"),n=e.length;for(;n--;){var o=e[n];o.checked&&xt.push(o)}}(o),!V&&!(/mousedown|pointerdown/.test(r)&&0!==e.button||t.disabled)&&!s.isContentEditable&&(this.nativeDraggable||!u||!l||"SELECT"!==l.tagName.toUpperCase())&&!((l=P(l,t.draggable,o,!1))&&l.animated||tt===l)){if(ot=j(l),rt=j(l,t.draggable),"function"==typeof c){if(c.call(this,e,l,this))return q({sortable:n,rootEl:s,name:"filter",targetEl:l,toEl:o,fromEl:o}),G("filter",n,{evt:e}),void(i&&e.cancelable&&e.preventDefault())}else if(c=c&&c.split(",").some(function(t){if(t=P(s,t.trim(),o,!1))return q({sortable:n,rootEl:t,name:"filter",targetEl:l,fromEl:o,toEl:o}),G("filter",n,{evt:e}),!0}))return void(i&&e.cancelable&&e.preventDefault());t.handle&&!P(s,t.handle,o,!1)||this._prepareDragStart(e,a,l)}}},_prepareDragStart:function(t,e,n){var o,i=this,r=i.el,a=i.options,l=r.ownerDocument;n&&!V&&n.parentNode===r&&(o=X(n),Q=r,Z=(V=n).parentNode,J=V.nextSibling,tt=n,lt=a.group,ct={target:Ft.dragged=V,clientX:(e||t).clientX,clientY:(e||t).clientY},ft=ct.clientX-o.left,pt=ct.clientY-o.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,V.style["will-change"]="all",o=function(){G("delayEnded",i,{evt:t}),Ft.eventCanceled?i._onDrop():(i._disableDelayedDragEvents(),!s&&i.nativeDraggable&&(V.draggable=!0),i._triggerDragStart(t,e),q({sortable:i,name:"choose",originalEvent:t}),k(V,a.chosenClass,!0))},a.ignore.split(",").forEach(function(t){b(V,t.trim(),Ht)}),h(l,"dragover",Yt),h(l,"mousemove",Yt),h(l,"touchmove",Yt),h(l,"mouseup",i._onDrop),h(l,"touchend",i._onDrop),h(l,"touchcancel",i._onDrop),s&&this.nativeDraggable&&(this.options.touchStartThreshold=4,V.draggable=!0),G("delayStart",this,{evt:t}),!a.delay||a.delayOnTouchOnly&&!e||this.nativeDraggable&&(w||y)?o():Ft.eventCanceled?this._onDrop():(h(l,"mouseup",i._disableDelayedDrag),h(l,"touchend",i._disableDelayedDrag),h(l,"touchcancel",i._disableDelayedDrag),h(l,"mousemove",i._delayedDragTouchMoveHandler),h(l,"touchmove",i._delayedDragTouchMoveHandler),a.supportPointer&&h(l,"pointermove",i._delayedDragTouchMoveHandler),i._dragStartTimer=setTimeout(o,a.delay)))},_delayedDragTouchMoveHandler:function(t){t=t.touches?t.touches[0]:t;Math.max(Math.abs(t.clientX-this._lastX),Math.abs(t.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){V&&Ht(V),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;f(t,"mouseup",this._disableDelayedDrag),f(t,"touchend",this._disableDelayedDrag),f(t,"touchcancel",this._disableDelayedDrag),f(t,"mousemove",this._delayedDragTouchMoveHandler),f(t,"touchmove",this._delayedDragTouchMoveHandler),f(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||"touch"==t.pointerType&&t,!this.nativeDraggable||e?this.options.supportPointer?h(document,"pointermove",this._onTouchMove):h(document,e?"touchmove":"mousemove",this._onTouchMove):(h(V,"dragend",this),h(Q,"dragstart",this._onDragStart));try{document.selection?Kt(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch(t){}},_dragStarted:function(t,e){var n;wt=!1,Q&&V?(G("dragStarted",this,{evt:e}),this.nativeDraggable&&h(document,"dragover",Bt),n=this.options,t||k(V,n.dragClass,!1),k(V,n.ghostClass,!0),Ft.active=this,t&&this._appendGhost(),q({sortable:this,name:"start",originalEvent:e})):this._nulling()},_emulateDragOver:function(){if(ut){this._lastX=ut.clientX,this._lastY=ut.clientY,Rt();for(var t=document.elementFromPoint(ut.clientX,ut.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(ut.clientX,ut.clientY))!==e;)e=t;if(V.parentNode[K]._isOutsideThisEl(t),e)do{if(e[K])if(e[K]._onDragOver({clientX:ut.clientX,clientY:ut.clientY,target:t,rootEl:e})&&!this.options.dragoverBubble)break}while(e=(t=e).parentNode);Xt()}},_onTouchMove:function(t){if(ct){var e=this.options,n=e.fallbackTolerance,o=e.fallbackOffset,i=t.touches?t.touches[0]:t,r=$&&v($,!0),a=$&&r&&r.a,l=$&&r&&r.d,e=Mt&&yt&&E(yt),a=(i.clientX-ct.clientX+o.x)/(a||1)+(e?e[0]-Ct[0]:0)/(a||1),l=(i.clientY-ct.clientY+o.y)/(l||1)+(e?e[1]-Ct[1]:0)/(l||1);if(!Ft.active&&!wt){if(n&&Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))D.right+10||S.clientY>x.bottom&&S.clientX>x.left:S.clientY>D.bottom+10||S.clientX>x.right&&S.clientY>x.top)||m.animated)){if(m&&(t=n,e=r,C=X(B((_=this).el,0,_.options,!0)),_=L(_.el,_.options,$),e?t.clientX<_.left-10||t.clientY { + const columnDiv = document.querySelector('.column.civmodellist'); + if (columnDiv) { + const firstFigure = columnDiv.querySelector('figure'); + if (firstFigure) { + firstFigure.click(); + } + } + }, 500); +} + +// Changes the card size +function updateCardSize(width, height) { + var styleSheet = document.styleSheets[0]; + var dimensionsKeyframes = `width: ${width}em !important; height: ${height}em !important;`; + + var fontSize = (width / 8) * 100; + var textKeyframes = `font-size: ${fontSize}% !important;`; + + addOrUpdateRule(styleSheet, '.civmodelcard img', dimensionsKeyframes); + addOrUpdateRule(styleSheet, '.civmodelcard .video-bg', dimensionsKeyframes); + addOrUpdateRule(styleSheet, '.civmodelcard figcaption', textKeyframes); +} + +// Toggles NSFW display +function toggleNSFWContent(hideAndBlur) { + const nsfwCards = document.querySelectorAll('.civcardnsfw'); + nsfwCards.forEach(card => { + card.style.display = hideAndBlur ? 'block' : 'none'; + }) + + const nsfwImages = document.querySelectorAll('.civnsfw img'); + nsfwImages.forEach(img => { + img.style.filter = hideAndBlur ? 'none' : 'blur(10px)'; + }); + + const dateSections = document.querySelectorAll('.date-section'); + dateSections.forEach(section => { + const cards = section.querySelectorAll('.civmodelcard'); + const nsfwCards = section.querySelectorAll('.civmodelcard.civcardnsfw'); + section.style.display = !hideAndBlur && cards.length === nsfwCards.length ? 'none' : 'block'; + }); +} + +// Updates site with css insertions +function addOrUpdateRule(styleSheet, selector, newRules) { + for (let i = 0; i < styleSheet.cssRules.length; i++) { + let rule = styleSheet.cssRules[i]; + if (rule.selectorText === selector) { + rule.style.cssText = newRules; + return; + } + } + styleSheet.insertRule(`${selector} { ${newRules} }`, styleSheet.cssRules.length); +} + +// Updates card border +function updateCard(modelNameWithSuffix) { + const lastDotIndex = modelNameWithSuffix.lastIndexOf('.'); + const modelName = modelNameWithSuffix.slice(0, lastDotIndex); + const suffix = modelNameWithSuffix.slice(lastDotIndex + 1); + let additionalClassName = ''; + switch(suffix) { + case 'None': + additionalClassName = ''; + break; + case 'Old': + additionalClassName = 'civmodelcardoutdated'; + break; + case 'New': + additionalClassName = 'civmodelcardinstalled'; + break; + default: + return; + } + const parentDiv = document.querySelector('.civmodellist'); + if (parentDiv) { + const cards = parentDiv.querySelectorAll('.civmodelcard'); + cards.forEach((card) => { + const onclickAttr = card.getAttribute('onclick'); + if (onclickAttr && onclickAttr.includes(`select_model('${modelName}', event)`)) { + card.className = `civmodelcard ${additionalClassName}`; + } + }); + } +} + +// Enables refresh with alt+enter and ctrl+enter +function keydownHandler(e) { + var handled = false; + + if (e.key !== undefined) { + if ((e.key == "Enter" && (e.metaKey || e.ctrlKey || e.altKey))) handled = true; + } else if (e.keyCode !== undefined) { + if ((e.keyCode == 13 && (e.metaKey || e.ctrlKey || e.altKey))) handled = true; + } + + if (handled) { + var currentTabContent = get_uiCurrentTabContent(); + if (currentTabContent && currentTabContent.id === "tab_civitai_interface") { + + var refreshButton = currentTabContent.querySelector('#refreshBtn'); + if (!refreshButton) { + refreshButton = currentTabContent.querySelector('#refreshBtnL'); + } + if (refreshButton) { + refreshButton.click(); + } + + e.preventDefault(); + } + } +} +document.addEventListener('keydown', keydownHandler); + +// Function for the back to top button +function BackToTop() { + const c = Math.max(document.body.scrollTop, document.documentElement.scrollTop); + if (c > 0) { + window.requestAnimationFrame(BackToTop); + document.body.scrollTop = c - c / 8; + document.documentElement.scrollTop = c - c / 8; + } +} + +// Function to adjust alignment of Filter Accordion +function adjustFilterBoxAndButtons() { + const element = document.querySelector("#filterBox") || document.querySelector("#filterBoxL"); + if (!element) return; + + const childDiv = element.querySelector("div:nth-child(3)"); + if (!childDiv) return; + + const isLargeScreen = window.innerWidth >= 1250; + const isMediumScreen = window.innerWidth < 1250 && window.innerWidth > 915; + const isNarrowScreen = window.innerWidth < 800; + const modelBlocks = document.querySelectorAll("#civitai_preview_html .model-block"); + const civitInfo = document.querySelector(".civitai-version-info"); + + if (modelBlocks) { + modelBlocks.forEach(modelBlock => { + if (isNarrowScreen) { + modelBlock.style.flexWrap = "wrap"; + modelBlock.style.justifyContent = "center"; + } else { + modelBlock.style.flexWrap = "nowrap"; + modelBlock.style.justifyContent = "flex-start"; + } + }); + } if (civitInfo) { + if (window.innerWidth < 900) { + civitInfo.style.flexWrap = "wrap"; + } else { + civitInfo.style.flexWrap = "nowrap"; + } + } + + + childDiv.style.marginLeft = isLargeScreen ? "0px" : isMediumScreen ? `${1250 - window.innerWidth}px` : "0px"; + element.style.justifyContent = isLargeScreen || isMediumScreen ? "center" : "flex-start"; + + const pageBtn1 = document.querySelector("#pageBtn1"); + const pageBtn2 = document.querySelector("#pageBtn2"); + const pageBox = document.querySelector("#pageBox"); + const pageBoxMobile = document.querySelector("#pageBoxMobile"); + + if (window.innerWidth < 530) { + childDiv.style.width = "300px"; + if (pageBoxMobile) { + pageBtn1 && pageBoxMobile.appendChild(pageBtn1); + pageBtn2 && pageBoxMobile.appendChild(pageBtn2); + pageBoxMobile.style.paddingBottom = "15px"; + } + } else { + childDiv.style.width = "400px"; + if (pageBox) { + pageBtn1 && pageBox.insertBefore(pageBtn1, pageBox.firstChild); + pageBtn2 && pageBox.appendChild(pageBtn2); + pageBoxMobile.style.paddingBottom = "0px"; + } + } +} + +// Calls the function above whenever the window is resized +window.addEventListener("resize", adjustFilterBoxAndButtons); + +// Function to trigger refresh button with extra checks for page slider +function pressRefresh() { + setTimeout(() => { + const input = document.querySelector("#pageSlider > div:nth-child(2) > div > input"); + if (document.activeElement === input) { + function keydownHandler(event) { + if (event.key === 'Enter' || event.keyCode === 13) { + input.blur(); + input.removeEventListener('keydown', keydownHandler); + input.removeEventListener('blur', blurHandler); + } + } + + function blurHandler() { + input.removeEventListener('keydown', keydownHandler); + input.removeEventListener('blur', blurHandler); + } + + input.addEventListener('keydown', keydownHandler); + input.addEventListener('blur', blurHandler); + + return; + } + let output = gradioApp().querySelector('#page_slider_trigger textarea'); + if (output) { + const randomNumber = Math.floor(Math.random() * 1000); + const paddedNumber = String(randomNumber).padStart(3, '0'); + output.value = paddedNumber; + updateInput(output); + } + }, 200); +} + +// Update SVG Icons based on dark theme or light theme +function updateSVGIcons() { + const isDark = document.body.classList.contains('dark'); + const filterIconUrl = isDark ? "https://gistcdn.githack.com/BlafKing/a20124cedafad23d4eecc1367ec22896/raw/04a4dae0771353377747dadf57c91d55bf841bed/filter-light.svg" : "https://gistcdn.githack.com/BlafKing/686c3438f5d0d13e7e47135f25445ef3/raw/46477777faac7209d001829a171462d9a2ff1467/filter-dark.svg"; + const searchIconUrl = isDark ? "https://gistcdn.githack.com/BlafKing/3f95619089bac3b4fd5470a986e1b3bb/raw/ebaa9cceee3436711eb560a7a65e151f1d651c6a/search-light.svg" : "https://gistcdn.githack.com/BlafKing/57573592d5857e102a4bfde852f62639/raw/aa213e9e82d705651603507e26545eb0ffe60c90/search-dark.svg"; + + if (isDark) { + + } + + const element = document.querySelector("#filterBox, #filterBoxL"); + const childDiv = element?.querySelector("div:nth-child(3)"); + + if (childDiv) { + childDiv.style.cssText = `box-shadow: ${isDark ? '#ffffff' : '#000000'} 0px 0px 2px 0px; display: none;`; + } + + const style = document.createElement('style'); + style.innerHTML = ` + #filterBox > div:nth-child(2) > span:nth-child(2)::before, + #filterBoxL > div:nth-child(2) > span:nth-child(2)::before { + background: url('${filterIconUrl}') no-repeat center center; + background-size: contain; + } + #refreshBtn > img, + #refreshBtnL > img { + content: url('${searchIconUrl}'); + } + + /* Gradio 4 */ + #filterBox > button:nth-child(2), + #filterBoxL > button:nth-child(2) { + background: url('${filterIconUrl}') no-repeat center center !important; + background-size: 22px !important; + } + #filterBox > button:nth-child(2) > span, + #filterBoxL > button:nth-child(2) > span { + visibility: hidden; + } + `; + document.head.appendChild(style); +} + +// Creates a tooltip if the user wants to filter liked models without a personal API key +function createTooltip(element, hover_element, insertText) { + if (element) { + const tooltip = document.createElement('div'); + tooltip.className = 'browser_tooltip'; + tooltip.textContent = insertText; + tooltip.style.cssText = 'display: none; text-align: center; white-space: pre;'; + + hover_element.addEventListener('mouseover', () => { + tooltip.style.display = 'block'; + }); + hover_element.addEventListener('mouseout', () => { + tooltip.style.display = 'none'; + }); + element.appendChild(tooltip); + } +} + +// Function that closes filter dropdown if clicked outside the dropdown +function setupClickOutsideListener() { + var filterBox = document.getElementById("filterBoxL") || document.getElementById("filterBox"); + var filterButton = filterBox.children[1]; + var dropDown = filterBox.getElementsByTagName("div")[2]; + + function clickOutsideHandler(event) { + var target = event.target; + if (!filterBox.contains(target)) { + if (!dropDown.contains(target)) { + if (filterButton.className.endsWith("open")) { + filterButton.click(); + } + } + } + } + document.addEventListener("click", clickOutsideHandler); +} + +// Create hyperlink in settings to CivitAI account settings +function createLink(infoElement) { + + const existingText = "(You can create your own API key in your CivitAI account settings, this required for some downloads, Requires UI reload)"; + const linkText = "CivitAI account settings"; + + const [textBefore, textAfter] = existingText.split(linkText); + + const link = document.createElement('a'); + link.textContent = linkText; + link.href = 'https://civitai.com/user/account'; + link.target = '_blank'; + + while (infoElement.firstChild) infoElement.removeChild(infoElement.firstChild); + + infoElement.appendChild(document.createTextNode(textBefore)); + infoElement.appendChild(link); + infoElement.appendChild(document.createTextNode(textAfter)); +} + +// Function to update the visibility of backToTopDiv based on the intersection with civitaiDiv +function updateBackToTopVisibility(entries) { + var backToTopDiv = document.getElementById('backToTopContainer'); + var civitaiDiv = document.getElementById('civitai_preview_html'); + + if (civitaiDiv.clientHeight > 0 && entries[0].isIntersecting && window.scrollY !== 0) { + backToTopDiv.style.visibility = 'visible'; + } else { + backToTopDiv.style.visibility = 'hidden'; + } +} + +// Create the accordion dropdown inside the settings tab +function createAccordion(containerDiv, subfolders, name, id_name) { + if (containerDiv == null) { + return; + } + var accordionContainer = document.createElement('div'); + accordionContainer.id = id_name; + accordionContainer.className = 'settings-accordion'; + var toggleButton = document.createElement('button'); + toggleButton.id = 'accordionToggle'; + toggleButton.innerHTML = name + '
▼
'; + toggleButton.onclick = function () { + accordionDiv.style.display = (accordionDiv.style.display === 'none') ? 'block' : 'none'; + toggleButton.lastChild.style.transform = accordionDiv.style.display === 'none' ? 'rotate(90deg)' : 'rotate(0)'; + }; + + accordionContainer.appendChild(toggleButton); + var accordionDiv = document.createElement('div'); + accordionDiv.classList.add('accordion'); + if (subfolders && subfolders.length > 0) { + accordionDiv.append(...subfolders); + } + + accordionDiv.style.display = 'none'; // Initially hidden + accordionContainer.appendChild(accordionDiv); + containerDiv.appendChild(accordionContainer); +} + +// Adds a button to the cards in txt2img and img2img +function createCivitAICardButtons() { + const copyButton = document.querySelector('.copy-path-button'); + let fontSize = '1.8rem'; + if (!copyButton) { + const editButton = document.querySelector('.edit-button'); + if (editButton) { + const originalDisplay = editButton.parentElement.style.display; + editButton.parentElement.style.display = 'flex'; + const editButtonBeforeStyle = window.getComputedStyle(editButton, ':before'); + fontSize = editButtonBeforeStyle.getPropertyValue('font-size'); + editButton.parentElement.style.display = originalDisplay; + } + } + + const checkForCardDivs = setInterval(() => { + const cardDivs = document.querySelectorAll('.card'); + if (cardDivs.length > 0) { + clearInterval(checkForCardDivs); + + cardDivs.forEach(cardDiv => { + const buttonRow = cardDiv.querySelector('.button-row'); + if (!buttonRow) return; + + buttonRow.addEventListener('click', function(event) { + event.stopPropagation(); + }); + + if (!buttonRow.querySelector('.goto-civitbrowser.card-button')) { + const modelName = cardDiv.querySelector('.actions .name')?.textContent.trim(); + if (!modelName) return; + + const newDiv = document.createElement('div'); + newDiv.className = 'goto-civitbrowser card-button'; + const svgIcon = createSVGIcon(fontSize); + newDiv.appendChild(svgIcon); + + newDiv.onclick = () => modelInfoPopUp(modelName, cardDiv.parentElement.id); + buttonRow.insertBefore(newDiv, buttonRow.firstChild); + } + }); + } + }, 200); + + setTimeout(() => { + clearInterval(checkForCardDivs); + }, 5000); +} + +function createSVGIcon(fontSize) { + const svgIcon = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svgIcon.setAttribute('width', fontSize); + svgIcon.setAttribute('height', fontSize); + svgIcon.setAttribute('viewBox', '75 85 350 350'); + svgIcon.setAttribute('fill', 'white'); + if (fontSize == "1.8rem") { + svgIcon.setAttribute('style', 'margin-top: -2px'); + } + svgIcon.innerHTML = ` + + + `; + + return svgIcon; +} + +function addOnClickToButtons() { + const tabs = ['img2img_extra_tabs', 'txt2img_extra_tabs'].map(id => document.getElementById(id)); + const buttonIds = [ + 'txt2img_checkpoints_extra_refresh', + 'img2img_checkpoints_extra_refresh', + 'txt2img_extra_refresh', + 'img2img_extra_refresh', + ]; + + buttonIds.forEach(buttonId => { + let button = document.getElementById(buttonId); + if (button) { + button.addEventListener('click', (event) => { + createCivitAICardButtons(button); + }); + } + }); + + tabs.forEach(tab => { + if (tab) { + const buttons = tab.querySelectorAll('div > button:not(:first-child)'); + buttons.forEach(button => { + button.addEventListener('click', (event) => { + createCivitAICardButtons(button); + }); + }); + } + }); +} + +function modelInfoPopUp(modelName=null, content_type=null, no_message=false) { + const sendToBrowserElement = gradioApp().querySelector('#setting_civitai_send_to_browser input'); + let sendToBrowser = false; + if (sendToBrowserElement) { + sendToBrowser = sendToBrowserElement.checked; + } + if (modelName) { + select_model(modelName, null, true, content_type, sendToBrowser); + } + if (sendToBrowser) { + const tabNav = document.querySelector('.tab-nav'); + const buttons = tabNav.querySelectorAll('button'); + for (const button of buttons) { + if (button.textContent.includes('Browser+')) { + button.click(); + + const firstButton = document.querySelector('#tab_civitai_interface > div > div > div > button'); + if (firstButton) { + firstButton.click(); + } + } + } + } else { + const createElementWithStyle = (tag, styles = {}) => { + const el = document.createElement(tag); + Object.assign(el.style, styles); + return el; + }; + + const overlay = createElementWithStyle('div', { + position: 'fixed', + top: '0', + left: '0', + width: '100%', + height: '100%', + backgroundColor: 'rgba(20, 20, 20, 0.95)', + zIndex: '1001', + overflowY: 'auto' + }); + overlay.classList.add('civitai-overlay'); + overlay.addEventListener('keydown', handleKeyPress); + overlay.addEventListener('click', event => { + if (event.target === overlay) hidePopup(); + }); + + const closeButton = createElementWithStyle('div', { + zIndex: '1011', + position: 'fixed', + right: '22px', + top: '0', + cursor: 'pointer', + color: 'white', + fontSize: '32pt' + }); + closeButton.classList.add('civitai-overlay-close'); + closeButton.textContent = '×'; + closeButton.addEventListener('click', hidePopup); + + const inner = createElementWithStyle('div', { + position: 'absolute', + top: '50%', + left: '50%', + width: 'auto', + transform: 'translate(-50%, -50%)', + background: 'var(--neutral-950)', + padding: '2em', + borderRadius: 'var(--block-radius)', + borderStyle: 'solid', + borderWidth: 'var(--block-border-width)', + borderColor: 'var(--block-border-color)', + zIndex: '1001' + }); + inner.classList.add('civitai-overlay-inner'); + + var modelInfo; + if (!no_message) { + modelInfo = createElementWithStyle('div', { + fontSize: '24px', + color: 'white', + fontFamily: 'var(--font)' + }); + modelInfo.classList.add('civitai-overlay-text'); + modelInfo.textContent = 'Loading model info, please wait!'; + } + + document.body.style.overflow = 'hidden'; + document.body.appendChild(overlay); + overlay.append(closeButton, inner); + if (!no_message) { + inner.appendChild(modelInfo); + } + + setDynamicWidth(inner); + window.addEventListener('resize', () => setDynamicWidth(inner)); + } +} + +function setDynamicWidth(inner) { + var windowWidth = window.innerWidth; + var dynamicWidth = Math.min(Math.max(windowWidth - 150, 350), 900); + inner.style.width = dynamicWidth + 'px'; +} + +// Function to hide the popup +function hidePopup() { + var overlay = document.querySelector('.civitai-overlay'); + if (overlay) { + document.body.removeChild(overlay); + document.body.style.overflow = 'auto'; + window.removeEventListener('resize', setDynamicWidth); + } +} + +// Function to handle key presses +function handleKeyPress(event) { + if (event.key === 'Escape') { + hidePopup(); + } +} + +function inputHTMLPreviewContent(html_input) { + //console.log("Last 500 characters of HTML input:", html_input.slice(-500)); + var inner = document.querySelector('.civitai-overlay-inner') + let startIndex = html_input.indexOf("'value': '"); + if (startIndex !== -1) { + startIndex += "'value': '".length; + let endIndex = html_input.indexOf(", 'placeholder'", startIndex); + if (endIndex === -1) { + endIndex = html_input.indexOf("', 'type': None,", startIndex); + } + if (endIndex !== -1) { + let extractedText = html_input.substring(startIndex, endIndex); + var modelIdNotFound = extractedText.includes(">Model ID not found.
The"); + + extractedText = extractedText.replace(/\\n\s* 0) { + return; + } + const genButton = gradioApp().querySelector('#txt2img_extra_tabs > div > button') + let input = element.querySelector('dd').textContent; + let inf; + if (input.endsWith(',')) { + inf = input + ' '; + } else { + inf = input + ', '; + } + let is_positive = false + let is_negative = false + switch(type) { + case 'Prompt': + is_positive = true + break; + case 'Negative prompt': + inf = 'Negative prompt: ' + inf; + is_negative = true + break; + case 'Seed': + inf = 'Seed: ' + inf; + inf = inf + inf + inf; + break; + case 'Size': + inf = 'Size: ' + inf; + inf = inf + inf + inf; + break; + case 'Model': + inf = 'Model: ' + inf; + inf = inf + inf + inf; + break; + case 'Clip skip': + inf = 'Clip skip: ' + inf; + inf = inf + inf + inf; + break; + case 'Sampler': + inf = 'Sampler: ' + inf; + inf = inf + inf + inf; + break; + case 'Steps': + inf = 'Steps: ' + inf; + inf = inf + inf + inf; + break; + case 'CFG scale': + inf = 'CFG scale: ' + inf; + inf = inf + inf + inf; + break; + } + const prompt = gradioApp().querySelector('#txt2img_prompt textarea'); + const neg_prompt = gradioApp().querySelector('#txt2img_neg_prompt textarea'); + const cfg_scale = gradioApp().querySelector('#txt2img_cfg_scale > div:nth-child(2) > div > input'); + let final = ''; + let cfg = 'CFG scale: ' + cfg_scale.value + ", " + let prompt_addon = cfg + cfg + cfg + if (is_positive) { + final = inf + "\nNegative prompt: " + neg_prompt.value + "\n" + prompt_addon; + } else if (is_negative) { + final = prompt.value + "\n" + inf + "\n" + prompt_addon; + } else { + final = prompt.value + "\nNegative prompt: " + neg_prompt.value + "\n" + inf; + } + genInfo_to_txt2img(final, false) + hidePopup(); + sendClick(genButton); +} + +// Creates a list of the selected models +var selectedModels = []; +var selectedTypes = []; +function multi_model_select(modelName, modelType, isChecked) { + if (arguments.length === 0) { + selectedModels = []; + selectedTypes = []; + return; + } + if (isChecked) { + if (!selectedModels.includes(modelName)) { + selectedModels.push(modelName); + } + selectedTypes.push(modelType) + } else { + var modelIndex = selectedModels.indexOf(modelName); + if (modelIndex > -1) { + selectedModels.splice(modelIndex, 1); + } + var typesIndex = selectedTypes.indexOf(modelType); + if (typesIndex > -1) { + selectedTypes.splice(typesIndex, 1); + } + } + const selected_model_list = gradioApp().querySelector('#selected_model_list textarea'); + selected_model_list.value = JSON.stringify(selectedModels); + + const selected_type_list = gradioApp().querySelector('#selected_type_list textarea'); + selected_type_list.value = JSON.stringify(selectedTypes); + + updateInput(selected_model_list); + updateInput(selected_type_list); +} + +function sendClick(location) { + const clickEvent = new MouseEvent('click', { + view: window, + bubbles: true, + cancelable: true + }); + location.dispatchEvent(clickEvent); +} + +let currentDlCancelled = false; + +function cancelCurrentDl() { + currentDlCancelled = true; +} + +let allDlCancelled = false; + +function cancelAllDl() { + allDlCancelled = true; +} + +function setSortable() { + new Sortable(document.getElementById('queue_list'), { + onEnd: function(evt) { + const gradio_input = document.querySelector('#civitai_dl_list.prose').innerHTML; + const gradio_html = gradioApp().querySelector('#queue_html_input textarea'); + let output = gradioApp().querySelector('#arrange_dl_id textarea'); + output.value = evt.item.getAttribute('dl_id') + "." + evt.newIndex; + updateInput(output); + gradio_html.value = gradio_input; + updateInput(gradio_html); + } + }); +} + +function cancelQueueDl() { + const cancelBtn = gradioApp().querySelector('#html_cancel_input textarea'); + const randomNumber = Math.floor(Math.random() * 1000); + const paddedNumber = String(randomNumber).padStart(3, '0'); + cancelBtn.value = paddedNumber; + updateInput(cancelBtn);cancelBtn +} + +function setDownloadProgressBar() { + const gradio_html = gradioApp().querySelector('#queue_html_input textarea'); + let browserContainer = document.querySelector('#DownloadProgress'); + let browserProgress = browserContainer.querySelector('.progress-bar'); + if (!browserProgress || !browserProgress.style.width) { + setTimeout(setDownloadProgressBar, 500); + return; + } + + let dlList = document.getElementById('civitai_dl_list'); + let nonQueue = dlList.querySelector('.civitai_nonqueue_list'); + let dlItem = dlList.querySelector('.civitai_dl_item'); + let dlBtn = dlItem.querySelector('.dl_action_btn > span'); + dlBtn.innerText = "Cancel"; + dlBtn.setAttribute('onclick', 'cancelQueueDl()'); + let dlId = dlItem.getAttribute('dl_id'); + let selector = '.civitai_dl_item[dl_id="' + parseInt(dlId) + '"]'; + + let dlProgressBar = null; + let percentage = null; + let dlText = null; + + nonQueue.appendChild(dlItem); + + const interval = setInterval(() => { + browserContainer = document.querySelector('#DownloadProgress'); + browserProgress = browserContainer.querySelector('.progress-bar'); + dlText = browserContainer.querySelector('.progress-level-inner'); + if (!dlText) { + return; + } + dlText = dlText.innerText + percentage = parseFloat(browserProgress.style.width); + + dlItem = dlList.querySelector(selector); + dlProgressBar = dlItem.querySelector('.dl_progress_bar'); + + dlProgressBar.textContent = percentage.toFixed(1) + '%'; + dlProgressBar.style.width = percentage + '%'; + + if (percentage >= 100) { + clearInterval(interval); + dlBtn = dlItem.querySelector('.dl_action_btn > span'); + dlBtn.innerText = "Remove"; + dlBtn.setAttribute('onclick', 'removeDlItem(' + parseInt(dlId) + ', this)'); + dlItem.className = 'civitai_dl_item_completed'; + dlProgressBar.textContent = 'Completed'; + dlProgressBar.style.width = '100%'; + const gradio_input = document.querySelector('#civitai_dl_list.prose').innerHTML; + gradio_html.value = gradio_input + updateInput(gradio_html); + return; + } + + if (currentDlCancelled) { + clearInterval(interval); + dlBtn = dlItem.querySelector('.dl_action_btn > span'); + dlBtn.innerText = "Remove"; + dlBtn.setAttribute('onclick', 'removeDlItem(' + parseInt(dlId) + ', this)'); + currentDlCancelled = false; + dlItem.className = 'civitai_dl_item_failed'; + dlProgressBar.textContent = 'Cancelled'; + dlProgressBar.style.width = "0%"; + const gradio_input = document.querySelector('#civitai_dl_list.prose').innerHTML; + gradio_html.value = gradio_input + updateInput(gradio_html); + return; + } else if (allDlCancelled) { + clearInterval(interval); + allDlCancelled = false; + let dlItems = dlList.querySelectorAll('.civitai_dl_item'); + dlItems.forEach(function(item) { + dlBtn = dlItem.querySelector('.dl_action_btn > span'); + dlBtn.innerText = "Remove"; + dlBtn.setAttribute('onclick', 'removeDlItem(' + parseInt(dlId) + ', this)'); + dlProgressBar = item.querySelector('.dl_progress_bar'); + dlProgressBar.textContent = 'Cancelled'; + dlProgressBar.style.width = "0%"; + nonQueue.appendChild(item); + item.className = 'civitai_dl_item_failed'; + }); + const gradio_input = document.querySelector('#civitai_dl_list.prose').innerHTML; + gradio_html.value = gradio_input + updateInput(gradio_html); + return; + } else if (dlText.includes('Encountered an error during download of') || dlText.includes('not found on CivitAI servers') || dlText.includes('requires a personal CivitAI API to be downloaded')) { + clearInterval(interval); + dlBtn = dlItem.querySelector('.dl_action_btn > span'); + dlBtn.innerText = "Remove"; + dlBtn.setAttribute('onclick', 'removeDlItem(' + parseInt(dlId) + ', this)'); + dlItem.className = 'civitai_dl_item_failed'; + dlProgressBar.textContent = 'Failed'; + dlProgressBar.style.width = "0%"; + const gradio_input = document.querySelector('#civitai_dl_list.prose').innerHTML; + gradio_html.value = gradio_input + updateInput(gradio_html); + return; + } + }, 500); +} + +function removeDlItem(dl_id, element) { + const gradio_html = gradioApp().querySelector('#queue_html_input textarea'); + const output = gradioApp().querySelector('#remove_dl_id textarea'); + var dl_item = element.parentNode.parentNode; + dl_item.parentNode.removeChild(dl_item); + output.value = dl_id + updateInput(output); + + const gradio_input = document.querySelector('#civitai_dl_list.prose').innerHTML; + gradio_html.value = gradio_input; + updateInput(gradio_html); +} + +// Selects all models +function selectAllModels() { + const checkboxes = Array.from(document.querySelectorAll('.model-checkbox')); + const allChecked = checkboxes.every(checkbox => checkbox.checked); + const allUnchecked = checkboxes.every(checkbox => !checkbox.checked); + if (allChecked || allUnchecked) { + checkboxes.forEach(sendClick); + } else { + checkboxes.filter(checkbox => !checkbox.checked).forEach(sendClick); + } +} + +// Deselects all models +function deselectAllModels() { + setTimeout(() => { + const checkboxes = Array.from(document.querySelectorAll('.model-checkbox')); + checkboxes.filter(checkbox => checkbox.checked).forEach(sendClick); + }, 1000); +} + +// Sends Image URL to Python to pull generation info +function sendImgUrl(image_url) { + const randomNumber = Math.floor(Math.random() * 1000); + const genButton = gradioApp().querySelector('#txt2img_extra_tabs > div > button') + const paddedNumber = String(randomNumber).padStart(3, '0'); + const input = gradioApp().querySelector('#civitai_text2img_input textarea'); + input.value = paddedNumber + "." + image_url; + updateInput(input); + hidePopup(); + sendClick(genButton); +} + +// Sends txt2img info to txt2img tab +function genInfo_to_txt2img(genInfo, do_slice=true) { + let insert = gradioApp().querySelector('#txt2img_prompt textarea'); + let pasteButton = gradioApp().querySelector('#paste'); + if (genInfo) { + insert.value = do_slice ? genInfo.slice(5) : genInfo; + insert.dispatchEvent(new Event('input', { bubbles: true })); + pasteButton.dispatchEvent(new Event('click', { bubbles: true })); + } +} + +// Hide installed models +function hideInstalled(toggleValue) { + const modelList = document.querySelectorAll('.column.civmodellist > .civmodelcardinstalled') + modelList.forEach(item => { + item.style.display = toggleValue ? 'none' : 'block'; + }); +} + +function setDescriptionToggle() { + const popUp = document.querySelector(".civitai-overlay-inner"); + let toggleButton = null; + let descriptionDiv = null; + + if (popUp) { + descriptionDiv = popUp.querySelector(".model-description"); + toggleButton = popUp.querySelector(".description-toggle-label"); + } else { + descriptionDiv = document.querySelector(".model-description"); + toggleButton = document.querySelector(".description-toggle-label"); + } + + if (descriptionDiv && descriptionDiv.scrollHeight <= 400) { + toggleButton.style.visibility = "hidden"; + toggleButton.style.height = "0"; + descriptionDiv.style.position = "unset"; + } +} + +function submitNewSubfolder(subfolderId, subfolderValue) { + const output = gradioApp().querySelector('#create_subfolder textarea'); + output.value = subfolderId + ".add." + subfolderValue; + updateInput(output) +} + +function deleteSubfolder(subfolderId) { + const output = gradioApp().querySelector('#create_subfolder textarea'); + output.value = subfolderId + ".delete."; + updateInput(output) +} + +function createCustomSubfolder(subfolderDiv, subfolderId, subfolderValue) { + if (typeof subfolderId === 'undefined') { + console.error('subfolderId is required.'); + return; + } + + const newContainerDiv = document.createElement("div"); + newContainerDiv.classList.add("svelte-1f354aw", "container", "CivitDefaultSubfolder"); + newContainerDiv.style.display = "flex"; + newContainerDiv.style.alignItems = "center"; + + newContainerDiv.setAttribute("subfolder_id", subfolderId); + + const newTextArea = document.createElement("textarea"); + newTextArea.setAttribute("data-testid", "textbox"); + newTextArea.classList.add("scroll-hide", "svelte-1f354aw"); + newTextArea.setAttribute("dir", "ltr"); + newTextArea.setAttribute("placeholder", "{BASEMODEL}/{NSFW}/{AUTHOR}/{MODELNAME}/{MODELID}/{VERSIONNAME}/{VERSIONID}"); + newTextArea.setAttribute("rows", "1"); + newTextArea.style.overflowY = "scroll"; + newTextArea.style.height = "42px"; + newTextArea.style.flex = "1"; + + if (typeof subfolderValue !== 'undefined') { + newTextArea.value = subfolderValue; + } + + newTextArea.addEventListener("keydown", function(event) { + if (event.key === "Enter") { + event.preventDefault(); + submitNewSubfolder(subfolderId, newTextArea.value); + } + }); + + const saveButton = document.createElement("button"); + saveButton.textContent = "Save"; + saveButton.classList.add("save-button", "lg", "primary", "gradio-button", "svelte-cmf5ev"); + saveButton.setAttribute("title", "") + saveButton.style.marginRight = "10px"; + saveButton.addEventListener("click", function() { + submitNewSubfolder(subfolderId, newTextArea.value); + }); + + const deleteButton = document.createElement("button"); + deleteButton.textContent = "Delete"; + deleteButton.classList.add("delete-button", "lg", "primary", "gradio-button", "svelte-cmf5ev"); + deleteButton.style.marginRight = "10px"; + deleteButton.addEventListener("click", function() { + deleteSubfolder(subfolderId); + newContainerDiv.remove(); + }); + + newContainerDiv.appendChild(deleteButton); + newContainerDiv.appendChild(saveButton); + newContainerDiv.appendChild(newTextArea); + + subfolderDiv.appendChild(newContainerDiv); +} + +function insertExistingSubfolders(input) { + const subfolder = document.querySelectorAll("civitai-custom-subfolder-div"); + createCustomSubfolder(subfolder, Id, Value); +} + +function createSubfolderButton() { + const subfolderParent = document.getElementById("create-sub-accordion"); + const subfolderDiv = subfolderParent.querySelector(".accordion"); + + const subfolder = document.createElement("div"); + subfolder.classList.add("flex-column-layout", "civitai-custom-subfolder-div"); + + const customSubfoldersList = document.querySelector('#custom_subfolders_list'); + const textarea = customSubfoldersList.querySelector('textarea'); + const subfoldersString = textarea ? textarea.value : ''; + + const subfoldersArray = subfoldersString.split('␞␞'); + + for (let i = 0; i < subfoldersArray.length; i += 2) { + const subfolderId = subfoldersArray[i]; + const subfolderValue = subfoldersArray[i + 1]; + + createCustomSubfolder(subfolder, subfolderId, subfolderValue); + } + + const buttonContainer = document.createElement("div"); + buttonContainer.classList.add("sub-folder-button-container"); + buttonContainer.style.display = "flex"; + buttonContainer.style.gap = "10px"; + + const optionsDiv = document.createElement("div"); + optionsDiv.classList.add("placeholder-options-container"); + optionsDiv.style.display = "flex"; + optionsDiv.style.justifyContent = "center"; + + const plusButton = document.createElement("button"); + plusButton.textContent = "Create new default sub folder entry"; + plusButton.classList.add("plus-button", "lg", "primary", "gradio-button", "svelte-cmf5ev"); + plusButton.style.marginTop = "10px"; + plusButton.addEventListener("click", function() { + const existingSubfolderDivs = document.querySelectorAll("div.CivitDefaultSubfolder"); + let highestSubfolderId = 0; + + existingSubfolderDivs.forEach((div) => { + const subfolderId = parseInt(div.getAttribute('subfolder_id'), 10); + if (subfolderId > highestSubfolderId) { + highestSubfolderId = subfolderId; + } + }); + + const newSubfolderId = highestSubfolderId + 1; + createCustomSubfolder(subfolder, newSubfolderId); + }); + + // Create the guide button + const guide_html = ` +
+
These options can be used to add sub-folder options.
+
There are a few placeholders you can use which will be automatically replaced with the selected model's information:
+
‎
+
{BASEMODEL}: Replaced with the base model name.
+
{NSFW}: Creates a folder named "nsfw", folder will not be created if model is sfw.
+
{AUTHOR}: Replaced with the author of the model.
+
{MODELNAME}: Replaced with the name of the model.
+
{MODELID}: Replaced with the unique ID of the model.
+
{VERSIONNAME}: Replaced with the version name of the model.
+
{VERSIONID}: Replaced with the unique ID of the model version.
+
‎
+
For example, if I select a model called 'ReV Animated'
+
and it's version is called 'V2 Rebirth' then the following:
+
{MODELNAME}/{VERSIONNAME}
+
Will be replaced with:
+
ReV Animated/V2 Rebirth
+
‎
+
Always use '/' as a seperator, regardless of your OS
+
+ `; + const guideButton = document.createElement("button"); + guideButton.textContent = "Guide"; + guideButton.classList.add("guide-button", "lg", "primary", "gradio-button", "svelte-cmf5ev"); + guideButton.style.marginTop = "10px"; + guideButton.addEventListener("click", function() { + modelInfoPopUp(null, null, true); + insertGuideMessage(guide_html); + }); + + const optionsText = document.createElement("span"); + optionsText.textContent = "Available options: {BASEMODEL} {NSFW} {AUTHOR} {MODELNAME} {MODELID} {VERSIONNAME} {VERSIONID}"; + + // Append buttons to the container + buttonContainer.appendChild(guideButton); + buttonContainer.appendChild(plusButton); + + optionsDiv.appendChild(optionsText); + + subfolder.insertBefore(optionsDiv, subfolder.firstChild); + subfolder.insertBefore(buttonContainer, subfolder.firstChild); + subfolderDiv.appendChild(subfolder); +} + +function insertGuideMessage(html_input) { + const overlayContainer = document.querySelector(".civitai-overlay-inner"); + if (overlayContainer) { + const guideHtml = document.createElement('div'); + guideHtml.innerHTML = html_input; + while (guideHtml.firstChild) { + overlayContainer.appendChild(guideHtml.firstChild); + } + } +} + +// Runs all functions when the page is fully loaded +function onPageLoad() { + updateSVGIcons(); + + let subfolderDiv = document.querySelector("#settings_civitai_browser_plus > div > div"); + let downloadDiv = document.querySelector("#settings_civitai_browser_download > div > div"); + let settingsDiv = document.querySelector("#settings_civitai_browser > div > div"); + + if (subfolderDiv || downloadDiv) { + let div = subfolderDiv || downloadDiv; + let subfolders = div.querySelectorAll("[id$='subfolder']"); + createAccordion(div, subfolders, "Default sub folders", 'default-sub-accordion'); + createAccordion(div, null, "Create sub folder entries", 'create-sub-accordion'); + createSubfolderButton(); + } + + if (subfolderDiv || settingsDiv) { + let div = subfolderDiv || settingsDiv; + let proxy = div.querySelectorAll("[id$='proxy']"); + createAccordion(div, proxy, "Proxy options", 'proxy-accordion'); + } + + let toggle4L = document.getElementById('toggle4L'); + let toggle4 = document.getElementById('toggle4'); + let hash_toggle_hover = document.querySelector('#skip_hash_toggle > label'); + let hash_toggle = document.querySelector('#skip_hash_toggle'); + + if (toggle4L || toggle4) { + let like_toggle = toggle4L || toggle4; + let insertText = 'Requires an API Key\nConfigurable in CivitAI settings tab'; + createTooltip(like_toggle, like_toggle, insertText); + } + + if (hash_toggle) { + let insertText = 'This option generates unique hashes for models that were not downloaded with this extension.\nA hash is required for any of the options below to work, a model with no hash will be skipped.\nInitial hash generation is a one-time process per file.'; + createTooltip(hash_toggle, hash_toggle_hover, insertText); + } + + addOnClickToButtons(); + createCivitAICardButtons(); + adjustFilterBoxAndButtons(); + setupClickOutsideListener(); + updateBackToTopVisibility([{isIntersecting: false}]); +} + +onUiLoaded(onPageLoad); + +function checkSettingsLoad() { + const divElement = gradioApp().querySelector('#setting_custom_api_key'); + const infoElement = divElement?.querySelector('.info'); + if (!infoElement) { + return; + } + clearInterval(settingsLoadInterval); + createLink(infoElement); +} +let settingsLoadInterval = setInterval(checkSettingsLoad, 1000); \ No newline at end of file diff --git a/extensions-builtin/sd-civitai-browser-plus-main/requirements.txt b/extensions-builtin/sd-civitai-browser-plus-main/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..1bbc4bb55e040a928898b72a6fec2f6b50aa8b86 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/requirements.txt @@ -0,0 +1,5 @@ +send2trash==1.8.2 +ZipUnicode==1.1.1 +beautifulsoup4==4.12.3 +packaging==23.2 +pysocks==1.7.1 \ No newline at end of file diff --git a/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_api.py b/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_api.py new file mode 100644 index 0000000000000000000000000000000000000000..7ab2fcbd26a3e152cbc767ff9b8895be74b6efc8 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_api.py @@ -0,0 +1,1165 @@ +import requests +import json +import gradio as gr +import urllib.request +import urllib.parse +import urllib.error +import os +import re +import datetime +import platform +from PIL import Image +from io import BytesIO +from collections import defaultdict +from datetime import datetime, timezone +from modules.images import read_info_from_image +from modules.shared import cmd_opts, opts +from modules.paths import models_path, extensions_dir, data_path +from html import escape +from scripts.civitai_global import print, debug_print +import scripts.civitai_global as gl +import scripts.civitai_download as _download +import scripts.civitai_file_manage as _file + +gl.init() + +def contenttype_folder(content_type, desc=None, fromCheck=False, custom_folder=None): + use_LORA = getattr(opts, "use_LORA", False) + folder = None + if desc: + desc = desc.upper() + else: + desc = "PLACEHOLDER" + if custom_folder: + main_models = custom_folder + main_data = custom_folder + else: + main_models = models_path + main_data = data_path + + if content_type == "modelFolder": + folder = os.path.join(main_models) + + if content_type == "Checkpoint": + if cmd_opts.ckpt_dir and not custom_folder: + folder = cmd_opts.ckpt_dir + else: + folder = os.path.join(main_models,"Stable-diffusion") + + elif content_type == "Hypernetwork": + if cmd_opts.hypernetwork_dir and not custom_folder: + folder = cmd_opts.hypernetwork_dir + else: + folder = os.path.join(main_models, "hypernetworks") + + elif content_type == "TextualInversion": + if cmd_opts.embeddings_dir and not custom_folder: + folder = cmd_opts.embeddings_dir + else: + folder = os.path.join(main_data, "embeddings") + + elif content_type == "AestheticGradient": + if not custom_folder: + folder = os.path.join(extensions_dir, "stable-diffusion-webui-aesthetic-gradients", "aesthetic_embeddings") + else: + folder = os.path.join(custom_folder, "aesthetic_embeddings") + + elif content_type == "LORA": + if cmd_opts.lora_dir and not custom_folder: + folder = cmd_opts.lora_dir + else: + folder = folder = os.path.join(main_models, "Lora") + + elif content_type == "LoCon": + folder = os.path.join(main_models, "LyCORIS") + if use_LORA and not fromCheck: + if cmd_opts.lora_dir and not custom_folder: + folder = cmd_opts.lora_dir + else: + folder = folder = os.path.join(main_models, "Lora") + + elif content_type == "DoRA": + if cmd_opts.lora_dir and not custom_folder: + folder = cmd_opts.lora_dir + else: + folder = folder = os.path.join(main_models, "Lora") + + elif content_type == "VAE": + if cmd_opts.vae_dir and not custom_folder: + folder = cmd_opts.vae_dir + else: + folder = os.path.join(main_models, "VAE") + + elif content_type == "Controlnet": + if hasattr(cmd_opts, 'controlnet_dir') and cmd_opts.controlnet_dir and not custom_folder: + folder = cmd_opts.controlnet_dir + else: + folder = os.path.join(main_models, "ControlNet") + + elif content_type == "Poses": + folder = os.path.join(main_models, "Poses") + + elif content_type == "Upscaler": + if "SWINIR" in desc: + if cmd_opts.swinir_models_path and not custom_folder: + folder = cmd_opts.swinir_models_path + else: + folder = os.path.join(main_models, "SwinIR") + elif "REALESRGAN" in desc: + if cmd_opts.realesrgan_models_path and not custom_folder: + folder = cmd_opts.realesrgan_models_path + else: + folder = os.path.join(main_models, "RealESRGAN") + elif "GFPGAN" in desc: + if cmd_opts.gfpgan_models_path and not custom_folder: + folder = cmd_opts.gfpgan_models_path + else: + folder = os.path.join(main_models, "GFPGAN") + elif "BSRGAN" in desc: + if cmd_opts.bsrgan_models_path and not custom_folder: + folder = cmd_opts.bsrgan_models_path + else: + folder = os.path.join(main_models, "BSRGAN") + else: + if cmd_opts.esrgan_models_path and not custom_folder: + folder = cmd_opts.esrgan_models_path + else: + folder = os.path.join(main_models, "ESRGAN") + + elif content_type == "MotionModule": + folder = os.path.join(extensions_dir, "sd-webui-animatediff", "model") + + elif content_type == "Workflows": + folder = os.path.join(main_models, "Workflows") + + elif content_type == "Other": + if "ADETAILER" in desc: + folder = os.path.join(main_models, "adetailer") + else: + folder = os.path.join(main_models, "Other") + + elif content_type == "Wildcards": + folder = os.path.join(extensions_dir, "UnivAICharGen", "wildcards") + if not os.path.exists(folder): + folder = os.path.join(extensions_dir, "sd-dynamic-prompts", "wildcards") + + return folder + +def model_list_html(json_data): + video_playback = getattr(opts, "video_playback", True) + playback = "" + if video_playback: playback = "autoplay loop" + + hide_early_access = getattr(opts, "hide_early_access", True) + filtered_items = [] + current_time = datetime.now(timezone.utc) + + for item in json_data['items']: + versions_to_keep = [] + + for version in item['modelVersions']: + if not version['files']: + continue + + if hide_early_access: + early_access_deadline_str = version.get('earlyAccessDeadline') + if early_access_deadline_str: + early_access_deadline = datetime.strptime(early_access_deadline_str, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc) + if current_time <= early_access_deadline: + continue + + versions_to_keep.append(version) + + if versions_to_keep: + item['modelVersions'] = versions_to_keep + filtered_items.append(item) + + json_data['items'] = filtered_items + + HTML = '
' + sorted_models = {} + existing_files = set() + existing_files_sha256 = set() + model_folders = set() + + for item in json_data['items']: + model_folder = os.path.join(contenttype_folder(item['type'], item['description'])) + model_folders.add(model_folder) + + for folder in model_folders: + for root, dirs, files in os.walk(folder, followlinks=True): + for file in files: + existing_files.add(file.lower()) + if file.endswith('.json'): + json_path = os.path.join(root, file) + with open(json_path, 'r', encoding="utf-8") as f: + try: + json_file = json.load(f) + if isinstance(json_file, dict): + sha256 = json_file.get('sha256') + if sha256: + existing_files_sha256.add(sha256.upper()) + else: + print(f"Invalid JSON data in {json_path}. Expected a dictionary.") + except Exception as e: + print(f"Error decoding JSON in {json_path}: {e}") + + for item in json_data['items']: + model_id = item.get('id') + model_name = item.get('name') + nsfw = "" + installstatus = "" + baseModel = "" + try: + if 'baseModel' in item['modelVersions'][0]: + baseModel = item['modelVersions'][0]['baseModel'] + except: + baseModel = "Not Found" + + try: + if 'publishedAt' in item['modelVersions'][0]: + date = item['modelVersions'][0]['publishedAt'].split('T')[0] + except: + date = "Not Found" + + if item.get("nsfw"): + nsfw = "civcardnsfw" + + if gl.sortNewest: + if date not in sorted_models: + sorted_models[date] = [] + + if any(item['modelVersions']): + if len(item['modelVersions'][0]['images']) > 0: + media_type = item["modelVersions"][0]["images"][0]["type"] + image = item["modelVersions"][0]["images"][0]["url"] + if media_type == "video": + image = image.replace("width=", "transcode=true,width=") + imgtag = f'' + else: + imgtag = f'' + else: + imgtag = f'' + + installstatus = None + + for version in reversed(item['modelVersions']): + for file in version.get('files', []): + file_name = os.path.splitext(file['name'])[0] + file_extension = os.path.splitext(file['name'])[1] + file_name = f"{file_name}_{file['id']}{file_extension}" + file_sha256 = file.get('hashes', {}).get('SHA256', "").upper() + + #filename_check + name_match = file_name.lower() in existing_files + sha256_match = file_sha256 in existing_files_sha256 + if name_match or sha256_match: + if version == item['modelVersions'][0]: + installstatus = "civmodelcardinstalled" + else: + installstatus = "civmodelcardoutdated" + model_name_js = model_name.replace("'", "\\'") + model_string = escape(f"{model_name_js} ({model_id})") + model_card = f'
' + if installstatus != "civmodelcardinstalled": + model_card += f'' \ + + f'' + if len(item["name"]) > 40: + display_name = item["name"][:40] + '...' + else: + display_name = item["name"] + + display_name = escape(display_name) + full_name = escape(item['name']) + model_card += imgtag \ + + f'
{display_name}
' + + if gl.sortNewest: + sorted_models[date].append(model_card) + else: + HTML += model_card + + if gl.sortNewest: + for date, cards in sorted(sorted_models.items(), reverse=True): + HTML += f'

{date}


' + HTML += '
' + for card in cards: + HTML += card + HTML += '
' + + HTML += '
' + return HTML + +def create_api_url(content_type=None, sort_type=None, period_type=None, use_search_term=None, base_filter=None, only_liked=None, tile_count=None, search_term=None, nsfw=None, isNext=None): + base_url = "https://civitai.com/api/v1/models" + version_url = "https://civitai.com/api/v1/model-versions" + + if isNext is not None: + api_url = gl.json_data['metadata']['nextPage' if isNext else 'prevPage'] + debug_print(api_url) + return api_url + + params = {'limit': tile_count, 'sort': sort_type, 'period': period_type.replace(" ", "") if period_type else None} + + if content_type: + params["types"] = content_type + + if use_search_term != "None" and search_term: + search_term = search_term.replace("\\", "\\\\").lower() + if "civitai.com" in search_term: + model_number = re.search(r'models/(\d+)', search_term).group(1) + params = {'ids': model_number} + + else: + key_map = {"User name": "username", "Tag": "tag"} + search_key = key_map.get(use_search_term, "query") + params[search_key] = search_term + + if base_filter: + params["baseModels"] = base_filter + + if only_liked: + params["favorites"] = "true" + + params["nsfw"] = "true" if nsfw else "false" + + query_parts = [] + for key, value in params.items(): + if isinstance(value, list): + for item in value: + query_parts.append((key, item)) + else: + query_parts.append((key, value)) + + query_string = urllib.parse.urlencode(query_parts, doseq=True, quote_via=urllib.parse.quote) + api_url = f"{base_url}?{query_string}" + + debug_print(api_url) + return api_url + +def convert_LORA_LoCon(content_type): + use_LORA = getattr(opts, "use_LORA", False) + if content_type: + if use_LORA and 'LORA, LoCon, DoRA' in content_type: + content_type.remove('LORA, LoCon, DoRA') + if 'LORA' not in content_type: + content_type.append('LORA') + if 'LoCon' not in content_type: + content_type.append('LoCon') + if 'DoRA' not in content_type: + content_type.append('DoRA') + return content_type + +def initial_model_page(content_type=None, sort_type=None, period_type=None, use_search_term=None, search_term=None, current_page=None, base_filter=None, only_liked=None, nsfw=None, tile_count=None, from_update_tab=False): + content_type = convert_LORA_LoCon(content_type) + current_inputs = (content_type, sort_type, period_type, use_search_term, search_term, tile_count, base_filter, nsfw) + if current_inputs != gl.previous_inputs and gl.previous_inputs != None or not current_page: + current_page = 1 + gl.previous_inputs = current_inputs + + if not from_update_tab: + gl.from_update_tab = False + + if current_page == 1: + api_url = create_api_url(content_type, sort_type, period_type, use_search_term, base_filter, only_liked, tile_count, search_term, nsfw) + gl.url_list = {1 : api_url} + else: + api_url = gl.url_list.get(current_page) + else: + api_url = gl.url_list.get(current_page) + gl.from_update_tab = True + + gl.json_data = request_civit_api(api_url) + + max_page = 1 + model_list = [] + hasPrev, hasNext = False, False + if not isinstance(gl.json_data, dict): + HTML = api_error_msg(gl.json_data) + + else: + gl.json_data = insert_metadata(1) + + metadata = gl.json_data['metadata'] + hasNext = 'nextPage' in metadata + hasPrev = 'prevPage' in metadata + + for item in gl.json_data['items']: + if len(item['modelVersions']) > 0: + model_list.append(f"{item['name']} ({item['id']})") + + max_page = max(gl.url_list.keys()) + HTML = model_list_html(gl.json_data) + + return ( + gr.Dropdown.update(choices=model_list, value="", interactive=True), # Model List + gr.Dropdown.update(choices=[], value=""), # Version List + gr.HTML.update(value=HTML), # HTML Tiles + gr.Button.update(interactive=hasPrev), # Prev Page Button + gr.Button.update(interactive=hasNext), # Next Page Button + gr.Slider.update(value=current_page, maximum=max_page), # Page Slider + gr.Button.update(interactive=False), # Save Tags + gr.Button.update(interactive=False), # Save Images + gr.Button.update(interactive=False, visible=False if gl.isDownloading else True), # Download Button + gr.Button.update(interactive=False, visible=False), # Delete Button + gr.Textbox.update(interactive=False, value=None, visible=True), # Install Path + gr.Dropdown.update(choices=[], value="", interactive=False), # Sub Folder List + gr.Dropdown.update(choices=[], value="", interactive=False), # File List + gr.HTML.update(value='
'), # Preview HTML + gr.Textbox.update(value=None), # Trained Tags + gr.Textbox.update(value=None), # Base Model + gr.Textbox.update(value=None) # Model Filename + ) + +def prev_model_page(content_type, sort_type, period_type, use_search_term, search_term, current_page, base_filter, only_liked, nsfw, tile_count): + return next_model_page(content_type, sort_type, period_type, use_search_term, search_term, current_page, base_filter, only_liked, nsfw, tile_count, isNext=False) + +def next_model_page(content_type, sort_type, period_type, use_search_term, search_term, current_page, base_filter, only_liked, nsfw, tile_count, isNext=True): + content_type = convert_LORA_LoCon(content_type) + + current_inputs = (content_type, sort_type, period_type, use_search_term, search_term, tile_count, base_filter, nsfw) + if current_inputs != gl.previous_inputs and gl.previous_inputs != None: + return initial_model_page(content_type, sort_type, period_type, use_search_term, search_term, current_page, base_filter, only_liked, nsfw, tile_count) + + api_url = create_api_url(isNext=isNext) + gl.json_data = request_civit_api(api_url) + + next_page = current_page + model_list = [] + max_page = 1 + hasPrev, hasNext = False, False + if not isinstance(gl.json_data, dict): + HTML = api_error_msg(gl.json_data) + + else: + next_page = current_page + 1 if isNext else current_page - 1 + + gl.json_data = insert_metadata(next_page, api_url) + + metadata = gl.json_data['metadata'] + hasNext = 'nextPage' in metadata + hasPrev = 'prevPage' in metadata + + for item in gl.json_data['items']: + if len(item['modelVersions']) > 0: + model_list.append(f"{item['name']} ({item['id']})") + + max_page = max(gl.url_list.keys()) + HTML = model_list_html(gl.json_data) + + return ( + gr.Dropdown.update(choices=model_list, value="", interactive=True), # Model List + gr.Dropdown.update(choices=[], value=""), # Version List + gr.HTML.update(value=HTML), # HTML Tiles + gr.Button.update(interactive=hasPrev), # Prev Page Button + gr.Button.update(interactive=hasNext), # Next Page Button + gr.Slider.update(value=next_page, maximum=max_page), # Current Page + gr.Button.update(interactive=False), # Save Tags + gr.Button.update(interactive=False), # Save Images + gr.Button.update(interactive=False, visible=False if gl.isDownloading else True), # Download Button + gr.Button.update(interactive=False, visible=False), # Delete Button + gr.Textbox.update(interactive=False, value=None), # Install Path + gr.Dropdown.update(choices=[], value="", interactive=False), # Sub Folder List + gr.Dropdown.update(choices=[], value="", interactive=False), # File List + gr.HTML.update(value='
'), # Preview HTML + gr.Textbox.update(value=None), # Trained Tags + gr.Textbox.update(value=None), # Base Model + gr.Textbox.update(value=None) # Model Filename + ) + +def insert_metadata(page_nr, api_url=None): + metadata = gl.json_data['metadata'] + + if not metadata.get('prevPage', None) and page_nr > 1: + metadata['prevPage'] = gl.url_list.get((page_nr - 1)) + + if gl.from_update_tab: + if gl.url_list.get((page_nr + 1), None): + metadata['nextPage'] = gl.url_list.get((page_nr + 1)) + + elif page_nr not in gl.url_list: + gl.url_list[page_nr] = api_url + + return gl.json_data + +def update_model_versions(model_id, json_input=None): + if json_input: + api_json = json_input + else: + api_json = gl.json_data + for item in api_json['items']: + if int(item['id']) == int(model_id): + content_type = item['type'] + desc = item.get('description', "None") + + versions_dict = defaultdict(list) + installed_versions = set() + + model_folder = os.path.join(contenttype_folder(content_type, desc)) + gl.main_folder = model_folder + versions = item['modelVersions'] + + version_files = set() + for version in versions: + versions_dict[version['name']].append(item["name"]) + for version_file in version['files']: + file_sha256 = version_file.get('hashes', {}).get('SHA256', "").upper() + version_filename = os.path.splitext(version_file['name'])[0] + version_extension = os.path.splitext(version_file['name'])[1] + version_filename = f"{version_filename}_{version_file['id']}{version_extension}" + version_files.add((version['name'], version_filename, file_sha256)) + + for root, _, files in os.walk(model_folder, followlinks=True): + for file in files: + if file.endswith('.json'): + try: + json_path = os.path.join(root, file) + with open(json_path, 'r', encoding="utf-8") as f: + json_data = json.load(f) + if isinstance(json_data, dict): + if 'sha256' in json_data and json_data['sha256']: + sha256 = json_data.get('sha256', "").upper() + for version_name, _, file_sha256 in version_files: + if sha256 == file_sha256: + installed_versions.add(version_name) + break + except Exception as e: + print(f"failed to read: \"{file}\": {e}") + + #filename_check + for version_name, version_filename, _ in version_files: + if file.lower() == version_filename.lower(): + installed_versions.add(version_name) + break + + version_names = list(versions_dict.keys()) + display_version_names = [f"{v} [Installed]" if v in installed_versions else v for v in version_names] + default_installed = next((f"{v} [Installed]" for v in installed_versions), None) + default_value = default_installed or next(iter(version_names), None) + + return gr.Dropdown.update(choices=display_version_names, value=default_value, interactive=True) # Version List + + return gr.Dropdown.update(choices=[], value=None, interactive=False) # Version List + +def cleaned_name(file_name): + if platform.system() == "Windows": + illegal_chars_pattern = r'[\\/:*?"<>|]' + else: + illegal_chars_pattern = r'/' + + name, extension = os.path.splitext(file_name) + clean_name = re.sub(illegal_chars_pattern, '', name) + clean_name = re.sub(r'\s+', ' ', clean_name.strip()) + + return f"{clean_name}{extension}" + +def fetch_and_process_image(image_url): + proxies, ssl = get_proxies() + try: + parsed_url = urllib.parse.urlparse(image_url) + if parsed_url.scheme and parsed_url.netloc: + response = requests.get(image_url, proxies=proxies, verify=ssl) + if response.status_code == 200: + image = Image.open(BytesIO(response.content)) + geninfo, _ = read_info_from_image(image) + return geninfo + else: + image = Image.open(image_url) + geninfo, _ = read_info_from_image(image) + return geninfo + except: + return None + +def extract_model_info(input_string): + last_open_parenthesis = input_string.rfind("(") + last_close_parenthesis = input_string.rfind(")") + + name = input_string[:last_open_parenthesis].strip() + id_number = input_string[last_open_parenthesis + 1:last_close_parenthesis] + + return name, int(id_number) + +def update_model_info(model_string=None, model_version=None, only_html=False, input_id=None, json_input=None, from_preview=False): + video_playback = getattr(opts, "video_playback", True) + meta_btn = getattr(opts, "individual_meta_btn", True) + playback = "" + if video_playback: playback = "autoplay loop" + + if json_input: + api_data = json_input + else: + api_data = gl.json_data + + BtnDownInt = True + BtnDel = False + BtnImage = False + model_id = None + + if not input_id: + _, model_id = extract_model_info(model_string) + else: + model_id = input_id + + if model_version and "[Installed]" in model_version: + model_version = model_version.replace(" [Installed]", "") + if model_id: + output_html = "" + output_training = "" + output_basemodel = "" + img_html = "" + dl_dict = {} + is_LORA = False + file_list = [] + file_dict = [] + default_file = None + model_filename = None + sha256_value = None + for item in api_data['items']: + if int(item['id']) == int(model_id): + content_type = item['type'] + if content_type == "LORA": + is_LORA = True + desc = item['description'] + model_name = item['name'] + model_folder = os.path.join(contenttype_folder(content_type, desc)) + model_uploader = None + uploader_avatar = None + nsfw = item['nsfw'] + creator = item.get('creator', None) + if creator: + model_uploader = creator.get('username', None) + uploader_avatar = creator.get('image', None) + if not model_uploader: + model_uploader = 'User not found' + uploader_avatar = 'https://rawcdn.githack.com/gist/BlafKing/8d3f7a19e3f72cfddab46ae835037ee6/raw/296e81afbdd268200278beef478f3018b15936de/profile_placeholder.svg' + uploader_avatar = f'
' + tags = item.get('tags', "") + model_desc = item.get('description', "") + if model_desc: + model_desc = model_desc.replace('', '') + if model_version is None: + selected_version = item['modelVersions'][0] + else: + for model in item['modelVersions']: + if model['name'] == model_version: + selected_version = model + break + + model_availability = selected_version.get('availability', 'Unknown') + model_date_published = selected_version.get('publishedAt', '').split('T')[0] + version_name = selected_version['name'] + version_id = selected_version['id'] + + if selected_version['trainedWords']: + output_training = ",".join(selected_version['trainedWords']) + output_training = re.sub(r'<[^>]*:[^>]*>', '', output_training) + output_training = re.sub(r', ?', ', ', output_training) + output_training = output_training.strip(', ') + if selected_version['baseModel']: + output_basemodel = selected_version['baseModel'] + for file in selected_version['files']: + dl_dict[file['name']] = file['downloadUrl'] + + if not model_filename: + model_filename = os.path.splitext(file['name'])[0] + model_extension = os.path.splitext(file['name'])[1] + model_filename = f"{model_filename}_{file['id']}{model_extension}" + dl_url = file['downloadUrl'] + gl.json_info = item + sha256_value = file['hashes'].get('SHA256', 'Unknown') + + size = file['metadata'].get('size', 'Unknown') + format = file['metadata'].get('format', 'Unknown') + fp = file['metadata'].get('fp', 'Unknown') + sizeKB = file.get('sizeKB', 0) * 1024 + filesize = _download.convert_size(sizeKB) + + unique_file_name = f"{size} {format} {fp} ({filesize})" + is_primary = file.get('primary', False) + file_list.append(unique_file_name) + file_dict.append({ + "format": format, + "sizeKB": sizeKB + }) + if is_primary: + default_file = unique_file_name + model_filename = os.path.splitext(file['name'])[0] + model_extension = os.path.splitext(file['name'])[1] + model_filename = f"{model_filename}_{file['id']}{model_extension}" + dl_url = file['downloadUrl'] + gl.json_info = item + sha256_value = file['hashes'].get('SHA256', 'Unknown') + + safe_tensor_found = False + pickle_tensor_found = False + if is_LORA and file_dict: + for file_info in file_dict: + file_format = file_info.get("format", "") + if "SafeTensor" in file_format: + safe_tensor_found = True + if "PickleTensor" in file_format: + pickle_tensor_found = True + + if safe_tensor_found and pickle_tensor_found: + if "PickleTensor" in file_dict[0].get("format", ""): + if file_dict[0].get("sizeKB", 0) <= 100: + model_folder = os.path.join(contenttype_folder("TextualInversion")) + + model_url = selected_version.get('downloadUrl', '') + model_main_url = f"https://civitai.com/models/{item['id']}" + img_html = '
' + + url = f"https://civitai.com/api/v1/model-versions/{selected_version['id']}" + api_version = request_civit_api(url) + + for index, pic in enumerate(api_version['images']): + + if from_preview: + index = f"preview_{index}" + + class_name = 'class="model-block"' + if pic.get('nsfwLevel') >= 4: + class_name = 'class="civnsfw model-block"' + + img_html += f''' +
+
+ + + + ''' + + if meta_button: + img_html += f''' +
+ +
+ ''' + else: + img_html += '
' + + if prompt_dict: + img_html += '
' + # Define the preferred order of keys + preferred_order = ["prompt", "negativePrompt", "seed", "Size", "Model", "Clip skip", "sampler", "steps", "cfgScale"] + # Loop through the keys in the preferred order and add them to the HTML + for key in preferred_order: + if key in prompt_dict: + value = prompt_dict[key] + key_map = { + "prompt": "Prompt", + "negativePrompt": "Negative prompt", + "seed": "Seed", + "Size": "Size", + "Model": "Model", + "Clip skip": "Clip skip", + "sampler": "Sampler", + "steps": "Steps", + "cfgScale": "CFG scale" + } + key = key_map.get(key, key) + + if meta_btn: + img_html += f'
{escape(str(key))}
{escape(str(value))}
' + else: + img_html += f'
{escape(str(key))}
{escape(str(value))}
' + # Check if there are remaining keys in meta + remaining_keys = [key for key in prompt_dict if key not in preferred_order] + + # Add the rest + if remaining_keys: + img_html += f""" +
+
+ + +
+ """ + for key in remaining_keys: + value = prompt_dict[key] + img_html += f'
{escape(str(key).capitalize())}
{escape(str(value))}
' + img_html = img_html + '
' + + img_html += '
' + + img_html = img_html + '
' + img_html = img_html + '' + tags_html = ''.join([f'{escape(str(tag))}' for tag in tags]) + def perms_svg(color): + return f''\ + f'' + allow_svg = f'{perms_svg("lime")}' + deny_svg = f'{perms_svg("red")}' + allowCommercialUse = item.get("allowCommercialUse", []) + perms_html= '

'\ + f'{allow_svg if item.get("allowNoCredit") else deny_svg} Use the model without crediting the creator
'\ + f'{allow_svg if "Image" in allowCommercialUse else deny_svg} Sell images they generate
'\ + f'{allow_svg if "Rent" in allowCommercialUse else deny_svg} Run on services that generate images for money
'\ + f'{allow_svg if "RentCivit" in allowCommercialUse else deny_svg} Run on Civitai
'\ + f'{allow_svg if item.get("allowDerivatives") else deny_svg} Share merges using this model
'\ + f'{allow_svg if "Sell" in allowCommercialUse else deny_svg} Sell this model or merges using this model
'\ + f'{allow_svg if item.get("allowDifferentLicense") else deny_svg} Have different permissions when sharing merges'\ + '

' + + if not creator or model_uploader == 'User not found': + uploader = f'

{escape(str(model_uploader))}{uploader_avatar}

' + else: + uploader = f'

Uploaded by {escape(str(model_uploader))}{uploader_avatar}

' + output_html = f''' +
+

{escape(str(model_name))}

+ {uploader} +
+
+
Version
+
{escape(str(model_version))}
+
Base Model
+
{escape(str(output_basemodel))}
+
Published
+
{model_date_published}
+
Availability
+
{model_availability}
+
CivitAI Tags
+
+
+ {tags_html} +
+
+ {"
Download Link
" if model_url else ''} + {f'
{model_url}
' if model_url else ''} +
+
+
+ {perms_html} +
+
+
+ +
+

Description

+ {model_desc} +
+ +
+
{img_html}
+ ''' + + if only_html: + return output_html + + folder_location = "None" + default_subfolder = "None" + sub_folders = _file.getSubfolders(model_folder, output_basemodel, nsfw, model_uploader, model_name, model_id, version_name, version_id) + + for root, dirs, files in os.walk(model_folder, followlinks=True): + for filename in files: + if filename.endswith('.json'): + json_file_path = os.path.join(root, filename) + with open(json_file_path, 'r', encoding="utf-8") as f: + try: + data = json.load(f) + sha256 = data.get('sha256') + if sha256: + sha256 = sha256.upper() + if sha256 == sha256_value: + folder_location = root + BtnDownInt = False + BtnDel = True + + break + except Exception as e: + print(f"Error decoding JSON: {str(e)}") + else: + #filename_check + for filename in files: + if filename.lower() == model_filename.lower() or filename.lower() == cleaned_name(model_filename).lower(): + folder_location = root + BtnDownInt = False + BtnDel = True + break + + if folder_location != "None": + break + + default_subfolder = sub_folder_value(content_type, desc) + if default_subfolder != "None": + default_subfolder = _file.convertCustomFolder(default_subfolder, output_basemodel, nsfw, model_uploader, model_name, model_id, version_name, version_id) + if folder_location == "None": + folder_location = model_folder + if default_subfolder != "None": + folder_path = folder_location + default_subfolder + else: + folder_path = folder_location + else: + folder_path = folder_location + + relative_path = os.path.relpath(folder_location, model_folder) + default_subfolder = f'{os.sep}{relative_path}' if relative_path != "." else default_subfolder if BtnDel == False else "None" + if gl.isDownloading: + item = gl.download_queue[0] + if int(model_id) == int(item['model_id']): + BtnDel = False + BtnDownTxt = "Download model" + if len(gl.download_queue) > 0: + BtnDownTxt = "Add to queue" + for item in gl.download_queue: + if item['version_name'] == model_version and int(item['model_id']) == int(model_id): + BtnDownInt = False + break + + return ( + gr.HTML.update(value=output_html), # Preview HTML + gr.Textbox.update(value=output_training, interactive=True), # Trained Tags + gr.Textbox.update(value=output_basemodel), # Base Model Number + gr.Button.update(visible=False if BtnDel else True, interactive=BtnDownInt, value=BtnDownTxt), # Download Button + gr.Button.update(interactive=BtnImage), # Images Button + gr.Button.update(visible=BtnDel, interactive=BtnDel), # Delete Button + gr.Dropdown.update(choices=file_list, value=default_file, interactive=True), # File List + gr.Textbox.update(value=cleaned_name(model_filename), interactive=True), # Model File Name + gr.Textbox.update(value=dl_url), # Download URL + gr.Textbox.update(value=model_id), # Model ID + gr.Textbox.update(value=sha256_value), # SHA256 + gr.Textbox.update(interactive=True, value=folder_path if model_name else None), # Install Path + gr.Dropdown.update(choices=sub_folders, value=default_subfolder, interactive=True) # Sub Folder List + ) + else: + return ( + gr.HTML.update(value=None), # Preview HTML + gr.Textbox.update(value=None, interactive=False), # Trained Tags + gr.Textbox.update(value=''), # Base Model Number + gr.Button.update(visible=False if BtnDel else True, value="Download model"), # Download Button + gr.Button.update(interactive=False), # Images Button + gr.Button.update(visible=BtnDel, interactive=BtnDel), # Delete Button + gr.Dropdown.update(choices=None, value=None, interactive=False), # File List + gr.Textbox.update(value=None, interactive=False), # Model File Name + gr.Textbox.update(value=None), # Download URL + gr.Textbox.update(value=None), # Model ID + gr.Textbox.update(value=None), # SHA256 + gr.Textbox.update(interactive=False, value=None), # Install Path + gr.Dropdown.update(choices=None, value=None, interactive=False) # Sub Folder List + ) + +def sub_folder_value(content_type, desc=None): + use_LORA = getattr(opts, "use_LORA", False) + if content_type in ["LORA", "LoCon"] and use_LORA: + folder = getattr(opts, "LORA_LoCon_default_subfolder", "None") + elif content_type == "Upscaler": + for upscale_type in ["SWINIR", "REALESRGAN", "GFPGAN", "BSRGAN"]: + if upscale_type in desc: + folder = getattr(opts, f"{upscale_type}_default_subfolder", "None") + folder = getattr(opts, "ESRGAN_default_subfolder", "None") + else: + folder = getattr(opts, f"{content_type}_default_subfolder", "None") + if folder == None: + return "None" + return folder + +def update_file_info(model_string, model_version, file_metadata): + file_list = [] + is_LORA = False + embed_check = False + model_name = None + model_id = None + model_name, model_id = extract_model_info(model_string) + + if model_version and "[Installed]" in model_version: + model_version = model_version.replace(" [Installed]", "") + if model_id and model_version: + for item in gl.json_data['items']: + if int(item['id']) == int(model_id): + content_type = item['type'] + if content_type == "LORA": + is_LORA = True + desc = item['description'] + for model in item['modelVersions']: + if model['name'] == model_version: + for file in model['files']: + size = file['metadata'].get('size', 'Unknown') + format = file['metadata'].get('format', 'Unknown') + unique_file_name = f"{size} {format}" + file_list.append(unique_file_name) + pass + + if is_LORA and file_list: + extracted_formats = [file.split(' ')[1] for file in file_list] + if "SafeTensor" in extracted_formats and "PickleTensor" in extracted_formats: + embed_check = True + + for file in model['files']: + model_id = item['id'] + file_name = file.get('name', 'Unknown') + sha256 = file['hashes'].get('SHA256', 'Unknown') + metadata = file.get('metadata', {}) + file_size = metadata.get('size', 'Unknown') + file_format = metadata.get('format', 'Unknown') + file_fp = metadata.get('fp', 'Unknown') + sizeKB = file.get('sizeKB', 0) + sizeB = sizeKB * 1024 + filesize = _download.convert_size(sizeB) + + if f"{file_size} {file_format} {file_fp} ({filesize})" == file_metadata: + installed = False + folder_location = "None" + model_folder = os.path.join(contenttype_folder(content_type, desc)) + if embed_check and file_format == "PickleTensor": + if sizeKB <= 100: + model_folder = os.path.join(contenttype_folder("TextualInversion")) + dl_url = file['downloadUrl'] + gl.json_info = item + for root, _, files in os.walk(model_folder, followlinks=True): + if file_name in files: + installed = True + folder_location = root + break + + if not installed: + for root, _, files in os.walk(model_folder, followlinks=True): + for filename in files: + if filename.endswith('.json'): + with open(os.path.join(root, filename), 'r', encoding="utf-8") as f: + try: + data = json.load(f) + sha256_value = data.get('sha256') + if sha256_value != None and sha256_value.upper() == sha256: + folder_location = root + installed = True + break + except Exception as e: + print(f"Error decoding JSON: {str(e)}") + default_sub = sub_folder_value(content_type, desc) + if folder_location == "None": + folder_location = model_folder + if default_sub != "None": + folder_path = folder_location + default_sub + else: + folder_path = folder_location + else: + folder_path = folder_location + relative_path = os.path.relpath(folder_location, model_folder) + default_subfolder = f'{os.sep}{relative_path}' if relative_path != "." else default_sub if installed == False else "None" + BtnDownInt = not installed + BtnDownTxt = "Download model" + if len(gl.download_queue) > 0: + BtnDownTxt = "Add to queue" + for item in gl.download_queue: + if item['version_name'] == model_version: + BtnDownInt = False + break + + return ( + gr.Textbox.update(value=cleaned_name(file['name']), interactive=True), # Model File Name Textbox + gr.Textbox.update(value=dl_url), # Download URL Textbox + gr.Textbox.update(value=model_id), # Model ID Textbox + gr.Textbox.update(value=sha256), # sha256 textbox + gr.Button.update(interactive=BtnDownInt, visible=False if installed else True, value=BtnDownTxt), # Download Button + gr.Button.update(interactive=True if installed else False, visible=True if installed else False), # Delete Button + gr.Textbox.update(interactive=True, value=folder_path if model_name else None), # Install Path + gr.Dropdown.update(value=default_subfolder, interactive=True) # Sub Folder List + ) + + return ( + gr.Textbox.update(value=None, interactive=False), # Model File Name Textbox + gr.Textbox.update(value=None), # Download URL Textbox + gr.Textbox.update(value=None), # Model ID Textbox + gr.Textbox.update(value=None), # sha256 textbox + gr.Button.update(interactive=False, visible=True), # Download Button + gr.Button.update(interactive=False, visible=False), # Delete Button + gr.Textbox.update(interactive=False, value=None), # Install Path + gr.Dropdown.update(choices=None, value=None, interactive=False) # Sub Folder List + ) + +def get_proxies(): + custom_proxy = getattr(opts, "custom_civitai_proxy", "") + disable_ssl = getattr(opts, "disable_sll_proxy", False) + cabundle_path = getattr(opts, "cabundle_path_proxy", "") + + ssl = True + proxies = {} + if custom_proxy: + if not disable_ssl: + if cabundle_path: + ssl = os.path(cabundle_path) + else: + ssl = False + proxies = { + 'http': custom_proxy, + 'https': custom_proxy, + } + return proxies, ssl + +def get_headers(referer=None, no_api=None): + api_key = getattr(opts, "custom_api_key", "") + headers = { + "Connection": "keep-alive", + "Sec-Ch-Ua-Platform": "Windows", + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36", + "Content-Type": "application/json" + } + if referer: + headers['Referer'] = f"https://civitai.com/models/{referer}" + if api_key and not no_api: + headers['Authorization'] = f'Bearer {api_key}' + + return headers + +def request_civit_api(api_url=None, skip_error_check=False): + headers = get_headers() + proxies, ssl = get_proxies() + try: + response = requests.get(api_url, headers=headers, timeout=(60,30), proxies=proxies, verify=ssl) + if skip_error_check: + response.encoding = "utf-8" + data = json.loads(response.text) + return data + response.raise_for_status() + except requests.exceptions.Timeout as e: + print("The request timed out. Please try again later.") + return "timeout" + except requests.exceptions.RequestException as e: + print(f"Error: {e}") + return "error" + else: + response.encoding = "utf-8" + try: + data = json.loads(response.text) + except json.JSONDecodeError: + print(response.text) + print("The CivitAI servers are currently offline. Please try again later.") + return "offline" + return data + +def api_error_msg(input_string): + div = '
' + if input_string == "not_found": + return div + "Model ID not found on CivitAI.
Maybe the model doesn\'t exist on CivitAI?
" + elif input_string == "path_not_found": + return div + "Local model not found.
Could not locate the model path." + elif input_string == "timeout": + return div + "The CivitAI-API has timed out, please try again.
The servers might be too busy or down if the issue persists." + elif input_string == "offline": + return div + "The CivitAI servers are currently offline.
Please try again later." + elif input_string == "no_items": + return div + "Failed to retrieve any models from CivitAI
The servers might be too busy or down if the issue persists." + else: + return div + "The CivitAI-API failed to respond due to an error.
Check the logs for more details." diff --git a/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_download.py b/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_download.py new file mode 100644 index 0000000000000000000000000000000000000000..8a98b8e60b1155c343038ad26d4755cf26e7b847 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_download.py @@ -0,0 +1,808 @@ +import requests +import gradio as gr +import time +import subprocess +import threading +import os +import re +import random +import platform +import stat +import json +import time +from pathlib import Path +from modules.shared import opts, cmd_opts +from scripts.civitai_global import print, debug_print +import scripts.civitai_global as gl +import scripts.civitai_api as _api +import scripts.civitai_file_manage as _file +try: + from zip_unicode import ZipHandler +except ImportError: + print("Python module 'ZipUnicode' has not been imported correctly, please try to restart or install it manually.") + +total_count = 0 +current_count = 0 +dl_manager_count = 0 + +def random_number(prev=None): + number = str(random.randint(10000, 99999)) + while number == prev: + number = str(random.randint(10000, 99999)) + + return number + +gl.init() +rpc_secret = "R7T5P2Q9K6" +try: + queue = not cmd_opts.no_gradio_queue +except AttributeError: + queue = not cmd_opts.disable_queue +except: + queue = True + +def start_aria2_rpc(): + start_file = os.path.join(aria2path, '_') + running_file = os.path.join(aria2path, 'running') + null = open(os.devnull, 'w') + + if os.path.exists(running_file): + try: + if os_type == 'Linux': + env = os.environ.copy() + env['PATH'] = '/usr/bin:' + env['PATH'] + subprocess.Popen("pkill aria2", shell=True, env=env) + else: + subprocess.Popen(stop_rpc, stdout=null, stderr=null) + time.sleep(1) + except Exception as e: + print(f"Failed to stop Aria2 RPC : {e}") + else: + if os.path.exists(start_file): + os.rename(start_file, running_file) + return + else: + with open(start_file, 'w', encoding="utf-8"): + pass + + try: + show_log = getattr(opts, "show_log", False) + aria2_flags = getattr(opts, "aria2_flags", "") + cmd = f'"{aria2}" --enable-rpc --rpc-listen-all --rpc-listen-port=24000 --rpc-secret {rpc_secret} --check-certificate=false --ca-certificate=" " --file-allocation=none {aria2_flags}' + subprocess_args = {'shell': True} + if not show_log: + subprocess_args.update({'stdout': subprocess.DEVNULL, 'stderr': subprocess.DEVNULL}) + + subprocess.Popen(cmd, **subprocess_args) + if os.path.exists(running_file): + print("Aria2 RPC restarted") + else: + print("Aria2 RPC started") + except Exception as e: + print(f"Failed to start Aria2 RPC server: {e}") + +aria2path = Path(__file__).resolve().parents[1] / "aria2" +os_type = platform.system() + +if os_type == 'Windows': + aria2 = os.path.join(aria2path, 'win', 'aria2.exe') + stop_rpc = "taskkill /im aria2.exe /f" + start_aria2_rpc() +elif os_type == 'Linux': + aria2 = os.path.join(aria2path, 'lin', 'aria2') + st = os.stat(aria2) + os.chmod(aria2, st.st_mode | stat.S_IEXEC) + stop_rpc = "pkill aria2" + start_aria2_rpc() + +class TimeOutFunction(Exception): + pass + +def create_model_item(dl_url, model_filename, install_path, model_name, version_name, model_sha256, model_id, create_json, from_batch=False): + global dl_manager_count + if model_id: + model_id = int(model_id) + if model_sha256: + model_sha256 = model_sha256.upper() + if model_sha256 == "UNKNOWN": + model_sha256 = None + + filtered_items = [] + + for item in gl.json_data['items']: + if int(item['id']) == int(model_id): + filtered_items.append(item) + content_type = item['type'] + desc = item['description'] + main_folder = _api.contenttype_folder(content_type, desc) + break + + sub_folder = os.path.normpath(os.path.relpath(install_path, main_folder)) + + model_json = {"items": filtered_items} + model_versions = _api.update_model_versions(model_id) + (preview_html,_,_,_,_,_,_,_,_,_,_,existing_path,_) = _api.update_model_info(None, model_versions.get('value'), False, model_id) + + for item in gl.download_queue: + if item['dl_url'] == dl_url: + return None + + dl_manager_count += 1 + + item = { + "dl_id": dl_manager_count, + "dl_url" : dl_url, + "model_filename" : model_filename, + "install_path" : install_path, + "model_name" : model_name, + "version_name" : version_name, + "model_sha256" : model_sha256, + "model_id" : model_id, + "create_json" : create_json, + "model_json" : model_json, + "model_versions" : model_versions, + "preview_html" : preview_html['value'], + "existing_path": existing_path['value'], + "from_batch" : from_batch, + "sub_folder" : sub_folder + } + + return item + +def selected_to_queue(model_list, subfolder, download_start, create_json, current_html): + global total_count, current_count + if gl.download_queue: + number = download_start + else: + number = random_number(download_start) + total_count = 0 + current_count = 0 + + model_list = json.loads(model_list) + + for model_string in model_list: + model_name, model_id = _api.extract_model_info(model_string) + for item in gl.json_data['items']: + if int(item['id']) == int(model_id): + model_id, desc, content_type = item['id'], item['description'], item['type'] + version = item.get('modelVersions', [])[0] + version_name = version.get('name') + files = version.get('files', []) + primary_file = next((file for file in files if file.get('primary', False)), None) + if primary_file: + model_filename = _api.cleaned_name(primary_file.get('name')) + model_sha256 = primary_file.get('hashes', {}).get('SHA256') + dl_url = primary_file.get('downloadUrl') + else: + model_filename = _api.cleaned_name(files[0].get('name')) + model_sha256 = files[0].get('hashes', {}).get('SHA256') + dl_url = files[0].get('downloadUrl') + break + + model_folder = _api.contenttype_folder(content_type, desc) + + default_subfolder = _api.sub_folder_value(content_type, desc) + if default_subfolder != "None": + default_subfolder = _file.convertCustomFolder(default_subfolder, output_basemodel, nsfw, model_uploader, model_name, model_id, version_name, version_id) + + if subfolder and subfolder != "None" and subfolder != "Only available if the selected files are of the same model type": + from_batch = False + if platform.system() == "Windows": + subfolder = re.sub(r'[/:*?"<>|]', '', subfolder) + + if not subfolder.startswith(os.sep): + subfolder = os.sep + subfolder + install_path = model_folder + subfolder + else: + from_batch = True + if default_subfolder != "None": + install_path = model_folder + default_subfolder + else: + install_path = model_folder + + model_item = create_model_item(dl_url, model_filename, install_path, model_name, version_name, model_sha256, model_id, create_json, from_batch) + if model_item: + gl.download_queue.append(model_item) + total_count += 1 + + html = download_manager_html(current_html) + + return ( + gr.Button.update(interactive=False, visible=False), # Download Button + gr.Button.update(interactive=True, visible=True), # Cancel Button + gr.Button.update(interactive=True if len(gl.download_queue) > 1 else False, visible=True), # Cancel All Button + gr.Textbox.update(value=number), # Download Start Trigger + gr.HTML.update(value='
'), # Download Progress + gr.HTML.update(value=html) # Download Manager HTML + ) + + +def gr_progress_threadable(): + """ + Gradio progress bars can no longer be updated from a separate thread, + so we need to use this to update them from the main thread. + """ + + # Gradio 3 does not need a wrapper + if not hasattr(gr, "__version__") or int(gr.__version__.split(".")[0]) <= 3: + return gr.Progress() + + gr_progress=gr.Progress() + value = [0, None, False] # progress, desc, has_update + + def progress(p, desc=None): + value[0] = p + value[1] = desc + value[2] = True + + def _update_progress(): + if value[2]: + gr_progress(value[0], desc=value[1]) + value[2] = False + + def join(thread): + _update_progress() + while thread.is_alive(): + thread.join(timeout=0.1) + _update_progress() + + progress.join = join + + return progress + + +def download_start(download_start, dl_url, model_filename, install_path, model_string, version_name, model_sha256, model_id, create_json, current_html): + global total_count, current_count + if model_string: + model_name, _ = _api.extract_model_info(model_string) + model_item = create_model_item(dl_url, model_filename, install_path, model_name, version_name, model_sha256, model_id, create_json) + + gl.download_queue.append(model_item) + + if len(gl.download_queue) > 1: + number = download_start + total_count += 1 + else: + number = random_number(download_start) + total_count = 1 + current_count = 0 + + html = download_manager_html(current_html) + + return ( + gr.Button.update(interactive=False, visible=True), # Download Button + gr.Button.update(interactive=True, visible=True), # Cancel Button + gr.Button.update(interactive=True if len(gl.download_queue) > 1 else False, visible=True), # Cancel All Button + gr.Textbox.update(value=number), # Download Start Trigger + gr.HTML.update(value='
'), # Download Progress + gr.HTML.update(value=html) # Download Manager HTML + ) + +def download_finish(model_filename, version, model_id): + if model_id: + model_id = int(model_id) + model_versions = _api.update_model_versions(model_id) + else: + model_versions = None + if model_versions: + version_choices = model_versions.get('choices', []) + else: + version_choices = [] + prev_version = gl.last_version + " [Installed]" + + if prev_version in version_choices: + version = prev_version + Del = True + Down = False + else: + Del = False + Down = True + + if gl.cancel_status: + Del = False + Down = True + + gl.download_fail = False + gl.cancel_status = False + + return ( + gr.Button.update(interactive=model_filename, visible=Down, value="Download model"), # Download Button + gr.Button.update(interactive=False, visible=False), # Cancel Button + gr.Button.update(interactive=False, visible=False), # Cancel All Button + gr.Button.update(interactive=Del, visible=Del), # Delete Button + gr.HTML.update(value='
'), # Download Progress + gr.Dropdown.update(value=version, choices=version_choices) # Version Dropdown + ) + +def download_cancel(): + gl.cancel_status = True + gl.download_fail = True + if gl.download_queue: + item = gl.download_queue[0] + else: + item = None + + while True: + if not gl.isDownloading: + if item: + model_string = f"{item['model_name']} ({item['model_id']})" + _file.delete_model(0, item['model_filename'], model_string, item['version_name'], False, model_ver=item['model_versions'], model_json=item['model_json']) + break + else: + time.sleep(0.5) + return + +def download_cancel_all(): + gl.cancel_status = True + gl.download_fail = True + + if gl.download_queue: + item = gl.download_queue[0] + + while True: + if not gl.isDownloading: + if item: + model_string = f"{item['model_name']} ({item['model_id']})" + _file.delete_model(0, item['model_filename'], model_string, item['version_name'], False, model_ver=item['model_versions'], model_json=item['model_json']) + gl.download_queue = [] + break + else: + time.sleep(0.5) + return + +def convert_size(size): + for unit in ['bytes', 'KB', 'MB', 'GB']: + if size < 1024: + return f"{size:.2f} {unit}" + size /= 1024 + return f"{size:.2f} GB" + +def get_download_link(url, model_id): + headers = _api.get_headers(model_id) + proxies, ssl = _api.get_proxies() + + response = requests.get(url, headers=headers, allow_redirects=False, proxies=proxies, verify=ssl) + + if 300 <= response.status_code <= 308: + if "login?returnUrl" in response.text and "reason=download-auth" in response.text: + return "NO_API" + + download_link = response.headers["Location"] + return download_link + else: + return None + +def download_file(url, file_path, install_path, model_id, progress=gr.Progress() if queue else None): + try: + disable_dns = getattr(opts, "disable_dns", False) + split_aria2 = getattr(opts, "split_aria2", 64) + max_retries = 5 + gl.download_fail = False + aria2_rpc_url = "http://localhost:24000/jsonrpc" + + file_name = os.path.basename(file_path) + + download_link = get_download_link(url, model_id) + if not download_link: + print(f'File: "{file_name}" not found on CivitAI servers, it looks like the file is not available for download.') + gl.download_fail = True + return + + elif download_link == "NO_API": + print(f'File: "{file_name}" requires a personal CivitAI API to be downloaded, you can set your own API key in the CivitAI Browser+ settings in the SD-WebUI settings tab') + gl.download_fail = "NO_API" + if progress != None: + progress(0, desc=f'File: "{file_name}" requires a personal CivitAI API to be downloaded, you can set your own API key in the CivitAI Browser+ settings in the SD-WebUI settings tab') + time.sleep(5) + return + + if os.path.exists(file_path): + os.remove(file_path) + + if disable_dns: + dns = "false" + else: + dns = "true" + + options = { + "dir": install_path, + "max-connection-per-server": str(f"{split_aria2}"), + "split": str(f"{split_aria2}"), + "async-dns": dns, + "out": file_name + } + + payload = json.dumps({ + "jsonrpc": "2.0", + "id": "1", + "method": "aria2.addUri", + "params": ["token:" + rpc_secret, [download_link], options] + }) + + try: + response = requests.post(aria2_rpc_url, data=payload) + data = json.loads(response.text) + if 'result' not in data: + raise ValueError(f'Failed to start download: {data}') + gid = data['result'] + except Exception as e: + print(f"Failed to start download: {e}") + gl.download_fail = True + return + + while True: + if gl.cancel_status: + payload = json.dumps({ + "jsonrpc": "2.0", + "id": "1", + "method": "aria2.remove", + "params": ["token:" + rpc_secret, gid] + }) + requests.post(aria2_rpc_url, data=payload) + if progress != None: + progress(0, desc=f"Download cancelled.") + return + + try: + payload = json.dumps({ + "jsonrpc": "2.0", + "id": "1", + "method": "aria2.tellStatus", + "params": ["token:" + rpc_secret, gid] + }) + + response = requests.post(aria2_rpc_url, data=payload) + status_info = json.loads(response.text)['result'] + + total_length = int(status_info['totalLength']) + completed_length = int(status_info['completedLength']) + download_speed = int(status_info['downloadSpeed']) + + progress_percent = (completed_length / total_length) * 100 if total_length else 0 + + remaining_size = total_length - completed_length + if download_speed > 0: + eta_seconds = remaining_size / download_speed + eta_formatted = time.strftime("%H:%M:%S", time.gmtime(eta_seconds)) + else: + eta_formatted = "XX:XX:XX" + if progress != None: + progress(progress_percent / 100, desc=f"Downloading: {file_name} - {convert_size(completed_length)}/{convert_size(total_length)} - Speed: {convert_size(download_speed)}/s - ETA: {eta_formatted} - Queue: {current_count}/{total_count}") + + if status_info['status'] == 'complete': + print(f"Model saved to: {file_path}") + if progress != None: + progress(1, desc=f"Model saved to: {file_path}") + gl.download_fail = False + return + + if status_info['status'] == 'error': + if progress != None: + progress(0, desc=f"Encountered an error during download of: \"{file_name}\" Please try again.") + gl.download_fail = True + return + + time.sleep(0.25) + + except Exception as e: + print(f"Error occurred during Aria2 status update: {e}") + max_retries -= 1 + if max_retries == 0: + if progress != None: + progress(0, desc=f"Encountered an error during download of: \"{file_name}\" Please try again.") + gl.download_fail = True + return + time.sleep(5) + except: + if progress != None: + progress(0, desc=f"Encountered an error during download of: \"{file_name}\" Please try again.") + gl.download_fail = True + if os.path.exists(file_path): + os.remove(file_path) + time.sleep(5) + +def info_to_json(install_path, model_id, model_sha256, unpackList=None): + json_file = os.path.splitext(install_path)[0] + ".json" + if os.path.exists(json_file): + try: + with open(json_file, 'r', encoding="utf-8") as f: + data = json.load(f) + except Exception as e: + print(f"Failed to open {json_file}: {e}") + else: + data = {} + + data['modelId'] = model_id + data['sha256'] = model_sha256 + if unpackList: + data['unpackList'] = unpackList + + with open(json_file, 'w', encoding="utf-8") as f: + json.dump(data, f, indent=4) + +def download_file_old(url, file_path, model_id, progress=gr.Progress() if queue else None): + try: + gl.download_fail = False + max_retries = 5 + if os.path.exists(file_path): + os.remove(file_path) + + downloaded_size = 0 + tokens = re.split(re.escape(os.sep), file_path) + file_name_display = tokens[-1] + start_time = time.time() + last_update_time = 0 + update_interval = 0.25 + + download_link = get_download_link(url, model_id) + if not download_link: + print(f'File: "{file_name_display}" not found on CivitAI servers, it looks like the file is not available for download.') + if progress != None: + progress(0, desc=f'File: "{file_name_display}" not found on CivitAI servers, it looks like the file is not available for download.') + time.sleep(5) + gl.download_fail = True + return + + elif download_link == "NO_API": + print(f'File: "{file_name_display}" requires a personal CivitAI API key to be downloaded, you can set your own API key in the CivitAI Browser+ settings in the SD-WebUI settings tab') + gl.download_fail = "NO_API" + if progress != None: + progress(0, desc=f'File: "{file_name_display}" requires a personal CivitAI API key to be downloaded, you can set your own API key in the CivitAI Browser+ settings in the SD-WebUI settings tab') + time.sleep(5) + return + + headers = _api.get_headers(model_id, True) + proxies, ssl = _api.get_proxies() + + while True: + if gl.cancel_status: + if progress != None: + progress(0, desc=f"Download cancelled.") + return + if os.path.exists(file_path): + downloaded_size = os.path.getsize(file_path) + headers['Range'] = f"bytes={downloaded_size}-" + + with open(file_path, "ab") as f: + while gl.isDownloading: + try: + if gl.cancel_status: + if progress != None: + progress(0, desc=f"Download cancelled.") + return + try: + if gl.cancel_status: + if progress != None: + progress(0, desc=f"Download cancelled.") + return + response = requests.get(download_link, headers=headers, stream=True, timeout=10, proxies=proxies, verify=ssl) + if response.status_code == 404: + if progress != None: + progress(0, desc=f"Encountered an error during download of: {file_name_display}, file is not found on CivitAI servers.") + gl.download_fail = True + return + total_size = int(response.headers.get("Content-Length", 0)) + except: + raise TimeOutFunction("Timed Out") + + if total_size == 0: + total_size = downloaded_size + + for chunk in response.iter_content(chunk_size=1024): + if chunk: + if gl.cancel_status: + if progress != None: + progress(0, desc=f"Download cancelled.") + return + f.write(chunk) + downloaded_size += len(chunk) + elapsed_time = time.time() - start_time + download_speed = downloaded_size / elapsed_time + remaining_size = total_size - downloaded_size + if download_speed > 0: + eta_seconds = remaining_size / download_speed + eta_formatted = time.strftime("%H:%M:%S", time.gmtime(eta_seconds)) + else: + eta_formatted = "XX:XX:XX" + current_time = time.time() + if current_time - last_update_time >= update_interval: + if progress != None: + progress(downloaded_size / total_size, desc=f"Downloading: {file_name_display} {convert_size(downloaded_size)} / {convert_size(total_size)} - Speed: {convert_size(int(download_speed))}/s - ETA: {eta_formatted} - Queue: {current_count}/{total_count}") + last_update_time = current_time + if gl.isDownloading == False: + response.close + break + downloaded_size = os.path.getsize(file_path) + break + + except TimeOutFunction: + if progress != None: + progress(0, desc="CivitAI API did not respond, retrying...") + max_retries -= 1 + if max_retries == 0: + if progress != None: + progress(0, desc=f"Encountered an error during download of: {file_name_display}, please try again.") + gl.download_fail = True + return + time.sleep(5) + + if (gl.isDownloading == False): + break + + gl.isDownloading = False + downloaded_size = os.path.getsize(file_path) + if downloaded_size >= total_size: + if not gl.cancel_status: + print(f"Model saved to: {file_path}") + if progress != None: + progress(1, desc=f"Model saved to: {file_path}") + gl.download_fail = False + return + + else: + if progress != None: + progress(0, desc=f"Encountered an error during download of: {file_name_display}, please try again.") + print(f"File download failed: {file_name_display}") + gl.download_fail = True + if os.path.exists(file_path): + os.remove(file_path) + except: + if progress != None: + progress(0, desc=f"Encountered an error during download of: {file_name_display}, please try again.") + gl.download_fail = True + if os.path.exists(file_path): + os.remove(file_path) + time.sleep(5) + +def download_create_thread(download_finish, queue_trigger, progress=gr_progress_threadable() if queue else None): + global current_count + current_count += 1 + if not gl.download_queue: + return ( + gr.HTML.update(), # Download Progress HTML + gr.Textbox.update(value=None), # Current Model + gr.Textbox.update(value=random_number(download_finish)), # Download Finish Trigger + gr.Textbox.update(value=queue_trigger), # Queue Trigger + gr.Button.update(interactive=False) # Cancel All Button + ) + item = gl.download_queue[0] + gl.cancel_status = False + use_aria2 = getattr(opts, "use_aria2", True) + unpack_zip = getattr(opts, "unpack_zip", False) + save_all_images = getattr(opts, "auto_save_all_img", False) + gl.recent_model = item['model_name'] + gl.last_version = item['version_name'] + + if item['from_batch']: + item['install_path'] = item['existing_path'] + + gl.isDownloading = True + _file.make_dir(item['install_path']) + + path_to_new_file = os.path.join(item['install_path'], item['model_filename']) + + if use_aria2 and os_type != 'Darwin': + thread = threading.Thread(target=download_file, args=(item['dl_url'], path_to_new_file, item['install_path'], item['model_id'], progress)) + else: + thread = threading.Thread(target=download_file_old, args=(item['dl_url'], path_to_new_file, item['model_id'], progress)) + thread.start() + if progress is not None and hasattr(progress, "join"): + progress.join(thread) + else: + thread.join() + + if not gl.cancel_status or gl.download_fail: + if os.path.exists(path_to_new_file): + unpackList = [] + if unpack_zip: + try: + if path_to_new_file.endswith('.zip'): + directory = Path(os.path.dirname(path_to_new_file)) + zip_handler = ZipHandler(path_to_new_file) + + for _, decoded_name in zip_handler.name_map.items(): + unpackList.append(decoded_name) + + zip_handler.extract_all(directory) + zip_handler.zip_ref.close() + + print(f"Successfully extracted {item['model_filename']} to {directory}") + os.remove(path_to_new_file) + except ImportError: + print("Python module 'ZipUnicode' has not been imported correctly, cannot extract zip file. Please try to restart or install it manually.") + except Exception as e: + print(f"Failed to extract {item['model_filename']} with error: {e}") + if not gl.cancel_status: + if item['create_json']: + _file.save_model_info(item['install_path'], item['model_filename'], item['sub_folder'], item['model_sha256'], item['preview_html'], api_response=item['model_json']) + info_to_json(path_to_new_file, item['model_id'], item['model_sha256'], unpackList) + _file.save_preview(path_to_new_file, item['model_json'], True, item['model_sha256']) + if save_all_images: + _file.save_images(item['preview_html'], item['model_filename'], item['install_path'], item['sub_folder'], api_response=item['model_json']) + + base_name = os.path.splitext(item['model_filename'])[0] + base_name_preview = base_name + '.preview' + + if gl.download_fail: + for root, dirs, files in os.walk(item['install_path'], followlinks=True): + for file in files: + file_base_name = os.path.splitext(file)[0] + if file_base_name == base_name or file_base_name == base_name_preview: + path_file = os.path.join(root, file) + os.remove(path_file) + + if gl.cancel_status: + print(f'Cancelled download of "{item["model_filename"]}"') + else: + if not gl.download_fail == "NO_API": + print(f'Error occured during download of "{item["model_filename"]}"') + + if gl.cancel_status: + card_name = None + else: + model_string = f"{item['model_name']} ({item['model_id']})" + (card_name, _, _) = _file.card_update(item['model_versions'], model_string, item['version_name'], True) + + if len(gl.download_queue) != 0: + gl.download_queue.pop(0) + gl.isDownloading = False + time.sleep(2) + + if len(gl.download_queue) == 0: + finish_nr = random_number(download_finish) + queue_nr = queue_trigger + else: + finish_nr = download_finish + queue_nr = random_number(queue_trigger) + + return ( + gr.HTML.update(), # Download Progress HTML + gr.Textbox.update(value=card_name), # Current Model + gr.Textbox.update(value=finish_nr), # Download Finish Trigger + gr.Textbox.update(value=queue_nr), # Queue Trigger + gr.Button.update(interactive=True if len(gl.download_queue) > 1 else False) # Cancel All Button + ) + +def remove_from_queue(dl_id): + global total_count + for item in gl.download_queue: + if int(dl_id) == int(item['dl_id']): + gl.download_queue.remove(item) + total_count -= 1 + return + +def arrange_queue(input): + id_and_index = input.split('.') + dl_id = int(id_and_index[0]) + index = int(id_and_index[1]) + 1 + for item in gl.download_queue: + if int(item['dl_id']) == dl_id: + current_item = gl.download_queue.pop(gl.download_queue.index(item)) + gl.download_queue.insert(index, current_item) + break + +def get_style(size, left_border): + return f"flex-grow: {size};" + ("border-left: 1px solid var(--border-color-primary);" if left_border else "") + "padding: 5px 10px 5px 10px;width: 0;align-self: center;" + +def download_manager_html(current_html): + html = current_html.rsplit("", 1)[0] + pattern = r'dl_id="(\d+)"' + matches = re.findall(pattern, html) + existing_item_ids = [int(match) for match in matches] + + for item in gl.download_queue: + if not item['dl_id'] in existing_item_ids: + download_item = f''' +
+
{item['model_name']}
+
{item['version_name']}
+
{item['install_path']}
+
In queue...
+
Remove
+
+ ''' + html = html + download_item + + html = html + "" + + return html \ No newline at end of file diff --git a/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_file_manage.py b/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_file_manage.py new file mode 100644 index 0000000000000000000000000000000000000000..709dd884b1aa2d316c285ba2c9579965d6b82120 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_file_manage.py @@ -0,0 +1,1289 @@ +import json +import gradio as gr +import urllib.request +import urllib.parse +import urllib.error +import os +import io +import re +import time +import errno +import requests +import hashlib +import base64 +from PIL import Image +from pathlib import Path +from urllib.parse import urlparse +from modules.shared import cmd_opts, opts +from scripts.civitai_global import print, debug_print +import scripts.civitai_global as gl +import scripts.civitai_api as _api +import scripts.civitai_file_manage as _file +import scripts.civitai_download as _download + +try: + from send2trash import send2trash +except ImportError: + print("Python module 'send2trash' has not been imported correctly, please try to restart or install it manually.") +try: + from bs4 import BeautifulSoup +except ImportError: + print("Python module 'BeautifulSoup' has not been imported correctly, please try to restart or install it manually.") + +gl.init() + +css_path = Path(__file__).resolve().parents[1] / "style_html.css" +no_update = False +from_ver = False +from_tag = False +from_installed = False +try: + queue = not cmd_opts.no_gradio_queue +except AttributeError: + queue = not cmd_opts.disable_queue +except: + queue = True + +def delete_model(delete_finish=None, model_filename=None, model_string=None, list_versions=None, sha256=None, selected_list=None, model_ver=None, model_json=None): + deleted = False + model_id = None + + if model_string: + _, model_id = _api.extract_model_info(model_string) + + if not model_ver: + model_versions = _api.update_model_versions(model_id) + else: model_versions = model_ver + + (model_name, ver_value, ver_choices) = _file.card_update(model_versions, model_string, list_versions, False) + if not model_json: + if model_id != None: + selected_content_type = None + for item in gl.json_data['items']: + if int(item['id']) == int(model_id): + selected_content_type = item['type'] + desc = item['description'] + break + + if selected_content_type is None: + print("Model ID not found in json_data. (delete_model)") + return + else: + for item in model_json["items"]: + selected_content_type = item['type'] + desc = item['description'] + + model_folder = os.path.join(_api.contenttype_folder(selected_content_type, desc)) + + # Delete based on provided SHA-256 hash + if sha256: + sha256_upper = sha256.upper() + for root, _, files in os.walk(model_folder, followlinks=True): + for file in files: + if file.endswith('.json'): + file_path = os.path.join(root, file) + try: + with open(file_path, 'r', encoding="utf-8") as json_file: + data = json.load(json_file) + file_sha256 = data.get('sha256', '') + if file_sha256: + file_sha256 = file_sha256.upper() + except Exception as e: + print(f"Failed to open: {file_path}: {e}") + file_sha256 = "0" + + if file_sha256 == sha256_upper: + unpack_list = data.get('unpackList', []) + for unpacked_file in unpack_list: + unpacked_file_path = os.path.join(root, unpacked_file) + if os.path.isfile(unpacked_file_path): + try: + send2trash(unpacked_file_path) + print(f"File moved to trash based on unpackList: {unpacked_file_path}") + except: + os.remove(unpacked_file_path) + print(f"File deleted based on unpackList: {unpacked_file_path}") + + base_name, _ = os.path.splitext(file) + if os.path.isfile(file_path): + try: + send2trash(file_path) + print(f"Model moved to trash based on SHA-256: {file_path}") + except: + os.remove(file_path) + print(f"Model deleted based on SHA-256: {file_path}") + delete_associated_files(root, base_name) + deleted = True + + # Fallback to delete based on filename if not deleted based on SHA-256 + filename_to_delete = os.path.splitext(model_filename)[0] + aria2_file = model_filename + ".aria2" + if not deleted: + for root, dirs, files in os.walk(model_folder, followlinks=True): + for file in files: + current_file_name = os.path.splitext(file)[0] + if filename_to_delete == current_file_name or aria2_file == file: + path_file = os.path.join(root, file) + if os.path.isfile(path_file): + try: + send2trash(path_file) + print(f"Model moved to trash based on filename: {path_file}") + except: + os.remove(path_file) + print(f"Model deleted based on filename: {path_file}") + delete_associated_files(root, current_file_name) + + number = _download.random_number(delete_finish) + + + btnDwn = not selected_list or selected_list == "[]" + + return ( + gr.Button.update(interactive=btnDwn, visible=btnDwn), # Download Button + gr.Button.update(interactive=False, visible=False), # Cancel Button + gr.Button.update(interactive=False, visible=False), # Delete Button + gr.Textbox.update(value=number), # Delete Finish Trigger + gr.Textbox.update(value=model_name), # Current Model + gr.Dropdown.update(value=ver_value, choices=ver_choices) # Version List + ) + +def delete_associated_files(directory, base_name): + for file in os.listdir(directory): + current_base_name, ext = os.path.splitext(file) + if current_base_name == base_name or current_base_name == f"{base_name}.preview" or current_base_name == f"{base_name}.api_info": + path_to_delete = os.path.join(directory, file) + try: + send2trash(path_to_delete) + print(f"Associated file moved to trash: {path_to_delete}") + except: + os.remove(path_to_delete) + print(f"Associated file deleted: {path_to_delete}") + +def save_preview(file_path, api_response, overwrite_toggle=False, sha256=None): + proxies, ssl = _api.get_proxies() + json_file = os.path.splitext(file_path)[0] + ".json" + install_path, file_name = os.path.split(file_path) + name = os.path.splitext(file_name)[0] + filename = f'{name}.preview.png' + image_path = os.path.join(install_path, filename) + + if not overwrite_toggle: + if os.path.exists(image_path): + return + + if not sha256: + if os.path.exists(json_file): + try: + with open(json_file, 'r', encoding="utf-8") as f: + data = json.load(f) + if 'sha256' in data and data['sha256']: + sha256 = data['sha256'].upper() + except Exception as e: + print(f"Failed to open {json_file}: {e}") + else: + sha256 = sha256.upper() + + for item in api_response["items"]: + for version in item["modelVersions"]: + for file_entry in version["files"]: + if file_entry["hashes"].get("SHA256") == sha256: + for image in version["images"]: + if image["type"] == "image": + url_with_width = re.sub(r'/width=\d+', f'/width={image["width"]}', image["url"]) + + response = requests.get(url_with_width, proxies=proxies, verify=ssl) + if response.status_code == 200: + with open(image_path, 'wb') as img_file: + img_file.write(response.content) + print(f"Preview saved at \"{image_path}\"") + else: + print(f"Failed to save preview. Status code: {response.status_code}") + + return + print(f"No preview images found for \"{name}\"") + return + +def get_image_path(install_path, api_response, sub_folder): + image_location = getattr(opts, "image_location", r"") + sub_image_location = getattr(opts, "sub_image_location", True) + image_path = install_path + if api_response: + json_info = api_response['items'][0] + else: + json_info = gl.json_info + if image_location: + if sub_image_location: + desc = json_info['description'] + content_type = json_info['type'] + image_path = os.path.join(_api.contenttype_folder(content_type, desc, custom_folder=image_location)) + + if sub_folder and sub_folder != "None" and sub_folder != "Only available if the selected files are of the same model type": + image_path = os.path.join(image_path, sub_folder.lstrip("/").lstrip("\\")) + else: + image_path = Path(image_location) + make_dir(image_path) + return image_path + +def save_images(preview_html, model_filename, install_path, sub_folder, api_response=None): + image_path = get_image_path(install_path, api_response, sub_folder) + img_urls = re.findall(r'data-sampleimg="true" src=[\'"]?([^\'" >]+)', preview_html) + + name = os.path.splitext(model_filename)[0] + + opener = urllib.request.build_opener() + opener.addheaders = [('User-agent', 'Mozilla/5.0')] + urllib.request.install_opener(opener) + + for i, img_url in enumerate(img_urls): + filename = f'{name}_{i}.jpg' + img_url = urllib.parse.quote(img_url, safe=':/=') + try: + with urllib.request.urlopen(img_url) as url: + with open(os.path.join(image_path, filename), 'wb') as f: + f.write(url.read()) + print(f"Downloaded {filename}") + + except urllib.error.URLError as e: + print(f'Error: {e.reason}') + +def card_update(gr_components, model_name, list_versions, is_install): + if gr_components: + version_choices = gr_components['choices'] + else: + print("Couldn't retrieve version, defaulting to installed") + model_name += ".New" + return model_name, None, None + + if is_install and not gl.download_fail and not gl.cancel_status: + version_value_clean = list_versions + " [Installed]" + version_choices_clean = [version if version + " [Installed]" != version_value_clean else version_value_clean for version in version_choices] + + else: + version_value_clean = list_versions.replace(" [Installed]", "") + version_choices_clean = [version if version.replace(" [Installed]", "") != version_value_clean else version_value_clean for version in version_choices] + + first_version_installed = "[Installed]" in version_choices_clean[0] + any_later_version_installed = any("[Installed]" in version for version in version_choices_clean[1:]) + + if first_version_installed: + model_name += ".New" + elif any_later_version_installed: + model_name += ".Old" + else: + model_name += ".None" + + return model_name, version_value_clean, version_choices_clean + +def list_files(folders): + model_files = [] + + extensions = ['.pt', '.ckpt', '.pth', '.safetensors', '.th', '.zip', '.vae'] + + for folder in folders: + if folder and os.path.exists(folder): + for root, _, files in os.walk(folder, followlinks=True): + for file in files: + _, file_extension = os.path.splitext(file) + if file_extension.lower() in extensions: + model_files.append(os.path.join(root, file)) + + model_files = sorted(list(set(model_files))) + return model_files + +def gen_sha256(file_path): + json_file = os.path.splitext(file_path)[0] + ".json" + + if os.path.exists(json_file): + try: + with open(json_file, 'r', encoding="utf-8") as f: + data = json.load(f) + + if 'sha256' in data and data['sha256']: + hash_value = data['sha256'] + return hash_value + except Exception as e: + print(f"Failed to open {json_file}: {e}") + + def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE): + while True: + chunk = file.read(size) + if not chunk: + break + yield chunk + + blocksize = 1 << 20 + h = hashlib.sha256() + length = 0 + with open(os.path.realpath(file_path), 'rb') as f: + for block in read_chunks(f, size=blocksize): + length += len(block) + h.update(block) + + hash_value = h.hexdigest() + + if os.path.exists(json_file): + try: + with open(json_file, 'r', encoding="utf-8") as f: + data = json.load(f) + + if 'sha256' in data and data['sha256']: + data['sha256'] = hash_value + + with open(json_file, 'w', encoding="utf-8") as f: + json.dump(data, f, indent=4) + except Exception as e: + print(f"Failed to open {json_file}: {e}") + else: + data = {'sha256': hash_value} + with open(json_file, 'w', encoding="utf-8") as f: + json.dump(data, f, indent=4) + + return hash_value + +def convert_local_images(html): + soup = BeautifulSoup(html) + for simg in soup.find_all("img", attrs={"data-sampleimg": "true"}): + url = urlparse(simg["src"]) + path = url.path + if not os.path.exists(path): + print("URL path does not exist: %s" % url.path) + # Try the raw url, files can be saved in windows as "C:\..." and + # that confuses urlparse because people only really test on Linux. + if os.path.exists(simg["src"]): + path = simg["src"] + else: + continue + with open(path, 'rb') as f: + imgdata = f.read() + b64img = base64.b64encode(imgdata).decode('utf-8') + imgtype = Image.open(io.BytesIO(imgdata)).format + if not imgtype: + imgtype = "PNG" + simg["src"] = f"data:image/{imgtype};base64,{b64img}" + return str(soup) + +def model_from_sent(model_name, content_type): + modelID_failed = False + output_html = None + model_file = None + use_local_html = getattr(opts, "use_local_html", False) + local_path_in_html = getattr(opts, "local_path_in_html", False) + + model_name = re.sub(r'\.\d{3}$', '', model_name) + content_type = re.sub(r'\.\d{3}$', '', content_type).lower() + if 'inversion' in content_type: + content_type = ['TextualInversion'] + elif 'hypernetwork' in content_type: + content_type = ['Hypernetwork'] + elif 'checkpoint' in content_type: + content_type = ['Checkpoint'] + elif 'lora' in content_type: + content_type = ['LORA', 'LoCon'] + + extensions = ['.pt', '.ckpt', '.pth', '.safetensors', '.th', '.zip', '.vae'] + + for content_type_item in content_type: + folder = _api.contenttype_folder(content_type_item) + for folder_path, _, files in os.walk(folder, followlinks=True): + for file in files: + if file.startswith(model_name) and file.endswith(tuple(extensions)): + model_file = os.path.join(folder_path, file) + + if not model_file: + output_html = _api.api_error_msg("path_not_found") + print(f'Error: Could not find model path for model: "{model_name}"') + print(f'Content type: "{content_type}"') + print(f'Main folder path: "{folder}"') + use_local_html = False + + if use_local_html: + html_file = os.path.splitext(model_file)[0] + ".html" + if os.path.exists(html_file): + with open(html_file, 'r', encoding='utf-8') as html: + output_html = html.read() + index = output_html.find("") + if index != -1: + output_html = output_html[index + len(""):] + if local_path_in_html: + output_html = convert_local_images(output_html) + + if not output_html: + modelID = get_models(model_file, True) + if not modelID or modelID == "Model not found": + output_html = _api.api_error_msg("not_found") + modelID_failed = True + if modelID == "offline": + output_html = _api.api_error_msg("offline") + modelID_failed = True + if not modelID_failed: + json_data = _api.request_civit_api(f"https://civitai.com/api/v1/models?ids={modelID}&nsfw=true") + else: + json_data = None + + if not isinstance(json_data, dict): + output_html = _api.api_error_msg(json_data) + else: + model_versions = _api.update_model_versions(modelID, json_data) + output_html = _api.update_model_info(None, model_versions.get('value'), True, modelID, json_data, True) + + css_path = Path(__file__).resolve().parents[1] / "style_html.css" + with open(css_path, 'r', encoding='utf-8') as css_file: + css = css_file.read() + replacements = { + '#0b0f19': 'var(--neutral-950)', + '#F3F4F6': 'var(--body-text-color)', + 'white': 'var(--body-text-color)', + '#80a6c8': 'var(--secondary-300)', + '#60A5FA': 'var(--link-text-color-hover)', + '#1F2937': 'var(--neutral-700)', + '#1F2937': 'var(--button-secondary-background-fill-hover)', + '#374151': 'var(--input-border-color)', + '#111827': 'var(--neutral-800)', + '#111827': 'var(--button-secondary-background-fill)', + 'top: 50%;': '', + 'padding-top: 0px;': 'padding-top: 475px;', + '.civitai_txt2img': '.civitai_placeholder' + } + + for old, new in replacements.items(): + css = css.replace(old, new) + + style_tag = f'' + head_section = f'{style_tag}' + + output_html = output_html.replace('display:flex;align-items:flex-start;', 'display:flex;align-items:flex-start;flex-wrap:wrap;justify-content:center;') + output_html = str(head_section + output_html) + output_html = output_html.replace('zoom-radio', 'zoom-preview-radio') + output_html = output_html.replace('zoomRadio', 'zoomPreviewRadio') + output_html = output_html.replace('zoom-overlay', 'zoom-preview-overlay') + output_html = output_html.replace('resetZoom', 'resetPreviewZoom') + + debug_print(output_html) + + number = _download.random_number() + + return ( + gr.Textbox.update(value=output_html, placeholder=number), # Preview HTML + ) + +def send_to_browser(model_name, content_type, click_first_item): + modelID_failed = False + output_html = None + model_file = None + number = click_first_item + + model_name = re.sub(r'\.\d{3}$', '', model_name) + content_type = re.sub(r'\.\d{3}$', '', content_type).lower() + if 'inversion' in content_type: + content_type = ['TextualInversion'] + elif 'hypernetwork' in content_type: + content_type = ['Hypernetwork'] + elif 'checkpoint' in content_type: + content_type = ['Checkpoint'] + elif 'lora' in content_type: + content_type = ['LORA', 'LoCon'] + extensions = ['.pt', '.ckpt', '.pth', '.safetensors', '.th', '.zip', '.vae'] + + for content_type_item in content_type: + folder = _api.contenttype_folder(content_type_item) + for folder_path, _, files in os.walk(folder, followlinks=True): + for file in files: + if file.startswith(model_name) and file.endswith(tuple(extensions)): + model_file = os.path.join(folder_path, file) + + if not model_file: + output_html = _api.api_error_msg("path_not_found") + print(f'Error: Could not find model path for model: "{model_name}"') + print(f'Content type: "{content_type}"') + print(f'Main folder path: "{folder}"') + if not output_html: + modelID = get_models(model_file, True) + if not modelID or modelID == "Model not found": + output_html = _api.api_error_msg("not_found") + modelID_failed = True + if modelID == "offline": + output_html = _api.api_error_msg("offline") + modelID_failed = True + + if not modelID_failed: + gl.json_data = _api.request_civit_api(f"https://civitai.com/api/v1/models?ids={modelID}&nsfw=true") + output_html = _api.model_list_html(gl.json_data) + + number = _download.random_number(click_first_item) + + return ( + gr.Textbox.update(value=output_html), # Card HTML + gr.Button.update(interactive=False), # Prev Button + gr.Button.update(interactive=False), # Next Button + gr.Slider.update(value=1, maximum=1), # Page Slider + gr.Textbox.update(value=number) # Click first card trigger + ) + +def convertCustomFolder(folderValue, basemodel, nsfw, author, modelName, modelId, versionName, versionId): + replacements = { + "BASEMODEL": _api.cleaned_name(str(basemodel)), + "AUTHOR": _api.cleaned_name(str(author)), + "MODELNAME": _api.cleaned_name(str(modelName)), + "MODELID": _api.cleaned_name(str(modelId)), + "VERSIONNAME": _api.cleaned_name(str(versionName)), + "VERSIONID": _api.cleaned_name(str(versionId)) + } + + if not nsfw: + segments = folderValue.split(os.sep) + segments = [seg for seg in segments if "{NSFW}" not in seg] + folderValue = os.sep.join(segments) + else: + replacements["NSFW"] = "nsfw" + + formatted_value = folderValue.format(**replacements) + + converted_folder = formatted_value.replace('/', os.sep).replace('\\', os.sep) + converted_folder = os.sep.join(part for part in converted_folder.split(os.sep) if part) + + if not converted_folder.startswith(os.sep): + converted_folder = os.sep + converted_folder + + return converted_folder + +def getSubfolders(model_folder, basemodel=None, nsfw=None, author=None, modelName=None, modelId=None, versionName=None, versionId=None): + try: + dot_subfolders = getattr(opts, "dot_subfolders", True) + sub_folders = ["None"] + for root, dirs, _ in os.walk(model_folder, followlinks=True): + if dot_subfolders: + dirs = [d for d in dirs if not d.startswith('.')] + dirs = [d for d in dirs if not any(part.startswith('.') for part in os.path.join(root, d).split(os.sep))] + for d in dirs: + sub_folder = os.path.relpath(os.path.join(root, d), model_folder) + if sub_folder: + if not sub_folder.startswith(os.sep): + sub_folder = os.sep + sub_folder + sub_folders.append(sub_folder) + + with open(gl.subfolder_json, 'r') as json_file: + config_data = json.load(json_file) + + for key, value in config_data.items(): + if basemodel: + try: + converted_value = convertCustomFolder(value, basemodel, nsfw, author, modelName, modelId, versionName, versionId) + sub_folders.append(converted_value) + except Exception as e: + print(f"Error: Failed to process custom subfolder: {e}") + else: + upper_value = value.upper() + if not upper_value.startswith(os.sep): + upper_value = os.sep + upper_value + sub_folders.append(upper_value) + + sub_folders.remove("None") + sub_folders = sorted(sub_folders, key=lambda x: (x.lower(), x)) + sub_folders.insert(0, "None") + + except Exception as e: + print(e) + sub_folders = ["None"] + + list = set() + sub_folders = [x for x in sub_folders if not (x in list or list.add(x))] + + return sub_folders + +def updateSubfolder(subfolderInput): + with open(gl.subfolder_json, 'r') as f: + data = json.load(f) + + index, action, value = subfolderInput.split('.', 2) + index = str(index) + + if action == "delete": + data.pop(index, None) + elif action == "add": + data[index] = value + + with open(gl.subfolder_json, 'w') as f: + json.dump(data, f, indent=4) + +def is_image_url(url): + image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp'] + parsed = urlparse(url) + path = parsed.path + return any(path.endswith(ext) for ext in image_extensions) + +def clean_description(desc): + try: + soup = BeautifulSoup(desc, 'html.parser') + for a in soup.find_all('a', href=True): + link_text = a.text + ' ' + a['href'] + if not is_image_url(a['href']): + a.replace_with(link_text) + + cleaned_text = soup.get_text() + except ImportError: + print("Python module 'BeautifulSoup' was not imported correctly, cannot clean description. Please try to restart or install it manually.") + cleaned_text = desc + return cleaned_text + +def make_dir(path): + try: + if not os.path.exists(path): + os.makedirs(path) + except OSError as e: + if e.errno == errno.EACCES: + try: + os.makedirs(path, mode=0o777) + except OSError as e: + if e.errno == errno.EACCES: + print("Permission denied even with elevated permissions.") + else: + print(f"Error creating directory: {e}") + else: + print(f"Error creating directory: {e}") + except Exception as e: + print(f"Error creating directory: {e}") + +def save_model_info(install_path, file_name, sub_folder, sha256=None, preview_html=None, overwrite_toggle=False, api_response=None): + save_path, filename = get_save_path_and_name(install_path, file_name, api_response, sub_folder) + image_path = get_image_path(install_path, api_response, sub_folder) + json_file = os.path.join(install_path, f'{filename}.json') + make_dir(install_path) + + save_api_info = getattr(opts, "save_api_info", False) + use_local = getattr(opts, "local_path_in_html", False) + + if not api_response: + api_response = gl.json_data + + result = find_and_save(api_response, sha256, file_name, json_file, False, overwrite_toggle) + if result != "found": + result = find_and_save(api_response, sha256, file_name, json_file, True, overwrite_toggle) + + if preview_html: + if use_local: + img_urls = re.findall(r'data-sampleimg="true" src=[\'"]?([^\'" >]+)', preview_html) + for i, img_url in enumerate(img_urls): + img_name = f'{filename}_{i}.jpg' + preview_html = preview_html.replace(img_url,f'{os.path.join(image_path, img_name)}') + + match = re.search(r'(\s*)
', preview_html) + if match: + indentation = match.group(1) + else: + indentation = '' + css_link = f'' + utf8_meta_tag = f'{indentation}' + head_section = f'{indentation}{indentation} {utf8_meta_tag}{indentation} {css_link}{indentation}' + HTML = head_section + preview_html + path_to_new_file = os.path.join(save_path, f'{filename}.html') + with open(path_to_new_file, 'wb') as f: + f.write(HTML.encode('utf8')) + print(f"HTML saved at \"{path_to_new_file}\"") + + if save_api_info: + path_to_new_file = os.path.join(save_path, f'{filename}.api_info.json') + if not os.path.exists(path_to_new_file) or overwrite_toggle: + with open(path_to_new_file, mode="w", encoding="utf-8") as f: + json.dump(gl.json_info, f, indent=4, ensure_ascii=False) + + +def find_and_save(api_response, sha256=None, file_name=None, json_file=None, no_hash=None, overwrite_toggle=None): + save_desc = getattr(opts, "model_desc_to_json", True) + for item in api_response.get('items', []): + for model_version in item.get('modelVersions', []): + for file in model_version.get('files', []): + file_name_api = file.get('name', '') + sha256_api = file.get('hashes', {}).get('SHA256', '') + + if file_name == file_name_api if no_hash else sha256 == sha256_api: + gl.json_info = item + trained_words = model_version.get('trainedWords', []) + + if save_desc: + description = item.get('description', '') + if description != None: + description = clean_description(description) + + base_model = model_version.get('baseModel', '') + + if base_model.startswith("SD 1"): + base_model = "SD1" + elif base_model.startswith("SD 2"): + base_model = "SD2" + elif base_model.startswith("SDXL"): + base_model = "SDXL" + else: + base_model = "Other" + + if isinstance(trained_words, list): + trained_tags = ",".join(trained_words) + trained_tags = re.sub(r'<[^>]*:[^>]*>', '', trained_tags) + trained_tags = re.sub(r', ?', ', ', trained_tags) + trained_tags = trained_tags.strip(', ') + else: + trained_tags = trained_words + + if os.path.exists(json_file): + with open(json_file, 'r', encoding="utf-8") as f: + try: + content = json.load(f) + except: + content = {} + else: + content = {} + changed = False + if not overwrite_toggle: + if "activation text" not in content: + content["activation text"] = trained_tags + changed = True + if save_desc and ("description" not in content): + content["description"] = description + changed = True + if "sd version" not in content: + content["sd version"] = base_model + changed = True + else: + content["activation text"] = trained_tags + if save_desc: + content["description"] = description + content["sd version"] = base_model + changed = True + + with open(json_file, 'w', encoding="utf-8") as f: + json.dump(content, f, indent=4) + + if changed: + print(f"Model info saved to \"{json_file}\"") + return "found" + + return "not found" + +def get_models(file_path, gen_hash=None): + modelId = None + modelVersionId = None + sha256 = None + json_file = os.path.splitext(file_path)[0] + ".json" + if os.path.exists(json_file): + try: + with open(json_file, 'r', encoding="utf-8") as f: + data = json.load(f) + + if 'modelId' in data: + modelId = data['modelId'] + if 'modelVersionId' in data: + modelVersionId = data['modelVersionId'] + if 'sha256' in data and data['sha256']: + sha256 = data['sha256'] + except Exception as e: + print(f"Failed to open {json_file}: {e}") + + if not modelId or not modelVersionId or not sha256: + if not sha256 and gen_hash: + sha256 = gen_sha256(file_path) + + if sha256: + by_hash = f"https://civitai.com/api/v1/model-versions/by-hash/{sha256}" + else: + return modelId if modelId else None + + proxies, ssl = _api.get_proxies() + try: + if not modelId or not modelVersionId: + response = requests.get(by_hash, timeout=(60,30), proxies=proxies, verify=ssl) + if response.status_code == 200: + api_response = response.json() + if 'error' in api_response: + print(f"\"{file_path}\": {api_response['error']}") + return None + else: + modelId = api_response.get("modelId", "") + modelVersionId = api_response.get("id", "") + elif response.status_code == 503: + return "offline" + elif response.status_code == 404: + modelId = "Model not found" + modelVersionId = "Model not found" + + if os.path.exists(json_file): + try: + with open(json_file, 'r', encoding="utf-8") as f: + data = json.load(f) + + data['modelId'] = modelId + data['modelVersionId'] = modelVersionId + data['sha256'] = sha256.upper() + + with open(json_file, 'w', encoding="utf-8") as f: + json.dump(data, f, indent=4) + except Exception as e: + print(f"Failed to open {json_file}: {e}") + else: + data = { + 'modelId': modelId, + 'modelVersionId': modelVersionId, + 'sha256': sha256.upper() + } + with open(json_file, 'w', encoding="utf-8") as f: + json.dump(data, f, indent=4) + + return modelId + except requests.exceptions.Timeout: + print(f"Request timed out for {file_path}. Skipping...") + return "offline" + except requests.exceptions.ConnectionError: + print("Failed to connect to the API. The CivitAI servers might be offline.") + return "offline" + except Exception as e: + print(f"An error occurred for {file_path}: {str(e)}") + return None + +def version_match(file_paths, api_response): + updated_models = [] + outdated_models = [] + sha256_hashes = {} + for file_path in file_paths: + json_path = f"{os.path.splitext(file_path)[0]}.json" + if os.path.exists(json_path): + with open(json_path, 'r', encoding="utf-8") as f: + try: + json_data = json.load(f) + sha256 = json_data.get('sha256') + if sha256: + sha256_hashes[os.path.basename(file_path)] = sha256.upper() + except Exception as e: + print(f"Failed to open {json_path}: {e}") + + file_names_and_hashes = set() + for file_path in file_paths: + file_name = os.path.basename(file_path) + file_name_without_ext = os.path.splitext(file_name)[0] + file_sha256 = sha256_hashes.get(file_name, "") + if file_sha256: file_sha256 = file_sha256.upper() + file_names_and_hashes.add((file_name_without_ext, file_sha256)) + + for item in api_response.get('items', []): + model_versions = item.get('modelVersions', []) + + if not model_versions: + continue + + for idx, model_version in enumerate(model_versions): + files = model_version.get('files', []) + match_found = False + for file_entry in files: + entry_name = os.path.splitext(file_entry.get('name', ''))[0] + entry_sha256 = file_entry.get('hashes', {}).get('SHA256', "") + if entry_sha256: entry_sha256 = entry_sha256.upper() + + if (entry_name, entry_sha256) in file_names_and_hashes: + match_found = True + break + + if match_found: + if idx == 0: + updated_models.append((f"&ids={item['id']}", item["name"])) + else: + outdated_models.append((f"&ids={item['id']}", item["name"])) + break + + return updated_models, outdated_models + +def get_content_choices(scan_choices=False): + use_LORA = getattr(opts, "use_LORA", False) + if use_LORA: + content_list = ["Checkpoint", "TextualInversion", "LORA, LoCon, DoRA", "Poses", "Controlnet", "Hypernetwork", "AestheticGradient", "VAE", "Upscaler", "MotionModule", "Wildcards", "Workflows", "Other"] + else: + content_list = ["Checkpoint", "TextualInversion", "LORA", "LoCon", "DoRA", "Poses", "Controlnet", "Hypernetwork", "AestheticGradient", "VAE", "Upscaler", "MotionModule", "Wildcards", "Workflows", "Other"] + if scan_choices: + content_list.insert(0, 'All') + return content_list + return content_list + +def get_save_path_and_name(install_path, file_name, api_response, sub_folder=None): + save_to_custom = getattr(opts, "save_to_custom", False) + + name = os.path.splitext(file_name)[0] + if not sub_folder: + sub_folder = os.path.normpath(os.path.relpath(install_path, gl.main_folder)) + image_path = _file.get_image_path(install_path, api_response, sub_folder) + + if save_to_custom: + save_path = image_path + else: + save_path = install_path + + return save_path, name + +def file_scan(folders, ver_finish, tag_finish, installed_finish, preview_finish, overwrite_toggle, tile_count, gen_hash, create_html, progress=gr.Progress() if queue else None): + global no_update + proxies, ssl = _api.get_proxies() + gl.scan_files = True + no_update = False + if from_ver: + number = _download.random_number(ver_finish) + elif from_tag: + number = _download.random_number(tag_finish) + elif from_installed: + number = _download.random_number(installed_finish) + elif from_preview: + number = _download.random_number(preview_finish) + + if not folders: + if progress != None: + progress(0, desc=f"No model type selected.") + no_update = True + gl.scan_files = False + time.sleep(2) + return (gr.HTML.update(value='
'), + gr.Textbox.update(value=number)) + + folders_to_check = [] + if 'All' in folders: + folders = _file.get_content_choices() + + for item in folders: + if item == "LORA, LoCon, DoRA": + folder = _api.contenttype_folder("LORA") + if folder: + folders_to_check.append(folder) + folder = _api.contenttype_folder("LoCon", fromCheck=True) + if folder: + folders_to_check.append(folder) + folder = _api.contenttype_folder("DoRA") + if folder: + folders_to_check.append(folder) + elif item == "Upscaler": + folder = _api.contenttype_folder(item, "SwinIR") + if folder: + folders_to_check.append(folder) + folder = _api.contenttype_folder(item, "RealESRGAN") + if folder: + folders_to_check.append(folder) + folder = _api.contenttype_folder(item, "GFPGAN") + if folder: + folders_to_check.append(folder) + folder = _api.contenttype_folder(item, "BSRGAN") + if folder: + folders_to_check.append(folder) + folder = _api.contenttype_folder(item, "ESRGAN") + if folder: + folders_to_check.append(folder) + else: + folder = _api.contenttype_folder(item) + if folder: + folders_to_check.append(folder) + + total_files = 0 + files_done = 0 + + files = list_files(folders_to_check) + total_files += len(files) + + if total_files == 0: + if progress != None: + progress(1, desc=f"No files in selected folder.") + no_update = True + gl.scan_files = False + time.sleep(2) + return (gr.HTML.update(value='
'), + gr.Textbox.update(value=number)) + + updated_models = [] + outdated_models = [] + all_model_ids = [] + file_paths = [] + all_ids = [] + + not_found_print = getattr(opts, "civitai_not_found_print", True) + + for file_path in files: + if gl.cancel_status: + if progress != None: + progress(files_done / total_files, desc=f"Processing files cancelled.") + no_update = True + gl.scan_files = False + time.sleep(2) + return (gr.HTML.update(value='
'), + gr.Textbox.update(value=number)) + file_name = os.path.basename(file_path) + if progress != None: + progress(files_done / total_files, desc=f"Processing file: {file_name}") + + model_id = get_models(file_path, gen_hash) + if model_id == "offline": + print("The CivitAI servers did not respond, unable to retrieve Model ID") + elif model_id == "Model not found": + if not_found_print: + print(f"model: \"{file_name}\" not found on CivitAI servers.") + elif model_id != None: + all_model_ids.append(f"&ids={model_id}") + all_ids.append(model_id) + file_paths.append(file_path) + elif not model_id: + print(f"model ID not found for: \"{file_name}\"") + files_done += 1 + + all_items = [] + + all_model_ids = list(set(all_model_ids)) + + if not all_model_ids: + progress(1, desc=f"No model IDs could be retrieved.") + print("Could not retrieve any Model IDs, please make sure to turn on the \"One-Time Hash Generation for externally downloaded models.\" option if you haven't already.") + no_update = True + gl.scan_files = False + time.sleep(2) + return (gr.HTML.update(value='
'), + gr.Textbox.update(value=number)) + + def chunks(lst, n): + for i in range(0, len(lst), n): + yield lst[i:i + n] + + if not from_installed: + model_chunks = list(chunks(all_model_ids, 500)) + + base_url = "https://civitai.com/api/v1/models?limit=100&nsfw=true" + url_list = [f"{base_url}{''.join(chunk)}" for chunk in model_chunks] + + url_count = len(all_model_ids) // 100 + if len(all_model_ids) % 100 != 0: + url_count += 1 + url_done = 0 + api_response = {} + for url in url_list: + while url: + try: + if progress is not None: + progress(url_done / url_count, desc=f"Sending API request... {url_done}/{url_count}") + response = requests.get(url, timeout=(60,30), proxies=proxies, verify=ssl) + if response.status_code == 200: + api_response_json = response.json() + + all_items.extend(api_response_json['items']) + metadata = api_response_json.get('metadata', {}) + url = metadata.get('nextPage', None) + elif response.status_code == 503: + print(f"Error: Received status code: {response.status_code} with URL: {url}") + print(response.text) + return ( + gr.HTML.update(value=_api.api_error_msg("error")), + gr.Textbox.update(value=number) + ) + else: + print(f"Error: Received status code {response.status_code} with URL: {url}") + url = None + url_done += 1 + except requests.exceptions.Timeout: + print(f"Request timed out for {url}. Skipping...") + url = None + except requests.exceptions.ConnectionError: + print("Failed to connect to the API. The servers might be offline.") + url = None + except Exception as e: + print(f"An unexpected error occurred: {e}") + url = None + + api_response['items'] = all_items + if api_response['items'] == []: + return ( + gr.HTML.update(value=_api.api_error_msg("no_items")), + gr.Textbox.update(value=number) + ) + + if progress != None: + progress(1, desc="Processing final results...") + + if from_ver: + updated_models, outdated_models = version_match(file_paths, api_response) + + updated_set = set(updated_models) + outdated_set = set(outdated_models) + outdated_set = {model for model in outdated_set if model[0] not in {updated_model[0] for updated_model in updated_set}} + + all_model_ids = [model[0] for model in outdated_set] + all_model_names = [model[1] for model in outdated_set] + + for model_name in all_model_names: + print(f'"{model_name}" is currently outdated.') + + if len(all_model_ids) == 0: + no_update = True + gl.scan_files = False + return ( + gr.HTML.update(value='
No updates found for selected models.
'), + gr.Textbox.update(value=number) + ) + + model_chunks = list(chunks(all_model_ids, tile_count)) + + base_url = "https://civitai.com/api/v1/models?limit=100&nsfw=true" + gl.url_list = {i+1: f"{base_url}{''.join(chunk)}" for i, chunk in enumerate(model_chunks)} + + if from_ver: + gl.scan_files = False + return ( + gr.HTML.update(value='
Outdated models have been found.
Please press the button above to load the models into the browser tab
'), + gr.Textbox.update(value=number) + ) + + elif from_installed: + gl.scan_files = False + return ( + gr.HTML.update(value='
Installed models have been loaded.
Please press the button above to load the models into the browser tab
'), + gr.Textbox.update(value=number) + ) + + elif from_tag: + completed_tags = 0 + tag_count = len(file_paths) + + for file_path, id_value in zip(file_paths, all_ids): + install_path, file_name = os.path.split(file_path) + save_path, name = get_save_path_and_name(install_path, file_name, api_response) + model_versions = _api.update_model_versions(id_value, api_response) + html_path = os.path.join(save_path, f'{name}.html') + + if create_html and not os.path.exists(html_path) or create_html and overwrite_toggle: + preview_html = _api.update_model_info(None, model_versions.get('value'), True, id_value, api_response, True) + else: + preview_html = None + completed_tags += 1 + if progress != None: + progress(completed_tags / tag_count, desc=f'Saving tags{" & HTML" if preview_html else ""}... {completed_tags}/{tag_count} | {name}') + sub_folder = os.path.normpath(os.path.relpath(install_path, gl.main_folder)) + save_model_info(install_path, file_name, sub_folder, preview_html=preview_html, api_response=api_response, overwrite_toggle=overwrite_toggle) + if progress != None: + progress(1, desc=f"All tags succesfully saved!") + gl.scan_files = False + time.sleep(2) + return ( + gr.HTML.update(value='
'), + gr.Textbox.update(value=number) + ) + + elif from_preview: + completed_preview = 0 + preview_count = len(file_paths) + for file in file_paths: + _, file_name = os.path.split(file) + name = os.path.splitext(file_name)[0] + completed_preview += 1 + if progress != None: + progress(completed_preview / preview_count, desc=f"Saving preview images... {completed_preview}/{preview_count} | {name}") + save_preview(file, api_response, overwrite_toggle) + gl.scan_files = False + return ( + gr.HTML.update(value='
'), + gr.Textbox.update(value=number) + ) + +def finish_returns(): + return ( + gr.Button.update(interactive=True, visible=True), + gr.Button.update(interactive=True, visible=True), + gr.Button.update(interactive=True, visible=True), + gr.Button.update(interactive=True, visible=True), + gr.Button.update(interactive=True, visible=False), # Organize models hidden until implemented + gr.Button.update(interactive=False, visible=False) + ) + +def start_returns(number): + return ( + gr.Textbox.update(value=number), + gr.Button.update(interactive=False, visible=False), + gr.Button.update(interactive=True, visible=True), + gr.Button.update(interactive=False, visible=True), + gr.Button.update(interactive=False, visible=True), + gr.Button.update(interactive=False, visible=True), + gr.Button.update(interactive=False, visible=False), # Organize models hidden until implemented + gr.HTML.update(value='
') + ) + +def set_globals(input_global=None): + global from_tag, from_ver, from_installed, from_preview, from_organize + from_tag = from_ver = from_installed = from_preview = from_organize = False + if input_global == "reset": + return + elif input_global == "from_tag": + from_tag = True + elif input_global == "from_ver": + from_ver = True + elif input_global == "from_installed": + from_installed = True + elif input_global == "from_preview": + from_preview = True + elif input_global == "from_organize": + from_organize = True + +def save_tag_start(tag_start): + set_globals('from_tag') + number = _download.random_number(tag_start) + return start_returns(number) + +def save_preview_start(preview_start): + set_globals('from_preview') + number = _download.random_number(preview_start) + return start_returns(number) + +def installed_models_start(installed_start): + set_globals('from_installed') + number = _download.random_number(installed_start) + return start_returns(number) + +def ver_search_start(ver_start): + set_globals('from_ver') + number = _download.random_number(ver_start) + return start_returns(number) + +def organize_start(organize_start): + set_globals('from_organize') + number = _download.random_number(organize_start) + return start_returns(number) + +def save_tag_finish(): + set_globals("reset") + return finish_returns() + +def save_preview_finish(): + set_globals("reset") + return finish_returns() + +def scan_finish(): + set_globals("reset") + return ( + gr.Button.update(interactive=no_update, visible=no_update), + gr.Button.update(interactive=no_update, visible=no_update), + gr.Button.update(interactive=no_update, visible=no_update), + gr.Button.update(interactive=no_update, visible=no_update), + gr.Button.update(interactive=no_update, visible=False), + gr.Button.update(interactive=False, visible=False), + gr.Button.update(interactive=not no_update, visible=not no_update) + ) + +def load_to_browser(content_type, sort_type, period_type, use_search_term, search_term, tile_count, base_filter, nsfw): + global from_ver, from_installed + + model_list_return = _api.initial_model_page(content_type, sort_type, period_type, use_search_term, search_term, 1, base_filter, False, nsfw, tile_count, True) + from_ver, from_installed = False, False + return ( + *model_list_return, + gr.Button.update(interactive=True, visible=True), + gr.Button.update(interactive=True, visible=True), + gr.Button.update(interactive=True, visible=True), + gr.Button.update(interactive=True, visible=True), + gr.Button.update(interactive=False, visible=False), + gr.Button.update(interactive=False, visible=False), + gr.HTML.update(value='
') + ) + +def cancel_scan(): + gl.cancel_status = True + + while True: + if not gl.scan_files: + gl.cancel_status = False + return + else: + time.sleep(0.5) + continue diff --git a/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_global.py b/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_global.py new file mode 100644 index 0000000000000000000000000000000000000000..ab8ef3684a3355163f6da2238718834be0239d02 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_global.py @@ -0,0 +1,42 @@ +from modules.shared import opts +do_debug_print = getattr(opts, "civitai_debug_prints", False) +def init(): + import warnings, os, json + from urllib3.exceptions import InsecureRequestWarning + warnings.simplefilter('ignore', InsecureRequestWarning) + + config_folder = os.path.join(os.getcwd(), "config_states") + if not os.path.exists(config_folder): + os.mkdir(config_folder) + + global download_queue, last_version, cancel_status, recent_model, last_url, json_data, json_info, main_folder, previous_inputs, download_fail, sortNewest, isDownloading, old_download, scan_files, from_update_tab, url_list, print, subfolder_json + + cancel_status = None + recent_model = None + json_data = None + json_info = None + main_folder = None + previous_inputs = None + last_version = None + url_list = {} + download_queue = [] + + subfolder_json = os.path.join(config_folder, "civitai_subfolders.json") + if not os.path.exists(subfolder_json): + with open(subfolder_json, 'w') as json_file: + json.dump({}, json_file) + + from_update_tab = False + scan_files = False + download_fail = False + sortNewest = False + isDownloading = False + old_download = False + +_print = print +def print(print_message): + _print(f'\033[96mCivitAI Browser+\033[0m: {print_message}') + +def debug_print(print_message): + if do_debug_print: + _print(f'\033[96m[DEBUG] CivitAI Browser+\033[0m: {print_message}') \ No newline at end of file diff --git a/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_gui.py b/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_gui.py new file mode 100644 index 0000000000000000000000000000000000000000..c29258363ce8c5476ec4f97953a4b59ed12822e9 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/scripts/civitai_gui.py @@ -0,0 +1,1358 @@ +import gradio as gr +from modules import script_callbacks, shared +import os +import json +import fnmatch +import re +import subprocess +from modules.shared import opts, cmd_opts +from modules.paths import extensions_dir +from scripts.civitai_global import print, debug_print +import scripts.civitai_global as gl +import scripts.civitai_download as _download +import scripts.civitai_file_manage as _file +import scripts.civitai_api as _api + +def git_tag(): + try: + return subprocess.check_output([os.environ.get('GIT', "git"), "describe", "--tags"], shell=False, encoding='utf8').strip() + except: + return None + +try: + import modules_forge + forge = True + ver_bool = True +except ImportError: + forge = False + +if not forge: + try: + from packaging import version + ver = git_tag() + + if not ver: + try: + from modules import launch_utils + ver = launch_utils.git_tag() + except: + ver_bool = False + if ver: + ver = ver.split('-')[0].rsplit('-', 1)[0] + ver_bool = version.parse(ver[0:]) >= version.parse("1.7") + except ImportError: + print("Python module 'packaging' has not been imported correctly, please try to restart or install it manually.") + ver_bool = False + +gl.init() + +def saveSettings(ust, ct, pt, st, bf, cj, td, ol, hi, sn, ss, ts): + config = cmd_opts.ui_config_file + + # Create a dictionary to map the settings to their respective variables + settings_map = { + "civitai_interface/Search type:/value": ust, + "civitai_interface/Content type:/value": ct, + "civitai_interface/Time period:/value": pt, + "civitai_interface/Sort by:/value": st, + "civitai_interface/Base model:/value": bf, + "civitai_interface/Save info after download/value": cj, + "civitai_interface/Divide cards by date/value": td, + "civitai_interface/Liked models only/value": ol, + "civitai_interface/Hide installed models/value": hi, + "civitai_interface/NSFW content/value": sn, + "civitai_interface/Tile size:/value": ss, + "civitai_interface/Tile count:/value": ts + } + + # Load the current contents of the config file into a dictionary + try: + with open(config, "r", encoding="utf8") as file: + data = json.load(file) + except: + print(f"Cannot save settings, failed to open \"{file}\"") + print("Please try to manually repair the file or remove it to reset settings.") + return + + # Remove any keys containing the text `civitai_interface` + keys_to_remove = [key for key in data if "civitai_interface" in key] + for key in keys_to_remove: + del data[key] + + # Update the dictionary with the new settings + data.update(settings_map) + + # Save the modified content back to the file + with open(config, 'w', encoding="utf-8") as file: + json.dump(data, file, indent=4) + print(f"Updated settings to: {config}") + +def all_visible(html_check): + return gr.Button.update(visible="model-checkbox" in html_check) + +def HTMLChange(input): + return gr.HTML.update(value=input) + +def show_multi_buttons(model_list, type_list, version_value): + model_list = json.loads(model_list) + type_list = json.loads(type_list) + otherButtons = True + multi_file_subfolder = False + default_subfolder = "Only available if the selected files are of the same model type" + sub_folders = ["None"] + BtnDwn = version_value and not version_value.endswith('[Installed]') and not model_list + BtnDel = version_value.endswith('[Installed]') + + dot_subfolders = getattr(opts, "dot_subfolders", True) + + multi = bool(model_list) and not len(gl.download_queue) > 0 + if model_list: + otherButtons = False + if type_list and all(x == type_list[0] for x in type_list): + multi_file_subfolder = True + model_folder = os.path.join(_api.contenttype_folder(type_list[0])) + default_subfolder = "None" + try: + for root, dirs, _ in os.walk(model_folder, followlinks=True): + if dot_subfolders: + dirs = [d for d in dirs if not d.startswith('.')] + dirs = [d for d in dirs if not any(part.startswith('.') for part in os.path.join(root, d).split(os.sep))] + for d in dirs: + sub_folder = os.path.relpath(os.path.join(root, d), model_folder) + if sub_folder: + sub_folders.append(f'{os.sep}{sub_folder}') + sub_folders.remove("None") + sub_folders = sorted(sub_folders, key=lambda x: (x.lower(), x)) + sub_folders.insert(0, "None") + + list = set() + sub_folders = [x for x in sub_folders if not (x in list or list.add(x))] + except: + sub_folders = ["None"] + + return (gr.Button.update(visible=multi, interactive=multi), # Download Multi Button + gr.Button.update(visible=BtnDwn if multi else True if not version_value.endswith('[Installed]') else False), # Download Button + gr.Button.update(visible=BtnDel if not model_list else False), # Delete Button + gr.Button.update(visible=otherButtons), # Save model info Button + gr.Button.update(visible=otherButtons), # Save images Button + gr.Dropdown.update(visible=multi, interactive=multi_file_subfolder, choices=sub_folders, value=default_subfolder) # Selected type sub folder + ) + +def txt2img_output(image_url): + clean_url = image_url[4:] + geninfo = _api.fetch_and_process_image(clean_url) + if geninfo: + nr = _download.random_number() + geninfo = nr + geninfo + return gr.Textbox.update(value=geninfo) + +def get_base_models(): + api_url = 'https://civitai.com/api/v1/models?baseModels=GetModels' + json_return = _api.request_civit_api(api_url, True) + default_options = ["SD 1.4","SD 1.5","SD 1.5 LCM","SD 2.0","SD 2.0 768","SD 2.1","SD 2.1 768", + "SD 2.1 Unclip","SDXL 0.9","SDXL 1.0","SDXL 1.0 LCM","SDXL Distilled","SDXL Turbo","SDXL Lightning", + "Stable Cascade","Pony","SVD","SVD XT","Playground v2","PixArt a", "Flux.1 S", "Flux.1 D","Other"] + + if not isinstance(json_return, dict): + print("Couldn't fetch latest baseModel options, using default.") + return default_options + + try: + options = json_return['error']['issues'][0]['unionErrors'][0]['issues'][0]['options'] + return options + except (KeyError, IndexError) as e: + print(f"Basemodel fetch error extracting options: {e}") + return default_options + +def on_ui_tabs(): + page_header = getattr(opts, "page_header", False) + lobe_directory = None + + for root, dirs, files in os.walk(extensions_dir, followlinks=True): + for dir_name in fnmatch.filter(dirs, '*lobe*'): + lobe_directory = os.path.join(root, dir_name) + break + + # Different ID's for Lobe Theme + component_id = "togglesL" if lobe_directory else "toggles" + toggle1 = "toggle1L" if lobe_directory else "toggle1" + toggle2 = "toggle2L" if lobe_directory else "toggle2" + toggle3 = "toggle3L" if lobe_directory else "toggle3" + toggle5 = "toggle5L" if lobe_directory else "toggle5" + refreshbtn = "refreshBtnL" if lobe_directory else "refreshBtn" + filterBox = "filterBoxL" if lobe_directory else "filterBox" + + if page_header: + header = "headerL" if lobe_directory else "header" + else: + header = "header_off" + + api_key = getattr(opts, "custom_api_key", "") + if api_key: + toggle4 = "toggle4L_api" if lobe_directory else "toggle4_api" + show_only_liked = True + else: + toggle4 = "toggle4L" if lobe_directory else "toggle4" + show_only_liked = False + + content_choices = _file.get_content_choices() + scan_choices = _file.get_content_choices(scan_choices=True) + with gr.Blocks() as civitai_interface: + with gr.Tab(label="Browser", elem_id="browserTab"): + with gr.Row(elem_id="searchRow"): + with gr.Accordion(label="", open=False, elem_id=filterBox): + with gr.Row(): + use_search_term = gr.Radio(label="Search type:", choices=["Model name", "User name", "Tag"], value="Model name", elem_id="searchType") + with gr.Row(): + content_type = gr.Dropdown(label='Content type:', choices=content_choices, value=None, type="value", multiselect=True, elem_id="centerText") + with gr.Row(): + base_filter = gr.Dropdown(label='Base model:', multiselect=True, choices=get_base_models(), value=None, type="value", elem_id="centerText") + with gr.Row(): + period_type = gr.Dropdown(label='Time period:', choices=["All Time", "Year", "Month", "Week", "Day"], value="All Time", type="value", elem_id="centerText") + sort_type = gr.Dropdown(label='Sort by:', choices=["Newest","Oldest","Most Downloaded","Highest Rated","Most Liked","Most Buzz","Most Discussed","Most Collected","Most Images"], value="Most Downloaded", type="value", elem_id="centerText") + with gr.Row(elem_id=component_id): + create_json = gr.Checkbox(label=f"Save info after download", value=True, elem_id=toggle1, min_width=171) + show_nsfw = gr.Checkbox(label="NSFW content", value=False, elem_id=toggle2, min_width=107) + toggle_date = gr.Checkbox(label="Divide cards by date", value=False, elem_id=toggle3, min_width=142) + only_liked = gr.Checkbox(label="Liked models only", value=False, interactive=show_only_liked, elem_id=toggle4, min_width=163) + hide_installed = gr.Checkbox(label="Hide installed models", value=False, elem_id=toggle5, min_width=170) + with gr.Row(): + size_slider = gr.Slider(minimum=4, maximum=20, value=8, step=0.25, label='Tile size:') + tile_count_slider = gr.Slider(label="Tile count:", minimum=1, maximum=100, value=15, step=1) + with gr.Row(elem_id="save_set_box"): + save_settings = gr.Button(value="Save settings as default", elem_id="save_set_btn") + search_term = gr.Textbox(label="", placeholder="Search CivitAI", elem_id="searchBox") + refresh = gr.Button(value="", elem_id=refreshbtn, icon="placeholder") + with gr.Row(elem_id=header): + with gr.Row(elem_id="pageBox"): + get_prev_page = gr.Button(value="Prev page", interactive=False, elem_id="pageBtn1") + page_slider = gr.Slider(label='Current page:', step=1, minimum=1, maximum=1, min_width=80, elem_id="pageSlider") + get_next_page = gr.Button(value="Next page", interactive=False, elem_id="pageBtn2") + with gr.Row(elem_id="pageBoxMobile"): + pass # Row used for button placement on mobile + with gr.Row(elem_id="select_all_models_container"): + select_all = gr.Button(value="Select All", elem_id="select_all_models", visible=False) + with gr.Row(): + list_html = gr.HTML(value='
Click the search icon to load models.
Use the filter icon to filter results.
') + with gr.Row(): + download_progress = gr.HTML(value='
', elem_id="DownloadProgress") + with gr.Row(): + list_models = gr.Dropdown(label="Model:", choices=[], interactive=False, elem_id="quicksettings1", value=None) + list_versions = gr.Dropdown(label="Version:", choices=[], interactive=False, elem_id="quicksettings0", value=None) + file_list = gr.Dropdown(label="File:", choices=[], interactive=False, elem_id="file_list", value=None) + with gr.Row(): + with gr.Column(scale=4): + install_path = gr.Textbox(label="Download folder:", interactive=False, max_lines=1) + with gr.Column(scale=2): + sub_folder = gr.Dropdown(label="Sub folder:", choices=[], interactive=False, value=None) + with gr.Row(): + with gr.Column(scale=4): + trained_tags = gr.Textbox(label='Trained tags (if any):', value=None, interactive=False, lines=1) + with gr.Column(scale=2, elem_id="spanWidth"): + base_model = gr.Textbox(label='Base model: ', value=None, interactive=False, lines=1, elem_id="baseMdl") + model_filename = gr.Textbox(label="Model filename:", interactive=False, value=None) + with gr.Row(): + save_info = gr.Button(value="Save model info", interactive=False) + save_images = gr.Button(value="Save images", interactive=False) + delete_model = gr.Button(value="Delete model", interactive=False, visible=False) + download_model = gr.Button(value="Download model", interactive=False) + subfolder_selected = gr.Dropdown(label="Sub folder for selected files:", choices=[], interactive=False, visible=False, value=None, allow_custom_value=True) + download_selected = gr.Button(value="Download all selected", interactive=False, visible=False, elem_id="download_all_button") + with gr.Row(): + cancel_all_model = gr.Button(value="Cancel all downloads", interactive=False, visible=False) + cancel_model = gr.Button(value="Cancel current download", interactive=False, visible=False) + with gr.Row(): + preview_html = gr.HTML(elem_id="civitai_preview_html") + with gr.Row(elem_id="backToTopContainer"): + back_to_top = gr.Button(value="↑", elem_id="backToTop") + with gr.Tab("Update Models"): + with gr.Row(): + selected_tags = gr.CheckboxGroup(elem_id="selected_tags", label="Selected content types:", choices=scan_choices) + with gr.Row(elem_id="civitai_update_toggles"): + overwrite_toggle = gr.Checkbox(elem_id="overwrite_toggle", label="Overwrite any existing files. (previews, HTMLs, tags, descriptions)", value=True, min_width=300) + skip_hash_toggle = gr.Checkbox(elem_id="skip_hash_toggle", label="One-Time Hash Generation for externally downloaded models.", value=True, min_width=300) + do_html_gen = gr.Checkbox(elem_id="do_html_gen", label="Save HTML file for each model when updating info & tags (increases process time).", value=False, min_width=300) + with gr.Row(): + save_all_tags = gr.Button(value="Update model info & tags", interactive=True, visible=True) + cancel_all_tags = gr.Button(value="Cancel updating model info & tags", interactive=False, visible=False) + with gr.Row(): + tag_progress = gr.HTML(value='
') + with gr.Row(): + update_preview = gr.Button(value="Update model preview", interactive=True, visible=True) + cancel_update_preview = gr.Button(value="Cancel updating model previews", interactive=False, visible=False) + with gr.Row(): + preview_progress = gr.HTML(value='
') + with gr.Row(): + ver_search = gr.Button(value="Scan for available updates", interactive=True, visible=True) + cancel_ver_search = gr.Button(value="Cancel updates scan", interactive=False, visible=False) + load_to_browser = gr.Button(value="Load outdated models to browser", interactive=False, visible=False) + with gr.Row(): + version_progress = gr.HTML(value='
') + with gr.Row(): + load_installed = gr.Button(value="Load all installed models", interactive=True, visible=True) + cancel_installed = gr.Button(value="Cancel loading models", interactive=False, visible=False) + load_to_browser_installed = gr.Button(value="Load installed models to browser", interactive=False, visible=False) + with gr.Row(): + installed_progress = gr.HTML(value='
') + with gr.Row(): + organize_models = gr.Button(value="Organize model files", interactive=True, visible=False) # Organize models hidden until implemented + cancel_organize = gr.Button(value="Cancel loading models", interactive=False, visible=False) + with gr.Row(): + organize_progress = gr.HTML(value='
') + with gr.Tab("Download Queue"): + + def get_style(size, left_border): + return f"flex-grow: {size};" + ("border-left: 1px solid var(--border-color-primary);" if left_border else "") + "border-bottom: 1px solid var(--border-color-primary);padding: 5px 10px 5px 10px;width: 0;" + + download_manager_html = gr.HTML(elem_id="civitai_dl_list", value=f''' +
+
Model:
+
Version:
+
Path:
+
Status:
+
Action:
+
+
+
+ In queue: (drag items to rearrange queue order) +
+
+ ''') + + def format_custom_subfolders(): + separator = '␞␞' + with open(gl.subfolder_json, 'r') as f: + data = json.load(f) + result = separator.join([f"{key}{separator}{value}" for key, value in data.items()]) + return result + + #Invisible triggers/variables + #Yes, there is probably a much better way of passing variables/triggering functions between javascript and python + + gr.Textbox(elem_id="custom_subfolders_list", visible=False, value=format_custom_subfolders()) + model_id = gr.Textbox(visible=False) + queue_trigger = gr.Textbox(visible=False) + dl_url = gr.Textbox(visible=False) + civitai_text2img_output = gr.Textbox(visible=False) + civitai_text2img_input = gr.Textbox(elem_id="civitai_text2img_input", visible=False) + page_slider_trigger = gr.Textbox(elem_id="page_slider_trigger", visible=False) + selected_model_list = gr.Textbox(elem_id="selected_model_list", visible=False) + selected_type_list = gr.Textbox(elem_id="selected_type_list", visible=False) + html_cancel_input = gr.Textbox(elem_id="html_cancel_input", visible=False) + queue_html_input = gr.Textbox(elem_id="queue_html_input", visible=False) + list_html_input = gr.Textbox(elem_id="list_html_input", visible=False) + preview_html_input = gr.Textbox(elem_id="preview_html_input", visible=False) + create_subfolder = gr.Textbox(elem_id="create_subfolder", visible=False) + send_to_browser = gr.Textbox(elem_id="send_to_browser", visible=False) + arrange_dl_id = gr.Textbox(elem_id="arrange_dl_id", visible=False) + remove_dl_id = gr.Textbox(elem_id="remove_dl_id", visible=False) + model_select = gr.Textbox(elem_id="model_select", visible=False) + model_sent = gr.Textbox(elem_id="model_sent", visible=False) + type_sent = gr.Textbox(elem_id="type_sent", visible=False) + click_first_item = gr.Textbox(visible=False) + empty = gr.Textbox(value="", visible=False) + download_start = gr.Textbox(visible=False) + download_finish = gr.Textbox(visible=False) + tag_start = gr.Textbox(visible=False) + tag_finish = gr.Textbox(visible=False) + preview_start = gr.Textbox(visible=False) + preview_finish = gr.Textbox(visible=False) + ver_start = gr.Textbox(visible=False) + ver_finish = gr.Textbox(visible=False) + installed_start = gr.Textbox(visible=None) + installed_finish = gr.Textbox(visible=None) + organize_start = gr.Textbox(visible=None) + organize_finish = gr.Textbox(visible=None) + delete_finish = gr.Textbox(visible=False) + current_model = gr.Textbox(visible=False) + current_sha256 = gr.Textbox(visible=False) + model_preview_html_input = gr.Textbox(visible=False) + + def ToggleDate(toggle_date): + gl.sortNewest = toggle_date + + def select_subfolder(sub_folder): + if sub_folder == "None" or sub_folder == "Only available if the selected files are of the same model type": + newpath = gl.main_folder + else: + newpath = gl.main_folder + sub_folder + return gr.Textbox.update(value=newpath) + + # Javascript Functions # + + list_html_input.change(fn=None, inputs=hide_installed, _js="(toggleValue) => hideInstalled(toggleValue)") + hide_installed.input(fn=None, inputs=hide_installed, _js="(toggleValue) => hideInstalled(toggleValue)") + + civitai_text2img_output.change(fn=None, inputs=civitai_text2img_output, _js="(genInfo) => genInfo_to_txt2img(genInfo)") + + download_selected.click(fn=None, _js="() => deselectAllModels()") + + select_all.click(fn=None, _js="() => selectAllModels()") + + list_models.select(fn=None, inputs=list_models, _js="(list_models) => select_model(list_models)") + + preview_html_input.change(fn=None, _js="() => adjustFilterBoxAndButtons()") + preview_html_input.change(fn=None, _js="() => setDescriptionToggle()") + + back_to_top.click(fn=None, _js="() => BackToTop()") + + page_slider.release(fn=None, _js="() => pressRefresh()") + + card_updates = [queue_trigger, download_finish, delete_finish] + for func in card_updates: + func.change(fn=None, inputs=current_model, _js="(modelName) => updateCard(modelName)") + + list_html_input.change(fn=None, inputs=show_nsfw, _js="(hideAndBlur) => toggleNSFWContent(hideAndBlur)") + show_nsfw.change(fn=None, inputs=show_nsfw, _js="(hideAndBlur) => toggleNSFWContent(hideAndBlur)") + + list_html_input.change(fn=None, inputs=size_slider, _js="(size) => updateCardSize(size, size * 1.5)") + size_slider.change(fn=None, inputs=size_slider, _js="(size) => updateCardSize(size, size * 1.5)") + + model_preview_html_input.change(fn=None, inputs=model_preview_html_input, _js="(html_input) => inputHTMLPreviewContent(html_input)") + + queue_html_input.change(fn=None, _js="() => setSortable()") + + click_first_item.change(fn=None, _js="() => clickFirstFigureInColumn()") + + # Filter button Functions # + + queue_html_input.change(fn=HTMLChange, inputs=[queue_html_input], outputs=download_manager_html) + list_html_input.change(fn=HTMLChange, inputs=[list_html_input], outputs=list_html) + preview_html_input.change(fn=HTMLChange, inputs=[preview_html_input], outputs=preview_html) + + remove_dl_id.change( + fn=_download.remove_from_queue, + inputs=[remove_dl_id] + ) + + arrange_dl_id.change( + fn=_download.arrange_queue, + inputs=[arrange_dl_id] + ) + + html_cancel_input.change( + fn=_download.download_cancel + ) + + html_cancel_input.change(fn=None, _js="() => cancelCurrentDl()") + + save_settings.click( + fn=saveSettings, + inputs=[ + use_search_term, + content_type, + period_type, + sort_type, + base_filter, + create_json, + toggle_date, + only_liked, + hide_installed, + show_nsfw, + size_slider, + tile_count_slider + ] + ) + + toggle_date.input( + fn=ToggleDate, + inputs=[toggle_date] + ) + + # Model Button Functions # + + civitai_text2img_input.change(fn=txt2img_output,inputs=civitai_text2img_input,outputs=civitai_text2img_output) + + list_html_input.change(fn=all_visible, inputs=list_html, outputs=select_all) + + def update_models_dropdown(input): + if not gl.json_data: + return ( + gr.Dropdown.update(value=None, choices=[], interactive=False), # List models + gr.Dropdown.update(value=None, choices=[], interactive=False), # List version + gr.Textbox.update(value=None), # Preview HTML + gr.Textbox.update(value=None, interactive=False), # Trained Tags + gr.Textbox.update(value=None, interactive=False), # Base Model + gr.Textbox.update(value=None, interactive=False), # Model filename + gr.Textbox.update(value=None, interactive=False), # Install path + gr.Dropdown.update(value=None, choices=[], interactive=False), # Sub folder + gr.Button.update(interactive=False), # Download model btn + gr.Button.update(interactive=False), # Save image btn + gr.Button.update(interactive=False, visible=False), # Delete model btn + gr.Dropdown.update(value=None, choices=[], interactive=False), # File list + gr.Textbox.update(value=None), # DL Url + gr.Textbox.update(value=None), # Model ID + gr.Textbox.update(value=None), # Current sha256 + gr.Button.update(interactive=False), # Save model info + gr.Textbox.update(value='
Click the search icon to load models.
Use the filter icon to filter results.
') # Model list + ) + + model_string = re.sub(r'\.\d{3}$', '', input) + model_name, model_id = _api.extract_model_info(model_string) + model_versions = _api.update_model_versions(model_id) + (html, tags, base_mdl, DwnButton, SaveImages, DelButton, filelist, filename, dl_url, id, current_sha256, install_path, sub_folder) = _api.update_model_info(model_string, model_versions.get('value')) + return (gr.Dropdown.update(value=model_string, interactive=True), + model_versions,html,tags,base_mdl,filename,install_path,sub_folder,DwnButton,SaveImages,DelButton,filelist,dl_url,id,current_sha256, + gr.Button.update(interactive=True), + gr.Textbox.update() + ) + + model_select.change( + fn=update_models_dropdown, + inputs=[model_select], + outputs=[ + list_models, + list_versions, + preview_html, + trained_tags, + base_model, + model_filename, + install_path, + sub_folder, + download_model, + save_images, + delete_model, + file_list, + dl_url, + model_id, + current_sha256, + save_info, + list_html_input + ] + ) + + model_sent.change( + fn=_file.model_from_sent, + inputs=[model_sent, type_sent], + outputs=[model_preview_html_input] + ) + + send_to_browser.change( + fn=_file.send_to_browser, + inputs=[send_to_browser, type_sent, click_first_item], + outputs=[list_html_input, get_prev_page , get_next_page, page_slider, click_first_item] + ) + + sub_folder.select( + fn=select_subfolder, + inputs=[sub_folder], + outputs=[install_path] + ) + + list_versions.select( + fn=_api.update_model_info, + inputs=[ + list_models, + list_versions + ], + outputs=[ + preview_html_input, + trained_tags, + base_model, + download_model, + save_images, + delete_model, + file_list, + model_filename, + dl_url, + model_id, + current_sha256, + install_path, + sub_folder + ] + ) + + file_list.input( + fn=_api.update_file_info, + inputs=[ + list_models, + list_versions, + file_list + ], + outputs=[ + model_filename, + dl_url, + model_id, + current_sha256, + download_model, + delete_model, + install_path, + sub_folder + ] + ) + + # Download/Save Model Button Functions # + + selected_model_list.change( + fn=show_multi_buttons, + inputs=[selected_model_list, selected_type_list, list_versions], + outputs=[ + download_selected, + download_model, + delete_model, + save_info, + save_images, + subfolder_selected + ] + ) + + download_model.click( + fn=_download.download_start, + inputs=[ + download_start, + dl_url, + model_filename, + install_path, + list_models, + list_versions, + current_sha256, + model_id, + create_json, + download_manager_html + ], + outputs=[ + download_model, + cancel_model, + cancel_all_model, + download_start, + download_progress, + download_manager_html + ] + ) + + download_selected.click( + fn=_download.selected_to_queue, + inputs=[ + selected_model_list, + subfolder_selected, + download_start, + create_json, + download_manager_html + ], + outputs=[ + download_model, + cancel_model, + cancel_all_model, + download_start, + download_progress, + download_manager_html + ] + ) + + + for component in [download_start, queue_trigger]: + component.change(fn=None, _js="() => setDownloadProgressBar()") + component.change( + fn=_download.download_create_thread, + inputs=[download_finish, queue_trigger], + outputs=[ + download_progress, + current_model, + download_finish, + queue_trigger + ] + ) + + download_finish.change( + fn=_download.download_finish, + inputs=[ + model_filename, + list_versions, + model_id + ], + outputs=[ + download_model, + cancel_model, + cancel_all_model, + delete_model, + download_progress, + list_versions + ] + ) + + cancel_model.click(_download.download_cancel) + cancel_all_model.click(_download.download_cancel_all) + + cancel_model.click(fn=None, _js="() => cancelCurrentDl()") + cancel_all_model.click(fn=None, _js="() => cancelAllDl()") + + delete_model.click( + fn=_file.delete_model, + inputs=[ + delete_finish, + model_filename, + list_models, + list_versions, + current_sha256, + selected_model_list + ], + outputs=[ + download_model, + cancel_model, + delete_model, + delete_finish, + current_model, + list_versions + ] + ) + + save_info.click( + fn=_file.save_model_info, + inputs=[ + install_path, + model_filename, + sub_folder, + current_sha256, + preview_html_input + ], + outputs=[] + ) + + save_images.click( + fn=_file.save_images, + inputs=[ + preview_html_input, + model_filename, + install_path, + sub_folder + ], + outputs=[] + ) + + # Common input&output lists # + + page_inputs = [ + content_type, + sort_type, + period_type, + use_search_term, + search_term, + page_slider, + base_filter, + only_liked, + show_nsfw, + tile_count_slider + ] + + refresh_inputs = [empty if item == page_slider else item for item in page_inputs] + + page_outputs = [ + list_models, + list_versions, + list_html_input, + get_prev_page, + get_next_page, + page_slider, + save_info, + save_images, + download_model, + delete_model, + install_path, + sub_folder, + file_list, + preview_html_input, + trained_tags, + base_model, + model_filename + ] + + file_scan_inputs = [ + selected_tags, + ver_finish, + tag_finish, + installed_finish, + preview_finish, + overwrite_toggle, + tile_count_slider, + skip_hash_toggle, + do_html_gen + ] + + load_to_browser_inputs = [ + content_type, + sort_type, + period_type, + use_search_term, + search_term, + tile_count_slider, + base_filter, + show_nsfw + ] + + cancel_btn_list = [cancel_all_tags,cancel_ver_search,cancel_installed,cancel_update_preview] + + browser = [ver_search,save_all_tags,load_installed,update_preview] + + browser_installed_load = [cancel_installed,load_to_browser_installed,installed_progress] + browser_load = [cancel_ver_search,load_to_browser,version_progress] + + browser_installed_list = page_outputs + browser + browser_installed_load + browser_list = page_outputs + browser + browser_load + + # Page Button Functions # + + page_btn_list = { + refresh.click: (_api.initial_model_page, True), + search_term.submit: (_api.initial_model_page, True), + page_slider_trigger.change: (_api.initial_model_page, False), + get_next_page.click: (_api.next_model_page, False), + get_prev_page.click: (_api.prev_model_page, False) + } + + for trigger, (function, use_refresh_inputs) in page_btn_list.items(): + inputs_to_use = refresh_inputs if use_refresh_inputs else page_inputs + trigger(fn=function, inputs=inputs_to_use, outputs=page_outputs) + trigger(fn=None, _js="() => multi_model_select()") + + for button in cancel_btn_list: + button.click(fn=_file.cancel_scan) + + # Update model Functions # + + ver_search.click( + fn=_file.ver_search_start, + inputs=[ver_start], + outputs=[ + ver_start, + ver_search, + cancel_ver_search, + load_installed, + save_all_tags, + update_preview, + organize_models, + version_progress + ] + ) + + ver_start.change( + fn=_file.file_scan, + inputs=file_scan_inputs, + outputs=[ + version_progress, + ver_finish + ] + ) + + ver_finish.change( + fn=_file.scan_finish, + outputs=[ + ver_search, + save_all_tags, + load_installed, + update_preview, + organize_models, + cancel_ver_search, + load_to_browser + ] + ) + + load_installed.click( + fn=_file.installed_models_start, + inputs=[installed_start], + outputs=[ + installed_start, + load_installed, + cancel_installed, + ver_search, + save_all_tags, + update_preview, + organize_models, + installed_progress + ] + ) + + installed_start.change( + fn=_file.file_scan, + inputs=file_scan_inputs, + outputs=[ + installed_progress, + installed_finish + ] + ) + + installed_finish.change( + fn=_file.scan_finish, + outputs=[ + ver_search, + save_all_tags, + load_installed, + update_preview, + organize_models, + cancel_installed, + load_to_browser_installed + ] + ) + + save_all_tags.click( + fn=_file.save_tag_start, + inputs=[tag_start], + outputs=[ + tag_start, + save_all_tags, + cancel_all_tags, + load_installed, + ver_search, + update_preview, + organize_models, + tag_progress + ] + ) + + tag_start.change( + fn=_file.file_scan, + inputs=file_scan_inputs, + outputs=[ + tag_progress, + tag_finish + ] + ) + + tag_finish.change( + fn=_file.save_tag_finish, + outputs=[ + ver_search, + save_all_tags, + load_installed, + update_preview, + organize_models, + cancel_all_tags + ] + ) + + update_preview.click( + fn=_file.save_preview_start, + inputs=[preview_start], + outputs=[ + preview_start, + update_preview, + cancel_update_preview, + load_installed, + ver_search, + save_all_tags, + organize_models, + preview_progress + ] + ) + + preview_start.change( + fn=_file.file_scan, + inputs=file_scan_inputs, + outputs=[ + preview_progress, + preview_finish + ] + ) + + preview_finish.change( + fn=_file.save_preview_finish, + outputs=[ + ver_search, + save_all_tags, + load_installed, + update_preview, + organize_models, + cancel_update_preview + ] + ) + + organize_models.click( + fn=_file.organize_start, + inputs=[organize_start], + outputs=[ + organize_start, + organize_models, + cancel_organize, + load_installed, + ver_search, + save_all_tags, + update_preview, + organize_progress + ] + ) + + organize_start.change( + fn=_file.file_scan, + inputs=file_scan_inputs, + outputs=[ + organize_progress, + organize_finish + ] + ) + + organize_finish.change( + fn=_file.save_preview_finish, + outputs=[ + ver_search, + save_all_tags, + load_installed, + update_preview, + organize_models, + cancel_update_preview + ] + ) + + + load_to_browser_installed.click( + fn=_file.load_to_browser, + inputs=load_to_browser_inputs, + outputs=browser_installed_list + ) + + load_to_browser.click( + fn=_file.load_to_browser, + inputs=load_to_browser_inputs, + outputs=browser_list + ) + + # Settings function + create_subfolder.change( + fn=_file.updateSubfolder, + inputs=create_subfolder, + outputs=[] + ) + + if ver_bool: + tab_name = "CivitAI Browser+" + else: + tab_name = "Civitai Browser+" + + return (civitai_interface, tab_name, "civitai_interface"), + +def subfolder_list(folder, desc=None): + if folder == None: + return + model_folder = _api.contenttype_folder(folder, desc) + sub_folders = _file.getSubfolders(model_folder) + return sub_folders + +def make_lambda(folder, desc): + return lambda: {"choices": subfolder_list(folder, desc)} + +def on_ui_settings(): + if ver_bool: + browser = ("civitai_browser", "Browser") + download = ("civitai_browser_download", "Downloads") + from modules.options import categories + categories.register_category("civitai_browser_plus", "CivitAI Browser+") + cat_id = "civitai_browser_plus" + else: + section = ("civitai_browser_plus", "CivitAI Browser+") + browser = download = section + if not (hasattr(shared.OptionInfo, "info") and callable(getattr(shared.OptionInfo, "info"))): + def info(self, info): + self.label += f" ({info})" + return self + shared.OptionInfo.info = info + + # Download Options + shared.opts.add_option( + "use_aria2", + shared.OptionInfo( + True, + "Download models using Aria2", + section=download, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Disable this option if you're experiencing any issues with downloads or if you want to use a proxy.") + ) + + shared.opts.add_option( + "disable_dns", + shared.OptionInfo( + False, + "Disable Async DNS for Aria2", + section=download, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Useful for users who use PortMaster or other software that controls the DNS") + ) + + shared.opts.add_option( + "show_log", + shared.OptionInfo( + False, + "Show Aria2 logs in console", + section=download, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Requires UI reload") + ) + + shared.opts.add_option( + "split_aria2", + shared.OptionInfo( + 64, + "Number of connections to use for downloading a model", + gr.Slider, + lambda: {"maximum": "64", "minimum": "1", "step": "1"}, + section=download, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Only applies to Aria2") + ) + + shared.opts.add_option( + "aria2_flags", + shared.OptionInfo( + r"", + "Custom Aria2 command line flags", + section=download, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Requires UI reload") + ) + + shared.opts.add_option( + "unpack_zip", + shared.OptionInfo( + False, + "Automatically unpack .zip files after downloading", + section=download, + **({'category_id': cat_id} if ver_bool else {}) + ) + ) + + shared.opts.add_option( + "save_api_info", + shared.OptionInfo( + False, + "Save API info of model when saving model info", + section=download, + **({'category_id': cat_id} if ver_bool else {}) + ).info("creates an api_info.json file when saving any model info with all the API data of the model") + ) + + shared.opts.add_option( + "auto_save_all_img", + shared.OptionInfo( + False, + "Automatically save all images", + section=download, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Automatically saves all the images of a model after downloading") + ) + + # Browser Options + shared.opts.add_option( + "custom_api_key", + shared.OptionInfo( + r"", + "Personal CivitAI API key", + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("You can create your own API key in your CivitAI account settings, this required for some downloads, Requires UI reload") + ) + + shared.opts.add_option( + "hide_early_access", + shared.OptionInfo( + True, + "Hide early access models", + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Early access models are only downloadable for supporter tier members") + ) + + shared.opts.add_option( + "use_LORA", + shared.OptionInfo( + ver_bool, + "Combine LoCon, LORA & DoRA as one option", + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("LoCon requires SD-WebUI v1.5 or higher, DoRA requires v1.9 or higher") + ) + + shared.opts.add_option( + "dot_subfolders", + shared.OptionInfo( + True, + "Hide sub-folders that start with a '.'", + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ) + ) + + shared.opts.add_option( + "use_local_html", + shared.OptionInfo( + False, + "Use local HTML file for model info", + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Uses the matching local HTML file when pressing CivitAI button on model cards in txt2img and img2img") + ) + + shared.opts.add_option( + "local_path_in_html", + shared.OptionInfo( + False, + "Use local images in the HTML", + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Only works if all images of the corresponding model are downloaded") + ) + + shared.opts.add_option( + "page_header", + shared.OptionInfo( + False, + "Page navigation as header", + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Keeps the page navigation always visible at the top, Requires UI reload") + ) + + shared.opts.add_option( + "video_playback", + shared.OptionInfo( + True, + 'Gif/video playback in the browser', + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Disable this option if you're experiencing high CPU usage during video/gif playback") + ) + + shared.opts.add_option( + "individual_meta_btn", + shared.OptionInfo( + True, + 'Individual prompt buttons', + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Turns individual prompts from an example image into a button to send it to txt2img") + ) + + shared.opts.add_option( + "model_desc_to_json", + shared.OptionInfo( + True, + 'Save model description to json', + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info('This saves the models description to the description field on model cards') + ) + + shared.opts.add_option( + "civitai_not_found_print", + shared.OptionInfo( + True, + 'Show "Model not found" print during update scanning', + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ) + ) + + shared.opts.add_option( + "civitai_send_to_browser", + shared.OptionInfo( + False, + 'Send model from the cards CivitAI button to the browser, instead of showing a popup', + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ) + ) + + shared.opts.add_option( + "image_location", + shared.OptionInfo( + r"", + "Custom save images location", + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Overrides the download folder location when saving images.") + ) + + shared.opts.add_option( + "sub_image_location", + shared.OptionInfo( + True, + 'Use sub folders inside custom images location', + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Will append any content type and sub folders to the custom path.") + ) + + shared.opts.add_option( + "save_to_custom", + shared.OptionInfo( + False, + "Store the HTML and api_info in the custom images location", + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ) + ) + + shared.opts.add_option( + "custom_civitai_proxy", + shared.OptionInfo( + r"", + "Proxy address", + gr.Textbox, + {"placeholder": "socks4://0.0.0.0:00000 | socks5://0.0.0.0:00000"}, + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Only works with proxies that support HTTPS, turn Aria2 off for proxy downloads") + ) + + shared.opts.add_option( + "cabundle_path_proxy", + shared.OptionInfo( + r"", + "Path to custom CA Bundle", + gr.Textbox, + {"placeholder": "/path/to/custom/cabundle.pem"}, + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Specify custom CA bundle for SSL certificate checks if required") + ) + + shared.opts.add_option( + "disable_sll_proxy", + shared.OptionInfo( + False, + "Disable SSL certificate checks", + section=browser, + **({'category_id': cat_id} if ver_bool else {}) + ).info("Not recommended for security, may be required if you do not have the correct CA Bundle available") + ) + + # Default sub folders + use_LORA = getattr(opts, "use_LORA", False) + folders = [ + "Checkpoint", + "LORA, LoCon, DoRA" if use_LORA else "LORA", + "LoCon" if not use_LORA else None, + "DoRA" if not use_LORA else None, + "TextualInversion", + "Poses", + "Controlnet", + "Hypernetwork", + "MotionModule", + ("Upscaler", "SWINIR"), + ("Upscaler", "REALESRGAN"), + ("Upscaler", "GFPGAN"), + ("Upscaler", "BSRGAN"), + ("Upscaler", "ESRGAN"), + "VAE", + "AestheticGradient", + "Wildcards", + "Workflows", + "Other" + ] + + for folder in folders: + if folder == None: + continue + desc = None + if isinstance(folder, tuple): + folder_name = " - ".join(folder) + setting_name = f"{folder[1]}_upscale" + folder = folder[0] + desc = folder[1] + else: + folder_name = folder + setting_name = folder + if folder == "LORA, LoCon, DoRA": + folder = "LORA" + setting_name = "LORA_LoCon" + + shared.opts.add_option(f"{setting_name}_default_subfolder", shared.OptionInfo("None", folder_name, gr.Dropdown, make_lambda(folder, desc), section=download, **({'category_id': cat_id} if ver_bool else {}))) + +script_callbacks.on_ui_tabs(on_ui_tabs) +script_callbacks.on_ui_settings(on_ui_settings) diff --git a/extensions-builtin/sd-civitai-browser-plus-main/style.css b/extensions-builtin/sd-civitai-browser-plus-main/style.css new file mode 100644 index 0000000000000000000000000000000000000000..41a2ed46c8f93b38c2caff2dcb28d63031e053f4 --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/style.css @@ -0,0 +1,813 @@ +/* Card list HTML */ +.civmodellist { + display: flex; + flex-wrap: wrap; + justify-content: center; +} + +.civmodellist figure { + margin: 6px; + transition: transform .3s ease-out, box-shadow 0.3s ease; + cursor: pointer; + border-radius: 10px; +} + +.civmodelcard { + position: relative; +} + +.civmodelcard:hover { + transform: scale(1.1, 1.1); + position: relative; + z-index: var(--layer-5); + box-shadow: 0px 0px 1px 3px whitesmoke; +} + +.civmodelcardinstalled { + box-shadow: 0px 0px 1px 3px aquamarine; +} + +.civmodelcardoutdated { + box-shadow: 0px 0px 1px 3px orange; +} + +.civmodelcard:hover figcaption{ + bottom: initial; + background-color: rgba(32, 32, 32, 0.9); +} + +.civmodelcard img, .civmodelcard .video-bg { + width: 8em; + height: 12em; + object-fit: cover; + border-radius: 10px; +} + +.civmodelcard figcaption { + position: absolute; + bottom: 5px; + text-align: center; + width: 8em; + word-break: break-word; + background-color: rgba(32, 32, 32, 0.5); + color: white !important; +} + +/* End of Card list HTML */ + +#quicksettings0 > div{ + max-width: None !important; + width: auto !important; +} + +#togglesL{ + margin-top: 3px; +} + +#toggles{ + margin-top: -10px; +} + +#searchType > div { + gap: 0.5em; +} + +#backToTopContainer { + position: fixed; + bottom: 0; + right: 0; + display: flex; + justify-content: flex-end; + z-index: 150; + pointer-events: none; + margin: 20px 51px 20px 20px; +} + +#backToTop { + margin: 0; + max-width: 60px; + min-width: unset; + z-index: 200; + pointer-events: auto; +} + +#browserTab { + position: relative; +} + +#browserTab > div { + gap: var(--layout-gap) !important; +} + +#browserTab > div > #header { + position: -webkit-sticky; + position: sticky; + top: 0; + background-color: var(--neutral-950); + z-index: 60; +} + +.acss-14flpmm .gap:has(#quicksettings0):first-child { + gap: var(--layout-gap); +} + +#txt2img_seed > label > input{ + height: unset !important; +} + +#browserTab > div > #header, #browserTab > div > #header_off { + display: flex; + flex-direction: column; + padding-top: 15px; + margin-top: -15px; +} + +#toggle1, #toggle2, #toggle3, #toggle4, #toggle4_api, #toggle5{ + margin-top: 5px; + margin-right: 0px; + margin-left: 0px; + display: flex; + justify-content: center; +} + +#civitai_update_toggles > div { + display: flex; + flex-direction: column; +} + +#civitai_update_toggles { + margin-top: calc(-1 * var(--layout-gap)); + margin-bottom: var(--layout-gap); +} + +#toggle1L, #toggle2L, #toggle3L, #toggle4L, #toggle4L_api, #toggle5L, +#overwrite_toggle, #skip_hash_toggle, #do_html_gen { + display: flex; + justify-content: center; +} + +#centerText, #searchType { + text-align: center; +} + +#browserTab { + min-height: 650px; +} + +#download_all_button { + max-height: 40px; + height: 40px; + align-self: end; + margin-bottom: 1px; +} + +#searchBox > label > textarea { + padding-top: 11px !important; +} + +#searchBox { + max-width: 800px; + align-self: center; +} + +#baseMdl { + min-width: 100px !important; + max-width: 100px !important; +} + +#spanWidth { + display: flex !important; + flex-direction: row; +} + +#spanWidth > div { + flex-wrap: nowrap; +} + +.gradio-container-3-32-0 .prose :last-child { + margin-bottom: auto !important; +} + +.date-section { + display: block; + width: 100%; + margin-bottom: 5px; + text-align: center; +} + +.card-row { + display: flex; + flex-wrap: wrap; + justify-content: center; +} + +#selected_tags { + text-align: center; +} + +#pageBtn1, #pageBtn2 { + max-width: 120px !important; + min-width: 50px !important; +} + +#pageSlider { + max-height: 44px; +} + +#pageSlider > div:nth-child(2) { + max-height: 25px; +} + +#pageBoxMobile { + display: flex; + justify-content: space-between; +} + +#pageBox { + display: flex; + justify-content: center; + align-self: center; + max-width: 950px !important; +} + +#pageBox > div:first-child { + align-items: end; +} + +#refreshBtn, #refreshBtnL { + align-self: end; + height: 42px !important; + min-height: 42px !important; + max-height: 42px !important; + max-width: 42px !important; + min-width: 42px !important; + width: 42px !important; + padding: 0px !important; +} + +#refreshBtn > img, +#refreshBtnL > img { + margin: unset; +} + +#searchRow { + max-width: 800px; + align-self: center; +} + +#save_set_box { + display: flex; + justify-content: center; +} + +#save_set_btn { + max-width: 220px !important; + min-width: 220px !important; + margin-bottom: -6px; + padding: 5px; + height: unset !important; + min-height: 35px !important; +} + +#searchType > div:nth-child(3) { + justify-content: center; +} + +.custom-checkbox { + position: absolute; + top: 10px; + right: 10px; + width: 20px; + min-width: 20px; + height: 20px; + background: #111B; + border-radius: var(--checkbox-border-radius); + border: 1px solid #bbbbbb; + cursor: pointer; +} + +.custom-checkbox:hover { + border-color: #ffffff; +} + +.model-checkbox:checked + .custom-checkbox { + background-color: var(--checkbox-background-color-selected); + border-color: var(--checkbox-border-color-selected); + background-image: var(--checkbox-check); + background-size: contain; + background-position: center; + background-repeat: no-repeat; +} + +.open-in-civitai { + font-size: 18pt; + color: var(--body-text-color); + display: flex; + justify-content: center; + margin-top: -12px; +} + +#model_header:hover{ + color: var(--link-text-color-hover); +} + +.civitai-txt2img-btn:hover { + border-color: var(--button-secondary-border-color-hover); + background: var(--button-secondary-background-fill-hover); + color: var(--button-secondary-text-color-hover); +} + +.civitai-txt2img-btn { + border-radius: var(--button-large-radius); + border: var(--button-border-width) solid var(--button-secondary-border-color); + padding: var(--button-large-padding); + font-weight: var(--button-large-text-weight); + font-size: var(--button-large-text-size); + background: var(--button-secondary-background-fill); + color: var(--button-secondary-text-color); +} + +.civitai-tags-container { + display: flex; + flex-wrap: wrap; + gap: 5px; +} + +.civitai-tag, +.civitai-meta, +.civitai-meta-btn { + background-image: var(--button-secondary-background-fill); + border-radius: 8px; + padding: 4px 6px; + border: 1px solid var(--input-border-color); +} + +.civitai-meta-btn:hover { + cursor: pointer; + background-image: var(--button-secondary-background-fill-hover); +} + +#select_all_models_container { + display: flex; + justify-content: flex-end; +} + +#select_all_models { + max-width: 100px; + min-width: 100px; + min-height: 30px; + padding: 0px; + margin-top: -25px; +} + +.civitai_dl_item, +.civitai_dl_item_completed, +.civitai_dl_item_failed { + background-color: var(--error-background-fill); + border-radius: 8px; + padding: 5px 0px; + border: 1px solid var(--input-border-color); + margin: 10px 0px; +} + +.civitai_dl_item_failed > .dl_stat > .dl_progress_bar { + background-color: transparent !important; + padding: 0px 0px 2px 0px !important; +} + +.dl_progress_bar { + background-color: var(--button-primary-border-color); + color: var(--body-text-color); + padding: 0px 0px 2px 5px; + border-radius: 8px; + transition: width 0.5s ease-in-out; +} + +.dl_progress_bar::before, +.dl_progress_bar::after { + content: ""; + display: table; + clear: both; +} + +.civitai-btn-text:hover { + color: var(--link-text-color-hover); + cursor: pointer; +} +/* Customized Accordion Filter */ + +#filterBox, +#filterBoxL { + align-self: end; + height: 42px; + max-width: 42px; + padding: unset !important; + margin: 0px !important; + display: flex; + justify-content: center; +} + +#filterBox { + background: var(--button-secondary-background-fill); +} + +#filterBoxL { + background: var(--input-background-fill); +} + +#filterBox:hover, +#filterBoxL:hover { + background: var(--button-secondary-background-fill-hover); +} + +#filterBox .label-wrap.open, +#filterBoxL .label-wrap.open{ + border-bottom: unset !important; + background: var(--button-secondary-background-fill-hover); + border-radius: 7px !important; + height: 40px; +} + +#filterBox > div:nth-child(3), +#filterBoxL > div:nth-child(3) { + padding: 20px; + position: absolute; + border-radius: 10px; + width: 300px; + z-index: 100 !important; + margin-top: 55px; +} + +.browser_tooltip { + box-shadow: var(--body-text-color) 0px 0px 2px 0px; + background: var(--background-fill-primary); + color: var(--body-text-color); + border-radius: 3px; + padding: 10px; + position: absolute; + z-index: 50; + margin-top: 30px; +} + +#toggle4 > label > span, #toggle4L > label > span { + color: var(--neutral-400); +} + +#filterBox > div:nth-child(3), #toggle4 > div:nth-child(3) { + background: var(--background-fill-primary); +} + +#filterBoxL > div:nth-child(3), #toggle4L > div:nth-child(3) { + background: var(--neutral-950); +} + +#filterBox > div:nth-child(2), +#filterBoxL > div:nth-child(2) { + padding: 10px !important; +} + +#filterBox .gradio-slider input[type="number"], +#filterBoxL .gradio-slider input[type="number"] { + width: 70px !important; +} + +#pageBox .gradio-slider input[type="number"] { + width: 5em !important; +} + +#filterBox > div:nth-child(2) > span:nth-child(1), +#filterBoxL > div:nth-child(2) > span:nth-child(1) { + display: none; +} + +#filterBox > div:nth-child(2) > span:nth-child(2), +#filterBoxL > div:nth-child(2) > span:nth-child(2) { + transform: rotate(0deg) !important; + transition: 0s !important; + display: inline-block; + width: 24px; + height: 24px; + font-size: 0; + color: transparent; + overflow: hidden; +} + +#filterBox > div:nth-child(2) > span:nth-child(2)::before, +#filterBoxL > div:nth-child(2) > span:nth-child(2)::before { + content: ""; + display: block; + width: 100%; + height: 100%; +} + +/* End of Custom Accordion */ + +.card-button { + width: 42px !important; +} + +.edit-button.card-button::before { + font-size: 90%; + vertical-align: top; +} + +.copy-path-button.card-button::before { + font-size: 110%; +} + +.copy-path-button.card-button { + margin-top: -4px; +} + +.goto-civitbrowser.card-button { + filter: drop-shadow(2px 2px 3px black); + display: flex; + align-items: center; +} + +.goto-civitbrowser.card-button:hover svg { + fill: red !important; +} + +/* Custom settings Accordion */ +.settings-accordion { + border: 1px solid var(--block-border-color); + border-radius: 8px !important; + margin: 15px 0px 2px 0px; + padding: 8px 8px; +} + +.flex-column-layout { + display: flex; + gap: 10px; + flex-direction: column; +} + +.sub-folder-button-container { + width: 100%; +} + +.guide-button { + position: relative; + z-index: 1; +} + +.plus-button { + position: absolute; + left: 50%; + transform: translateX(-50%); + z-index: 0; +} + + +#accordionToggle { + width: 100%; + display: flex; + font-size: 12pt; + justify-content: space-between; +} + +#selected_tags > div { + justify-content: center; + padding-top: 10px; + padding-bottom: 20px; +} + +#civitai_preview_html .model-block { + box-shadow: 0px 0px 1px 3px var(--button-secondary-border-color); + border-radius: 10px; + padding: 1px 20px 10px; + margin-bottom: 20px; +} + +#civitai_preview_html .model-block code { + white-space: pre-wrap; +} + +#civitai_preview_html .model-block dl { + overflow-wrap: anywhere; +} + +#civitai_preview_html .sampleimgs .model-block img, +#civitai_preview_html .sampleimgs .model-block video { + padding-top: 1em; + max-width: 20em; + cursor: zoom-in; + transition: max-width 0.1s; +} + +/* Preview Image zoom */ +#civitai_preview_html .zoom-radio { + display: none!important; +} + +/* Style for when the image is clicked (radio button checked) */ +#civitai_preview_html .zoom-radio:checked + label > img, +#civitai_preview_html .zoom-radio:checked + label > video { + max-width: 95vw; + max-height: 95vh; + padding-top: 0px; + cursor: zoom-out; + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + z-index: 1000; /* Higher than the overlay */ + pointer-events: none; /* Allow clicks to penetrate through to the overlay for resetting */ +} + +/* Overlay for resetting zoomed state */ +#civitai_preview_html .zoom-overlay { + display: none; + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(0, 0, 0, .5); + z-index: 999; /* Below the zoomed image */ + cursor: zoom-out; +} + +#civitai_preview_html .zoom-radio:checked + label + .zoom-overlay { + display: block; + pointer-events: all; /* Capture click events when displayed */ +} + +#civitai_preview_html .zoom-img-container { + min-width: 20em; +} + +#civitai_preview_html .model-uploader { + border-bottom: 1px solid; + padding-bottom: 10px; + } + +#civitai_preview_html .model-description { + border-top: 1px solid; + overflow-wrap: break-word; + overflow: hidden; + position: relative; + max-height: 400px; +} + +#civitai_preview_html .model-description::after { + content: ""; + position: absolute; + bottom: 0; + width: 100%; + height: 75px; + background: linear-gradient(to bottom, rgb(255 255 255 / 0%), var(--background-fill-primary)); + z-index: 1; +} + +.description-toggle-label { + cursor: pointer; +} + +.description-toggle-checkbox { + position: absolute; + opacity: 0; + z-index: -1; +} + +.description-toggle-checkbox:checked + .model-description { + max-height: unset !important; + position: unset !important; +} + +.model-description + .description-toggle-label::before { + content: "❯"; + width: 1em; + height: 1em; + text-align: center; + transition: all 0.3s; +} + +.model-description + .description-toggle-label { + display: flex; + padding: 10px 0px; + font-weight: bold; + cursor: pointer; + font-size: large; +} + +.description-toggle-checkbox:checked + .model-description + .description-toggle-label::before { + transform: rotate(-90deg); + margin-right: 10px; +} + +.description-toggle-checkbox:checked + .model-description + .description-toggle-label::after { + content: "Show Less..."; +} + +.description-toggle-checkbox:not(:checked) + .model-description + .description-toggle-label::after { + content: "Show All..."; +} +/*------------------------------------------*/ +/*End CSS accordion for toggling description*/ + +/*Avatar CSS mostly copied from CivitAI, but 48px instead of 32px*/ +#civitai_preview_html .avatar { + user-select: none; + overflow: hidden; + width: 48px; + height: 48px; + min-width: 48px; + border-radius: 48px; + text-decoration: none; + border: 0; + padding: 0; + background-color: rgba(0,0,0,0.31); + display: inline-block!important; + margin-left: 5px!important; + vertical-align: middle; +} + +#civitai_preview_html .avatar img { + object-fit: cover; + width: 100%; + height: 100%; + display: block; + overflow-clip-margin: content-box; + overflow: clip; + border-style: none; +} + +#civitai_preview_html dt { + font-size: medium; + color: #80a6c8!important; +} + +/* +#civitai_preview_html dt { + font-size: medium; + color: #3966bb !important; +} +*/ + +#civitai_preview_html dd { + padding: 0px 0px 10px 10px; +} + +/*CSS accordion for toggling extra metadata*/ +/*-----------------------------------------*/ +#civitai_preview_html .accordionCheckbox { + position: absolute; + opacity: 0; + z-index: -1; +} + +#civitai_preview_html .tabs { + border-radius: 10px; + overflow: hidden; +} + +#civitai_preview_html .tab { + width: 100%; + color: white; + overflow: hidden; + margin-left: -15px; +} + +#civitai_preview_html .tab-label { + display: flex; + padding: 1em; + font-weight: bold; + cursor: pointer; + font-size: large; +} + +/* Icon */ +#civitai_preview_html .tab-label::before { + content: "❯"; + width: 1em; + height: 1em; + text-align: center; + transition: all 0.3s; +} + +#civitai_preview_html .accordionCheckbox:checked + .tab-label::before { + transform: rotate(90deg); +} + +#civitai_preview_html .tab-content { + max-height: 0; + padding: 0 1em; + transition: all 0.3s; +} + +#civitai_preview_html .tab-close { + display: flex; + justify-content: flex-end; + padding: 1em; + font-size: 0.75em; + cursor: pointer; +} + +#civitai_preview_html .accordionCheckbox:checked ~ .tab-content { + max-height: unset; + padding: 1em; +} +/*-----------------------------------------*/ +/*End CSS accordion for toggling extra metadata*/ \ No newline at end of file diff --git a/extensions-builtin/sd-civitai-browser-plus-main/style_html.css b/extensions-builtin/sd-civitai-browser-plus-main/style_html.css new file mode 100644 index 0000000000000000000000000000000000000000..59a5af188bd26fd5088990eb8fc0988692d480ca --- /dev/null +++ b/extensions-builtin/sd-civitai-browser-plus-main/style_html.css @@ -0,0 +1,303 @@ +body { + background-color: #0b0f19; +} + +.model-block { + box-shadow: 0px 0px 1px 3px #3339ff30; + border-radius: 10px; + padding: 1px 20px 10px; + margin-bottom: 20px; +} + +.model-block code { + white-space: pre-wrap; +} + +.model-block dl { + overflow-wrap: anywhere; +} + +.civnsfw img { + filter: unset; +} + +.sampleimgs .model-block img, +.sampleimgs .model-block video { + padding-top: 1em; + max-width: 20em; + cursor: zoom-in; + transition: max-width 0.1s; +} + +/* Text adjustments */ +h1, h2, h3, h4, h5, dd, dt, p, a, label { + font-family: 'Source Sans Pro', 'ui-sans-serif', 'system-ui', sans-serif; +} + +h3 { + font-size: 16px; +} + +h2 { + margin: 16px 0px 8px; + font-size: 22px; +} + +ul { + padding-left: 18px; +} + +p { + color: #F3F4F6; + margin: 0px 0px 6px; + font-size: 14px; +} + +dt { + font-size: medium; + color: #80a6c8 !important; + font-size: 16px; +} + +dd { + padding: 0px 0px 5px 10px; + margin-inline-start: 0px; + font-size: 14px; + color: #F3F4F6; +} + +a { + color: #F3F4F6; + font-weight: bold; + text-decoration: unset; +} + +a:hover { + color: #60A5FA; +} + +.civitai_txt2img { + display: none; +} + +/* Preview Image zoom */ +.zoom-radio { + display: none !important; +} + +/* Style for when the image is clicked (radio button checked) */ +.zoom-radio:checked + label > img, +.zoom-radio:checked + label > video { + max-width: 95vw; + max-height: 95vh; + padding-top: 0px; + cursor: zoom-out; + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + z-index: 1000; /* Higher than the overlay */ + pointer-events: none; /* Allow clicks to penetrate through to the overlay for resetting */ +} + +/* Overlay for resetting zoomed state */ +.zoom-overlay { + display: none; + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(0, 0, 0, .5); + z-index: 999; /* Below the zoomed image */ + cursor: zoom-out; +} + +.zoom-radio:checked + label + .zoom-overlay { + display: block; + pointer-events: all; /* Capture click events when displayed */ +} + +.zoom-img-container { + min-width: 20em; +} + +.model-uploader { + border-bottom: 1px solid; + padding-bottom: 10px; + color: white; + } + +.model-description { + border-top: 1px solid; + padding-bottom: 10px; + margin-bottom: 10px; + color: white; + } + +/*Avatar CSS mostly copied from CivitAI, but 48px instead of 32px*/ +.avatar { + user-select: none; + overflow: hidden; + width: 48px; + height: 48px; + min-width: 48px; + border-radius: 48px; + text-decoration: none; + border: 0; + padding: 0; + background-color: rgba(0,0,0,0.31); + display: inline-block!important; + margin-left: 5px!important; + vertical-align: middle; +} + +.avatar img { + object-fit: cover; + width: 100%; + height: 100%; + display: block; + overflow-clip-margin: content-box; + overflow: clip; + border-style: none; +} + +.model-description { + border-top: 1px solid; + overflow-wrap: break-word; + overflow: hidden; + position: relative; + max-height: 400px; +} + +.model-description::after { + content: ""; + position: absolute; + bottom: 0; + width: 100%; + height: 75px; + background: linear-gradient(to bottom, rgb(255 255 255 / 0%), #0b0f19); + z-index: 1; +} + +.description-toggle-label { + display: flex; + padding: 10px 0px 0px 0px; + font-weight: bold; + cursor: pointer; + font-size: large; + color: white; +} + +.description-toggle-checkbox { + position: absolute; + opacity: 0; + z-index: -1; +} + +.description-toggle-checkbox:checked + .model-description { + max-height: none !important; + position: unset !important; +} + +.model-description + .description-toggle-label::before { + content: "❯"; + width: 1em; + height: 1em; + text-align: center; + transition: all 0.3s; +} + +.description-toggle-checkbox:checked + .model-description + .description-toggle-label::before { + transform: rotate(-90deg); + margin-right: 10px; +} + +.description-toggle-checkbox:checked + .model-description + .description-toggle-label::after { + content: "Show Less..."; +} + +.description-toggle-checkbox:not(:checked) + .model-description + .description-toggle-label::after { + content: "Show All..."; +} + +/*CSS accordion for toggling extra metadata*/ +/*-----------------------------------------*/ +.accordionCheckbox { + position: absolute; + opacity: 0; + z-index: -1; +} + +.tabs { + border-radius: 10px; + overflow: hidden; +} + +.tab { + width: 100%; + color: white; + overflow: hidden; + margin-left: -15px; +} + +.tab-label { + display: flex; + padding: 1em; + font-weight: bold; + cursor: pointer; + font-size: large; +} + +.civitai-tags-container { + display: flex; + flex-wrap: wrap; + gap: 5px; +} + +.civitai-tag, +.civitai-meta-btn { + background-color: #111827; + border-radius: 8px; + padding: 4px 6px; + border: 1px solid #374151; +} + +.civitai-meta-btn:hover { + cursor: pointer; + background-color: #1F2937; +} + +/* Icon */ +.tab-label::before { + content: "❯"; + width: 1em; + height: 1em; + text-align: center; + transition: all 0.3s; +} + +.accordionCheckbox:checked + .tab-label::before { + transform: rotate(90deg); +} + +.tab-content { + max-height: 0; + padding: 0 1em; + transition: all 0.3s; +} + +.tab-close { + display: flex; + justify-content: flex-end; + padding: 1em; + font-size: 0.75em; + cursor: pointer; +} + +.accordionCheckbox:checked ~ .tab-content { + max-height: 100vh; + padding: 1em; +} +/*-----------------------------------------*/ +/*End CSS accordion for toggling extra metadata*/ \ No newline at end of file diff --git a/extensions-builtin/sd-model-downloader/README.md b/extensions-builtin/sd-model-downloader/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b5df43fd62f9b38a936bdd2eece927671b1cabc1 --- /dev/null +++ b/extensions-builtin/sd-model-downloader/README.md @@ -0,0 +1,21 @@ +# sd-model-downloader +SD Web UI Extension to Download Model from URL + +# This Extension Work on AUTO1111 SD Webui + +To install it, clone the repo into the `extensions` directory and run terminal:
+`git clone https://github.com/Iyashinouta/sd-model-downloader /content/stable-diffusion-webui/extensions/sd-model-downloader` + +or Install from SD Webui:
+install from URL, and Paste Link https://github.com/Iyashinouta/sd-model-downloader + +# Instructions + +
tap to see image + + ![preview](https://raw.githubusercontent.com/Iyashinouta/sd-model-downloader/main/images/instructions.png) + +
+ +# Update fix/features + for more details, Check Releases diff --git a/extensions-builtin/sd-model-downloader/images/card-no-prev.png b/extensions-builtin/sd-model-downloader/images/card-no-prev.png new file mode 100644 index 0000000000000000000000000000000000000000..e2beb2692067db56ac5f7bd5bfc3d895d9063371 Binary files /dev/null and b/extensions-builtin/sd-model-downloader/images/card-no-prev.png differ diff --git a/extensions-builtin/sd-model-downloader/images/instructions.png b/extensions-builtin/sd-model-downloader/images/instructions.png new file mode 100644 index 0000000000000000000000000000000000000000..f5d12164ee072b35aa3ef259d4a79bbef737abdf --- /dev/null +++ b/extensions-builtin/sd-model-downloader/images/instructions.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:df593f96755c2ff4aa607deed18d4a3655ab3fd231d282628faeab29bad4b216 +size 5204329 diff --git a/extensions-builtin/sd-model-downloader/install.py--- b/extensions-builtin/sd-model-downloader/install.py--- new file mode 100644 index 0000000000000000000000000000000000000000..88d820d351bb786969c6d0b6e3fe20a510e05121 --- /dev/null +++ b/extensions-builtin/sd-model-downloader/install.py--- @@ -0,0 +1,27 @@ +import os +import launch +import platform +import subprocess + +def checking(): + try: + subprocess.run("aria2c", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + return True + except FileNotFoundError: + return False + +if platform.system() == "Linux": + if not checking(): + launch.run("apt update && apt -y install -qq aria2", "Installing requirements for Model Downloader") + else: + pass +elif platform.system() == "Darwin": + if not checking(): + launch.run("brew install aria2", "Installing requirements for Model Downloader") + else: + pass +elif platform.system() == "Windows": + if not checking(): + print("Model Downloader required aria2c, see tutorial https://www.youtube.com/watch?v=JnWQST4ay_E") + else: + pass diff --git a/extensions-builtin/sd-model-downloader/scripts/model-downloader.py b/extensions-builtin/sd-model-downloader/scripts/model-downloader.py new file mode 100644 index 0000000000000000000000000000000000000000..1afaad4e96dc10ab7ae9e01e63564f8765b3917c --- /dev/null +++ b/extensions-builtin/sd-model-downloader/scripts/model-downloader.py @@ -0,0 +1,370 @@ +import os +import requests +import argparse +import subprocess +import gradio as gr +from urllib.parse import urlparse +from modules import scripts, script_callbacks +try: + from modules.paths_internal import data_path, models_path, extensions_dir +except ImportError: + from modules.paths import data_path, models_path + extensions_dir = os.path.join(data_path, 'extensions') + +sd_path = os.getcwd() +ext = '/extensions' +no_prev = None +addnet_path = None +md_path = scripts.basedir() + +parser = argparse.ArgumentParser() +parser.add_argument('--ckpt-dir', type=str, default=os.path.join(models_path, 'Stable-diffusion')) +parser.add_argument('--vae-dir', type=str, default=os.path.join(models_path, 'VAE')) +parser.add_argument('--embeddings-dir', type=str, default=os.path.join(data_path, 'embeddings')) +parser.add_argument('--hypernetwork-dir', type=str, default=os.path.join(models_path, 'hypernetworks')) +parser.add_argument('--lora-dir', type=str, default=os.path.join(models_path, 'Lora')) +parser.add_argument('--lyco-dir', type=str, default=os.path.join(models_path, 'LyCORIS')) +args, _ = parser.parse_known_args() + +if not os.path.exists(os.path.join(sd_path, 'html', 'card-no-preview.png')): + try: + no_prev = os.path.join(md_path, 'images', 'card-no-prev.png') + except: + pass +else: + no_prev = os.path.join(sd_path, 'html', 'card-no-preview.png') +if not os.path.exists(os.path.join(sd_path, ext, 'sd-webui-additional-networks')): + addnet_path = os.path.join(extensions_dir, 'sd-webui-additional-networks') +else: + addnet_path = os.path.join(sd_path, ext, 'sd-webui-additional-networks') + +checkpoint_path = args.ckpt_dir +vae_path = args.vae_dir +embedding_path = args.embeddings_dir +hypernetwork_path = args.hypernetwork_dir +lora_path = args.lora_dir +lycoris_path = args.lyco_dir +controlnet_path = os.path.join(extensions_dir, 'sd-webui-controlnet') +controlnet_model_path = os.path.join(controlnet_path, 'models') + +print(f'Model Downloader v1.0.8') +print('Checking Directories...') +if not os.path.exists(checkpoint_path): + os.makedirs(checkpoint_path) + print ('Creating Checkpoint Folder') +if not os.path.exists(hypernetwork_path): + os.makedirs(hypernetwork_path) + print ('Creating Hypernetwork Folder') +if not os.path.exists(embedding_path): + os.makedirs(embedding_path) + print ('Creating TextualInversion/Embeddings Folder') +if not os.path.exists(vae_path): + os.makedirs(vae_path) + print ('Creating VAE Folder') +if not os.path.exists(lora_path): + os.makedirs(lora_path) + print ('Creating LoRA Folder') +if not os.path.exists(lycoris_path): + os.makedirs(lycoris_path) + print ('Creating LyCORIS Folder') +else: + pass +print('all Directories already Created.') + +def folder(content_type): + if content_type == 'Checkpoint': + downloadpath = checkpoint_path + elif content_type == 'Hypernetwork': + downloadpath = hypernetwork_path + elif content_type == 'TextualInversion/Embedding': + downloadpath = embedding_path + elif content_type == 'VAE': + downloadpath = vae_path + elif content_type == 'LoRA': + downloadpath = lora_path + elif content_type == 'LyCORIS(LoCon/LoHA)': + downloadpath = lycoris_path + elif content_type == 'ControlNet Model': + downloadpath = controlnet_model_path + else: + downloadpath = 'Unset, Please Choose your Content Type' + return downloadpath + +def get_filename_from_url(url): + if url.find('https://civitai.com/')!=-1: + convert = '' + url.replace('download/models', 'v1/model-versions') + req = requests.get(convert, stream=True) + basename, extension = os.path.splitext(req.json()['files'][0]['name'].replace(' ', '_')) + else: + parse = urlparse(url).path + req = parse[parse.rfind('/') + 1:].replace(' ', '_') + basename, extension = os.path.splitext(req) + return basename, extension + +def get_image_from_url(url): + if url.find('https://civitai.com/')!=-1: + convert = '' + url.replace('download/models', 'v1/model-versions') + req = requests.get(convert, stream=True) + imgurl = req.json()['images'][0]['url'] + else: + imgurl = no_prev + return imgurl + +def change_name(changename): + if changename: + filename = gr.Textbox.update(visible=True) + else: + filename = gr.Textbox.update(visible=False) + return filename + +def custom_download_path(custompath): + if custompath: + downloadpath = gr.Textbox.update(visible=True) + else: + downloadpath = gr.Textbox.update(visible=False) + return downloadpath + +def get_data_from_url(url, downloadpath): + try: + imgurl = get_image_from_url(url) + basename, extension = get_filename_from_url(url) + markdown2 = f''' + +
Model Information
+ URL : {url}
+ Folder Path : {downloadpath}
+ File Name : {basename}{extension}
+ ''' + except: + imgurl = no_prev + markdown2 = f''' + +
Model Information
+ URL : {url}
+ Folder Path : {downloadpath}
+ File Name : ??? + ''' + filename = gr.Textbox.update(basename) + image = gr.Image.update(imgurl) + download_btn = gr.Button.update(visible=True, variant='primary') + out_text = gr.Textbox.update('Ready', visible=True) + info = gr.Markdown.update(markdown2) + return filename, image, download_btn, out_text, info + +def start_downloading(downloader_type, download_btn, url, downloadpath, filename, addnet, logging, new_folder, preview): + complete1 = f'SUCCESS: Download Completed, Saved to\n' + complete2 = f'ERROR: File Already Exist in\n' + complete3 = 'ERROR: Something went wrong, please try again later' + path, extension = get_filename_from_url(url) + imgname = f'{filename}.preview.png' + if new_folder: + target1 = os.path.join(downloadpath, filename) + target2 = os.path.join(addnet_path, 'models', 'lora', filename) + else: + target1 = os.path.join(downloadpath) + target2 = os.path.join(addnet_path, 'models', 'lora') + final_target = None + if addnet: + final_target = target2 + else: + final_target = target1 + back(download_btn) + if not os.path.exists(os.path.join(final_target, f'{filename}{extension}')): + try: + if downloader_type == 'aria2': + command = f'aria2c --console-log-level=error -c -x 16 -s 16 -k 1M --input-file model.txt -d {final_target}' + with open('model.txt', 'w') as w: + if not url.find('https://civitai.com/')!=-1: + w.write(f'{url}\n out={filename}{extension}') + else: + if preview: + imgurl = get_image_from_url(url) + w.write(f'{url}\n out={filename}{extension}\n{imgurl}\n out={imgname}') + else: + w.write(f'{url}\n out={filename}{extension}') + if logging: + command.replace(' --console-log-level=error', ' ') + line = subprocess.getoutput(command) + yield line + print(line) + else: + line = os.popen(command) + for l in line: + l = l.rstrip() + yield f'{complete1}{final_target}' + print(f'{complete1}{final_target}') + elif downloader_type == 'requests': + if new_folder: + os.makedirs(final_target, exist_ok=True) + else: + pass + download = requests.get(url, allow_redirects=True) + if not url.find('https://civitai.com/')!=-1: + with open(os.path.join(final_target, f'{filename}{extension}'), 'wb') as f: + f.write(download.content) + else: + if preview: + imgurl = get_image_from_url(url) + img_download = requests.get(str(imgurl), allow_redirects=True) + with open(os.path.join(final_target, f'{filename}{extension}'), 'wb') as f: + f.write(download.content) + with open(os.path.join(final_target, imgname), 'wb') as img: + img.write(img_download.content) + else: + with open(os.path.join(final_target, f'{filename}{extension}'), 'wb') as f: + f.write(download.content) + yield f'{complete1}{final_target}' + print(f'{complete1}{final_target}') + except Exception as e: + yield f'{e}\n{complete3}' + print(f'{e}\n{complete3}') + else: + yield f'{complete2}{final_target}' + print(f'{complete2}{final_target}') + +def back(download_btn): + return gr.Button.update(visible=True, variant='secondary') + +def on_ui_tabs(): + with gr.Blocks() as downloader: + with gr.Row(): + with gr.Column(): + downloader_type = gr.Radio( + label='Downloader Type', + choices=[ + 'aria2', + 'requests' + ], + value='aria2', + type='value' + ) + with gr.Row(): + content_type = gr.Radio( + label='1. Choose Content Type', + choices=[ + 'Checkpoint', + 'Hypernetwork', + 'TextualInversion/Embedding', + 'VAE', + 'LoRA', + 'LyCORIS(LoCon/LoHA)', + 'ControlNet Model' + ] + ) + addnet = None + if os.path.exists(addnet_path): + addnet = gr.Checkbox(label='save to Additional Networks', value=False, visible=True) + print('Model Downloader detects Additional Networks, creating checkbox for AddNet.') + else: + addnet = gr.Checkbox(value=False, visible=False) + with gr.Row(): + with gr.Column(): + url = gr.Textbox( + label='2. Put Link Download Below', + max_lines=1, placeholder='Type/Paste URL Here' + ) + downloadpath = gr.Textbox( + value='Unset, Please Choose your Content Type', + label='Custom Download Path', + placeholder='Paste Folder Path Here', + visible=False + ) + filename = gr.Textbox( + label='Change Filename', + placeholder='Filename', + visible=False + ) + with gr.Row(): + logging = gr.Checkbox(label='turn on log', value=False) + changename = gr.Checkbox(label='Change Filename', value=False) + custompath = gr.Checkbox(label='Custom Download Path', value=False) + preview = gr.Checkbox(label='Download Preview', value=True) + new_folder = gr.Checkbox(label='Create New Folder', value=False) + with gr.Row(): + with gr.Column(): + download_btn = gr.Button( + 'Start Download', + visible=False, + variant='secondary' + ) + out_text = gr.Textbox( + label='Download Result', + placeholder='Result', + visible=False, + ) + with gr.Row(): + with gr.Column(): + info = gr.Markdown( + ''' + +
Model Information
+ URL :
+ Folder Path :
+ File Name : + ''' + ) + with gr.Column(): + prev_markdown = gr.Markdown('''Preview Model :''') + image = gr.Image(value=no_prev, show_label=False) + image.style(width=156, height=234) + with gr.Row(): + github = gr.Markdown( + ''' +
Having Issue? | + + Report Here
+
Model Downloader v1.0.8 + ''' + ) + content_type.change(folder, content_type, downloadpath) + changename.change(change_name, changename, filename) + custompath.change(custom_download_path, custompath, downloadpath) + url.change( + get_data_from_url, + [ + url, + downloadpath + ], + [ + filename, + image, + download_btn, + out_text, + info + ] + ) + download_btn.click( + start_downloading, + [ + downloader_type, + download_btn, + url, + downloadpath, + filename, + addnet, + logging, + new_folder, + preview + ], + out_text + ) + url.submit( + start_downloading, + [ + downloader_type, + download_btn, + url, + downloadpath, + filename, + addnet, + logging, + new_folder, + preview + ], + out_text + ) + download_btn.click(back, download_btn, download_btn) + url.submit(back, url, download_btn) + return (downloader, 'Model Downloader', 'downloader'), + +script_callbacks.on_ui_tabs(on_ui_tabs) diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/.github/workflows/pytest.yml b/extensions-builtin/sd-webui-aspect-ratio-helper-main/.github/workflows/pytest.yml new file mode 100644 index 0000000000000000000000000000000000000000..1c57d08221beaffd96176da66384661b4c4c899a --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/.github/workflows/pytest.yml @@ -0,0 +1,31 @@ +name: Tests + +on: + pull_request: + push: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + + strategy: + matrix: + python-version: ['3.11', '3.10'] + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install tox + + - name: Run tox + run: tox diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/.gitignore b/extensions-builtin/sd-webui-aspect-ratio-helper-main/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..689264bad5776046b9d205383c4983c599db144a --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/.gitignore @@ -0,0 +1,2 @@ +.idea +.pytest_cache diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/.pre-commit-config.yaml b/extensions-builtin/sd-webui-aspect-ratio-helper-main/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0e1a718fa24808c7f30521d606ab5251ddc2d284 --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/.pre-commit-config.yaml @@ -0,0 +1,35 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + - id: debug-statements + - id: double-quote-string-fixer + - id: name-tests-test + - repo: https://github.com/asottile/reorder_python_imports + rev: v3.9.0 + hooks: + - id: reorder-python-imports + args: [--py37-plus, --add-import, "from __future__ import annotations"] + - repo: https://github.com/asottile/add-trailing-comma + rev: v2.4.0 + hooks: + - id: add-trailing-comma + args: [--py36-plus] + - repo: https://github.com/asottile/pyupgrade + rev: v3.3.2 + hooks: + - id: pyupgrade + args: [--py37-plus] + - repo: https://github.com/pre-commit/mirrors-autopep8 + rev: v2.0.2 + hooks: + - id: autopep8 + - repo: https://github.com/PyCQA/flake8 + rev: 6.0.0 + hooks: + - id: flake8 + args: + - --max-line-length=120 diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/README.md b/extensions-builtin/sd-webui-aspect-ratio-helper-main/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6236dd14fadf3e670d365aae1557562322d13123 --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/README.md @@ -0,0 +1,91 @@ +# Aspect Ratio Helper [![pytest](https://github.com/thomasasfk/sd-webui-aspect-ratio-helper/actions/workflows/pytest.yml/badge.svg?branch=main)](https://github.com/thomasasfk/sd-webui-aspect-ratio-helper/actions/workflows/pytest.yml) + +Simple extension to easily maintain aspect ratio while changing dimensions. + +Install via the extensions tab on the [AUTOMATIC1111 webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui). + +## Features + +**(note this list is a little out of date, will need to find time to update it)** + +- JavaScript aspect ratio controls + - Adds a dropdown of configurable aspect ratios, to which the dimensions will auto-scale + - When selected, you will only be able to modify the higher dimension + - The smaller or equivalent dimension will scale accordingly + - If "Lock/🔒" is selected, the aspect ratio of the current dimensions will be kept + - If "Image/🖼️" is selected, the aspect ratio of the current image will be kept (img2img only) + - If you click the "Swap/⇅" button, the current dimensions will swap + - Configurable aspect ratios will also flip, reducing the need for duplication of config + +https://user-images.githubusercontent.com/22506439/227396634-7a63671a-fd38-419a-b734-a3d26647cc1d.mp4 + +
+ +- Scale to maximum dimension + - Upon clicking, the width and height will scale according to the configured maximum value + - Aspect ratio will be retained, the smaller or equivalent dimension will be scaled to match +- Scale to aspect ratio + - Upon clicking, the current dimensions will be scaled to the given aspect ratio, using the highest width or height + - i.e `4:3 of 256x512 = 512x384` `9:16 of 512x256 = 288x512` `1:1 of 256x300 = 300x300` + - You can optionally toggle this to use the "Maximum dimension" slider value + - i.e `4:3 of 512 = 512x384` `9:16 of 512 = 288x512` `1:1 of 300 = 300x300` +- Scale by percentage + - Upon clicking, the current dimensions will be multiplied by the given percentage, with aspect ratio maintained + - i.e `-25% of 512x256 = 384x192` `+50% of 512x512 = 768x768` + - You can also change the display of these if you find it more intuitive + - i.e `75% of 512x256 = 384x192` `150% of 512x512 = 768x768` + - i.e `x0.75 of 512x256 = 384x192` `x1.5 of 512x512 = 768x768` + +![user-interface.png](docs%2Fui.png) + +## Settings + +- Hide accordion by default (`False`) +- Expand accordion by default (`False`) + - Determines whether the 'Aspect Ratio Helper' accordion expands by default +- UI Component order (`MaxDimensionScaler, PredefinedAspectRatioButtons, PredefinedPercentageButtons`) + - Determines the order in which the UI components will render +- Enable JavaScript aspect ratio controls +- JavaScript aspect ratio buttons `(1:1, 4:3, 16:9, 9:16, 21:9)` + - i.e `1:1, 4:3, 16:9, 9:16, 21:9` `2:3, 1:5, 3:5` +- Show maximum dimension button (`True`) +- Maximum dimension default (`1024`) +- Show pre-defined aspect ratio buttons (`True`) +- Use "Maximum dimension" for aspect ratio buttons (`False`) +- Pre-defined aspect ratio buttons (`1:1, 4:3, 16:9, 9:16, 21:9`) + - i.e `1:1, 4:3, 16:9, 9:16, 21:9` `2:3, 1:5, 3:5` +- Show pre-defined percentage buttons (`True`) +- Pre-defined percentage buttons (`25, 50, 75, 125, 150, 175, 200`) + - i.e `25, 50, 75, 125, 150, 175, 200` `50, 125, 300` +- Pre-defined percentage display format (`Incremental/decremental percentage (-50%, +50%)`) + - `Incremental/decremental percentage (-50%, +50%)` + - `Raw percentage (50%, 150%)` + - `Multiplication (x0.5, x1.5)` + +![settings.png](docs%2Fopts.png) + + +JavaScript & accordion aspect ratios _might_ not play well together - I don't think many users will use both simultaneously, but we'll see. + +## Contributing + +- Open an issue for suggestions +- Raise a pull request + +## Dependencies + +Developed using existing [AUTOMATIC1111 webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui) dependencies. + +It's recommended to use the python version specified by A1111 webui. + +However - for running unit tests, we use pytest. + +```bash +pip install pytest +``` + +## Testing +From the root of the repository. +```bash +pytest +``` diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/_components.py b/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/_components.py new file mode 100644 index 0000000000000000000000000000000000000000..2fae4e7f0e258024c3bfb868f88fa3ae040513dc --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/_components.py @@ -0,0 +1,360 @@ +from __future__ import annotations + +from abc import ABC +from abc import abstractmethod +from functools import partial +from typing import Callable + +import gradio as gr + +import aspect_ratio_helper._constants as _constants +import aspect_ratio_helper._settings as _settings +import aspect_ratio_helper._util as _util + + +class ArhUIComponent(ABC): + + def __init__(self, script): + self.script = script + + @abstractmethod + def render(self): ... + + @staticmethod + @abstractmethod + def should_show() -> bool: ... + + @staticmethod + @abstractmethod + def add_options(): ... + + +class MaxDimensionScaler(ArhUIComponent): + + def render(self): + max_dim_default = _settings.safe_opt( + _constants.ARH_MAX_WIDTH_OR_HEIGHT_KEY, + ) + self.script.max_dimension = float(max_dim_default) + + inputs = outputs = [self.script.wc, self.script.hc] + + with gr.Row( + visible=self.should_show(), + ): + max_dim_default = _settings.safe_opt( + _constants.ARH_MAX_WIDTH_OR_HEIGHT_KEY, + ) + # todo: when using gr.Slider (not deprecated), the default value + # is somehow always 270?... can't figure out why. + # using legacy inputs.Slider for now as it doesn't have the issue. + max_dimension_slider = gr.inputs.Slider( + minimum=_constants.MIN_DIMENSION, + maximum=_constants.MAX_DIMENSION, + step=8, + default=max_dim_default, + label='Maximum dimension', + ) + + def _update_max_dimension(_max_dimension): + self.script.max_dimension = _max_dimension + + max_dimension_slider.change( + _update_max_dimension, + inputs=[max_dimension_slider], + show_progress=False, + ) + + gr.Button( + value='Scale to maximum dimension', + visible=self.should_show(), + ).click( + fn=_util.scale_dimensions_to_max_dim, + inputs=[*inputs, max_dimension_slider], + outputs=outputs, + ) + + @staticmethod + def should_show() -> bool: + return _settings.safe_opt(_constants.ARH_SHOW_MAX_WIDTH_OR_HEIGHT_KEY) + + @staticmethod + def add_options(shared): + shared.opts.add_option( + key=_constants.ARH_SHOW_MAX_WIDTH_OR_HEIGHT_KEY, + info=shared.OptionInfo( + default=_settings.OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_SHOW_MAX_WIDTH_OR_HEIGHT_KEY, + ), + label='Show maximum dimension button', + section=_constants.SECTION, + ), + ) + shared.opts.add_option( + key=_constants.ARH_MAX_WIDTH_OR_HEIGHT_KEY, + info=shared.OptionInfo( + default=_settings.OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_MAX_WIDTH_OR_HEIGHT_KEY, + ), + label='Maximum dimension default', + component=gr.Slider, + component_args={ + 'minimum': _constants.MIN_DIMENSION, + 'maximum': _constants.MAX_DIMENSION, + 'step': 8, + }, + section=_constants.SECTION, + ), + ) + + +class MinDimensionScaler(ArhUIComponent): + + def render(self): + min_dim_default = _settings.safe_opt( + _constants.ARH_MIN_WIDTH_OR_HEIGHT_KEY, + ) + self.script.min_dimension = float(min_dim_default) + + inputs = outputs = [self.script.wc, self.script.hc] + + with gr.Row( + visible=self.should_show(), + ): + min_dim_default = _settings.safe_opt( + _constants.ARH_MIN_WIDTH_OR_HEIGHT_KEY, + ) + # todo: when using gr.Slider (not deprecated), the default value + # is somehow always 270?... can't figure out why. + # using legacy inputs.Slider for now as it doesn't have the issue. + min_dimension_slider = gr.inputs.Slider( + minimum=_constants.MIN_DIMENSION, + maximum=_constants.MAX_DIMENSION, + step=8, + default=min_dim_default, + label='Minimum dimension', + ) + + def _update_min_dimension(_min_dimension): + self.script.min_dimension = _min_dimension + + min_dimension_slider.change( + _update_min_dimension, + inputs=[min_dimension_slider], + show_progress=False, + ) + + gr.Button( + value='Scale to minimum dimension', + visible=self.should_show(), + ).click( + fn=_util.scale_dimensions_to_min_dim, + inputs=[*inputs, min_dimension_slider], + outputs=outputs, + ) + + @staticmethod + def should_show() -> bool: + return _settings.safe_opt(_constants.ARH_SHOW_MIN_WIDTH_OR_HEIGHT_KEY) + + @staticmethod + def add_options(shared): + shared.opts.add_option( + key=_constants.ARH_SHOW_MIN_WIDTH_OR_HEIGHT_KEY, + info=shared.OptionInfo( + default=_settings.OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_SHOW_MIN_WIDTH_OR_HEIGHT_KEY, + ), + label='Show minimum dimension button', + section=_constants.SECTION, + ), + ) + shared.opts.add_option( + key=_constants.ARH_MIN_WIDTH_OR_HEIGHT_KEY, + info=shared.OptionInfo( + default=_settings.OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_MIN_WIDTH_OR_HEIGHT_KEY, + ), + label='Minimum dimension default', + component=gr.Slider, + component_args={ + 'minimum': _constants.MIN_DIMENSION, + 'maximum': _constants.MAX_DIMENSION, + 'step': 8, + }, + section=_constants.SECTION, + ), + ) + + +class PredefinedAspectRatioButtons(ArhUIComponent): + + def render(self): + use_max_dim_op = _settings.safe_opt( + _constants.ARH_PREDEFINED_ASPECT_RATIO_USE_MAX_DIM_KEY, + ) + aspect_ratios = _settings.safe_opt( + _constants.ARH_PREDEFINED_ASPECT_RATIOS_KEY, + ).split(',') + + with gr.Column( + variant='panel', + visible=self.should_show(), + ), gr.Row( + variant='compact', + visible=self.should_show(), + elem_classes='arh-btn-row', + ): + for ar_str in aspect_ratios: + w, h, *_ = (abs(float(d)) for d in ar_str.split(':')) + + inputs = [] + if use_max_dim_op: + ar_func = partial( + _util.scale_dimensions_to_max_dim_func, + width=w, height=h, + max_dim=lambda: self.script.max_dimension, + ) + else: + inputs.extend([self.script.wc, self.script.hc]) + ar_func = partial( + _util.scale_dimensions_to_ui_width_or_height, + arw=w, arh=h, + ) + + gr.Button( + value=self.display_func(ar_str) or ar_str, + visible=self.should_show(), + ).click( + fn=ar_func, + inputs=inputs, + outputs=[self.script.wc, self.script.hc], + ) + + @staticmethod + def should_show() -> bool: + return _settings.safe_opt( + _constants.ARH_SHOW_PREDEFINED_ASPECT_RATIOS_KEY, + ) + + @staticmethod + def add_options(shared): + shared.opts.add_option( + key=_constants.ARH_SHOW_PREDEFINED_ASPECT_RATIOS_KEY, + info=shared.OptionInfo( + default=_settings.OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_SHOW_PREDEFINED_ASPECT_RATIOS_KEY, + ), + label='Show pre-defined aspect ratio buttons', + section=_constants.SECTION, + ), + ) + shared.opts.add_option( + key=_constants.ARH_PREDEFINED_ASPECT_RATIO_USE_MAX_DIM_KEY, + info=shared.OptionInfo( + default=_settings.OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_PREDEFINED_ASPECT_RATIO_USE_MAX_DIM_KEY, + ), + label='Use "Maximum dimension" for aspect ratio buttons (by ' + 'default we use the max width or height)', + section=_constants.SECTION, + ), + ) + shared.opts.add_option( + key=_constants.ARH_PREDEFINED_ASPECT_RATIOS_KEY, + info=shared.OptionInfo( + default=_settings.OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_PREDEFINED_ASPECT_RATIOS_KEY, + ), + label='Pre-defined aspect ratio buttons ' + '(1:1, 4:3, 16:9, 9:16, 21:9)', + section=_constants.SECTION, + ), + ) + + @property + def display_func(self) -> Callable[[str], str]: + return lambda _: None # todo: different displays for aspect ratios. + + +class PredefinedPercentageButtons(ArhUIComponent): + + def render(self): + inputs = outputs = [self.script.wc, self.script.hc] + with gr.Column( + variant='panel', + visible=self.should_show(), + ), gr.Row( + variant='compact', + visible=self.should_show(), + elem_classes='arh-btn-row', + ): + pps = _settings.safe_opt(_constants.ARH_PREDEFINED_PERCENTAGES_KEY) + percentages = [abs(int(x)) for x in pps.split(',')] + + for percentage in percentages: + display = self.display_func(percentage) + gr.Button( + value=display, + visible=self.should_show(), + ).click( + fn=partial( + _util.scale_by_percentage, + pct=percentage / 100, + ), + inputs=inputs, + outputs=outputs, + ) + + @staticmethod + def should_show() -> bool: + return _settings.safe_opt( + _constants.ARH_SHOW_PREDEFINED_PERCENTAGES_KEY, + ) + + @staticmethod + def add_options(shared): + shared.opts.add_option( + key=_constants.ARH_SHOW_PREDEFINED_PERCENTAGES_KEY, + info=shared.OptionInfo( + default=_settings.OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_SHOW_PREDEFINED_PERCENTAGES_KEY, + ), + label='Show pre-defined percentage buttons', + section=_constants.SECTION, + ), + ) + shared.opts.add_option( + key=_constants.ARH_PREDEFINED_PERCENTAGES_KEY, + info=shared.OptionInfo( + default=_settings.OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_PREDEFINED_PERCENTAGES_KEY, + ), + label='Pre-defined percentage buttons (75, 125, 150)', + section=_constants.SECTION, + ), + ) + shared.opts.add_option( + key=_constants.ARH_PREDEFINED_PERCENTAGES_DISPLAY_KEY, + info=shared.OptionInfo( + default=_settings.OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_PREDEFINED_PERCENTAGES_DISPLAY_KEY, + ), + label='Pre-defined percentage display format', + component=gr.Dropdown, + component_args=lambda: { + 'choices': tuple( + _settings.PREDEFINED_PERCENTAGES_DISPLAY_MAP.keys(), + ), + }, + section=_constants.SECTION, + ), + ) + + @property + def display_func(self) -> Callable[[str], str]: + return _settings.PREDEFINED_PERCENTAGES_DISPLAY_MAP.get( + _settings.safe_opt( + _constants.ARH_PREDEFINED_PERCENTAGES_DISPLAY_KEY, + ), + ) diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/_constants.py b/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a7c89c51415c63a579beaa959794469096dd4b --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/_constants.py @@ -0,0 +1,27 @@ +from __future__ import annotations +EXTENSION_NAME = 'Aspect Ratio Helper' + +MAX_DIMENSION = 2048 +MIN_DIMENSION = 64 + +ARH_EXPAND_BY_DEFAULT_KEY = 'arh_expand_by_default' +ARH_HIDE_ACCORDION_BY_DEFAULT_KEY = 'arh_hide_accordion_by_default' +ARH_UI_COMPONENT_ORDER_KEY = 'arh_ui_component_order_key' +ARH_UI_JAVASCRIPT_SELECTION_METHOD = 'arh_ui_javascript_selection_method' +ARH_JAVASCRIPT_ASPECT_RATIO_SHOW_KEY = 'arh_javascript_aspect_ratio_show' +ARH_JAVASCRIPT_ASPECT_RATIOS_KEY = 'arh_javascript_aspect_ratio' +ARH_SHOW_MAX_WIDTH_OR_HEIGHT_KEY = 'arh_show_max_width_or_height' +ARH_SHOW_MIN_WIDTH_OR_HEIGHT_KEY = 'arh_show_min_width_or_height' +ARH_MAX_WIDTH_OR_HEIGHT_KEY = 'arh_max_width_or_height' +ARH_MIN_WIDTH_OR_HEIGHT_KEY = 'arh_min_width_or_height' +ARH_SHOW_PREDEFINED_PERCENTAGES_KEY = 'arh_show_predefined_percentages' +ARH_PREDEFINED_PERCENTAGES_KEY = 'arh_predefined_percentages' +ARH_SHOW_PREDEFINED_ASPECT_RATIOS_KEY = 'arh_show_predefined_aspect_ratios' +ARH_PREDEFINED_ASPECT_RATIOS_KEY = 'arh_predefined_aspect_ratios' +ARH_PREDEFINED_ASPECT_RATIO_USE_MAX_DIM_KEY \ + = 'arh_predefined_aspect_ratio_use_max_dim' +ARH_PREDEFINED_PERCENTAGES_DISPLAY_KEY \ + = 'arh_predefined_percentages_display_key' +DEFAULT_PERCENTAGES_DISPLAY_KEY \ + = 'Incremental/decremental percentage (-50%, +50%)' +SECTION = 'aspect_ratio_helper', EXTENSION_NAME diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/_settings.py b/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..075d8bf85f84b04868c3b52a9e1f596e810a5c93 --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/_settings.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +import itertools + +import gradio as gr +from modules import shared + +import aspect_ratio_helper._components as _components +import aspect_ratio_helper._constants as _constants +import aspect_ratio_helper._util as _util + +PREDEFINED_PERCENTAGES_DISPLAY_MAP = { + _constants.DEFAULT_PERCENTAGES_DISPLAY_KEY: _util.display_minus_and_plus, + 'Raw percentage (50%, 150%)': _util.display_raw_percentage, + 'Multiplication (x0.5, x1.5)': _util.display_multiplication, +} + +COMPONENTS = ( + _components.MaxDimensionScaler, + _components.MinDimensionScaler, + _components.PredefinedAspectRatioButtons, + _components.PredefinedPercentageButtons, +) + +DEFAULT_UI_COMPONENT_ORDER_KEY_LIST = [e.__name__ for e in COMPONENTS] +DEFAULT_UI_COMPONENT_ORDER_KEY = ', '.join( + DEFAULT_UI_COMPONENT_ORDER_KEY_LIST, +) +OPT_KEY_TO_DEFAULT_MAP = { + _constants.ARH_EXPAND_BY_DEFAULT_KEY: False, + _constants.ARH_HIDE_ACCORDION_BY_DEFAULT_KEY: True, + _constants.ARH_UI_COMPONENT_ORDER_KEY: + DEFAULT_UI_COMPONENT_ORDER_KEY, + _constants.ARH_UI_JAVASCRIPT_SELECTION_METHOD: 'Aspect Ratios Dropdown', + _constants.ARH_JAVASCRIPT_ASPECT_RATIO_SHOW_KEY: True, + _constants.ARH_JAVASCRIPT_ASPECT_RATIOS_KEY: + '1:1, 3:2, 4:3, 5:4, 16:9', + _constants.ARH_SHOW_MAX_WIDTH_OR_HEIGHT_KEY: False, + _constants.ARH_MAX_WIDTH_OR_HEIGHT_KEY: + _constants.MAX_DIMENSION / 2, + _constants.ARH_SHOW_MIN_WIDTH_OR_HEIGHT_KEY: False, + _constants.ARH_MIN_WIDTH_OR_HEIGHT_KEY: + _constants.MAX_DIMENSION / 2, + _constants.ARH_SHOW_PREDEFINED_PERCENTAGES_KEY: False, + _constants.ARH_PREDEFINED_PERCENTAGES_KEY: + '25, 50, 75, 125, 150, 175, 200', + _constants.ARH_PREDEFINED_PERCENTAGES_DISPLAY_KEY: + _constants.DEFAULT_PERCENTAGES_DISPLAY_KEY, + _constants.ARH_SHOW_PREDEFINED_ASPECT_RATIOS_KEY: False, + _constants.ARH_PREDEFINED_ASPECT_RATIO_USE_MAX_DIM_KEY: False, + _constants.ARH_PREDEFINED_ASPECT_RATIOS_KEY: + '1:1, 4:3, 16:9, 9:16, 21:9', +} + + +def safe_opt(key): + return _util.safe_opt_util(shared.opts, key, OPT_KEY_TO_DEFAULT_MAP) + + +def sort_components_by_keys( + components: list[_components.ArhUIComponent], +) -> list[_components.ArhUIComponent]: + ordered_component_keys = safe_opt( + _constants.ARH_UI_COMPONENT_ORDER_KEY, + ).split(',') + + # this can happen if we add new components, but the user has old settings. + # if this happens, we find the missing components, and append them. + if len(ordered_component_keys) != len(COMPONENTS): + all_components = set(DEFAULT_UI_COMPONENT_ORDER_KEY_LIST) + missing_components = all_components - set(ordered_component_keys) + ordered_component_keys.extend(missing_components) + + try: + component_key_to_order_dict = { + key: order for order, key in enumerate( + [k.strip() for k in ordered_component_keys], + ) + } + return sorted( + components, + key=lambda c: component_key_to_order_dict.get( + c.__class__.__name__, + ), + ) + except ValueError: + print( + f'{_constants.EXTENSION_NAME} UI component order is erroneous. ' + f'Defaulting to regular order, to fix this, please use' + f'the intended syntax for the setting, i.e ' + f'"{DEFAULT_UI_COMPONENT_ORDER_KEY}"', + ) + return components + + +def on_ui_settings(): + # javascript ui options + shared.opts.add_option( + key=_constants.ARH_JAVASCRIPT_ASPECT_RATIO_SHOW_KEY, + info=shared.OptionInfo( + default=OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_JAVASCRIPT_ASPECT_RATIO_SHOW_KEY, + ), + label='Enable JavaScript aspect ratio controls', + section=_constants.SECTION, + ), + ) + shared.opts.add_option( + key=_constants.ARH_JAVASCRIPT_ASPECT_RATIOS_KEY, + info=shared.OptionInfo( + default=OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_JAVASCRIPT_ASPECT_RATIOS_KEY, + ), + label='JavaScript aspect ratio buttons' + ' (1:1, 4:3, 16:9, 9:16, 21:9)', + section=_constants.SECTION, + ), + ) + shared.opts.add_option( + key=_constants.ARH_UI_JAVASCRIPT_SELECTION_METHOD, + info=shared.OptionInfo( + default=OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_UI_JAVASCRIPT_SELECTION_METHOD, + ), + label='JavaScript selection method', + component=gr.Dropdown, + component_args=lambda: { + 'choices': [ + 'Aspect Ratios Dropdown', + 'Default Options Button', + ], + }, + section=_constants.SECTION, + ), + ) + + # accordion options + shared.opts.add_option( + key=_constants.ARH_HIDE_ACCORDION_BY_DEFAULT_KEY, + info=shared.OptionInfo( + default=OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_HIDE_ACCORDION_BY_DEFAULT_KEY, + ), + label='Hide accordion by default', + section=_constants.SECTION, + ), + ) + shared.opts.add_option( + key=_constants.ARH_EXPAND_BY_DEFAULT_KEY, + info=shared.OptionInfo( + default=OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_EXPAND_BY_DEFAULT_KEY, + ), + label='Expand accordion by default', + section=_constants.SECTION, + ), + ) + shared.opts.add_option( + key=_constants.ARH_UI_COMPONENT_ORDER_KEY, + info=shared.OptionInfo( + default=OPT_KEY_TO_DEFAULT_MAP.get( + _constants.ARH_UI_COMPONENT_ORDER_KEY, + ), + label='UI Component order', + component=gr.Dropdown, + component_args=lambda: { + 'choices': [ + ', '.join(p) for p in itertools.permutations( # TODO: Rethink this, exponential growth... + DEFAULT_UI_COMPONENT_ORDER_KEY_LIST, + ) + ], + }, + section=_constants.SECTION, + ), + ) + + for component in COMPONENTS: + component.add_options(shared) diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/_util.py b/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b10be805845ec58a21eafedc0f26842f13399ffc --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/_util.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +import contextlib + +import aspect_ratio_helper._constants as _const + + +def safe_opt_util(shared_opts, key, default_key_map: dict[str, object]): + # attempt to retrieve key from shared options + with contextlib.suppress(AttributeError): + value = shared_opts.__getattr__(key) + if value is not None: + return value + + # attempt to retrieve default, and last resort the constant default + return shared_opts.get_default(key) or default_key_map.get(key) + + +def display_multiplication(num) -> str: + return f'x{round(num / 100, 3)}' + + +def display_raw_percentage(num) -> str: + return f'{num}%' + + +def display_minus_and_plus(num) -> str: + num -= 100 + if num > 0: + return f'+{num}%' + return f'{num}%' + + +def scale_by_percentage(width, height, pct) -> tuple[int, int]: + aspect_ratio = float(width) / float(height) + step = (pct - 1.0) + new_width = int(round(width * (1.0 + step))) + new_height = int(round(new_width / aspect_ratio)) + return clamp_to_boundaries(new_width, new_height, aspect_ratio) + + +def scale_dimensions_to_ui_width_or_height( + width, height, arw, arh, +) -> tuple[int, int]: + return scale_dimensions_to_max_dim(arw, arh, max(width, height)) + + +def scale_dimensions_to_max_dim_func( + width, height, max_dim: callable, +) -> tuple[int, int]: + return scale_dimensions_to_max_dim(width, height, max_dim()) + + +def scale_dimensions_to_max_dim( + width, height, max_dim, +) -> tuple[int, int]: + aspect_ratio = float(width) / float(height) + return scale_dimensions_to_ar(width, height, max_dim, aspect_ratio) + + +def scale_dimensions_to_min_dim( + width, height, min_dim, +) -> tuple[int, int]: + aspect_ratio = float(width) / float(height) + if width >= height: + max_dim = min_dim * aspect_ratio + else: + max_dim = min_dim / aspect_ratio + return scale_dimensions_to_ar(width, height, max_dim, aspect_ratio) + + +def scale_dimensions_to_ar( + width, height, max_dim, aspect_ratio, +) -> tuple[int, int]: + if width > height: + new_width = max_dim + new_height = int(round(max_dim / aspect_ratio)) + else: + new_height = max_dim + new_width = int(round(max_dim * aspect_ratio)) + return clamp_to_boundaries(new_width, new_height, aspect_ratio) + + +def round_to_multiple_of_8(value): + return int(round(value / 8.0)) * 8 + + +def clamp_to_boundaries(owidth, oheight, aspect_ratio) -> tuple[int, int]: + width, height = owidth, oheight + if width > _const.MAX_DIMENSION: + width = _const.MAX_DIMENSION + height = int(round(width / aspect_ratio)) + if height > _const.MAX_DIMENSION: + height = _const.MAX_DIMENSION + width = int(round(height * aspect_ratio)) + if width < _const.MIN_DIMENSION: + width = _const.MIN_DIMENSION + height = int(round(width / aspect_ratio)) + if height < _const.MIN_DIMENSION: + height = _const.MIN_DIMENSION + width = int(round(height * aspect_ratio)) + + width = round_to_multiple_of_8(width) + height = round_to_multiple_of_8(height) + # for insane aspect ratios we don't support... i.e 1:100 + # 64:6400 when run through this function, so we clamp to 64:2048 (‾◡◝) + # also. when the user does this it breaks the "scale to max" function + # on the ui until they change to another reasonable aspect ratio. + # todo: figure out why ^ and handle it better. + if width < _const.MIN_DIMENSION: + width = _const.MIN_DIMENSION + elif width > _const.MAX_DIMENSION: + width = _const.MAX_DIMENSION + if height < _const.MIN_DIMENSION: + height = _const.MIN_DIMENSION + elif height > _const.MAX_DIMENSION: + height = _const.MAX_DIMENSION + + return width, height diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/main.py b/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/main.py new file mode 100644 index 0000000000000000000000000000000000000000..814569e123b3d9c3e6d83cdece9b7f6b7523b468 --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/aspect_ratio_helper/main.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +import gradio as gr +from modules import script_callbacks +from modules import scripts + +import aspect_ratio_helper._constants as _constants +import aspect_ratio_helper._settings as _settings + + +class AspectRatioStepScript(scripts.Script): + + def __init__(self): + self.t2i_w: gr.components.Slider | None = None + self.t2i_h: gr.components.Slider | None = None + self.i2i_w: gr.components.Slider | None = None + self.i2i_h: gr.components.Slider | None = None + self.wc: gr.components.Slider + self.hc: gr.components.Slider + self.max_dimension: float + + def title(self) -> str: + return _constants.EXTENSION_NAME + + def show(self, _) -> scripts.AlwaysVisible: + return scripts.AlwaysVisible + + def ui(self, is_img2img): + if is_img2img: + self.wc, self.hc = self.i2i_w, self.i2i_h + else: + self.wc, self.hc = self.t2i_w, self.t2i_h # noqa + + components = _settings.sort_components_by_keys( + [component(self) for component in _settings.COMPONENTS], + ) + + hide_accordion: bool = _settings.safe_opt( + _constants.ARH_HIDE_ACCORDION_BY_DEFAULT_KEY, + ) + + if hide_accordion or not any(c.should_show() for c in components): + return # no components should render, so just return. + + start_expanded: bool = _settings.safe_opt( + _constants.ARH_EXPAND_BY_DEFAULT_KEY, + ) + with gr.Group(), gr.Accordion( + _constants.EXTENSION_NAME, + open=start_expanded, + ): + for component in components: + # we deliberately DON'T check component.should_show() here. + # we need to call render to instantiate the components, we use + # the visible property on each component to hide them. + component.render() + + def after_component(self, component: gr.components.Component, **kwargs): + element_id = kwargs.get('elem_id') + + if isinstance(component, gr.components.Slider): + if element_id == 'txt2img_width': + self.t2i_w: gr.components.Slider = component + elif element_id == 'txt2img_height': + self.t2i_h: gr.components.Slider = component + elif element_id == 'img2img_width': + self.i2i_w: gr.components.Slider = component + elif element_id == 'img2img_height': + self.i2i_h: gr.components.Slider = component + + +script_callbacks.on_ui_settings(_settings.on_ui_settings) diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/docs/opts.png b/extensions-builtin/sd-webui-aspect-ratio-helper-main/docs/opts.png new file mode 100644 index 0000000000000000000000000000000000000000..76037916f8a8501e0d8209eac0b6ec8ac4f759e0 Binary files /dev/null and b/extensions-builtin/sd-webui-aspect-ratio-helper-main/docs/opts.png differ diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/docs/ui.png b/extensions-builtin/sd-webui-aspect-ratio-helper-main/docs/ui.png new file mode 100644 index 0000000000000000000000000000000000000000..51b1371f094efa2875be1559d009dd9fbabfb23e Binary files /dev/null and b/extensions-builtin/sd-webui-aspect-ratio-helper-main/docs/ui.png differ diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/javascript/aspectRatioController.js b/extensions-builtin/sd-webui-aspect-ratio-helper-main/javascript/aspectRatioController.js new file mode 100644 index 0000000000000000000000000000000000000000..c699fb708506d49b69e38bf0983e6da3a7cf3fe1 --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/javascript/aspectRatioController.js @@ -0,0 +1,474 @@ +// constants +const _OFF = "Off"; // Don't use the functionality at all +const _LOCK = '🔒'; // Aspect ratio is "locked" +const _IMAGE = '🖼️'; // Aspect ratio is "locked" to that of the image + +const _MAXIMUM_DIMENSION = 2048; +const _MINIMUM_DIMENSION = 64; + +const _IMAGE_INPUT_CONTAINER_IDS = [ + 'img2img_image', + 'img2img_sketch', + 'img2maskimg', + 'inpaint_sketch', + 'img_inpaint_base', +]; + +const getSelectedImage2ImageTab = () => { + const selectedButton = gradioApp().getElementById('mode_img2img').querySelector('button.selected'); + const allButtons = gradioApp().getElementById('mode_img2img').querySelectorAll('button'); + const selectedIndex = Array.prototype.indexOf.call(allButtons, selectedButton); + return selectedIndex; +} + +const getCurrentImage = () => { + const currentTabIndex = getSelectedImage2ImageTab(); + const currentTabImageId = _IMAGE_INPUT_CONTAINER_IDS[currentTabIndex]; + return document.getElementById(currentTabImageId).querySelector('img'); +} + +const roundToClosestMultiple = (num, multiple) => { + const rounded = Math.round(Number(num) / multiple) * multiple; + return rounded; +} + +const aspectRatioFromStr = (ar) => { + if (!ar.includes(':')) return; + return ar.split(':').map(x => Number(x)); +} + +const reverseAspectRatio = (ar) => { + if (!ar.includes(':')) return; + const [width, height] = ar.split(':'); + return `${height}:${width}`; +} + +const clampToBoundaries = (width, height) => { + const aspectRatio = width / height; + width = Math.max(Math.min(width, _MAXIMUM_DIMENSION), _MINIMUM_DIMENSION); + height = Math.max(Math.min(height, _MAXIMUM_DIMENSION), _MINIMUM_DIMENSION); + if (width / height > aspectRatio) { + height = Math.round(width / aspectRatio); + } else if (width / height < aspectRatio) { + width = Math.round(height * aspectRatio); + } + + if (width > _MAXIMUM_DIMENSION) { + width = _MAXIMUM_DIMENSION; + } else if (width < _MINIMUM_DIMENSION) { + width = _MINIMUM_DIMENSION; + } + + if (height < _MINIMUM_DIMENSION) { + height = _MINIMUM_DIMENSION; + } else if (height > _MAXIMUM_DIMENSION) { + height = _MAXIMUM_DIMENSION; + } + + return [width, height]; +} + +const getOptions = () => { + return window.opts.arh_javascript_aspect_ratio.split(',').map(o => o.trim()); +} + +const reverseAllOptions = () => { + const allAspectRatioOptions = Array.from(gradioApp().querySelectorAll('.ar-option')); + allAspectRatioOptions.forEach(el => { + const reversed = reverseAspectRatio(el.value); + if (reversed) { + el.value = reversed; + el.textContent = reversed; + } + }); +} + +class OptionPickingController { + constructor(page, defaultOptions, controller) { + this.page = page; + this.options = this.getOptions(defaultOptions); + this.switchButton = gradioApp().getElementById(page + '_res_switch_btn'); + + const wrapperDiv = document.createElement('div'); + wrapperDiv.setAttribute("id", `${this.page}_size_toolbox`); + wrapperDiv.setAttribute("class", "flex flex-col relative col gap-4"); + wrapperDiv.setAttribute("style", "min-width: min(320px, 100%); flex-grow: 0"); + wrapperDiv.innerHTML = this.getElementInnerHTML(); + + const parent = this.switchButton.parentNode; + parent.removeChild(this.switchButton); + wrapperDiv.appendChild(this.switchButton); + parent.insertBefore(wrapperDiv, parent.lastChild.previousElementSibling); + + this.getPickerElement().onchange = this.pickerChanged(controller); + this.switchButton.onclick = this.switchButtonOnclick(controller); + } + + getOptions(defaultOptions) { + return [...new Set([...defaultOptions, ...getOptions()])]; + } + + pickerChanged(controller) { + return () => { + const picked = this.getCurrentOption(); + if (_IMAGE === picked) { + // this.switchButton.disabled = true; + } else { + this.switchButton.removeAttribute('disabled') + } + + controller.setAspectRatio(picked); + }; + } + + switchButtonOnclick(controller) { + return () => { + reverseAllOptions(); + const picked = this.getCurrentOption(); + if (_LOCK === picked) { + controller.setAspectRatio(`${controller.heightRatio}:${controller.widthRatio}`); + } else { + controller.setAspectRatio(picked); + } + }; + } + + getElementInnerHTML() { + throw new Error('Not implemented'); + } + + getPickerElement() { + throw new Error('Not implemented'); + } + + getCurrentOption() { + throw new Error('Not implemented'); + } +} + + +class SelectOptionPickingController extends OptionPickingController { + constructor(page, defaultOptions, controller) { + super(page, defaultOptions, controller); + } + + getElementInnerHTML() { + return ` +
+ +
+ `; + } + + getPickerElement() { + return gradioApp().getElementById(`${this.page}_select_aspect_ratio`); + } + + getCurrentOption() { + const selectElement = this.getPickerElement(); + const options = Array.from(selectElement); + return options[selectElement.selectedIndex].value; + } +} + +class DefaultOptionsButtonOptionPickingController extends OptionPickingController { + constructor(page, defaultOptions, controller) { + super(page, defaultOptions, controller); + this.currentIndex = 0; + this.getPickerElement().onclick = this.pickerChanged(controller); + } + + pickerChanged(controller) { + return () => { + this.currentIndex = (this.currentIndex + 1) % this.options.length; + this.getPickerElement().querySelector('button').textContent = this.getCurrentOption(); + super.pickerChanged(controller)(); + } + } + + getElementInnerHTML() { + const classes = Array.from(this.switchButton.classList); + return ` +
+ +
+ `; + } + + getPickerElement() { + return gradioApp().getElementById(`${this.page}_ar_default_options_button`); + } + + getOptions(defaultOptions) { + return defaultOptions; + } + + getCurrentOption() { + return this.options[this.currentIndex || 0]; + } +} + + +class SliderController { + constructor(element) { + this.element = element; + this.numberInput = this.element.querySelector('input[type=number]'); + this.rangeInput = this.element.querySelector('input[type=range]'); + this.inputs = [this.numberInput, this.rangeInput]; + this.inputs.forEach(input => { + input.isWidth = element.isWidth; + }); + } + + getVal() { + return Number(this.numberInput.value); + } + + updateVal(value) { + this.inputs.forEach(input => { + input.value = Number(value) + }) + } + + updateMin(value) { + this.inputs.forEach(input => { + input.min = roundToClosestMultiple(Number(value), 8); + }) + } + + updateMax(value) { + this.inputs.forEach(input => { + input.max = roundToClosestMultiple(Number(value), 8); + }) + } + + triggerEvent(event) { + this.numberInput.dispatchEvent(event) + } + + setVal(value) { + value = Number(value) + const newValue = roundToClosestMultiple(value, 8) + this.updateVal(newValue); + } + +} + +class AspectRatioController { + constructor(page, widthContainer, heightContainer, defaultOptions) { + widthContainer.isWidth = true; + heightContainer.isWidth = false; + this.widthContainer = new SliderController(widthContainer); + this.heightContainer = new SliderController(heightContainer); + this.inputs = [...this.widthContainer.inputs, ...this.heightContainer.inputs]; + this.inputs.forEach(input => { + input.addEventListener('change', (e) => { + e.preventDefault() + this.maintainAspectRatio(input); + }); + }) + + if (window.opts.arh_ui_javascript_selection_method === 'Default Options Button') { + this.optionPickingControler = new DefaultOptionsButtonOptionPickingController(page, defaultOptions, this); + } else { + this.optionPickingControler = new SelectOptionPickingController(page, defaultOptions, this); + } + + this.setAspectRatio(_OFF); + } + + updateInputStates() { + if (this.isLandscapeOrSquare()) { + const AR = this.widthRatio / this.heightRatio; + + const minWidthByAr = Math.round(_MINIMUM_DIMENSION * AR); + const minWidth = Math.max(minWidthByAr, _MINIMUM_DIMENSION); + this.widthContainer.updateMin(minWidth); + this.heightContainer.updateMin(_MINIMUM_DIMENSION); + + const maxHeightByAr = Math.round(_MAXIMUM_DIMENSION / AR) + const maxHeight = Math.min(_MAXIMUM_DIMENSION, maxHeightByAr); + this.heightContainer.updateMax(maxHeight); + this.widthContainer.updateMax(_MAXIMUM_DIMENSION); + } else { + const AR = this.heightRatio / this.widthRatio; + + const minHeightByAr = Math.round(_MINIMUM_DIMENSION * AR) + const minHeight = Math.max(minHeightByAr, _MINIMUM_DIMENSION); + this.heightContainer.updateMin(minHeight); + this.widthContainer.updateMin(_MINIMUM_DIMENSION); + + const maxWidthByAr = Math.round(_MAXIMUM_DIMENSION / AR) + const maxWidth = Math.min(_MAXIMUM_DIMENSION, maxWidthByAr); + this.widthContainer.updateMax(maxWidth); + this.heightContainer.updateMax(_MAXIMUM_DIMENSION); + } + } + + disable() { + this.widthContainer.updateMin(_MINIMUM_DIMENSION); + this.heightContainer.updateMin(_MINIMUM_DIMENSION); + this.widthContainer.updateMax(_MAXIMUM_DIMENSION); + this.heightContainer.updateMax(_MAXIMUM_DIMENSION); + } + + isLandscapeOrSquare() { + return this.widthRatio >= this.heightRatio; + } + + setAspectRatio(aspectRatio) { + this.aspectRatio = aspectRatio; + + let wR, hR; + if (aspectRatio === _OFF) { + return this.disable(); + } else if (aspectRatio === _IMAGE) { + const img = getCurrentImage(); + wR = img && img.naturalWidth || 1; + hR = img && img.naturalHeight || 1; + } else if (aspectRatio === _LOCK) { + wR = this.widthContainer.getVal(); + hR = this.heightContainer.getVal(); + } else { + [wR, hR] = aspectRatioFromStr(aspectRatio); + } + + [wR, hR] = clampToBoundaries(wR, hR); + + this.widthRatio = wR; + this.heightRatio = hR; + this.updateInputStates(); + this.maintainAspectRatio(); + } + + maintainAspectRatio(changedElement) { + if (this.aspectRatio === _OFF) return; + if (!changedElement) { + const allValues = Object.values(this.inputs).map(x => Number(x.value)); + changedElement = {value: Math.max(...allValues)}; + } + + const aspectRatio = this.widthRatio / this.heightRatio; + let w, h; + + if (changedElement.isWidth === undefined) { + if (this.isLandscapeOrSquare()) { + if (changedElement.isWidth) {} + w = Math.round(changedElement.value); + h = Math.round(changedElement.value / aspectRatio); + } else { + h = Math.round(changedElement.value); + w = Math.round(changedElement.value * aspectRatio); + } + } else { + if (changedElement.isWidth) { + w = Math.round(changedElement.value); + h = Math.round(changedElement.value / aspectRatio); + } else { + h = Math.round(changedElement.value); + w = Math.round(changedElement.value * aspectRatio); + } + } + + const [width, height] = clampToBoundaries(w, h) + + const inputEvent = new Event("input", {bubbles: true}); + this.widthContainer.setVal(width); + this.widthContainer.triggerEvent(inputEvent); + this.heightContainer.setVal(height); + this.heightContainer.triggerEvent(inputEvent); + this.heightContainer.inputs.forEach(input => { + dimensionChange({target: input}, false, true); + }); + this.widthContainer.inputs.forEach(input => { + dimensionChange({target: input}, true, false); + }); + } + + static observeStartup(key, page, defaultOptions, postSetup = (_) => { + }) { + let observer = new MutationObserver(() => { + const widthContainer = gradioApp().querySelector(`#${page}_width`); + const heightContainer = gradioApp().querySelector(`#${page}_height`); + + // wait for width and height containers to exist. + if (widthContainer && heightContainer && window.opts && window.opts.arh_javascript_aspect_ratio_show !== undefined) { + observer.disconnect(); + if (!window.opts.arh_javascript_aspect_ratio_show) { + return; + } + + const controller = new AspectRatioController( + page, + widthContainer, + heightContainer, + defaultOptions, + ); + + postSetup(controller); + window[key] = controller; + } + }); + + observer.observe(gradioApp(), {childList: true, subtree: true}); + } + +} + +const addImg2ImgTabSwitchClickListeners = (controller) => { + const img2imgTabButtons = Array.from(document.querySelectorAll('#img2img_settings > div > div > button:not(.selected):not(.hasTabSwitchListener)')); + img2imgTabButtons.forEach(button => { + button.addEventListener('click', (_) => { + // set aspect ratio is RECALLED to change to the image specific to the newly selected tab. + if (controller.optionPickingControler.getCurrentOption() === _IMAGE) { + controller.setAspectRatio(_IMAGE); + } + + addImg2ImgTabSwitchClickListeners(controller); + }); + + button.classList.add('hasTabSwitchListener'); + }); +} + +const postImageControllerSetupFunction = (controller) => { + const scaleToImg2ImgImage = (e) => { + const picked = controller.optionPickingControler.getCurrentOption(); + if (picked !== _IMAGE) return; + const files = e.dataTransfer ? e.dataTransfer.files : e.target.files; + const img = new Image(); + img.src = URL.createObjectURL(files[0]); + img.onload = () => { + controller.setAspectRatio(`${img.naturalWidth}:${img.naturalHeight}`) + }; + } + + _IMAGE_INPUT_CONTAINER_IDS.forEach(imageContainerId => { + const imageContainer = document.getElementById(imageContainerId); + const inputElement = imageContainer.querySelector('input'); + inputElement.parentElement.addEventListener('drop', scaleToImg2ImgImage); + inputElement.addEventListener('change', scaleToImg2ImgImage); + }) + + addImg2ImgTabSwitchClickListeners(controller); +} + +document.addEventListener("DOMContentLoaded", () => { + AspectRatioController.observeStartup( + "__txt2imgAspectRatioController", + "txt2img", + [_OFF, _LOCK] + ); + AspectRatioController.observeStartup( + "__img2imgAspectRatioController", + "img2img", + [_OFF, _LOCK, _IMAGE], + postImageControllerSetupFunction + ); +}); diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/scripts/sd_webui_aspect_ratio_helper.py b/extensions-builtin/sd-webui-aspect-ratio-helper-main/scripts/sd_webui_aspect_ratio_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..ed78b20d6a33f4f180b0f04392dfbb08f72ec1a8 --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/scripts/sd_webui_aspect_ratio_helper.py @@ -0,0 +1,5 @@ +from __future__ import annotations + +from aspect_ratio_helper.main import AspectRatioStepScript + +__all__ = ['AspectRatioStepScript'] diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/style.css b/extensions-builtin/sd-webui-aspect-ratio-helper-main/style.css new file mode 100644 index 0000000000000000000000000000000000000000..d6a3378cdb00d7d716570823ad5e49d8d091f39e --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/style.css @@ -0,0 +1,36 @@ +#txt2img_size_toolbox, #img2img_size_toolbox { + min-width: unset !important; + gap: 0; +} + +#txt2img_ratio, #img2img_ratio { + padding: 0px; + min-width: unset; + max-width: fit-content; +} + +#txt2img_ratio select, #img2img_ratio select { + background: var(--background-fill-primary); + border: 1px solid var(--block-border-color); + color: var(--block-label-text-color); + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; + background-image: none; + tab-size: 4; + font-size: 14px; + line-height: 1.4; + box-sizing: border-box; + position: relative; + border-radius: 8px; + box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); + padding-right: 1px; + margin-bottom: 10px; + padding-left: 2px; + text-align: center; + min-width: 2.5em; +} + +.arh-btn-row button { + min-width: fit-content; +} diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/tests/__init__.py b/extensions-builtin/sd-webui-aspect-ratio-helper-main/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/tests/_util_test.py b/extensions-builtin/sd-webui-aspect-ratio-helper-main/tests/_util_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4d736c15376638b53e564b0d8449e49d00f0bcb1 --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/tests/_util_test.py @@ -0,0 +1,291 @@ +from __future__ import annotations + +import pytest + +import aspect_ratio_helper._constants as _constants +import aspect_ratio_helper._util as _util + + +@pytest.mark.parametrize( + 'num, expected', + [ + (50, 'x0.5'), + (150, 'x1.5'), + (175, 'x1.75'), + (250, 'x2.5'), + ], +) +def test_display_multiplication(num, expected): + assert _util.display_multiplication(num) == expected + + +@pytest.mark.parametrize( + 'num, expected', + [ + (50, '50%'), + (75, '75%'), + (100, '100%'), + (150, '150%'), + (250, '250%'), + ], +) +def test_display_raw_percentage(num, expected): + assert _util.display_raw_percentage(num) == expected + + +@pytest.mark.parametrize( + 'num, expected_output', [ + (150, '+50%'), + (100, '0%'), + (50, '-50%'), + (0, '-100%'), + (200, '+100%'), + (75, '-25%'), + ], +) +def test_display_minus_and_plus(num, expected_output): + assert _util.display_minus_and_plus(num) == expected_output + + +@pytest.mark.parametrize( + 'width, height, pct, expected', + [ + pytest.param(200, 400, 0.5, (96, 200), id='50_percent_scale_down'), + pytest.param(100, 200, 2.0, (200, 400), id='200_percent_scale_up'), + pytest.param(100, 200, 1.1, (112, 224), id='10_percent_scale_up'), + pytest.param(100, 200, 0.9, (88, 176), id='10_percent_scale_down'), + pytest.param(100, 200, 0.0, (64, 128), id='scale_full_down'), + pytest.param( + _constants.MIN_DIMENSION - 1, + _constants.MIN_DIMENSION - 1, + 0.5, + (_constants.MIN_DIMENSION, _constants.MIN_DIMENSION), + id='scale_belowMIN_DIMENSION', + ), + pytest.param( + _constants.MAX_DIMENSION + 1, + _constants.MAX_DIMENSION + 1, + 2.0, + (_constants.MAX_DIMENSION, _constants.MAX_DIMENSION), + id='scale_aboveMAX_DIMENSION', + ), + ], +) +def test_scale_by_percentage( + width, height, pct, expected, +): + assert _util.scale_by_percentage( + width, height, pct, + ) == expected + + +@pytest.mark.parametrize( + 'width, height, max_dim, expected', + [ + # pytest.param( + # 100, 200, 400, (200, 400), + # id='scale_up_to_max_dimension_horizontally', + # ), + # pytest.param( + # 200, 100, 400, (400, 200), + # id='scale_up_to_max_dimension_vertically', + # ), + # pytest.param( + # 400, 64, 400, (400, 64), + # id='no_scale_up_needed_with_max_dimension_width', + # ), + # pytest.param( + # 64, 400, 400, (64, 400), + # id='no_scale_up_needed_with_max_dimension_height', + # ), + # pytest.param( + # _constants.MIN_DIMENSION, + # _constants.MIN_DIMENSION, + # _constants.MAX_DIMENSION, + # (_constants.MAX_DIMENSION, _constants.MAX_DIMENSION), + # id='scale_from_min_to_max', + # ), + # pytest.param( + # _constants.MAX_DIMENSION, + # _constants.MAX_DIMENSION, + # _constants.MIN_DIMENSION, + # (_constants.MIN_DIMENSION, _constants.MIN_DIMENSION), + # id='scale_from_max_to_min', + # ), + pytest.param( + _constants.MIN_DIMENSION, 32, _constants.MIN_DIMENSION, + (128, _constants.MIN_DIMENSION), + id='scale_below_min_height_dimension_clamps_retains_ar', + ), + pytest.param( + 32, _constants.MIN_DIMENSION, _constants.MIN_DIMENSION, + (_constants.MIN_DIMENSION, 128), + id='scale_below_min_width_dimension_clamps_retains_ar', + ), + # pytest.param( + # _constants.MAX_DIMENSION, 4096, _constants.MAX_DIMENSION, + # (1024, _constants.MAX_DIMENSION), + # id='scale_above_max_height_dimension_clamps_retains_ar', + # ), + # pytest.param( + # 4096, _constants.MAX_DIMENSION, _constants.MAX_DIMENSION, + # (_constants.MAX_DIMENSION, 1024), + # id='scale_above_max_width_dimension_clamps_retains_ar', + # ), + # pytest.param( + # 64, 64, _constants.MIN_DIMENSION - 1, + # (_constants.MIN_DIMENSION, _constants.MIN_DIMENSION), + # id='scale_dimension_below_min_dimension_clamps_retains_ar', + # ), + # pytest.param( + # 64, 64, _constants.MAX_DIMENSION + 1, + # (_constants.MAX_DIMENSION, _constants.MAX_DIMENSION), + # id='scale_dimension_above_max_dimension_clamps_retains_ar', + # ), + ], +) +def test_scale_dimensions_to_max_dim( + width, height, max_dim, expected, +): + assert _util.scale_dimensions_to_max_dim( + width, height, max_dim, + ) == expected + + +@pytest.mark.parametrize( + 'width, height, min_dim, expected', + [ + pytest.param( + 100, 200, 400, (400, 800), + id='scale_up_to_min_dimension_with_ar_preservation', + ), + pytest.param( + 200, 100, 400, (800, 400), + id='scale_up_to_min_dimension_with_ar_preservation', + ), + pytest.param( + 100, 100, 400, (400, 400), + id='no_scale_up_needed_with_min_dimension', + ), + pytest.param( + _constants.MIN_DIMENSION, _constants.MIN_DIMENSION, _constants.MAX_DIMENSION, + (_constants.MAX_DIMENSION, _constants.MAX_DIMENSION), + id='scale_up_to_max_dimension_with_ar_preservation', + ), + pytest.param( + _constants.MAX_DIMENSION, _constants.MAX_DIMENSION, _constants.MIN_DIMENSION, + (_constants.MIN_DIMENSION, _constants.MIN_DIMENSION), + id='scale_down_to_min_dimension_with_ar_preservation', + ), + pytest.param( + 100, 100, _constants.MAX_DIMENSION, + (_constants.MAX_DIMENSION, _constants.MAX_DIMENSION), + id='scale_up_to_max_dimension_with_ar_preservation', + ), + ], +) +def test_scale_dimensions_to_min_dim( + width, height, min_dim, expected, +): + assert _util.scale_dimensions_to_min_dim( + width, height, min_dim, + ) == expected + + +class SharedOpts: + def __init__(self, options=None, defaults=None): + self.options = options or {} + self.defaults = defaults or {} + + def __getattr__(self, key): + try: + return self.options[key] + except KeyError: + raise AttributeError() + + def get_default(self, key): + return self.defaults.get(key, None) + + +def test_safe_opt_util(): + shared_opts = SharedOpts(options={'key': 'value'}) + assert _util.safe_opt_util(shared_opts, 'key', {}) == 'value' + + +def test_safe_opt_util_none(): + shared_opts = SharedOpts(options={'key': None}, defaults={'key': 'value'}) + assert _util.safe_opt_util(shared_opts, 'key', {}) == 'value' + + +def testsafe_opt_util_default_a(): + shared_opts = SharedOpts( + defaults={'key': 'default_a'}, + ) + assert _util.safe_opt_util( + shared_opts, 'key', {'key': 'default_b'}, + ) == 'default_a' + + +def test_safe_opt_util_default_b(): + shared_opts = SharedOpts(defaults={'key': None}) + assert _util.safe_opt_util( + shared_opts, 'key', {'key': 'default_b'}, + ) == 'default_b' + + +@pytest.mark.parametrize( + 'options', ({'key': None}, {}), +) +def test_safe_opt_safe_return_no_defaults_b(options): + shared_opts = SharedOpts(options=options) + assert _util.safe_opt_util(shared_opts, 'unknown_key', {}) is None + + +@pytest.mark.parametrize( + 'value, expected', [ + (0, 0), + (7, 8), + (10, 8), + (16, 16), + (23, 24), + (32, 32), + (33, 32), + (100, 96), + (10.5, 8), + (15.3, 16), + (21.8, 24), + (33.9, 32), + (98.7, 96), + ], +) +def test_round_to_multiple_of_8(value, expected): + assert _util.round_to_multiple_of_8(value) == expected + + +@pytest.mark.parametrize( + 'width, height, aspect_ratio, expected', [ + (100, 100, 1.0, (96, 96)), + (3000, 2000, 1.5, (2048, 1368)), + (500, 8000, 0.5, (1024, 2048)), + (500, 300, 2.0, (496, 304)), + (100, 200, 0.5, (96, 200)), + (500, 500, 1.2, (496, 496)), + (2048, 2048, 1.0, (2048, 2048)), + (2049, 2048, 1.0, (2048, 2048)), + (2048, 2049, 1.0, (2048, 2048)), + (2049, 2049, 1.0, (2048, 2048)), + (63, 63, 1.0, (64, 64)), + (2050, 2050, 1.0, (2048, 2048)), + (63, 64, 1.0, (64, 64)), + (64, 63, 1.0, (64, 64)), + (64, 64, 1.0, (64, 64)), + (63, 63, 1.0, (64, 64)), + (2050, 63, 1.0, (2048, 2048)), + (63, 2050, 1.0, (2048, 2048)), + (2050, 2050, 0.01, (64, 2048)), + (100.5, 100.5, 1.0, (104, 104)), + (200.3, 100.7, 0.5, (200, 104)), + ], +) +def test_clamp_to_boundaries(width, height, aspect_ratio, expected): + assert _util.clamp_to_boundaries(width, height, aspect_ratio) == expected diff --git a/extensions-builtin/sd-webui-aspect-ratio-helper-main/tox.ini b/extensions-builtin/sd-webui-aspect-ratio-helper-main/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..4c6cac4b77bc3e9d6f668da6c3ce61e3c1551929 --- /dev/null +++ b/extensions-builtin/sd-webui-aspect-ratio-helper-main/tox.ini @@ -0,0 +1,6 @@ +[tox] +envlist = py310, py311 + +[testenv] +deps = pytest +commands = pytest diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/.env.example b/extensions-builtin/sd-webui-infinite-image-browsing-main/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..36aae60cebd7ee4ec4921ef3b6913adf2d2538ba --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/.env.example @@ -0,0 +1,41 @@ +# This document is used for additional control over the security and privacy of IIB. By default, IIB is already sufficiently secure, and you do not need to take any additional actions. +# Copy this file and rename it to ".env" . Then, fill in the necessary values for your specific use case. +# Remember to never share your .env file with anyone else as it may contain sensitive information. + +# This attribute is used for authentication. If you input a key here, it will be validated for authentication purposes. +# It will be prompted to enter your key when you open the extension. If the authentication fails, all your requests will be rejected. +IIB_SECRET_KEY= + +# Configuring the server-side language for this extension, +# including the tab title and most of the server-side error messages returned. Options are 'zh', 'en', or 'auto'. +# If you want to configure the language for the front-end pages, please set it on the extension's global settings page. +IIB_SERVER_LANG=auto + +# This configuration parameter specifies the maximum number of database file backups for the IIB . +IIB_DB_FILE_BACKUP_MAX=8 + +# Set the cache directory for IIB, including image cache and video cover cache. +# The default is the system's temporary directory, but if you want to specify a custom directory, set it here. +# You can use --generate_video_cover and --generate_image_cache to pre-generate the cache. +# IIB_CACHE_DIR= + + +# ---------------------------- ACCESS_CONTROL ---------------------------- + +# Used to configure whether to enable access control to the file system. +# If enabled, only access to the provided pre-set folders (including those provided by sd-webui and manually \ +# added to Quick Move or specified via IIB_ACCESS_CONTROL_ALLOWED_PATHS) will be allowed. +# The available options are 'enable', 'disable', and 'auto'. +# The default value is 'auto', which will be determined based on the command-line parameters used to start sd-webui (such as --server-name, --share, --listen). +IIB_ACCESS_CONTROL=auto + +# This variable is used to define a list of allowed paths for the application to access when access control mode is enabled. +# It can be set to a comma-separated string of file paths or directory paths, representing the resources that are allowed to be accessed by the application. +# In addition, if sd_webui_config or sd_webui_dir has been configured, or if you're running this repository as an extension of sd-webui, +# you can use the following shortcuts (txt2img, img2img, extra, save) as values for the ALLOWED_PATHS variable. +# IIB_ACCESS_CONTROL_ALLOWED_PATHS=save,extra,/output ...etc + +# This variable is used to control fine-grained access control for different types of requests, but only if access control mode is enabled. +# It can be set to a string value that represents a specific permission or set of permissions, such as "read-only", "write-only", "read-write", or "no-access". +# This variable can be used to restrict access to certain API endpoints or data sources based on the permissions required by the user. +# IIB_ACCESS_CONTROL_PERMISSION=read-write diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/.github/FUNDING.yml b/extensions-builtin/sd-webui-infinite-image-browsing-main/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..4173aa12afce4920be16c9243d49aef687c10964 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/.github/FUNDING.yml @@ -0,0 +1,4 @@ +# These are supported funding model platforms + +ko_fi: zanllp +custom: https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/.github/wechat_funding.jpg diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/.github/wechat_funding.jpg b/extensions-builtin/sd-webui-infinite-image-browsing-main/.github/wechat_funding.jpg new file mode 100644 index 0000000000000000000000000000000000000000..02eed2dba13e10167c4c7a256cc3db2d0c22532a Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/.github/wechat_funding.jpg differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/.github/workflows/tauri_app_build.yml b/extensions-builtin/sd-webui-infinite-image-browsing-main/.github/workflows/tauri_app_build.yml new file mode 100644 index 0000000000000000000000000000000000000000..1d2d9346ecfa551ca58c9ac61078146f7e80ee8d --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/.github/workflows/tauri_app_build.yml @@ -0,0 +1,231 @@ +name: tauri_app_build + +on: + push: + branches: + - 'releases/**' + +jobs: + build: + strategy: + matrix: + os: [windows-latest,ubuntu-20.04] + + runs-on: ${{ matrix.os }} + + permissions: + contents: write + steps: + - name: Check-out repository + uses: actions/checkout@v3 + + - run: echo "VERSION=$(jq -r '.package.version' vue/src-tauri/tauri.conf.json)" >> "$GITHUB_ENV" + if: matrix.os == 'ubuntu-20.04' + - run: echo "VERSION=$(jq -r '.package.version' vue/src-tauri/tauri.conf.json)" >> $env:GITHUB_ENV + if: matrix.os == 'windows-latest' + + - name: Setup Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + cache: 'pip' + cache-dependency-path: | + **/requirements*.txt + + - name: Install Dependencies + run: | + + pip install -r requirements.txt + + - name: Build Executable + uses: Nuitka/Nuitka-Action@main + with: + nuitka-version: main + script-name: app.py + output-file: iib_api_server + output-dir: out + include-data-dir: | + vue/dist=vue/dist + + - run: cp out/iib_api_server out/iib_app_cli-${{ env.VERSION }}-${{ runner.os }} + if: matrix.os == 'ubuntu-20.04' + - run: cp out/iib_api_server.exe out/iib_app_cli-${{ env.VERSION }}-${{ runner.os }}.exe + if: matrix.os == 'windows-latest' + + - name: Upload Server Artifacts + uses: actions/upload-artifact@v3 + with: + name: iib_app_cli_${{ runner.os }} + path: | + out/iib_app_cli-${{ env.VERSION }}-${{ runner.os }} + out/iib_app_cli-${{ env.VERSION }}-${{ runner.os }}.exe + + - name: Upload Server Artifacts + uses: actions/upload-artifact@v3 + with: + name: iib_api_server-${{ env.VERSION }}-${{ runner.os }} + path: | + out/iib_api_server.exe + out/iib_api_server + + - run: mv out/iib_api_server.exe vue/src-tauri/iib_api_server-x86_64-pc-windows-msvc.exe + if: matrix.os == 'windows-latest' + + - run: mv out/iib_api_server vue/src-tauri/iib_api_server-x86_64-unknown-linux-gnu + if: matrix.os == 'ubuntu-20.04' + + - name: Install frontend dependencies + run: yarn install + working-directory: vue + + - name: Rust setup + uses: dtolnay/rust-toolchain@stable + + - name: Use Node.js + uses: actions/setup-node@v3 + with: + node-version: 18 + + - name: Rust cache + uses: swatinem/rust-cache@v2 + with: + workspaces: './vue/src-tauri -> target' + + - name: Install dependencies (ubuntu only) + if: matrix.os == 'ubuntu-20.04' + run: | + sudo apt-get update + sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libayatana-appindicator3-dev librsvg2-dev patchelf + + - name: Build the app + run: | + yarn tauri-build + working-directory: vue + + + - name: Upload Artifacts + uses: actions/upload-artifact@v3 + with: + name: bundle-${{ env.VERSION }}-${{ runner.os }} + path: | + vue/src-tauri/target/release/bundle/nsis/Infinite Image Browsing_${{ env.VERSION }}_x64-setup.exe + vue/src-tauri/target/release/bundle/deb/infinite-image-browsing_${{ env.VERSION }}_amd64.deb + + + build-by-pyinstaller: + strategy: + matrix: + os: [windows-latest] + + runs-on: ${{ matrix.os }} + + permissions: + contents: write + steps: + - name: Check-out repository + uses: actions/checkout@v3 + + - run: echo "VERSION=$(jq -r '.package.version' vue/src-tauri/tauri.conf.json)" >> $env:GITHUB_ENV + + - name: Setup Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + cache: 'pip' + cache-dependency-path: | + **/requirements*.txt + + - name: Install Dependencies + run: | + pip install -r requirements.txt + + - uses: sayyid5416/pyinstaller@v1 + with: + spec: 'app.py' + upload_exe_with_name: 'My executable' + options: --onefile + + - run: mv dist/app.exe vue/src-tauri/iib_api_server-x86_64-pc-windows-msvc.exe + + - name: Install frontend dependencies + run: yarn install + working-directory: vue + + - name: Rust setup + uses: dtolnay/rust-toolchain@stable + + - name: Use Node.js + uses: actions/setup-node@v3 + with: + node-version: 18 + + - name: Rust cache + uses: swatinem/rust-cache@v2 + with: + workspaces: './vue/src-tauri -> target' + + - name: Install dependencies (ubuntu only) + if: matrix.os == 'ubuntu-20.04' + run: | + sudo apt-get update + sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libayatana-appindicator3-dev librsvg2-dev patchelf + + - name: Build the app + run: | + yarn tauri-build + working-directory: vue + + - run: | + cd vue/src-tauri/target/release/bundle/nsis + mv "Infinite Image Browsing_${{ env.VERSION }}_x64-setup.exe" "Infinite Image Browsing_${{ env.VERSION }}_x64-setup-pyinstaller.exe" + + - name: Upload Artifacts + uses: actions/upload-artifact@v3 + with: + name: bundle-${{ env.VERSION }}-${{ runner.os }} + path: | + vue/src-tauri/target/release/bundle/nsis/Infinite Image Browsing_${{ env.VERSION }}_x64-setup-pyinstaller.exe + + release: + needs: [build-by-pyinstaller, build] + runs-on: ubuntu-latest + + permissions: + contents: write + steps: + - name: Check-out repository + uses: actions/checkout@v3 + - run: echo "VERSION=$(jq -r '.package.version' vue/src-tauri/tauri.conf.json)" >> "$GITHUB_ENV" + + - name: Delete drafts + uses: hugo19941994/delete-draft-releases@v1.0.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - uses: actions/download-artifact@v3 + with: + name: bundle-${{ env.VERSION }}-Windows + path: artifacts + + - uses: actions/download-artifact@v3 + with: + name: bundle-${{ env.VERSION }}-Linux + path: artifacts + + - uses: actions/download-artifact@v3 + with: + name: iib_app_cli_Windows + path: artifacts + + - uses: actions/download-artifact@v3 + with: + name: iib_app_cli_Linux + path: artifacts + + - name: Release + uses: softprops/action-gh-release@v1 + with: + draft: true + tag_name: v${{ env.VERSION }} + files: artifacts/**/* + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/.gitignore b/extensions-builtin/sd-webui-infinite-image-browsing-main/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..328362e49d1dad2608d479f73e88ebbd48fc61b5 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/.gitignore @@ -0,0 +1,22 @@ +*.log +__pycache__ +iib.db +tags-translate.csv +launch.sh +conf.json +iib.db-journal +.env +standalone.cmd +.vscode +build/**/* +dist/**/* +*.spec +out/**/* +venv/**/* +zip_temp/*.zip +iib_db_backup +db_migrate_temp.db +plugins/* +!plugins/.gitkeep +test_data/* +.DS_Store diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/.vscode/settings.json b/extensions-builtin/sd-webui-infinite-image-browsing-main/.vscode/settings.json new file mode 100644 index 0000000000000000000000000000000000000000..6ba1afd2f5a4843c84363308d83a515e8f3bb589 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "[python]": { + "editor.defaultFormatter": "ms-python.black-formatter" + }, + "python.formatting.provider": "none" +} \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/LICENSE b/extensions-builtin/sd-webui-infinite-image-browsing-main/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..46d1025428452c2dfcfb56411d8a1bd4f5d026d2 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 zanllp + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/README-zh.md b/extensions-builtin/sd-webui-infinite-image-browsing-main/README-zh.md new file mode 100644 index 0000000000000000000000000000000000000000..930e2fa4c5083449e7b0745a2bb44af2121ffd26 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/README-zh.md @@ -0,0 +1,162 @@ +> 🌐 在线体验: http://39.105.110.128:0721 , 这是我一个空闲的2c2g3m的云主机没有cdn +> +# Stable-Diffusion-WebUI无边图像浏览 + + +[查看近期更新](https://github.com/zanllp/sd-webui-infinite-image-browsing/wiki/Change-log) + +[安装/运行](#安装运行) + + +## 主要特性 + +### 🔥 极佳性能 +- 存在缓存的情况下后,图像可以在几毫秒内显示。 +- 默认使用缩略图显示图像,默认大小为512像素,您可以在全局设置页中调整缩略图分辨率。 +- 你还可以控制网格图像的宽度,允许以64px到1024px的宽度范围进行显示 +- 支持通过`--generate_video_cover`和`--generate_image_cache`来预先生成缩略图和视频封面,以提高性能。 +- 支持通过`IIB_CACHE_DIR`环境变量来指定缓存目录。 + +### 🔍 图像搜索和收藏 +- 将会把Prompt、Model、Lora等信息转成标签,将根据使用频率排序以供进行精确的搜索。 +- 支持标签自动完成、[翻译](https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/39)和自定义。 +- 可通过在右键菜单切换自定义标签来实现图像收藏。 +- 支持类似谷歌的高级搜索。 +- 同样支持模糊搜索,您可以使用文件名或生成信息的一部分进行搜索。 +- 支持添加自定义搜索路径,方便管理自己创建的文件夹集合。 + +### 🖼️ 查看图像/视频和“发送到” +- 支持查看图像生成信息。全屏预览下同样支持。 +- 支持将图像发送到其他选项卡和其他插件,例如 ControlNet, openOutpaint。 +- 支持全屏预览,并且支持在全屏预览下使用自定义快捷键进行操作 +- 支持在全屏预览模式下通过按下方向键或点击按钮移动到前一个或后一个图像。 +- 支持播放远程服务器上的视频文件 + +### 💻 多种使用方法 +- 您可以将其作为 SD-webui 的扩展安装。 +- 您可以使用 Python 独立运行它。 +- 还提供桌面应用程序版本。 +- 支持多种流行的AI软件 + +### 🚶‍♀️ Walk模式 +- 自动加载下一个文件夹 `(类似于 os.walk)`,可让您无需分页浏览所有图像。 +- 已测试可正常处理超过 27,000 个文件。 +- 当存在文件夹的情况下你可以通过右上角的walk按钮从其他模式切换到walk模式,它会将所有的文件夹打平,避免来回进出文件夹的繁琐操作。 + +### 🌳 基于文件树结构的预览和文件操作 +- 支持基于文件树结构的预览。 +- 支持自动刷新。 +- 支持基本文件操作以及多选删除/移动/复制,新建文件夹等。 +- 按住 Ctrl、Shift 或 Cmd 键可选择多个项目。 + - 支持多选的操作有:删除、移动、复制、打包下载、添加标签、移除标签,移动到其他文件夹,复制到其他文件夹,拖拽 + - 你可以通过右下角的保持多选按钮来保持多选的状态,对选中的文件集合可以很方便的进行多次操作 + +### 🆚 图像对比 (类似ImgSli) +- 提供两张图片的并排比较 +- 同时提供图像生成信息的比较 + +### 🌐 多语言支持 +- 目前支持简体中文/繁体中文/英文/德语。 +- 如果您希望添加新的语言,请参考 [i18n.ts](https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/vue/src/i18n/zh-hans.ts) 并提交相关的代码。 + + +### 🔐 隐私和安全 +- 支持自定义secret key来进行身份验证 +- 支持配置对文件系统的访问控制,默认将在服务允许公开访问时启用(仅限作为sd-webui的拓展时) +- 支持自定义访问控制允许的路径。 +- 支持控制访问权限。你可以让IIB以只读模式运行 +- [点击这里查看详情](.env.example) + +### ⌨️ 快捷键 +- 支持删除和添加/移除Tag,在全局设置页进行自定义触发按钮 + +### 📦 打包 / 批量下载 +- 允许你一次性打包下载多个图像 +- 数据来源可以是搜索结果/普通的图像网格查看页面/walk模式等。使用拖拽或者“发送到”都可将图片添加待处理列表 + + +如果您喜欢这个项目并且觉得它对您有帮助,请考虑给我点个⭐️。这将对我持续开发和维护这个项目非常重要。如果您有任何建议或者想法,请随时在issue中提出,我会尽快回复。再次感谢您的支持! + + +[在微信上赞助我](.github/wechat_funding.jpg) + +Buy Me a Coffee at ko-fi.com + + +[视频演示可以在Bilibili上观看](https://space.bilibili.com/27227392/channel/series) + +# 安装/运行 + +## 作为SD-webui的扩展程序: +1. 在SD-webui中打开`扩展`选项卡。 +2. 选择`从URL安装`选项。 +3. 输入 `https://github.com/zanllp/sd-webui-infinite-image-browsing`。 +4. 点击`安装`按钮。 +5. 等待安装完成,然后点击`应用并重启UI`。 + +## 作为使用Python运行的独立程序(不需要SD-webui): +请参考[Can the extension function without the web UI?](https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/47) + +如果需要查看ComfyUI/Fooocus/NovelAI生成的图片相关,请先参考 https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/202#issuecomment-1655764627 + +如果你需要dockerfile 参考 https://github.com/zanllp/sd-webui-infinite-image-browsing/discussions/366 + +## 作为桌面应用程序(不需要SD-webui和Python): +exe版本同样支持ComfyUI/Fooocus/NovelAI + +从仓库页面右侧的`releases`部分下载并安装程序。如果提示检测到病毒忽略即可这是误报。在windows下的编译有两个版本, pyinstaller版本拥有比较低的误报率。 + +如果你需要自行编译请参考 https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/.github/workflows/tauri_app_build.yml +## 作为库使用 + +使用iframe接入IIB,将IIB作为你应用的文件浏览器使用。 参考 https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/vue/usage.md + +# 预览 + +image + +## 图像搜索 + +在第一次使用时,你需要点击等待索引的生成,我2万张图像的情况下大概需要15秒(配置是amd 5600x和pcie ssd)。后续使用他会检查文件夹是否发生变化,如果发生变化则需要重新生成索引,通常这个过程极快。 + +图像搜索支持翻译,具体看这个 https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/39 。 +image +image +## 图像比较 + +![ezgif com-video-to-gif](https://github.com/zanllp/sd-webui-infinite-image-browsing/assets/25872019/4023317b-0b2d-41a3-8155-c4862eb43846) + +## 全屏预览 (并排布局) +![11](https://github.com/zanllp/sd-webui-infinite-image-browsing/assets/25872019/ee941bfc-0c1b-4777-91df-115435cc8542) + +## 全屏预览 +image + +在全屏预览下同样可以查看图片信息和进行上下文菜单上的的操作,支持拖拽/调整/展开收起 + +https://user-images.githubusercontent.com/25872019/235327735-bfb50ea7-7682-4e50-b303-38159456e527.mp4 + + +如果你和我一样不需要查看生成信息,你可以选择直接缩小这个面板,所有上下文操作仍然可用 + +image + +### 右键菜单 +image + +也可以通过右上角的图标来触发 +image + +### Walk模式 + + +https://user-images.githubusercontent.com/25872019/230768207-daab786b-d4ab-489f-ba6a-e9656bd530b8.mp4 + + + + +### 深色模式 + +image + + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/README.md b/extensions-builtin/sd-webui-infinite-image-browsing-main/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2cabe3b9e1ec68a2714d89d556bc0d3aee3aff0a --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/README.md @@ -0,0 +1,177 @@ +> 🌍 i18n Advisory: Some translations may be incomplete or inaccurate. Pull requests are welcome for improvements! + +> 🌐 Try our application online at: http://39.105.110.128:0721. This is my idle 2c2g3m cloud server without CDN. + +[中文文档](./README-zh.md) +[Change log](https://github.com/zanllp/sd-webui-infinite-image-browsing/wiki/Change-log) +[Installation / Running](#installation--running) + + +# Stable Diffusion webui Infinite Image Browsing + +### Software Support and Development Progress Overview +| Software | Support | Provided by | +| ---------------------- | ---------------- | ----------- | +| Stable Diffusion web UI| Supported | Built-in | +| ComfyUI | Partially supported | Built-in | +| Fooocus | Supported | Built-in | +| NovelAI | Supported | Built-in | +| StableSwarmUI | Supported | Built-in | +| Invoke.AI | Supported | Built-in | +| Pixiv | Supported | [pixiv_iib_plugin](https://github.com/zanllp/pixiv_iib_plugin) | + +If you would like to support more software, please refer to: [parsers](https://github.com/zanllp/sd-webui-infinite-image-browsing/tree/main/scripts/iib/parsers) or [pixiv_iib_plugin](https://github.com/zanllp/pixiv_iib_plugin) + +## Key Features + +### 🔥 Excellent Performance +- Once caching is generated, images can be displayed in just a few milliseconds. +- Images are displayed with thumbnails by default, with a default size of 512 pixels. You can adjust the thumbnail resolution on the global settings page. +- You can also control the width of the grid images, allowing them to be displayed in widths ranging from 64px to 1024px. +- Supports pre-generating thumbnails and video covers to improve performance using `--generate_video_cover` and `--generate_image_cache`. +- Supports specifying the cache directory through the `IIB_CACHE_DIR` environment variable. + +### 🔍 Image Search & Favorite +- The prompt, model, Lora, and other information will be converted into tags and sorted by frequency of use for precise searching. +- Supports tag autocomplete, [auto-translation](https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/39), and customization. +- Image favorite can be achieved by toggling custom tags for images in the right-click menu. +- Support for advanced search similar to Google +- Also supports fuzzy search, you can search by a part of the filename or generated information. +- Support adding custom search paths for easy management of folders created by the user. + +### 🖼️ View Images/Videos & `Send To` +- Supports viewing image generation information. Also supported in full-screen preview mode. +- Supports sending images to other tabs and third-party extensions such as ControlNet , openOutpaint. +- Support full-screen preview and enable custom shortcut key operations while in full-screen preview mode. +- Support navigating to the previous or next image in full-screen preview mode by pressing arrow keys or clicking buttons. +- Support playing video files from a remote server. + +### 💻 Multiple Usage Methods +- You can install it as an extension on SD-webui. +- You can run it independently using Python. +- The desktop app version is also available. +- Supports multiple popular AI software. + + +### 🚶‍♀️ Walk Mode +- Automatically load the next folder `(similar to os.walk)`, allowing you to browse all images without paging. +- Tested to work properly with over 27,000 files. +- When there are folders, you can switch to walk mode from other modes by clicking the walk button in the upper right corner. It will flatten all the folders, avoiding the tedious operation of going in and out of folders. + +### 🌳 Preview based on File Tree Structure & File operations +- Supports file tree-based preview. +- Supports automatic refreshing. +- Supports basic file operations, such as multiple selection for deleting/moving/copying, and creating new folders. +- Hold down the Ctrl, Shift, or Cmd key to select multiple items. + - Supported multi-select operations include: delete, move, copy, pack download, add tags, remove tags, move to another folder, copy to another folder, drag and drop. + - You can keep the multi-select state by clicking the "Keep Multi-Select" button in the lower right corner, allowing you to perform multiple operations on the selected file collection conveniently. + +### 🆚 image comparison (similar to Imgsli) +- Provides a side-by-side comparison of two images. +- Provides a comparison of image generation information at the same time. + +### 🌐 Multilingual Support +- Currently supports Simplified Chinese/Traditional Chinese/English/German. +- If you would like to add a new language, please refer to [i18n.ts](https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/vue/src/i18n/zh-hans.ts) and submit the relevant code. + +### 🔐 Privacy and Security +- Supports custom secret key for authentication. +- Supports configuring access control for the file system, which will be enabled by default when the service allows public access (Only when used as an extension of sd-webui). +- Supports customizing the allowed paths for access control. +- Supports controlling access permissions. You can run IIB in read-only mode. +- [Click here to see details](.env.example) + + +### 📦 Packaging/Batch Download +- Allows you to download multiple images at once. +- The data source can be search results, a regular image grid view page, walk mode, etc. Images can be added to the processing list through drag-and-drop or "Send To". +### ⌨️ Keyboard Shortcuts +- Allows for deleting and adding/removing tags, with customizable trigger buttons in the global settings page. + + +If you like this project and find it helpful, please consider giving it a ⭐️. This would be very important for me to continue developing and maintaining this project. If you have any suggestions or ideas, please feel free to raise them in the issue section, and I will respond as soon as possible. Thank you again for your support! + + +Buy Me a Coffee at ko-fi.com + +[Sponsor me on WeChat](.github/wechat_funding.jpg) + +# Installation / Running +## As an extension for SD-webui: +1. Open the `Extensions` tab in SD-webui. +2. Select the `Install from URL` option. +3. Enter `https://github.com/zanllp/sd-webui-infinite-image-browsing`. +4. Click on the `Install` button. +5. Wait for the installation to complete and click on `Apply and restart UI`. + +## As a standalone program that runs using Python. (without SD-webui): + +Refer to [Can the extension function without the web UI?](https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/47) + +If you need to view images generated by ComfyUI/Fooocus/NovelAI, please refer to [https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/202](https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/202#issuecomment-1655764627). + +If you need a Dockerfile, you can refer to this link. https://github.com/zanllp/sd-webui-infinite-image-browsing/discussions/366 + +## As a desktop application (without SD-webui and Python): +The executable version also supports ComfyUI/Fooocus/NovelAI. + +Download and install the program from the `releases` section on the right-hand side of the repository page. +If the antivirus detects a virus, it can be ignored as a false positive. There are two versions of the compiled version for Windows, with the pyinstaller version having a lower false positive rate. + +If you need to compile it yourself, please refer to https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/.github/workflows/tauri_app_build.yml. + +## As a Library Usage: + +Use iframe to access IIB and use it as a file browser for your application. Refer to https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/vue/usage.md + + +# Preview + +image + +## Image Search + +During the first use, you need to click and wait for the index generation. For my case with 20,000 images, it took about 45 seconds (with an AMD 5600X CPU and PCIe SSD). For subsequent uses, it will check whether there are changes in the folder, and if so, it needs to regenerate the index. Usually, this process is very fast. + +Image search supports translation, see https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/39 for more detail. Feel free to share files for other languages to facilitate everyone's use. +image +image + +## Full Screen Preview (Side-by-Side Layout) +![11](https://github.com/zanllp/sd-webui-infinite-image-browsing/assets/25872019/ee941bfc-0c1b-4777-91df-115435cc8542) + +## Full Screen Preview + +image + +In full-screen preview mode, you can also view image information and perform operations on the context menu. It supports dragging, resizing and expanding/collapsing . + +https://user-images.githubusercontent.com/25872019/235327735-bfb50ea7-7682-4e50-b303-38159456e527.mp4 + +If you, like me, don't need to view the generation information, you can choose to simply minimize this panel, and all contextual operations will still be available. + +image + +## Image comparison + +![ezgif com-video-to-gif](https://github.com/zanllp/sd-webui-infinite-image-browsing/assets/25872019/4023317b-0b2d-41a3-8155-c4862eb43846) +## Transfer files between different tab panes. +https://github.com/zanllp/sd-webui-infinite-image-browsing/assets/25872019/e631e3c3-1cbf-49bc-8577-f2963a6c9e4d +### Right-click menu +image + +You can also trigger it by hovering your mouse over the icon in the top right corner. + +image + +### Walk mode + + +https://user-images.githubusercontent.com/25872019/230768207-daab786b-d4ab-489f-ba6a-e9656bd530b8.mp4 + + + + +### Dark mode + +image diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/app.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/app.py new file mode 100644 index 0000000000000000000000000000000000000000..8088ceb638fd015bb382fb39635b4a023281be49 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/app.py @@ -0,0 +1,299 @@ +import codecs +from typing import List +from fastapi import FastAPI, Response +from fastapi.responses import FileResponse +import uvicorn +import os +from scripts.iib.api import infinite_image_browsing_api, index_html_path, DEFAULT_BASE +from scripts.iib.tool import ( + get_sd_webui_conf, + get_valid_img_dirs, + sd_img_dirs, + normalize_paths, +) +from scripts.iib.db.datamodel import DataBase, Image, ExtraPath +from scripts.iib.db.update_image_data import update_image_data +import argparse +from typing import Optional, Coroutine +import json + +tag = "\033[31m[warn]\033[0m" + +default_port = 8000 +default_host = "127.0.0.1" + +def get_all_img_dirs(sd_webui_config: str, relative_to_config: bool): + dirs = get_valid_img_dirs( + get_sd_webui_conf( + sd_webui_config=sd_webui_config, + sd_webui_path_relative_to_config=relative_to_config, + ) + ) + dirs += list(map(lambda x: x.path, ExtraPath.get_extra_paths(DataBase.get_conn()))) + return dirs + + +def sd_webui_paths_check(sd_webui_config: str, relative_to_config: bool): + conf = {} + with codecs.open(sd_webui_config, "r", "utf-8") as f: + conf = json.loads(f.read()) + if relative_to_config: + for dir in sd_img_dirs: + if not os.path.isabs(conf[dir]): + conf[dir] = os.path.normpath( + os.path.join(sd_webui_config, "../", conf[dir]) + ) + paths = [conf.get(key) for key in sd_img_dirs] + paths_check(paths) + + +def paths_check(paths): + for path in paths: + if not path or len(path.strip()) == 0: + continue + if os.path.isabs(path): + abs_path = path + else: + abs_path = os.path.normpath(os.path.join(os.getcwd(), path)) + if not os.path.exists(abs_path): + print(f"{tag} The path '{abs_path}' will be ignored (value: {path}).") + + +def do_update_image_index(sd_webui_config: str, relative_to_config=False): + dirs = get_all_img_dirs(sd_webui_config, relative_to_config) + if not len(dirs): + return print(f"{tag} no valid image directories, skipped") + conn = DataBase.get_conn() + update_image_data(dirs) + if Image.count(conn=conn) == 0: + return print(f"{tag} it appears that there is some issue") + print("update image index completed. ✨") + + +class AppUtils: + def __init__( + self, + sd_webui_config: Optional[str] = None, + update_image_index: bool = False, + extra_paths: List[str] = [], + sd_webui_path_relative_to_config=False, + allow_cors=False, + enable_shutdown=False, + sd_webui_dir: Optional[str] = None, + base: Optional[str] = None, + export_fe_fn=False, + **args: dict, + ): + """ + Parameter definitions can be found by running the `python app.py -h `command or by examining the setup_parser() function. + """ + self.sd_webui_config = sd_webui_config + self.update_image_index = update_image_index + self.extra_paths = extra_paths + self.sd_webui_path_relative_to_config = sd_webui_path_relative_to_config + self.allow_cors = allow_cors + self.enable_shutdown = enable_shutdown + self.sd_webui_dir = sd_webui_dir + if base and not base.startswith("/"): + base = "/" + base + self.base = base + self.export_fe_fn = export_fe_fn + if sd_webui_dir: + DataBase.path = os.path.join( + sd_webui_dir, "extensions/sd-webui-infinite-image-browsing/iib.db" + ) + self.sd_webui_config = os.path.join(sd_webui_dir, "config.json") + self.sd_webui_path_relative_to_config = True + + def set_params(self, *args, **kwargs) -> None: + """改变参数,与__init__的行为一致""" + self.__init__(*args, **kwargs) + + @staticmethod + def async_run( + app: FastAPI, port: int = default_port, host=default_host + ) -> Coroutine: + """ + 用于从异步运行的 FastAPI,在 Jupyter Notebook 环境中非常有用 + """ + # 不建议改成 async def,并且用 await 替换 return, + # 因为这样会失去对 server.serve() 的控制。 + config = uvicorn.Config(app, host=host, port=port) + server = uvicorn.Server(config) + return server.serve() + + def wrap_app(self, app: FastAPI) -> None: + """ + 为传递的app挂载上infinite_image_browsing后端 + """ + sd_webui_config = self.sd_webui_config + update_image_index = self.update_image_index + extra_paths = self.extra_paths + + if sd_webui_config: + sd_webui_paths_check(sd_webui_config, self.sd_webui_path_relative_to_config) + if update_image_index: + do_update_image_index( + sd_webui_config, self.sd_webui_path_relative_to_config + ) + paths_check(extra_paths) + + infinite_image_browsing_api( + app, + sd_webui_config=sd_webui_config, + extra_paths_cli=normalize_paths(extra_paths, os.getcwd()), + sd_webui_path_relative_to_config=self.sd_webui_path_relative_to_config, + allow_cors=self.allow_cors, + enable_shutdown=self.enable_shutdown, + launch_mode="server", + base=self.base, + export_fe_fn=self.export_fe_fn, + ) + + def get_root_browser_app(self) -> FastAPI: + """ + 获取首页挂载在"/"上的infinite_image_browsing FastAPI实例 + """ + app = FastAPI() + + # 用于在首页显示 + @app.get("/") + def index(): + if isinstance(self.base, str): + with open(index_html_path, "r", encoding="utf-8") as file: + content = file.read().replace(DEFAULT_BASE, self.base) + return Response(content=content, media_type="text/html") + return FileResponse(index_html_path) + + self.wrap_app(app) + return app + + +def setup_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="A fast and powerful image/video browser with infinite scrolling and advanced search capabilities. It also supports parsing/viewing image information generated by multiple AI software." + ) + parser.add_argument( + "--host", type=str, default=default_host, help="The host to use" + ) + parser.add_argument( + "--port", type=int, help="The port to use", default=default_port + ) + parser.add_argument( + "--sd_webui_config", type=str, default=None, help="The path to the config file" + ) + parser.add_argument( + "--update_image_index", action="store_true", help="Update the image index" + ) + parser.add_argument( + "--generate_video_cover", + action="store_true", + help="Pre-generate video cover images to speed up browsing.", + ) + parser.add_argument( + "--generate_image_cache", + action="store_true", + help="Pre-generate image cache to speed up browsing. By default, only the extra paths added by the user are processed, not the paths in sd_webui_config. If you need to process paths in sd_webui_config, you must use the --sd_webui_config and --sd_webui_path_relative_to_config parameters.", + ) + parser.add_argument( + "--generate_image_cache_size", + type=str, + default="512x512", + help="The size of the image cache to generate. Default is 512x512", + ) + parser.add_argument( + "--gen_cache_verbose", + action="store_true", + help="Verbose mode for cache generation.", + ) + parser.add_argument( + "--extra_paths", + nargs="+", + help="Extra paths to use, these paths will be added to the homepage but the images in these paths will not be indexed. They are only used for browsing. If you need to index them, please add them via the '+ Add' button on the homepage.", + default=[], + ) + parser.add_argument( + "--sd_webui_path_relative_to_config", + action="store_true", + help="Use the file path of the sd_webui_config file as the base for all relative paths provided within the sd_webui_config file.", + ) + parser.add_argument( + "--allow_cors", + action="store_true", + help="Allow Cross-Origin Resource Sharing (CORS) for the API.", + ) + parser.add_argument( + "--enable_shutdown", + action="store_true", + help="Enable the shutdown endpoint.", + ) + parser.add_argument( + "--sd_webui_dir", + type=str, + default=None, + help="The path to the sd_webui folder. When specified, the sd_webui's configuration will be used and the extension must be installed within the sd_webui. Data will be shared between the two.", + ) + parser.add_argument( + "--export_fe_fn", + default=True, + action="store_true", + help="Export front-end functions to enable external access through iframe.", + ) + parser.add_argument("--base", type=str, help="The base URL for the IIB Api.") + return parser + + +def launch_app( + port: int = default_port, host: str = default_host, *args, **kwargs: dict +) -> None: + """ + Launches the application on the specified port. + + Args: + **kwargs (dict): Optional keyword arguments that can be used to configure the application. + These can be viewed by running 'python app.py -h' or by checking the setup_parser() function. + """ + app_utils = AppUtils(*args, **kwargs) + app = app_utils.get_root_browser_app() + uvicorn.run(app, host=host, port=port) + + +async def async_launch_app( + port: int = default_port, host: str = default_host, *args, **kwargs: dict +) -> None: + """ + Asynchronously launches the application on the specified port. + + Args: + **kwargs (dict): Optional keyword arguments that can be used to configure the application. + These can be viewed by running 'python app.py -h' or by checking the setup_parser() function. + """ + app_utils = AppUtils(*args, **kwargs) + app = app_utils.get_root_browser_app() + await app_utils.async_run(app, host=host, port=port) + + +if __name__ == "__main__": + parser = setup_parser() + args = parser.parse_args() + args_dict = vars(args) + + if args_dict.get("generate_video_cover"): + from scripts.iib.video_cover_gen import generate_video_covers + + conn = DataBase.get_conn() + generate_video_covers( + dirs = map(lambda x: x.path, ExtraPath.get_extra_paths(conn)), + verbose=args.gen_cache_verbose, + ) + exit(0) + if args_dict.get("generate_image_cache"): + from scripts.iib.img_cache_gen import generate_image_cache + generate_image_cache( + dirs = get_all_img_dirs(args.sd_webui_config, args.sd_webui_path_relative_to_config), + size = args.generate_image_cache_size, + verbose = args.gen_cache_verbose + ) + exit(0) + + launch_app(**vars(args)) \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/install.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/install.py new file mode 100644 index 0000000000000000000000000000000000000000..a0acdf9723dfcbdf7a5ad4bf0bc7a39b11a14b4b --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/install.py @@ -0,0 +1,28 @@ +import launch +import os +import pkg_resources + +req_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "requirements.txt") + +def dist2package(dist: str): + return ({ + "python-dotenv": "dotenv", + "Pillow": "PIL", + "pillow-avif-plugin": "pillow_avif" + }).get(dist, dist) + +# copy from controlnet, thanks +with open(req_file) as file: + for package in file: + try: + package = package.strip() + if '==' in package: + package_name, package_version = package.split('==') + installed_version = pkg_resources.get_distribution(package_name).version + if installed_version != package_version: + launch.run_pip(f"install {package}", f"sd-webui-infinite-image-browsing requirement: changing {package_name} version from {installed_version} to {package_version}") + elif not launch.is_installed(dist2package(package)): + launch.run_pip(f"install {package}", f"sd-webui-infinite-image-browsing requirement: {package}") + except Exception as e: + print(e) + print(f'Warning: Failed to install {package}, something may not work.') diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/javascript/index.js b/extensions-builtin/sd-webui-infinite-image-browsing-main/javascript/index.js new file mode 100644 index 0000000000000000000000000000000000000000..18abd47305962b6f49c8f1ecfb56df0ad912262a --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/javascript/index.js @@ -0,0 +1,186 @@ +/* eslint-disable no-undef */ +Promise.resolve().then(async () => { + /** + * This is a file generated using `yarn build`. + * If you want to make changes, please modify `index.tpl.js` and run the command to generate it again. + */ + const html = ` + + + + + + + + Infinite Image Browsing + + + + + + +
+ + + +`.replace(/\/infinite_image_browsing/g, (window.location.pathname + '/infinite_image_browsing').replace(/\/\//g, '/')) + let containerSelector = '#infinite_image_browsing_container_wrapper' + let shouldMaximize = localStorage.getItem('iib://disable_maximize') !== 'true' + + try { + containerSelector = __iib_root_container__ + shouldMaximize = __iib_should_maximize__ + } catch (e) { /* empty */ } + + const delay = (timeout = 0) => new Promise((resolve) => setTimeout(resolve, timeout)) + const asyncCheck = async (getter, checkSize = 100, timeout = 1000) => { + let target = getter() + let num = 0 + while (checkSize * num < timeout && (target === undefined || target === null)) { + await delay(checkSize) + target = getter() + num++ + } + return target + } + + const getTabIdxById = (id) => { + const tabList = gradioApp().querySelectorAll('#tabs > .tabitem[id^=tab_]') + return Array.from(tabList).findIndex((v) => v.id.includes(id)) + } + + const switch2targetTab = (idx) => { + try { + gradioApp().querySelector('#tabs').querySelectorAll('button')[idx].click() + } catch (error) { + console.error(error) + } + } + + const isLobe = () => { + try { + return !!gradioApp().querySelector('[alt*="lobehub"]') + } catch (error) { + return false + } + } + + /** + * @type {HTMLDivElement} + */ + const wrap = await asyncCheck(() => gradioApp().querySelector(containerSelector), 500, Infinity) + wrap.childNodes.forEach((v) => wrap.removeChild(v)) + const iframe = document.createElement('iframe') + iframe.srcdoc = html + iframe.style = 'width: 100%;height:100vh' + wrap.appendChild(iframe) + + if (shouldMaximize) { + onUiTabChange(() => { + const el = get_uiCurrentTabContent() + if (el?.id.includes('infinite-image-browsing')) { + try { + const iibTop = gradioApp().querySelector('#iib_top') + if (!iibTop) { + throw new Error('element \'#iib_top\' is not found') + } + const topRect = iibTop.getBoundingClientRect() + wrap.style = ` + top:${Math.max(isLobe() ? 32 : 128, topRect.top) - 10}px; + position: fixed; + left: 10px; + right: 10px; + z-index: 100; + width: unset; + bottom: 10px;` + iframe.style = 'width: 100%;height:100%' + } catch (error) { + console.error('Error mounting IIB. Running fallback.', error) + wrap.style = '' + iframe.style = 'width: 100%;height:100vh' + } + } + }) + } + + const IIB_container_id = [Date.now(), Math.random()].join() + window.IIB_container_id = IIB_container_id + const imgTransferBus = new BroadcastChannel('iib-image-transfer-bus') + imgTransferBus.addEventListener('message', async (ev) => { + const data = ev.data + if ( + typeof data !== 'object' || + (typeof data.IIB_container_id === 'string' && data.IIB_container_id !== IIB_container_id) + ) { + return + } + console.log('iib-message:', data) + const appDoc = gradioApp() + switch (data.event) { + case 'click_hidden_button': { + const btn = gradioApp().querySelector(`#${data.btnEleId}`) + btn.click() + break + } + case 'send_to_control_net': { + data.type === 'img2img' ? window.switch_to_img2img() : window.switch_to_txt2img() + await delay(100) + const cn = appDoc.querySelector(`#${data.type}_controlnet`) + const wrap = cn.querySelector('.label-wrap') + if (!wrap.className.includes('open')) { + wrap.click() + await delay(100) + } + wrap.scrollIntoView() + wrap.dispatchEvent(await createPasteEvent(data.url)) + break + } + case 'send_to_outpaint': { + switch2targetTab(getTabIdxById('openOutpaint')) + await delay(100) + const iframe = appDoc.querySelector('#openoutpaint-iframe') + openoutpaint_send_image(await imgUrl2DataUrl(data.url)) + iframe.contentWindow.postMessage({ + key: appDoc.querySelector('#openoutpaint-key').value, + type: 'openoutpaint/set-prompt', + prompt: data.prompt, + negPrompt: data.negPrompt + }) + break + } + } + + function imgUrl2DataUrl(imgUrl) { + return new Promise((resolve, reject) => { + fetch(imgUrl) + .then((response) => response.blob()) + .then((blob) => { + const reader = new FileReader() + reader.readAsDataURL(blob) + reader.onloadend = function () { + const dataURL = reader.result + resolve(dataURL) + } + }) + .catch((error) => reject(error)) + }) + } + + async function createPasteEvent(imgUrl) { + const response = await fetch(imgUrl) + const imageBlob = await response.blob() + const imageFile = new File([imageBlob], 'image.jpg', { + type: imageBlob.type, + lastModified: Date.now() + }) + const dataTransfer = new DataTransfer() + dataTransfer.items.add(imageFile) + const pasteEvent = new ClipboardEvent('paste', { + clipboardData: dataTransfer, + bubbles: true + }) + return pasteEvent + } + }) +}) diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/migrate.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/migrate.py new file mode 100644 index 0000000000000000000000000000000000000000..8bf092664d46023cc7ec0a039b6e34ba512d31a0 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/migrate.py @@ -0,0 +1,84 @@ +from contextlib import closing +import argparse +from scripts.iib.db.datamodel import DataBase +import os + +import shutil + + +def replace_path(old_base, new_base): + """ + Custom SQL function to replace part of a path. + + Args: + old_base (str): The base part of the path to be replaced. + new_base (str): The new base part of the path. + + Returns: + str: Updated path. + """ + + def replace_func(path): + if path.startswith(old_base): + return new_base + path[len(old_base) :] + else: + return path + + return replace_func + + +def update_paths(conn, table_name, old_base): + """ + Update paths in a specified SQLite table using a custom SQL function. + + Args: + db_path (str): Path to the SQLite database file. + table_name (str): Name of the table containing the paths. + + Returns: + None + """ + with closing(conn.cursor()) as cur: + # Use the custom function in an UPDATE statement + cur.execute( + f"UPDATE {table_name} SET path = replace_path(path) WHERE path LIKE ?", + (f"{old_base}%",), + ) + + # Commit the changes and close the connection + conn.commit() + + +def setup_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Script to migrate paths in an IIB SQLite database from an old directory structure to a new one." + ) + parser.add_argument( + "--db_path", type=str, help="Path to the input IIB QLite database file to be migrated. Default value is 'iib.db'.", default="iib.db" + ) + parser.add_argument( + "--old_dir", type=str, help="Old base directory to be replaced in the paths.", required=True + ) + parser.add_argument( + "--new_dir", type=str, help="New base directory to replace the old base directory in the paths.", required=True + ) + return parser + + +if __name__ == "__main__": + parser = setup_parser() + args = parser.parse_args() + old_base = args.old_dir + new_base = args.new_dir + db_path = args.db_path + db_temp_path = "db_migrate_temp.db" + shutil.copy2(db_path, db_temp_path) + DataBase.path = os.path.normpath(os.path.join(os.getcwd(), db_temp_path)) + conn = DataBase.get_conn() + conn.create_function("replace_path", 1, replace_path(old_base, new_base)) + update_paths(conn, "image", old_base) + update_paths(conn, "extra_path", old_base) + update_paths(conn, "folders", old_base) + shutil.copy(db_temp_path, "iib.db") + # os.remove(db_temp_path) + print("Database migration completed successfully.") diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/plugins/.gitkeep b/extensions-builtin/sd-webui-infinite-image-browsing-main/plugins/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/requirements.txt b/extensions-builtin/sd-webui-infinite-image-browsing-main/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ab7e64fa30ec44a209e81431a2be61a89de1fbc8 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/requirements.txt @@ -0,0 +1,9 @@ +fastapi +uvicorn +piexif +python-dotenv +Pillow +pillow-avif-plugin +imageio +av +lxml \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/api.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/api.py new file mode 100644 index 0000000000000000000000000000000000000000..d9fe6d0761dd56dc8271d3c3632de6cae110ee8f --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/api.py @@ -0,0 +1,1213 @@ +import base64 +from datetime import datetime, timedelta +import io +import os +from pathlib import Path +import shutil +import sqlite3 + + +from scripts.iib.dir_cover_cache import get_top_4_media_info +from scripts.iib.tool import ( + get_created_date_by_stat, + get_video_type, + human_readable_size, + is_valid_media_path, + is_media_file, + get_cache_dir, + get_formatted_date, + is_win, + cwd, + locale, + enable_access_control, + get_windows_drives, + get_sd_webui_conf, + get_valid_img_dirs, + open_folder, + get_img_geninfo_txt_path, + unique_by, + create_zip_file, + normalize_paths, + to_abs_path, + is_secret_key_required, + open_file_with_default_app, + is_exe_ver, + backup_db_file, + get_current_commit_hash, + get_current_tag, + get_file_info_by_path, + get_data_file_path +) +from fastapi import FastAPI, HTTPException, Header, Response +from fastapi.staticfiles import StaticFiles +import asyncio +from typing import List, Optional +from pydantic import BaseModel +from fastapi.responses import FileResponse, JSONResponse, StreamingResponse +from PIL import Image +from fastapi import Depends, FastAPI, HTTPException, Request +from fastapi.middleware.cors import CORSMiddleware +import hashlib +from scripts.iib.db.datamodel import ( + DataBase, + ExtraPathType, + Image as DbImg, + Tag, + Folder, + ImageTag, + ExtraPath, + FileInfoDict, + Cursor, + GlobalSetting +) +from scripts.iib.db.update_image_data import update_image_data, rebuild_image_index, add_image_data_single +from scripts.iib.logger import logger +from scripts.iib.seq import seq +import urllib.parse +from scripts.iib.fastapi_video import range_requests_response, close_video_file_reader +from scripts.iib.parsers.index import parse_image_info +import scripts.iib.plugin + +try: + import pillow_avif +except Exception as e: + logger.error(e) + + +index_html_path = get_data_file_path("vue/dist/index.html") if is_exe_ver else os.path.join(cwd, "vue/dist/index.html") # 在app.py也被使用 + + +send_img_path = {"value": ""} +mem = {"secret_key_hash": None, "extra_paths": [], "all_scanned_paths": []} +secret_key = os.getenv("IIB_SECRET_KEY") +if secret_key: + print("Secret key loaded successfully. ") + +WRITEABLE_PERMISSIONS = ["read-write", "write-only"] + +is_api_writeable = not (os.getenv("IIB_ACCESS_CONTROL_PERMISSION")) or ( + os.getenv("IIB_ACCESS_CONTROL_PERMISSION") in WRITEABLE_PERMISSIONS +) +IIB_DEBUG=False + + +async def write_permission_required(): + if not is_api_writeable: + error_msg = ( + "User is not authorized to perform this action. Required permission: " + + ", ".join(WRITEABLE_PERMISSIONS) + ) + raise HTTPException(status_code=403, detail=error_msg) + + +async def verify_secret(request: Request): + if not secret_key: + if is_secret_key_required: + raise HTTPException(status_code=400, detail={"type": "secret_key_required"}) + return + token = request.cookies.get("IIB_S") + if not token: + raise HTTPException(status_code=401, detail="Unauthorized") + if not mem["secret_key_hash"]: + mem["secret_key_hash"] = hashlib.sha256( + (secret_key + "_ciallo").encode("utf-8") + ).hexdigest() + if mem["secret_key_hash"] != token: + raise HTTPException(status_code=401, detail="Unauthorized") + +DEFAULT_BASE = "/infinite_image_browsing" +def infinite_image_browsing_api(app: FastAPI, **kwargs): + backup_db_file(DataBase.get_db_file_path()) + api_base = kwargs.get("base") if isinstance(kwargs.get("base"), str) else DEFAULT_BASE + fe_public_path = kwargs.get("fe_public_path") if isinstance(kwargs.get("fe_public_path"), str) else api_base + cache_base_dir = get_cache_dir() + + # print(f"IIB api_base:{api_base} fe_public_path:{fe_public_path}") + if IIB_DEBUG or is_exe_ver: + @app.exception_handler(Exception) + async def exception_handler(request: Request, exc: Exception): + error_msg = f"An exception occurred while processing {request.method} {request.url}: {exc}" + logger.error(error_msg) + + return JSONResponse( + status_code=500, content={"message": "Internal Server Error"} + ) + @app.middleware("http") + async def log_requests(request: Request, call_next): + path = request.url.path + if ( + path.find("infinite_image_browsing/image-thumbnail") == -1 + and path.find("infinite_image_browsing/file") == -1 + and path.find("infinite_image_browsing/fe-static") == -1 + ): + logger.info(f"Received request: {request.method} {request.url}") + if request.query_params: + logger.debug(f"Query Params: {request.query_params}") + if request.path_params: + logger.debug(f"Path Params: {request.path_params}") + + try: + return await call_next(request) + except HTTPException as http_exc: + logger.warning( + f"HTTPException occurred while processing {request.method} {request.url}: {http_exc}" + ) + raise http_exc + except Exception as exc: + logger.error( + f"An exception occurred while processing {request.method} {request.url}: {exc}" + ) + + + if kwargs.get("allow_cors"): + app.add_middleware( + CORSMiddleware, + allow_origin_regex="^[\w./:-]+$", + allow_methods=["*"], + allow_headers=["*"], + ) + + def get_img_search_dirs(): + try: + return get_valid_img_dirs(get_sd_webui_conf(**kwargs)) + except Exception as e: + print(e) + return [] + + def update_all_scanned_paths(): + allowed_paths = os.getenv("IIB_ACCESS_CONTROL_ALLOWED_PATHS") + if allowed_paths: + sd_webui_conf = get_sd_webui_conf(**kwargs) + path_config_key_map = { + "save": "outdir_save", + "extra": "outdir_extras_samples", + "txt2img": "outdir_txt2img_samples", + "img2img": "outdir_img2img_samples", + } + + def path_map(path: str): + path = path.strip() + if path in path_config_key_map: + return sd_webui_conf.get(path_config_key_map.get(path)) + return path + + paths = normalize_paths( + seq(allowed_paths.split(",")) + .map(path_map) + .filter(lambda x: x) + .to_list(), + os.getcwd() + ) + else: + paths = ( + get_img_search_dirs() + + mem["extra_paths"] + + kwargs.get("extra_paths_cli", []) + ) + mem["all_scanned_paths"] = unique_by(paths) + + update_all_scanned_paths() + + def update_extra_paths(conn: sqlite3.Connection): + r = ExtraPath.get_extra_paths(conn) + mem["extra_paths"] = [x.path for x in r] + update_all_scanned_paths() + + def safe_commonpath(seq): + try: + return os.path.commonpath(seq) + except Exception as e: + # logger.error(e) + return "" + + def is_path_under_parents(path, parent_paths: List[str] = []): + """ + Check if the given path is under one of the specified parent paths. + :param path: The path to check. + :param parent_paths: By default, all scanned paths are included in the list of parent paths + :return: True if the path is under one of the parent paths, False otherwise. + """ + try: + if not parent_paths: + parent_paths = mem["all_scanned_paths"] + path = to_abs_path(path) + for parent_path in parent_paths: + if safe_commonpath([path, parent_path]) == parent_path: + return True + except Exception as e: + logger.error(e) + return False + + def is_path_trusted(path: str): + if not enable_access_control: + return True + try: + parent_paths = mem["all_scanned_paths"] + path = to_abs_path(path) + for parent_path in parent_paths: + if len(path) <= len(parent_path): + if parent_path.startswith(path): + return True + else: + if path.startswith(parent_path): + return True + except: + pass + return False + + def check_path_trust(path: str): + if not is_path_trusted(path): + raise HTTPException(status_code=403) + + def filter_allowed_files(files: List[FileInfoDict]): + return [x for x in files if is_path_trusted(x["fullpath"])] + + + + class PathsReq(BaseModel): + paths: List[str] + + @app.get(f"{api_base}/hello") + async def greeting(): + return "hello" + + @app.get(f"{api_base}/global_setting", dependencies=[Depends(verify_secret)]) + async def global_setting(): + all_custom_tags = [] + + extra_paths = [] + app_fe_setting = {} + try: + conn = DataBase.get_conn() + all_custom_tags = Tag.get_all_custom_tag(conn) + extra_paths = ExtraPath.get_extra_paths(conn) + [ + ExtraPath(path, ExtraPathType.cli_only.value) + for path in kwargs.get("extra_paths_cli", []) + ] + update_extra_paths(conn) + app_fe_setting = GlobalSetting.get_all_settings(conn) + except Exception as e: + print(e) + return { + "global_setting": get_sd_webui_conf(**kwargs), + "cwd": cwd, + "is_win": is_win, + "home": os.environ.get("USERPROFILE") if is_win else os.environ.get("HOME"), + "sd_cwd": os.getcwd(), + "all_custom_tags": all_custom_tags, + "extra_paths": extra_paths, + "enable_access_control": enable_access_control, + "launch_mode": kwargs.get("launch_mode", "sd"), + "export_fe_fn": bool(kwargs.get("export_fe_fn")), + "app_fe_setting": app_fe_setting, + "is_readonly": not is_api_writeable, + } + + + class AppFeSettingReq(BaseModel): + name: str + value: str + + @app.post(f"{api_base}/app_fe_setting", dependencies=[Depends(verify_secret), Depends(write_permission_required)]) + async def app_fe_setting(req: AppFeSettingReq): + conn = DataBase.get_conn() + GlobalSetting.save_setting(conn, req.name, req.value) + + class AppFeSettingDelReq(BaseModel): + name: str + + @app.delete(f"{api_base}/app_fe_setting", dependencies=[Depends(verify_secret), Depends(write_permission_required)]) + async def remove_app_fe_setting(req: AppFeSettingDelReq): + conn = DataBase.get_conn() + GlobalSetting.remove_setting(conn, req.name) + + @app.get(f"{api_base}/version", dependencies=[Depends(verify_secret)]) + async def get_version(): + return { + "hash": get_current_commit_hash(), + "tag": get_current_tag(), + } + + class DeleteFilesReq(BaseModel): + file_paths: List[str] + + @app.post( + api_base + "/delete_files", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def delete_files(req: DeleteFilesReq): + conn = DataBase.get_conn() + for path in req.file_paths: + check_path_trust(path) + try: + if os.path.isdir(path): + if len(os.listdir(path)): + error_msg = ( + "When a folder is not empty, it is not allowed to be deleted." + if locale == "en" + else "文件夹不为空时不允许删除。" + ) + raise HTTPException(400, detail=error_msg) + shutil.rmtree(path) + else: + close_video_file_reader(path) + os.remove(path) + txt_path = get_img_geninfo_txt_path(path) + if txt_path: + os.remove(txt_path) + img = DbImg.get(conn, os.path.normpath(path)) + if img: + logger.info("delete file: %s", path) + ImageTag.remove(conn, img.id) + DbImg.remove(conn, img.id) + except OSError as e: + # 处理删除失败的情况 + logger.error("delete failed") + error_msg = ( + f"Error deleting file {path}: {e}" + if locale == "en" + else f"删除文件 {path} 时出错:{e}" + ) + raise HTTPException(400, detail=error_msg) + + class CreateFoldersReq(BaseModel): + dest_folder: str + + @app.post( + api_base + "/mkdirs", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def create_folders(req: CreateFoldersReq): + if enable_access_control: + if not is_path_under_parents(req.dest_folder): + raise HTTPException(status_code=403) + os.makedirs(req.dest_folder, exist_ok=True) + + class MoveFilesReq(BaseModel): + file_paths: List[str] + dest: str + create_dest_folder: Optional[bool] = False + + @app.post( + api_base + "/copy_files", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def copy_files(req: MoveFilesReq): + for path in req.file_paths: + check_path_trust(path) + try: + shutil.copy(path, req.dest) + txt_path = get_img_geninfo_txt_path(path) + if txt_path: + shutil.copy(txt_path, req.dest) + except OSError as e: + error_msg = ( + f"Error copying file {path} to {req.dest}: {e}" + if locale == "en" + else f"复制文件 {path} 到 {req.dest} 时出错:{e}" + ) + raise HTTPException(400, detail=error_msg) + + @app.post( + api_base + "/move_files", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def move_files(req: MoveFilesReq): + if req.create_dest_folder: + os.makedirs(req.dest, exist_ok=True) + elif not os.path.isdir(req.dest): + error_msg = ( + f"Destination folder {req.dest} does not exist." + if locale == "en" + else f"目标文件夹 {req.dest} 不存在。" + ) + raise HTTPException(400, detail=error_msg) + + conn = DataBase.get_conn() + + def move_file_with_geninfo(path: str, dest: str): + path = os.path.normpath(path) + txt_path = get_img_geninfo_txt_path(path) + if txt_path: + shutil.move(txt_path, dest) + img = DbImg.get(conn, path) + new_path = os.path.normpath(os.path.join(dest, os.path.basename(path))) + if img: + logger.info(f"update file path: {path} -> {new_path} in db") + img.update_path(conn, new_path, force=True) + + for path in req.file_paths: + check_path_trust(path) + path = os.path.normpath(path) + base_dir = os.path.dirname(path) + try: + files = list(os.walk(path)) + is_dir = os.path.isdir(path) + shutil.move(path, req.dest) + if is_dir: + for root, _, files in files: + relative_path = root[len(base_dir) + 1 :] + dest = os.path.join(req.dest, relative_path) + for file in files: + is_valid = is_media_file(file) + if is_valid: + move_file_with_geninfo(os.path.join(root, file), dest) + else: + move_file_with_geninfo(path, req.dest) + + conn.commit() + except OSError as e: + + conn.rollback() + error_msg = ( + f"Error moving file {path} to {req.dest}: {e}" + if locale == "en" + else f"移动文件 {path} 到 {req.dest} 时出错:{e}" + ) + raise HTTPException(400, detail=error_msg) + + @app.get(api_base + "/files", dependencies=[Depends(verify_secret)]) + async def get_target_folder_files(folder_path: str): + files: List[FileInfoDict] = [] + try: + if is_win and folder_path == "/": + for item in get_windows_drives(): + files.append( + {"type": "dir", "size": "-", "name": item, "fullpath": item} + ) + else: + if not os.path.exists(folder_path): + return {"files": []} + folder_path = to_abs_path(folder_path) + check_path_trust(folder_path) + folder_listing: List[os.DirEntry] = os.scandir(folder_path) + is_under_scanned_path = is_path_under_parents(folder_path) + for item in folder_listing: + if not os.path.exists(item.path): + continue + fullpath = os.path.normpath(item.path) + name = os.path.basename(item.path) + stat = item.stat() + date = get_formatted_date(stat.st_mtime) + created_time = get_created_date_by_stat(stat) + if item.is_file(): + bytes = stat.st_size + size = human_readable_size(bytes) + files.append( + { + "type": "file", + "date": date, + "size": size, + "name": name, + "bytes": bytes, + "created_time": created_time, + "fullpath": fullpath, + "is_under_scanned_path": is_under_scanned_path, + } + ) + elif item.is_dir(): + files.append( + { + "type": "dir", + "date": date, + "created_time": created_time, + "size": "-", + "name": name, + "is_under_scanned_path": is_under_scanned_path, + "fullpath": fullpath, + } + ) + except Exception as e: + # logger.error(e) + raise HTTPException(status_code=400, detail=str(e)) + + return {"files": filter_allowed_files(files)} + + + @app.post(api_base + "/batch_get_files_info", dependencies=[Depends(verify_secret)]) + async def batch_get_files_info(req: PathsReq): + res = {} + for path in req.paths: + check_path_trust(path) + res[path] = get_file_info_by_path(path) + return res + + @app.get(api_base + "/image-thumbnail", dependencies=[Depends(verify_secret)]) + async def thumbnail(path: str, t: str, size: str = "256x256"): + check_path_trust(path) + if not cache_base_dir: + return + # 生成缓存文件的路径 + hash_dir = hashlib.md5((path + t).encode("utf-8")).hexdigest() + hash = hash_dir + size + cache_dir = os.path.join(cache_base_dir, "iib_cache", hash_dir) + cache_path = os.path.join(cache_dir, f"{size}.webp") + + # 如果缓存文件存在,则直接返回该文件 + if os.path.exists(cache_path): + return FileResponse( + cache_path, + media_type="image/webp", + headers={"Cache-Control": "max-age=31536000", "ETag": hash}, + ) + + + # 如果小于64KB,直接返回原图 + if os.path.getsize(path) < 64 * 1024: + return FileResponse( + path, + media_type="image/" + path.split(".")[-1], + headers={"Cache-Control": "max-age=31536000", "ETag": hash}, + ) + + + # 如果缓存文件不存在,则生成缩略图并保存 + with Image.open(path) as img: + w, h = size.split("x") + img.thumbnail((int(w), int(h))) + os.makedirs(cache_dir, exist_ok=True) + img.save(cache_path, "webp") + + # 返回缓存文件 + return FileResponse( + cache_path, + media_type="image/webp", + headers={"Cache-Control": "max-age=31536000", "ETag": hash}, + ) + + @app.get(api_base + "/file", dependencies=[Depends(verify_secret)]) + async def get_file(path: str, t: str, disposition: Optional[str] = None): + filename = path + import mimetypes + + check_path_trust(path) + if not os.path.exists(filename): + raise HTTPException(status_code=404) + if not os.path.isfile(filename): + raise HTTPException(status_code=400, detail=f"{filename} is not a file") + # 根据文件后缀名获取媒体类型 + media_type, _ = mimetypes.guess_type(filename) + headers = {} + if disposition: + encoded_filename = urllib.parse.quote(disposition.encode('utf-8')) + headers['Content-Disposition'] = f"attachment; filename*=UTF-8''{encoded_filename}" + + if is_path_under_parents(filename) and is_valid_media_path( + filename + ): # 认为永远不变,不要协商缓存了试试 + headers[ + "Cache-Control" + ] = "public, max-age=31536000" # 针对同样名字文件但实际上不同内容的文件要求必须传入创建时间来避免浏览器缓存 + headers["Expires"] = (datetime.now() + timedelta(days=365)).strftime( + "%a, %d %b %Y %H:%M:%S GMT" + ) + + return FileResponse( + filename, + media_type=media_type, + headers=headers, + ) + + @app.get(api_base + "/stream_video", dependencies=[Depends(verify_secret)]) + async def stream_video(path: str, request: Request): + check_path_trust(path) + import mimetypes + media_type, _ = mimetypes.guess_type(path) + return range_requests_response( + request, file_path=path, content_type=media_type + ) + + @app.get(api_base + "/video_cover", dependencies=[Depends(verify_secret)]) + async def video_cover(path: str, mt: str): + check_path_trust(path) + if not cache_base_dir: + return + + if not os.path.exists(path): + raise HTTPException(status_code=404) + if not os.path.isfile(path) and get_video_type(path): + raise HTTPException(status_code=400, detail=f"{path} is not a video file") + # 生成缓存文件的路径 + hash_dir = hashlib.md5((path + mt).encode("utf-8")).hexdigest() + hash = hash_dir + cache_dir = os.path.join(cache_base_dir, "iib_cache", "video_cover", hash_dir) + cache_path = os.path.join(cache_dir, "cover.webp") + # 如果缓存文件存在,则直接返回该文件 + if os.path.exists(cache_path): + return FileResponse( + cache_path, + media_type="image/webp", + headers={ + "Cache-Control": "no-store", + }, + ) + # 如果缓存文件不存在,则生成缩略图并保存 + + import imageio.v3 as iio + frame = iio.imread( + path, + index=16, + plugin="pyav", + ) + + os.makedirs(cache_dir, exist_ok=True) + iio.imwrite(cache_path,frame, extension=".webp") + + # 返回缓存文件 + return FileResponse( + cache_path, + media_type="image/webp", + headers={ + "Cache-Control": "no-store", + }, + ) + + class SetTargetFrameAsCoverReq(BaseModel): + base64_img: str + path: str + updated_time: str + + def save_base64_image(base64_str, file_path): + if base64_str.startswith('data:image'): + base64_str = base64_str.split(',')[1] + image_data = base64.b64decode(base64_str) + with open(file_path, 'wb') as file: + file.write(image_data) + + @app.post(api_base+ "/set_target_frame_as_video_cover", dependencies=[Depends(verify_secret), Depends(write_permission_required)]) + async def set_target_frame_as_video_cover(req: SetTargetFrameAsCoverReq): + hash_dir = hashlib.md5((req.path + req.updated_time).encode("utf-8")).hexdigest() + hash = hash_dir + cache_dir = os.path.join(cache_base_dir, "iib_cache", "video_cover", hash_dir) + cache_path = os.path.join(cache_dir, "cover.webp") + + os.makedirs(cache_dir, exist_ok=True) + + save_base64_image(req.base64_img, cache_path) + return FileResponse( + cache_path, + media_type="image/webp", + headers={"ETag": hash}, + ) + + @app.post(api_base + "/send_img_path", dependencies=[Depends(verify_secret)]) + async def api_set_send_img_path(path: str): + send_img_path["value"] = path + + # 等待图片信息生成完成 + @app.get(api_base + "/gen_info_completed", dependencies=[Depends(verify_secret)]) + async def api_set_send_img_path(): + for _ in range(30): # timeout 3s + if send_img_path["value"] == "": # 等待setup里面生成完成 + return True + v = send_img_path["value"] + # is_dev and logger.info("gen_info_completed %s %s", _, v) + await asyncio.sleep(0.1) + return send_img_path["value"] == "" + + @app.get(api_base + "/image_geninfo", dependencies=[Depends(verify_secret)]) + async def image_geninfo(path: str): + return parse_image_info(path).raw_info + + class GeninfoBatchReq(BaseModel): + paths: List[str] + + @app.post(api_base + "/image_geninfo_batch", dependencies=[Depends(verify_secret)]) + async def image_geninfo_batch(req: GeninfoBatchReq): + res = {} + conn = DataBase.get_conn() + for path in req.paths: + try: + img = DbImg.get(conn, path) + if img: + res[path] = img.exif + else: + res[path] = parse_image_info(path).raw_info + except Exception as e: + logger.error(e, stack_info=True) + return res + + + class CheckPathExistsReq(BaseModel): + paths: List[str] + + @app.post(api_base + "/check_path_exists", dependencies=[Depends(verify_secret)]) + async def check_path_exists(req: CheckPathExistsReq): + update_all_scanned_paths() + res = {} + for path in req.paths: + res[path] = os.path.exists(path) and is_path_trusted(path) + return res + + @app.get(api_base) + def index_bd(): + if fe_public_path: + with open(index_html_path, "r", encoding="utf-8") as file: + content = file.read().replace(DEFAULT_BASE, fe_public_path) + return Response(content=content, media_type="text/html") + return FileResponse(index_html_path) + + static_dir = get_data_file_path("vue/dist") if is_exe_ver else f"{cwd}/vue/dist" + @app.get(api_base + "/fe-static/{file_path:path}") + async def serve_static_file(file_path: str): + file_full_path = f"{static_dir}/{file_path}" + if file_path.endswith(".js"): + with open(file_full_path, "r", encoding="utf-8") as file: + content = file.read().replace(DEFAULT_BASE, fe_public_path) + return Response(content=content, media_type="text/javascript") + else: + return FileResponse(file_full_path) + + class OpenFolderReq(BaseModel): + path: str + + @app.post( + api_base + "/open_folder", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + def open_folder_using_explore(req: OpenFolderReq): + if not is_path_trusted(req.path): + raise HTTPException(status_code=403) + open_folder(*os.path.split(req.path)) + + @app.post(api_base + "/shutdown") + async def shutdown_app(): + # This API endpoint is mainly used as a sidecar in Tauri applications to shut down the application + if not kwargs.get("enable_shutdown"): + raise HTTPException(status_code=403, detail="Shutdown is disabled.") + os.kill(os.getpid(), 9) + return {"message": "Application is shutting down."} + + + class PackReq(BaseModel): + paths: List[str] + compress: bool + pack_only: bool + + + @app.post( + api_base + "/zip", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + def zip_files(req: PackReq): + for path in req.paths: + check_path_trust(path) + if not os.path.isfile(path): + raise HTTPException(400, "The corresponding path must be a file.") + now = datetime.now() + timestamp = now.strftime("%Y-%m-%d-%H-%M-%S") + zip_temp_dir = os.path.join(cwd, "zip_temp") + os.makedirs(zip_temp_dir, exist_ok=True) + file_path = os.path.join(zip_temp_dir, f"iib_batch_download_{timestamp}.zip") + create_zip_file(req.paths, file_path, req.compress) + if not req.pack_only: + return FileResponse(file_path, media_type="application/zip") + + @app.post( + api_base + "/open_with_default_app", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + def open_target_file_withDefault_app(req: OpenFolderReq): + check_path_trust(req.path) + open_file_with_default_app(req.path) + + + @app.post( + api_base + "/batch_top_4_media_info", + dependencies=[Depends(verify_secret)], + ) + def batch_get_top_4_media_cover_info(req: PathsReq): + for path in req.paths: + check_path_trust(path) + res = {} + for path in req.paths: + res[path] = get_top_4_media_info(path) + return res + + db_api_base = api_base + "/db" + + @app.get(db_api_base + "/basic_info", dependencies=[Depends(verify_secret)]) + async def get_db_basic_info(): + conn = DataBase.get_conn() + img_count = DbImg.count(conn) + tags = Tag.get_all(conn) + expired_dirs = Folder.get_expired_dirs(conn) + return { + "img_count": img_count, + "tags": tags, + "expired": len(expired_dirs) != 0, + "expired_dirs": expired_dirs, + } + + @app.get(db_api_base + "/expired_dirs", dependencies=[Depends(verify_secret)]) + async def get_db_expired(): + conn = DataBase.get_conn() + expired_dirs = Folder.get_expired_dirs(conn) + return { + "expired": len(expired_dirs) != 0, + "expired_dirs": expired_dirs, + } + + @app.post( + db_api_base + "/update_image_data", + dependencies=[Depends(verify_secret)], + ) + async def update_image_db_data(): + try: + DataBase._initing = True + conn = DataBase.get_conn() + img_count = DbImg.count(conn) + update_extra_paths(conn) + dirs = ( + get_img_search_dirs() + if img_count == 0 + else Folder.get_expired_dirs(conn) + ) + mem["extra_paths"] + + update_image_data(dirs) + finally: + DataBase._initing = False + + class SearchBySubstrReq(BaseModel): + surstr: str + cursor: str + regexp: str + folder_paths: List[str] = None + size: Optional[int] = 200 + path_only: Optional[bool] = False + + @app.post(db_api_base + "/search_by_substr", dependencies=[Depends(verify_secret)]) + async def search_by_substr(req: SearchBySubstrReq): + if IIB_DEBUG: + logger.info(req) + conn = DataBase.get_conn() + folder_paths=normalize_paths(req.folder_paths, os.getcwd()) + if(not folder_paths and req.folder_paths): + return { "files": [], "cursor": Cursor(has_next=False) } + imgs, next_cursor = DbImg.find_by_substring( + conn=conn, + substring=req.surstr, + cursor=req.cursor, + limit=req.size, + regexp=req.regexp, + folder_paths=folder_paths, + path_only=req.path_only + ) + return { + "files": filter_allowed_files([x.to_file_info() for x in imgs]), + "cursor": next_cursor + } + + class MatchImagesByTagsReq(BaseModel): + and_tags: List[int] + or_tags: List[int] + not_tags: List[int] + cursor: str + folder_paths: List[str] = None + size: Optional[int] = 200 + + @app.post(db_api_base + "/match_images_by_tags", dependencies=[Depends(verify_secret)]) + async def match_image_by_tags(req: MatchImagesByTagsReq): + if IIB_DEBUG: + logger.info(req) + conn = DataBase.get_conn() + folder_paths=normalize_paths(req.folder_paths, os.getcwd()) + if(not folder_paths and req.folder_paths): + return { "files": [], "cursor": Cursor(has_next=False) } + imgs, next_cursor = ImageTag.get_images_by_tags( + conn=conn, + tag_dict={"and": req.and_tags, "or": req.or_tags, "not": req.not_tags}, + cursor=req.cursor, + folder_paths=folder_paths, + limit=req.size + ) + return { + "files": filter_allowed_files([x.to_file_info() for x in imgs]), + "cursor": next_cursor + } + + @app.get(db_api_base + "/img_selected_custom_tag", dependencies=[Depends(verify_secret)]) + async def get_img_selected_custom_tag(path: str): + path = os.path.normpath(path) + if not is_valid_media_path(path): + return [] + conn = DataBase.get_conn() + update_extra_paths(conn) + if not is_path_under_parents(path): + return [] + img = DbImg.get(conn, path) + if not img: + if DbImg.count(conn) == 0: + return [] + update_image_data([os.path.dirname(path)]) + img = DbImg.get(conn, path) + assert img + # tags = Tag.get_all_custom_tag() + return ImageTag.get_tags_for_image(conn, img.id, type="custom") + + @app.post(db_api_base + "/get_image_tags", dependencies=[Depends(verify_secret)]) + async def get_img_tags(req: PathsReq): + conn = DataBase.get_conn() + return ImageTag.batch_get_tags_by_path(conn, req.paths) + + + # update tag + class UpdateTagReq(BaseModel): + id: int + color: str + + @app.post( + db_api_base + "/update_tag", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def update_tag(req: UpdateTagReq): + conn = DataBase.get_conn() + tag = Tag.get(conn, req.id) + if tag: + tag.color = req.color + tag.save(conn) + conn.commit() + + + class ToggleCustomTagToImgReq(BaseModel): + img_path: str + tag_id: int + + @app.post( + db_api_base + "/toggle_custom_tag_to_img", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def toggle_custom_tag_to_img(req: ToggleCustomTagToImgReq): + conn = DataBase.get_conn() + path = os.path.normpath(req.img_path) + update_extra_paths(conn) + if not is_path_under_parents(path): + raise HTTPException( + 400, + '当前文件不在搜索路径内,你可以将它添加到扫描路径再尝试。在右上角的"更多"里面' + if locale == "zh" + else 'The current file is not within the scan path. You can add it to the scan path and try again. In the top right corner, click on "More".', + ) + img = DbImg.get(conn, path) + if not img: + if DbImg.count(conn): + # update_image_data([os.path.dirname(path)]) + add_image_data_single(path) + img = DbImg.get(conn, path) + else: + raise HTTPException( + 400, + "你需要先通过图像搜索页生成索引" + if locale == "zh" + else "You need to generate an index through the image search page first.", + ) + tags = ImageTag.get_tags_for_image( + conn=conn, image_id=img.id, type="custom", tag_id=req.tag_id + ) + is_remove = len(tags) + if is_remove: + ImageTag.remove(conn, img.id, tags[0].id) + else: + ImageTag(img.id, req.tag_id).save(conn) + conn.commit() + return {"is_remove": is_remove} + + class BatchUpdateImageReq(BaseModel): + img_paths: List[str] + action: str + tag_id: int + + @app.post( + db_api_base + "/batch_update_image_tag", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def batch_update_image_tag(req: BatchUpdateImageReq): + assert req.action in ["add", "remove"] + conn = DataBase.get_conn() + paths: List[str] = seq(req.img_paths).map(os.path.normpath).to_list() + update_extra_paths(conn) + for path in paths: + if not is_path_under_parents(path): + raise HTTPException( + 400, + '当前文件不在搜索路径内,你可以将它添加到扫描路径再尝试。在右上角的"更多"里面' + if locale == "zh" + else 'The current file is not within the scan path. You can add it to the scan path and try again. In the top right corner, click on "More".', + ) + img = DbImg.get(conn, path) + if not img: + if DbImg.count(conn): + add_image_data_single(path) + img = DbImg.get(conn, path) + else: + raise HTTPException( + 400, + "你需要先通过图像搜索页生成索引" + if locale == "zh" + else "You need to generate an index through the image search page first.", + ) + try: + for path in paths: + img = DbImg.get(conn, path) + if req.action == "add": + ImageTag(img.id, req.tag_id).save_or_ignore(conn) + else: + ImageTag.remove(conn, img.id, req.tag_id) + finally: + conn.commit() + + class AddCustomTagReq(BaseModel): + tag_name: str + + @app.post( + db_api_base + "/add_custom_tag", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def add_custom_tag(req: AddCustomTagReq): + conn = DataBase.get_conn() + tag = Tag.get_or_create(conn, name=req.tag_name, type="custom") + conn.commit() + return tag + + class RenameFileReq(BaseModel): + path: str + name: str + + @app.post( + db_api_base + "/rename", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def rename_file(req: RenameFileReq): + conn = DataBase.get_conn() + try: + # Normalize the paths + + path = os.path.normpath(req.path) + new_path = os.path.join(os.path.dirname(path), req.name) + + # Check if the file exists + if not os.path.exists(path): + raise HTTPException(status_code=404, detail="File not found") + + # Check if a file with the new name already exists + if os.path.exists(new_path): + raise HTTPException(status_code=400, detail="A file with the new name already exists") + close_video_file_reader(path) + img = DbImg.get(conn, path) + if img: + img.update_path(conn, new_path) + conn.commit() + + # Perform the file rename operation + os.rename(path, new_path) + + + return {"detail": "File renamed successfully", "new_path": new_path} + + except PermissionError: + raise HTTPException(status_code=403, detail="Permission denied") + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + class RemoveCustomTagReq(BaseModel): + tag_id: int + + @app.post( + db_api_base + "/remove_custom_tag", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def remove_custom_tag(req: RemoveCustomTagReq): + conn = DataBase.get_conn() + ImageTag.remove(conn, tag_id=req.tag_id) + Tag.remove(conn, req.tag_id) + + class RemoveCustomTagFromReq(BaseModel): + img_id: int + tag_id: str + + @app.post( + db_api_base + "/remove_custom_tag_from_img", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def remove_custom_tag_from_img(req: RemoveCustomTagFromReq): + conn = DataBase.get_conn() + ImageTag.remove(conn, image_id=req.img_id, tag_id=req.tag_id) + + + + + class ExtraPathModel(BaseModel): + path: str + types: List[str] + + @app.post( + f"{db_api_base}/extra_paths", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def create_extra_path(extra_path: ExtraPathModel): + if enable_access_control: + if not is_path_under_parents(extra_path.path): + raise HTTPException(status_code=403) + conn = DataBase.get_conn() + path = ExtraPath.get_target_path(conn, extra_path.path) + if path: + for t in extra_path.types: + path.types.append(t) + path.types = unique_by(path.types) + else: + path = ExtraPath(extra_path.path, extra_path.types) + try: + path.save(conn) + finally: + conn.commit() + + class ExtraPathAliasModel(BaseModel): + path: str + alias: str + + + @app.post( + f"{db_api_base}/alias_extra_path", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def alias_extra_path(req: ExtraPathAliasModel): + conn = DataBase.get_conn() + path = ExtraPath.get_target_path(conn, req.path) + if not path: + raise HTTPException(400) + path.alias = req.alias + try: + path.save(conn) + finally: + conn.commit() + return path + + + @app.get( + f"{db_api_base}/extra_paths", + dependencies=[Depends(verify_secret)], + ) + async def read_extra_paths(): + conn = DataBase.get_conn() + return ExtraPath.get_extra_paths(conn) + + + + @app.delete( + f"{db_api_base}/extra_paths", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def delete_extra_path(extra_path: ExtraPathModel): + path = to_abs_path(extra_path.path) + conn = DataBase.get_conn() + ExtraPath.remove(conn, path, extra_path.types, img_search_dirs=get_img_search_dirs()) + + + @app.post( + f"{db_api_base}/rebuild_index", + dependencies=[Depends(verify_secret), Depends(write_permission_required)], + ) + async def rebuild_index(): + update_extra_paths(conn = DataBase.get_conn()) + rebuild_image_index(search_dirs = get_img_search_dirs() + mem["extra_paths"]) + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/db/datamodel.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/db/datamodel.py new file mode 100644 index 0000000000000000000000000000000000000000..7853d627b8d4d3aaa1250a17e3d6e2934697327e --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/db/datamodel.py @@ -0,0 +1,869 @@ +from datetime import datetime +import json +from sqlite3 import Connection, connect +from enum import Enum +import sqlite3 +from typing import Dict, List, Optional, TypedDict, Union +from scripts.iib.tool import ( + cwd, + get_modified_date, + human_readable_size, + tags_translate, + is_dev, + find, + unique_by, +) +from contextlib import closing +import os +import threading +import re + + +class FileInfoDict(TypedDict): + type: str + date: float + size: int + name: str + bytes: bytes + created_time: float + fullpath: str + + +class Cursor: + def __init__(self, has_next=True, next=""): + self.has_next = has_next + self.next = next + + +class DataBase: + local = threading.local() + + _initing = False + + num = 0 + + path = "iib.db" + + @classmethod + def get_conn(clz) -> Connection: + # for : sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread + if hasattr(clz.local, "conn"): + return clz.local.conn + else: + conn = clz.init() + clz.local.conn = conn + + return conn + + @classmethod + def get_db_file_path(clz): + return clz.path if os.path.isabs(clz.path) else os.path.join(cwd, clz.path) + + @classmethod + def init(clz): + # 创建连接并打开数据库 + conn = connect(clz.get_db_file_path()) + + def regexp(expr, item): + if not isinstance(item, str): + return False + reg = re.compile(expr, flags=re.IGNORECASE | re.MULTILINE | re.DOTALL) + return reg.search(item) is not None + + conn.create_function("regexp", 2, regexp) + try: + Folder.create_table(conn) + ImageTag.create_table(conn) + Tag.create_table(conn) + Image.create_table(conn) + ExtraPath.create_table(conn) + DirCoverCache.create_table(conn) + GlobalSetting.create_table(conn) + finally: + conn.commit() + clz.num += 1 + if is_dev: + print(f"当前连接数{clz.num}") + return conn + + +class Image: + def __init__(self, path, exif=None, size=0, date="", id=None): + self.path = path + self.exif = exif + self.id = id + self.size = size + self.date = date + + def to_file_info(self) -> FileInfoDict: + return { + "type": "file", + "id": self.id, + "date": self.date, + "created_date": self.date, + "size": human_readable_size(self.size), + "is_under_scanned_path": True, + "bytes": self.size, + "name": os.path.basename(self.path), + "fullpath": self.path, + } + + def save(self, conn): + with closing(conn.cursor()) as cur: + cur.execute( + "INSERT OR REPLACE INTO image (path, exif, size, date) VALUES (?, ?, ?, ?)", + (self.path, self.exif, self.size, self.date), + ) + self.id = cur.lastrowid + + def update_path(self, conn: Connection, new_path: str, force=False): + self.path = os.path.normpath(new_path) + with closing(conn.cursor()) as cur: + if force: # force update path + cur.execute("DELETE FROM image WHERE path = ?", (self.path,)) + cur.execute("UPDATE image SET path = ? WHERE id = ?", (self.path, self.id)) + + @classmethod + def get(cls, conn: Connection, id_or_path): + with closing(conn.cursor()) as cur: + cur.execute( + "SELECT * FROM image WHERE id = ? OR path = ?", (id_or_path, id_or_path) + ) + row = cur.fetchone() + if row is None: + return None + else: + return cls.from_row(row) + + @classmethod + def get_by_ids(cls, conn: Connection, ids: List[int]) -> List["Image"]: + if not ids: + return [] + + query = """ + SELECT * FROM image + WHERE id IN ({}) + """.format( + ",".join("?" * len(ids)) + ) + + with closing(conn.cursor()) as cur: + cur.execute(query, ids) + rows = cur.fetchall() + + images = [] + for row in rows: + images.append(cls.from_row(row)) + return images + + @classmethod + def create_table(cls, conn): + with closing(conn.cursor()) as cur: + cur.execute( + """CREATE TABLE IF NOT EXISTS image ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + path TEXT UNIQUE, + exif TEXT, + size INTEGER, + date TEXT + )""" + ) + cur.execute("CREATE INDEX IF NOT EXISTS image_idx_path ON image(path)") + + @classmethod + def count(cls, conn): + with closing(conn.cursor()) as cur: + cur.execute("SELECT COUNT(*) FROM image") + count = cur.fetchone()[0] + return count + + @classmethod + def from_row(cls, row: tuple): + image = cls(path=row[1], exif=row[2], size=row[3], date=row[4]) + image.id = row[0] + return image + + @classmethod + def remove(cls, conn: Connection, image_id: int) -> None: + with closing(conn.cursor()) as cur: + cur.execute("DELETE FROM image WHERE id = ?", (image_id,)) + conn.commit() + + @classmethod + def safe_batch_remove(cls, conn: Connection, image_ids: List[int]) -> None: + if not (image_ids): + return + with closing(conn.cursor()) as cur: + try: + placeholders = ",".join("?" * len(image_ids)) + cur.execute( + f"DELETE FROM image_tag WHERE image_id IN ({placeholders})", + image_ids, + ) + cur.execute( + f"DELETE FROM image WHERE id IN ({placeholders})", image_ids + ) + except BaseException as e: + print(e) + finally: + conn.commit() + + @classmethod + def find_by_substring( + cls, conn: Connection, substring: str, limit: int = 500, cursor="", regexp="", path_only=False, + folder_paths: List[str] = [] + ) -> tuple[List["Image"], Cursor]: + api_cur = Cursor() + with closing(conn.cursor()) as cur: + params = [] + where_clauses = [] + if regexp: + if path_only: + where_clauses.append("(path REGEXP ?)") + params.append(regexp) + else: + where_clauses.append("((exif REGEXP ?) OR (path REGEXP ?))") + params.extend((regexp, regexp)) + else: + if path_only: + where_clauses.append("(path LIKE ?)") + params.append(f"%{substring}%") + else: + where_clauses.append("(path LIKE ? OR exif LIKE ?)") + params.extend((f"%{substring}%", f"%{substring}%")) + if cursor: + where_clauses.append("(date < ?)") + params.append(cursor) + if folder_paths: + folder_clauses = [] + for folder_path in folder_paths: + folder_clauses.append("(image.path LIKE ?)") + params.append(os.path.join(folder_path, "%")) + where_clauses.append("(" + " OR ".join(folder_clauses) + ")") + sql = "SELECT * FROM image" + if where_clauses: + sql += " WHERE " + sql += " AND ".join(where_clauses) + sql += " ORDER BY date DESC LIMIT ? " + params.append(limit) + cur.execute(sql, params) + rows = cur.fetchall() + + api_cur.has_next = len(rows) >= limit + images = [] + deleted_ids = [] + for row in rows: + img = cls.from_row(row) + if os.path.exists(img.path): + images.append(img) + else: + deleted_ids.append(img.id) + cls.safe_batch_remove(conn, deleted_ids) + if images: + api_cur.next = str(images[-1].date) + return images, api_cur + + +class Tag: + def __init__(self, name: str, score: int, type: str, count=0, color = ""): + self.name = name + self.score = score + self.type = type + self.count = count + self.id = None + self.color = color + self.display_name = tags_translate.get(name) + + def save(self, conn): + with closing(conn.cursor()) as cur: + cur.execute( + "INSERT OR REPLACE INTO tag (id, name, score, type, count, color) VALUES (?, ?, ?, ?, ?, ?)", + (self.id, self.name, self.score, self.type, self.count, self.color), + ) + self.id = cur.lastrowid + + @classmethod + def remove(cls, conn, tag_id): + with closing(conn.cursor()) as cur: + cur.execute("DELETE FROM tag WHERE id = ?", (tag_id,)) + conn.commit() + + @classmethod + def get(cls, conn: Connection, id): + with closing(conn.cursor()) as cur: + cur.execute("SELECT * FROM tag WHERE id = ?", (id,)) + row = cur.fetchone() + if row is None: + return None + else: + return cls.from_row(row) + + @classmethod + def get_all_custom_tag(cls, conn): + with closing(conn.cursor()) as cur: + cur.execute("SELECT * FROM tag where type = 'custom'") + rows = cur.fetchall() + tags: list[Tag] = [] + for row in rows: + tags.append(cls.from_row(row)) + return tags + + @classmethod + def get_all(cls, conn): + with closing(conn.cursor()) as cur: + cur.execute("SELECT * FROM tag") + rows = cur.fetchall() + tags: list[Tag] = [] + for row in rows: + tags.append(cls.from_row(row)) + return tags + + @classmethod + def get_or_create(cls, conn: Connection, name: str, type: str): + assert name and type + with closing(conn.cursor()) as cur: + cur.execute( + "SELECT tag.* FROM tag WHERE name = ? and type = ?", (name, type) + ) + row = cur.fetchone() + if row is None: + tag = cls(name=name, score=0, type=type) + tag.save(conn) + return tag + else: + return cls.from_row(row) + + @classmethod + def from_row(cls, row: tuple): + tag = cls(name=row[1], score=row[2], type=row[3], count=row[4], color=row[5]) + tag.id = row[0] + return tag + + @classmethod + def create_table(cls, conn): + with closing(conn.cursor()) as cur: + cur.execute( + """CREATE TABLE IF NOT EXISTS tag ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + score INTEGER, + type TEXT, + count INTEGER, + UNIQUE(name, type) ON CONFLICT REPLACE + ); + """ + ) + cur.execute("CREATE INDEX IF NOT EXISTS tag_idx_name ON tag(name)") + cur.execute( + """INSERT OR IGNORE INTO tag(name, score, type, count) + VALUES ("like", 0, "custom", 0); + """ + ) + try: + cur.execute( + """ALTER TABLE tag + ADD COLUMN color TEXT DEFAULT ''""" + ) + except sqlite3.OperationalError as e: + pass + + +class ImageTag: + def __init__(self, image_id: int, tag_id: int): + assert tag_id and image_id + self.image_id = image_id + self.tag_id = tag_id + + def save(self, conn): + with closing(conn.cursor()) as cur: + cur.execute( + "INSERT INTO image_tag (image_id, tag_id, created_at) VALUES (?, ?, CURRENT_TIMESTAMP)", + (self.image_id, self.tag_id), + ) + + def save_or_ignore(self, conn): + with closing(conn.cursor()) as cur: + cur.execute( + "INSERT OR IGNORE INTO image_tag (image_id, tag_id, created_at) VALUES (?, ?, CURRENT_TIMESTAMP)", + (self.image_id, self.tag_id), + ) + + @classmethod + def get_tags_for_image( + cls, + conn: Connection, + image_id: int, + tag_id: Optional[int] = None, + type: Optional[str] = None, + ): + with closing(conn.cursor()) as cur: + query = "SELECT tag.* FROM tag INNER JOIN image_tag ON tag.id = image_tag.tag_id WHERE image_tag.image_id = ?" + params = [image_id] + if tag_id: + query += " AND image_tag.tag_id = ?" + params.append(tag_id) + if type: + query += " AND tag.type = ?" + params.append(type) + cur.execute(query, tuple(params)) + rows = cur.fetchall() + return [Tag.from_row(x) for x in rows] + + @classmethod + def get_images_for_tag(cls, conn: Connection, tag_id): + with closing(conn.cursor()) as cur: + cur.execute( + "SELECT image.* FROM image INNER JOIN image_tag ON image.id = image_tag.image_id WHERE image_tag.tag_id = ?", + (tag_id,), + ) + rows = cur.fetchall() + images = [] + for row in rows: + images.append(Image.from_row(row)) + return images + + @classmethod + def create_table(cls, conn): + with closing(conn.cursor()) as cur: + cur.execute( + """CREATE TABLE IF NOT EXISTS image_tag ( + image_id INTEGER, + tag_id INTEGER, + FOREIGN KEY (image_id) REFERENCES image(id), + FOREIGN KEY (tag_id) REFERENCES tag(id), + PRIMARY KEY (image_id, tag_id) + )""" + ) + try: + cur.execute( + """ALTER TABLE image_tag + ADD COLUMN created_at TIMESTAMP""" + ) + + cur.execute( + """UPDATE image_tag + SET created_at = CURRENT_TIMESTAMP + WHERE created_at IS NULL""" + ) + except sqlite3.OperationalError as e: + pass + + @classmethod + def get_images_by_tags( + cls, + conn: Connection, + tag_dict: Dict[str, List[int]], + limit: int = 500, + cursor="", + folder_paths: List[str] = None, + ) -> tuple[List[Image], Cursor]: + query = """ + SELECT image.id, image.path, image.size,image.date + FROM image + INNER JOIN image_tag ON image.id = image_tag.image_id + """ + + where_clauses = [] + params = [] + + for operator, tag_ids in tag_dict.items(): + if operator == "and" and tag_dict["and"]: + where_clauses.append( + "tag_id IN ({})".format(",".join("?" * len(tag_ids))) + ) + params.extend(tag_ids) + elif operator == "not" and tag_dict["not"]: + where_clauses.append( + """(image_id NOT IN ( + SELECT image_id + FROM image_tag + WHERE tag_id IN ({}) +))""".format( + ",".join("?" * len(tag_ids)) + ) + ) + params.extend(tag_ids) + elif operator == "or" and tag_dict["or"]: + where_clauses.append( + """(image_id IN ( + SELECT image_id + FROM image_tag + WHERE tag_id IN ({}) + GROUP BY image_id + HAVING COUNT(DISTINCT tag_id) >= 1 +) +)""".format( + ",".join("?" * len(tag_ids)) + ) + ) + params.extend(tag_ids) + + if folder_paths: + folder_clauses = [] + for folder_path in folder_paths: + folder_clauses.append("(image.path LIKE ?)") + params.append(os.path.join(folder_path, "%")) + print(folder_path) + where_clauses.append("(" + " OR ".join(folder_clauses) + ")") + + if cursor: + where_clauses.append("(image.date < ?)") + params.append(cursor) + if where_clauses: + query += " WHERE " + " AND ".join(where_clauses) + query += " GROUP BY image.id" + if "and" in tag_dict and tag_dict['and']: + query += " HAVING COUNT(DISTINCT tag_id) = ?" + params.append(len(tag_dict["and"])) + + query += " ORDER BY date DESC LIMIT ?" + params.append(limit) + api_cur = Cursor() + with closing(conn.cursor()) as cur: + cur.execute(query, params) + rows = cur.fetchall() + images = [] + deleted_ids = [] + for row in rows: + img = Image(id=row[0], path=row[1], size=row[2], date=row[3]) + if os.path.exists(img.path): + images.append(img) + else: + deleted_ids.append(img.id) + Image.safe_batch_remove(conn, deleted_ids) + api_cur.has_next = len(rows) >= limit + if images: + api_cur.next = str(images[-1].date) + return images, api_cur + + @classmethod + def batch_get_tags_by_path( + cls, conn: Connection, paths: List[str], type="custom" + ) -> Dict[str, List[Tag]]: + if not paths: + return {} + tag_dict = {} + with closing(conn.cursor()) as cur: + placeholders = ",".join("?" * len(paths)) + query = f""" + SELECT image.path, tag.* FROM image_tag + INNER JOIN image ON image_tag.image_id = image.id + INNER JOIN tag ON image_tag.tag_id = tag.id + WHERE tag.type = '{type}' AND image.path IN ({placeholders}) + """ + cur.execute(query, paths) + rows = cur.fetchall() + for row in rows: + path = row[0] + tag = Tag.from_row(row[1:]) + if path in tag_dict: + tag_dict[path].append(tag) + else: + tag_dict[path] = [tag] + return tag_dict + + @classmethod + def remove( + cls, + conn: Connection, + image_id: Optional[int] = None, + tag_id: Optional[int] = None, + ) -> None: + assert image_id or tag_id + with closing(conn.cursor()) as cur: + if tag_id and image_id: + cur.execute( + "DELETE FROM image_tag WHERE image_id = ? and tag_id = ?", + (image_id, tag_id), + ) + elif tag_id: + cur.execute("DELETE FROM image_tag WHERE tag_id = ?", (tag_id,)) + else: + cur.execute("DELETE FROM image_tag WHERE image_id = ?", (image_id,)) + conn.commit() + + +class Folder: + def __init__(self, id: int, path: str, modified_date: str): + self.id = id + self.path = path + self.modified_date = modified_date + + @classmethod + def create_table(cls, conn): + with closing(conn.cursor()) as cur: + cur.execute( + """CREATE TABLE IF NOT EXISTS folders + (id INTEGER PRIMARY KEY AUTOINCREMENT, + path TEXT, + modified_date TEXT)""" + ) + cur.execute("CREATE INDEX IF NOT EXISTS folders_idx_path ON folders(path)") + + @classmethod + def check_need_update(cls, conn: Connection, folder_path: str): + folder_path = os.path.normpath(folder_path) + with closing(conn.cursor()) as cur: + if not os.path.exists(folder_path): + return False + cur.execute("SELECT * FROM folders WHERE path=?", (folder_path,)) + folder_record = cur.fetchone() # 如果这个文件夹没有记录,或者修改时间与数据库不同,则需要修改 + return not folder_record or ( + folder_record[2] != get_modified_date(folder_path) + ) + + @classmethod + def update_modified_date_or_create(cls, conn: Connection, folder_path: str): + folder_path = os.path.normpath(folder_path) + with closing(conn.cursor()) as cur: + cur.execute("SELECT * FROM folders WHERE path = ?", (folder_path,)) + row = cur.fetchone() + if row: + cur.execute( + "UPDATE folders SET modified_date = ? WHERE path = ?", + (get_modified_date(folder_path), folder_path), + ) + else: + cur.execute( + "INSERT INTO folders (path, modified_date) VALUES (?, ?)", + (folder_path, get_modified_date(folder_path)), + ) + + @classmethod + def get_expired_dirs(cls, conn: Connection): + dirs: List[str] = [] + with closing(conn.cursor()) as cur: + cur.execute("SELECT * FROM folders") + result_set = cur.fetchall() + extra_paths = ExtraPath.get_extra_paths(conn) + for ep in extra_paths: + if not find(result_set, lambda x: x[1] == ep.path): + dirs.append(ep.path) + for row in result_set: + folder_path = row[1] + if ( + os.path.exists(folder_path) + and get_modified_date(folder_path) != row[2] + ): + dirs.append(folder_path) + return unique_by(dirs, os.path.normpath) + + @classmethod + def remove_folder(cls, conn: Connection, folder_path: str): + folder_path = os.path.normpath(folder_path) + with closing(conn.cursor()) as cur: + cur.execute("DELETE FROM folders WHERE path = ?", (folder_path,)) + + @classmethod + def remove_all(cls, conn: Connection): + with closing(conn.cursor()) as cur: + cur.execute("DELETE FROM folders") + conn.commit() + + +class ExtraPathType(Enum): + scanned = "scanned" + scanned_fixed = "scanned-fixed" + walk = "walk" + cli_only = "cli_access_only" + + +class ExtraPath: + def __init__(self, path: str, types: Union[str, List[str]], alias = ''): + self.path = os.path.normpath(path) + self.types = types.split('+') if isinstance(types, str) else types + self.alias = alias + + def save(self, conn): + type_str = '+'.join(self.types) + for type in self.types: + assert type in [ExtraPathType.walk.value, ExtraPathType.scanned.value, ExtraPathType.scanned_fixed.value] + with closing(conn.cursor()) as cur: + cur.execute( + "INSERT INTO extra_path (path, type, alias) VALUES (?, ?, ?) " + "ON CONFLICT (path) DO UPDATE SET type = excluded.type, alias = excluded.alias", + (self.path, type_str, self.alias), + ) + + @classmethod + def get_target_path(cls, conn, path) -> Optional['ExtraPath']: + path = os.path.normpath(path) + query = f"SELECT * FROM extra_path where path = ?" + params = (path,) + with closing(conn.cursor()) as cur: + cur.execute(query, params) + rows = cur.fetchall() + paths: List[ExtraPath] = [] + for row in rows: + path = row[0] + if os.path.exists(path): + paths.append(ExtraPath(*row)) + else: + sql = "DELETE FROM extra_path WHERE path = ?" + cur.execute(sql, (path,)) + conn.commit() + return paths[0] if paths else None + + @classmethod + def get_extra_paths(cls, conn) -> List["ExtraPath"]: + query = "SELECT * FROM extra_path" + with closing(conn.cursor()) as cur: + cur.execute(query) + rows = cur.fetchall() + paths: List[ExtraPath] = [] + for row in rows: + path = row[0] + if os.path.exists(path): + paths.append(ExtraPath(*row)) + else: + cls.remove(conn, path) + return paths + + @classmethod + def remove( + cls, + conn, + path: str, + types: List[str] = None, + img_search_dirs: Optional[List[str]] = [], + ): + with closing(conn.cursor()) as cur: + path = os.path.normpath(path) + + target = cls.get_target_path(conn, path) + if not target: + return + new_types = [] + for type in target.types: + if type not in types: + new_types.append(type) + if new_types: + target.types = new_types + target.save(conn) + else: + sql = "DELETE FROM extra_path WHERE path = ?" + cur.execute(sql, (path,)) + + if path not in img_search_dirs: + Folder.remove_folder(conn, path) + conn.commit() + + @classmethod + def create_table(cls, conn): + with closing(conn.cursor()) as cur: + cur.execute( + """CREATE TABLE IF NOT EXISTS extra_path ( + path TEXT PRIMARY KEY, + type TEXT NOT NULL, + alias TEXT DEFAULT '' + )""" + ) + try: + cur.execute( + """ALTER TABLE extra_path + ADD COLUMN alias TEXT DEFAULT ''""" + ) + except sqlite3.OperationalError: + pass + +class DirCoverCache: + @classmethod + def create_table(cls, conn): + with closing(conn.cursor()) as cur: + cur.execute(""" + CREATE TABLE IF NOT EXISTS dir_cover_cache ( + folder_path TEXT PRIMARY KEY, + modified_time TEXT, + media_files TEXT + ) + """) + + @classmethod + def is_cache_expired(cls, conn, folder_path): + with closing(conn.cursor()) as cur: + cur.execute("SELECT modified_time FROM dir_cover_cache WHERE folder_path = ?", (folder_path,)) + result = cur.fetchone() + + if not result: + return True + + cached_time = datetime.fromisoformat(result[0]) + folder_modified_time = os.path.getmtime(folder_path) + return datetime.fromtimestamp(folder_modified_time) > cached_time + + @classmethod + def cache_media_files(cls, conn, folder_path, media_files): + media_files_json = json.dumps(media_files) + with closing(conn.cursor()) as cur: + cur.execute(""" + INSERT INTO dir_cover_cache (folder_path, modified_time, media_files) + VALUES (?, ?, ?) + ON CONFLICT(folder_path) DO UPDATE SET modified_time = excluded.modified_time, media_files = excluded.media_files + """, (folder_path, datetime.now().isoformat(), media_files_json)) + conn.commit() + + @classmethod + def get_cached_media_files(cls, conn, folder_path): + with closing(conn.cursor()) as cur: + cur.execute("SELECT media_files FROM dir_cover_cache WHERE folder_path = ?", (folder_path,)) + result = cur.fetchone() + + if result: + media_files_json = result[0] + return json.loads(media_files_json) + else: + return [] + + +class GlobalSetting: + @classmethod + def create_table(cls, conn): + with closing(conn.cursor()) as cur: + cur.execute( + """CREATE TABLE IF NOT EXISTS global_setting ( + setting_json TEXT, + name TEXT PRIMARY KEY, + created_time TEXT, + modified_time TEXT + )""" + ) + + @classmethod + def get_setting(cls, conn, name): + with closing(conn.cursor()) as cur: + cur.execute("SELECT setting_json FROM global_setting WHERE name = ?", (name,)) + result = cur.fetchone() + if result: + return json.loads(result[0]) + else: + return None + + @classmethod + def save_setting(cls, conn, name: str, setting: str): + json.loads(setting) # check if it is valid json + with closing(conn.cursor()) as cur: + cur.execute( + """INSERT INTO global_setting (setting_json, name, created_time, modified_time) + VALUES (?, ?, ?, ?) + ON CONFLICT(name) DO UPDATE SET setting_json = excluded.setting_json, modified_time = excluded.modified_time + """, + (setting, name, datetime.now().isoformat(), datetime.now().isoformat()), + ) + conn.commit() + + + @classmethod + def remove_setting(cls, conn, name: str): + with closing(conn.cursor()) as cur: + cur.execute("DELETE FROM global_setting WHERE name = ?", (name,)) + conn.commit() + + @classmethod + def get_all_settings(cls, conn): + with closing(conn.cursor()) as cur: + cur.execute("SELECT * FROM global_setting") + rows = cur.fetchall() + settings = {} + for row in rows: + settings[row[1]] = json.loads(row[0]) + return settings \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/db/update_image_data.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/db/update_image_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c9b5a88d0cc16c21442c0b4d5dbf807d3abd5d50 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/db/update_image_data.py @@ -0,0 +1,199 @@ +from contextlib import closing +from typing import Dict, List +from scripts.iib.db.datamodel import Image as DbImg, Tag, ImageTag, DataBase, Folder +import os +from scripts.iib.tool import ( + is_valid_media_path, + get_modified_date, + get_video_type, + is_dev, + get_modified_date, + is_image_file, + case_insensitive_get +) +from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams +from scripts.iib.logger import logger +from scripts.iib.parsers.index import parse_image_info +from scripts.iib.plugin import plugin_inst_map + +# 定义一个函数来获取图片文件的EXIF数据 +def get_exif_data(file_path): + if get_video_type(file_path): + return ImageGenerationInfo() + try: + return parse_image_info(file_path) + except Exception as e: + if is_dev: + logger.error("get_exif_data %s", e) + return ImageGenerationInfo() + + +def update_image_data(search_dirs: List[str], is_rebuild = False): + conn = DataBase.get_conn() + tag_incr_count_rec: Dict[int, int] = {} + + if is_rebuild: + Folder.remove_all(conn) + + def safe_save_img_tag(img_tag: ImageTag): + tag_incr_count_rec[img_tag.tag_id] = ( + tag_incr_count_rec.get(img_tag.tag_id, 0) + 1 + ) + img_tag.save_or_ignore(conn) # 原先用来处理一些意外,但是写的正确完全没问题,去掉了try catch + + # 递归处理每个文件夹 + def process_folder(folder_path: str): + if not Folder.check_need_update(conn, folder_path): + return + print(f"Processing folder: {folder_path}") + for filename in os.listdir(folder_path): + file_path = os.path.normpath(os.path.join(folder_path, filename)) + try: + + if os.path.isdir(file_path): + process_folder(file_path) + elif is_valid_media_path(file_path): + build_single_img_idx(conn, file_path, is_rebuild, safe_save_img_tag) + # neg暂时跳过感觉个没人会搜索这个 + except Exception as e: + logger.error("Tag generation failed. Skipping this file. file:%s error: %s", file_path, e) + # 提交对数据库的更改 + Folder.update_modified_date_or_create(conn, folder_path) + conn.commit() + + for dir in search_dirs: + process_folder(dir) + conn.commit() + for tag_id in tag_incr_count_rec: + tag = Tag.get(conn, tag_id) + tag.count += tag_incr_count_rec[tag_id] + tag.save(conn) + conn.commit() + +def add_image_data_single(file_path): + conn = DataBase.get_conn() + tag_incr_count_rec: Dict[int, int] = {} + + def safe_save_img_tag(img_tag: ImageTag): + tag_incr_count_rec[img_tag.tag_id] = ( + tag_incr_count_rec.get(img_tag.tag_id, 0) + 1 + ) + img_tag.save_or_ignore(conn) + + file_path = os.path.normpath(file_path) + try: + if not is_valid_media_path(file_path): + return + build_single_img_idx(conn, file_path, False, safe_save_img_tag) + # neg暂时跳过感觉个没人会搜索这个 + except Exception as e: + logger.error("Tag generation failed. Skipping this file. file:%s error: %s", file_path, e) + conn.commit() + + for tag_id in tag_incr_count_rec: + tag = Tag.get(conn, tag_id) + tag.count += tag_incr_count_rec[tag_id] + tag.save(conn) + conn.commit() + +def rebuild_image_index(search_dirs: List[str]): + conn = DataBase.get_conn() + with closing(conn.cursor()) as cur: + cur.execute( + """DELETE FROM image_tag + WHERE image_tag.tag_id IN ( + SELECT tag.id FROM tag WHERE tag.type <> 'custom' + ) + """ + ) + cur.execute("""DELETE FROM tag WHERE tag.type <> 'custom'""") + conn.commit() + update_image_data(search_dirs=search_dirs, is_rebuild=True) + + +def get_extra_meta_keys_from_plugins(source_identifier: str): + try: + plugin = plugin_inst_map.get(source_identifier) + if plugin: + return plugin.extra_convert_to_tag_meta_keys + except Exception as e: + logger.error("get_extra_meta_keys_from_plugins %s", e) + return [] + +def build_single_img_idx(conn, file_path, is_rebuild, safe_save_img_tag): + img = DbImg.get(conn, file_path) + parsed_params = None + if is_rebuild: + info = get_exif_data(file_path) + parsed_params = info.params + if not img: + img = DbImg( + file_path, + info.raw_info, + os.path.getsize(file_path), + get_modified_date(file_path), + ) + img.save(conn) + else: + if img: # 已存在的跳过 + if img.date == get_modified_date(img.path): + return + else: + DbImg.safe_batch_remove(conn=conn, image_ids=[img.id]) + info = get_exif_data(file_path) + parsed_params = info.params + img = DbImg( + file_path, + info.raw_info, + os.path.getsize(file_path), + get_modified_date(file_path), + ) + img.save(conn) + + if not parsed_params: + return + meta = parsed_params.meta + lora = parsed_params.extra.get("lora", []) + lyco = parsed_params.extra.get("lyco", []) + pos = parsed_params.pos_prompt + size_tag = Tag.get_or_create( + conn, + str(meta.get("Size-1", 0)) + " * " + str(meta.get("Size-2", 0)), + type="size", + ) + safe_save_img_tag(ImageTag(img.id, size_tag.id)) + media_type_tag = Tag.get_or_create(conn, "Image" if is_image_file(file_path) else "Video", 'Media Type') + safe_save_img_tag(ImageTag(img.id, media_type_tag.id)) + keys = [ + "Model", + "Sampler", + "Source Identifier", + "Postprocess upscale by", + "Postprocess upscaler", + "Size", + "Refiner", + "Hires upscaler" + ] + keys += get_extra_meta_keys_from_plugins(meta.get("Source Identifier", "")) + for k in keys: + v = case_insensitive_get(meta, k) + if not v: + continue + + tag = Tag.get_or_create(conn, str(v), k) + safe_save_img_tag(ImageTag(img.id, tag.id)) + if "Hires upscaler" == k: + tag = Tag.get_or_create(conn, 'Hires All', k) + safe_save_img_tag(ImageTag(img.id, tag.id)) + elif "Refiner" == k: + tag = Tag.get_or_create(conn, 'Refiner All', k) + safe_save_img_tag(ImageTag(img.id, tag.id)) + for i in lora: + tag = Tag.get_or_create(conn, i["name"], "lora") + safe_save_img_tag(ImageTag(img.id, tag.id)) + for i in lyco: + tag = Tag.get_or_create(conn, i["name"], "lyco") + safe_save_img_tag(ImageTag(img.id, tag.id)) + for k in pos: + tag = Tag.get_or_create(conn, k, "pos") + safe_save_img_tag(ImageTag(img.id, tag.id)) \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/dir_cover_cache.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/dir_cover_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..7b850d3af75b370f58e2787e1eb29eafaa6e1be9 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/dir_cover_cache.py @@ -0,0 +1,53 @@ +import os +from scripts.iib.db.datamodel import DirCoverCache, DataBase +from scripts.iib.tool import get_created_date_by_stat, get_formatted_date, is_valid_media_path, get_video_type, birthtime_sort_key_fn + +def get_top_4_media_info(folder_path): + """ + 获取给定文件夹路径下的前4个媒体文件的完整路径。 + + 参数: + folder_path (str): 文件夹的路径。 + + 返回值: + list: 包含前4个媒体文件完整路径的列表。 + """ + conn = DataBase.get_conn() + if DirCoverCache.is_cache_expired(conn, folder_path): + media_files = get_media_files_from_folder(folder_path) + DirCoverCache.cache_media_files(conn, folder_path, media_files) + else: + media_files = DirCoverCache.get_cached_media_files(conn, folder_path) + + return media_files[:4] + +def get_media_files_from_folder(folder_path): + """ + 从文件夹中获取媒体文件的完整路径。 + + 参数: + folder_path (str): 文件夹的路径。 + + 返回值: + list: 包含媒体文件完整路径的列表。 + """ + media_files = [] + with os.scandir(folder_path) as entries: + for entry in sorted(entries, key=birthtime_sort_key_fn, reverse=True): + if entry.is_file() and is_valid_media_path(entry.path): + name = os.path.basename(entry.path) + stat = entry.stat() + date = get_formatted_date(stat.st_mtime) + created_time = get_created_date_by_stat(stat) + media_files.append({ + "fullpath": entry.path, + "media_type": "video" if get_video_type(entry.path) else "image", + "type": "file", + "date": date, + "created_time": created_time, + "name": name, + }) + if len(media_files) > 3: + return media_files + + return media_files diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/fastapi_video.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/fastapi_video.py new file mode 100644 index 0000000000000000000000000000000000000000..bd2ade1ca72869d74582e118af40b7502f685680 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/fastapi_video.py @@ -0,0 +1,86 @@ +import os +from typing import BinaryIO + +from fastapi import FastAPI, HTTPException, Request, status +from fastapi.responses import StreamingResponse +from scripts.iib.tool import get_video_type + +video_file_handler = {} + +def close_video_file_reader(path): + if not get_video_type(path): + return + try: + video_file_handler[path].close() + except Exception as e: + print(f"close file error: {e}") + + +def send_bytes_range_requests( + file_path, start: int, end: int, chunk_size: int = 10_000 +): + """Send a file in chunks using Range Requests specification RFC7233 + + `start` and `end` parameters are inclusive due to specification + """ + with open(file_path, mode="rb") as f: + video_file_handler[file_path] = f + f.seek(start) + while (pos := f.tell()) <= end: + read_size = min(chunk_size, end + 1 - pos) + yield f.read(read_size) + + +def _get_range_header(range_header: str, file_size: int) -> tuple[int, int]: + def _invalid_range(): + return HTTPException( + status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE, + detail=f"Invalid request range (Range:{range_header!r})", + ) + + try: + h = range_header.replace("bytes=", "").split("-") + start = int(h[0]) if h[0] != "" else 0 + end = int(h[1]) if h[1] != "" else file_size - 1 + except ValueError: + raise _invalid_range() + + if start > end or start < 0 or end > file_size - 1: + raise _invalid_range() + return start, end + + +def range_requests_response( + request: Request, file_path: str, content_type: str +): + """Returns StreamingResponse using Range Requests of a given file""" + + file_size = os.stat(file_path).st_size + range_header = request.headers.get("range") + + headers = { + "content-type": content_type, + "accept-ranges": "bytes", + "content-encoding": "identity", + "content-length": str(file_size), + "access-control-expose-headers": ( + "content-type, accept-ranges, content-length, " + "content-range, content-encoding" + ), + } + start = 0 + end = file_size - 1 + status_code = status.HTTP_200_OK + + if range_header is not None: + start, end = _get_range_header(range_header, file_size) + size = end - start + 1 + headers["content-length"] = str(size) + headers["content-range"] = f"bytes {start}-{end}/{file_size}" + status_code = status.HTTP_206_PARTIAL_CONTENT + + return StreamingResponse( + send_bytes_range_requests(file_path, start, end), + headers=headers, + status_code=status_code, + ) diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/img_cache_gen.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/img_cache_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..be8d5e6821e94f7de49dcc5b37e8d3701eed0bd2 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/img_cache_gen.py @@ -0,0 +1,58 @@ +import hashlib +import os +from typing import List +from scripts.iib.tool import get_formatted_date, get_cache_dir, is_image_file +from concurrent.futures import ThreadPoolExecutor +import time +from PIL import Image + +def generate_image_cache(dirs, size:str, verbose=False): + start_time = time.time() + cache_base_dir = get_cache_dir() + + def process_image(item): + if item.is_dir(): + verbose and print(f"Processing directory: {item.path}") + for sub_item in os.scandir(item.path): + process_image(sub_item) + return + if not os.path.exists(item.path) or not is_image_file(item.path): + return + + try: + path = os.path.normpath(item.path) + stat = item.stat() + t = get_formatted_date(stat.st_mtime) + hash_dir = hashlib.md5((path + t).encode("utf-8")).hexdigest() + cache_dir = os.path.join(cache_base_dir, "iib_cache", hash_dir) + cache_path = os.path.join(cache_dir, f"{size}.webp") + + if os.path.exists(cache_path): + verbose and print(f"Image cache already exists: {path}") + return + + if os.path.getsize(path) < 64 * 1024: + verbose and print(f"Image size less than 64KB: {path}", "skip") + return + + with Image.open(path) as img: + w, h = size.split("x") + img.thumbnail((int(w), int(h))) + os.makedirs(cache_dir, exist_ok=True) + img.save(cache_path, "webp") + + verbose and print(f"Image cache generated: {path}") + except Exception as e: + print(f"Error generating image cache: {path}") + print(e) + + with ThreadPoolExecutor() as executor: + for dir_path in dirs: + folder_listing: List[os.DirEntry] = os.scandir(dir_path) + for item in folder_listing: + executor.submit(process_image, item) + + print("Image cache generation completed. ✨") + end_time = time.time() + execution_time = end_time - start_time + print(f"Execution time: {execution_time} seconds") \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/logger.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..3d795279695ff805e6076982e02794c5c6912581 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/logger.py @@ -0,0 +1,20 @@ + +from scripts.iib.tool import is_dev,cwd + +import logging +logger = logging.getLogger(__name__) +logger.setLevel(logging.DEBUG) + +console_handler = logging.StreamHandler() +console_handler.setLevel(logging.INFO) + +file_handler = logging.FileHandler(f"{cwd}/log.log") +file_handler.setLevel(logging.DEBUG) + +formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") +console_handler.setFormatter(formatter) +file_handler.setFormatter(formatter) + +logger.addHandler(file_handler) +if is_dev: + logger.addHandler(console_handler) diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/comfyui.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/comfyui.py new file mode 100644 index 0000000000000000000000000000000000000000..9a4d2063abee587bf935aadf4eb856a043a5260e --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/comfyui.py @@ -0,0 +1,51 @@ +from PIL import Image + +from scripts.iib.tool import ( + comfyui_exif_data_to_str, + is_img_created_by_comfyui, + is_img_created_by_comfyui_with_webui_gen_info, + get_comfyui_exif_data, + parse_generation_parameters, + read_sd_webui_gen_info_from_image, +) +from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams +from scripts.iib.logger import logger + + +class ComfyUIParser: + def __init__(self): + pass + + @classmethod + def parse(clz, img, file_path): + info = "" + params = None + if not clz.test(img, file_path): + raise Exception("The input image does not match the current parser.") + try: + if is_img_created_by_comfyui_with_webui_gen_info(img): + info = read_sd_webui_gen_info_from_image(img, file_path) + info += ", Source Identifier: ComfyUI" + params = parse_generation_parameters(info) + else: + params = get_comfyui_exif_data(img) + info = comfyui_exif_data_to_str(params) + except Exception as e: + logger.error('parse comfyui image failed. prompt:') + logger.error(img.info.get('prompt')) + return ImageGenerationInfo() + return ImageGenerationInfo( + info, + ImageGenerationParams( + meta=params["meta"], pos_prompt=params["pos_prompt"], extra=params + ), + ) + + @classmethod + def test(clz, img: Image, file_path: str) -> bool: + try: + return is_img_created_by_comfyui( + img + ) or is_img_created_by_comfyui_with_webui_gen_info(img) + except Exception: + return False diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/fooocus.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/fooocus.py new file mode 100644 index 0000000000000000000000000000000000000000..7c1df198e5ba93365935d8da12cff27353314f9e --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/fooocus.py @@ -0,0 +1,77 @@ +import os +import re +from PIL import Image + +from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams +from scripts.iib.tool import omit, parse_generation_parameters, unique_by + + +def remove_extra_spaces(text): + return re.sub(r"\s+", " ", text) + + +def get_log_file(file_path: str): + dir = os.path.dirname(file_path) + with open(os.path.join(dir, "log.html")) as f: + return f.read() + +lora_re = re.compile("LoRA \d+", re.IGNORECASE) + +class FooocusParser: + def __init__(self): + pass + + @classmethod + def parse(clz, img: Image, file_path): + if not clz.test(img, file_path): + raise Exception("The input image does not match the current parser.") + from lxml import etree + + log = get_log_file(file_path) + root = etree.HTML(log) + id = str(os.path.basename(file_path)).replace(".", "_") + metadata = root.xpath(f'//div[@id="{id}"]/descendant::table[@class="metadata"]') + tr_elements = metadata[0].xpath(".//tr") + lora_list = [] + # As a workaround to bypass parsing errors in the parser. + # https://github.com/jiw0220/stable-diffusion-image-metadata/blob/00b8d42d4d1a536862bba0b07c332bdebb2a0ce5/src/index.ts#L130 + metadata_list_str = "Steps: Unknown , Source Identifier: Fooocus ," + params = {"meta": {"Source Identifier": "Fooocus"}} + for tr in tr_elements: + label = tr.xpath('.//td[@class="label" or @class="key"]/text()') + value = tr.xpath('.//td[@class="value"]/text()') + if label: + k = label[0] + v = value[0] if value else "None" + if k == "Fooocus V2 Expansion": + continue + if k == "Prompt" or k == "Negative Prompt": + params[k] = remove_extra_spaces(v.replace("\n", "").strip()) + else: + v = v.replace(",", ",") + params["meta"][k] = v + metadata_list_str += f" {k}: {v}," + if lora_re.search(k): + lora_list.append({ "name": v.strip(), "value": 1 }) + params["meta"]["Model"] = params["meta"]["Base Model"] + params["meta"]["Size"] = str(params["meta"]["Resolution"]).replace("(", "").replace(")", "").replace(",", " * ") + metadata_list_str = metadata_list_str.strip() + info = f"""{params['Prompt']}\nNegative prompt: {params['Negative Prompt']}\n{metadata_list_str}""".strip() + return ImageGenerationInfo( + info, + ImageGenerationParams( + meta=params["meta"], + pos_prompt=parse_generation_parameters(info)["pos_prompt"], + extra={ + "lora": unique_by(lora_list, lambda x: x["name"].lower()) + } + ), + ) + + @classmethod + def test(clz, img: Image, file_path: str): + filename = os.path.basename(file_path) + try: + return get_log_file(file_path).find(filename) != -1 + except Exception as e: + return False diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/index.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/index.py new file mode 100644 index 0000000000000000000000000000000000000000..66fb5dba6fd48f211c1e4ca74b6c9cfbbc033dc6 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/index.py @@ -0,0 +1,33 @@ +from scripts.iib.parsers.comfyui import ComfyUIParser +from scripts.iib.parsers.sd_webui import SdWebUIParser +from scripts.iib.parsers.fooocus import FooocusParser +from scripts.iib.parsers.novelai import NovelAIParser +from scripts.iib.parsers.model import ImageGenerationInfo +from scripts.iib.parsers.stable_swarm_ui import StableSwarmUIParser +from scripts.iib.parsers.invoke_ai import InvokeAIParser +from scripts.iib.logger import logger +from PIL import Image +from scripts.iib.plugin import plugin_insts +import traceback + + +def parse_image_info(image_path: str) -> ImageGenerationInfo: + parsers = plugin_insts + [ + ComfyUIParser, + FooocusParser, + NovelAIParser, + InvokeAIParser, + StableSwarmUIParser, + SdWebUIParser, + ] + with Image.open(image_path) as img: + for parser in parsers: + if parser.test(img, image_path): + try: + return parser.parse(img, image_path) + except Exception as e: + logger.error(e, stack_info=True) + print(e) + print(traceback.format_exc()) + return ImageGenerationInfo() + raise Exception("matched parser is not found") diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/invoke_ai.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/invoke_ai.py new file mode 100644 index 0000000000000000000000000000000000000000..0765ca0da9f3d15aad567913fe68c236d96bf3fe --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/invoke_ai.py @@ -0,0 +1,64 @@ +from PIL import Image +import json + +from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams +from scripts.iib.tool import omit, parse_generation_parameters, unique_by + +class InvokeAIParser: + def __init__(self): + pass + + @classmethod + def parse(clz, img: Image, file_path): + if not clz.test(img, file_path): + raise Exception("The input image does not match the current parser.") + raw_infos = json.loads(img.info["invokeai_graph"]) + core_metadata = {} + for key in raw_infos['nodes']: + if key.startswith("core_metadata"): + core_metadata = raw_infos['nodes'][key] + break + + positive_prompt = core_metadata.get("positive_prompt", "None") + negative_prompt = core_metadata.get("negative_prompt", "None") + steps = core_metadata.get("steps", 'Unknown') + cfg_scale = core_metadata.get("cfg_scale", 'Unknown') + model_name = core_metadata.get("model", {}).get("name", "Unknown") + model_hash = core_metadata.get("model", {}).get("hash", "Unknown") + + meta_kv = [ + f"Steps: {steps}", + "Source Identifier: InvokeAI", + f"CFG scale: {cfg_scale}", + f"Model: {model_name}", + f"Model hash: {model_hash}", + ] + + for key in core_metadata: + if key not in ["positive_prompt", "negative_prompt", "steps", "cfg_scale", "model"]: + val = core_metadata[key] + if bool(val): + meta_kv.append(f"{key}: {val}") + + meta = ", ".join(meta_kv) + meta_obj = {} + for kv in meta_kv: + k, v = kv.split(": ", 1) + meta_obj[k] = v + info = f"{positive_prompt}\nNegative prompt: {negative_prompt}\n{meta}" + + return ImageGenerationInfo( + info, + ImageGenerationParams( + meta=meta_obj, + pos_prompt=parse_generation_parameters(info)["pos_prompt"], + # extra=params + ), + ) + + @classmethod + def test(clz, img: Image, file_path: str): + try: + return 'invokeai_graph' in img.info + except Exception as e: + return False diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/model.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/model.py new file mode 100644 index 0000000000000000000000000000000000000000..282048d8e4df6a38fb6b20b3ab235656a876229c --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/model.py @@ -0,0 +1,18 @@ +from scripts.iib.tool import omit + + +class ImageGenerationParams: + def __init__(self, meta: dict = {}, pos_prompt: list = [], extra: dict = {}) -> None: + self.meta = meta + self.pos_prompt = pos_prompt + self.extra = omit(extra, ["meta", "pos_prompt"]) + + +class ImageGenerationInfo: + def __init__( + self, + raw_info: str = "", + params: ImageGenerationParams = ImageGenerationParams(), + ): + self.raw_info = raw_info + self.params = params diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/novelai.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/novelai.py new file mode 100644 index 0000000000000000000000000000000000000000..680e1cd03417f5e2e55d110533ec620e0cd8bb0b --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/novelai.py @@ -0,0 +1,44 @@ +import json +from PIL import Image + +from scripts.iib.tool import ( + parse_generation_parameters, + replace_punctuation +) +from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams + + +class NovelAIParser: + def __init__(self): + pass + + @classmethod + def parse(clz, img, file_path): + info = "" + params = None + if not clz.test(img, file_path): + raise Exception("The input image does not match the current parser.") + data = json.loads(img.info.get('Comment')) + meta_kv = [f"""Steps: {data["steps"]}, Source Identifier: NovelAI"""] + for key, value in data.items(): + if key not in ["prompt"]: + value = replace_punctuation(str(value)) + meta_kv.append(f"{key}: {value}") + meta = ', '.join(meta_kv) + info = data["prompt"] + '\n' + meta + + params = parse_generation_parameters(info) + + return ImageGenerationInfo( + info, + ImageGenerationParams( + meta=params["meta"], pos_prompt=params["pos_prompt"] + ), + ) + + @classmethod + def test(clz, img: Image, file_path: str) -> bool: + try: + return img.info.get('Software') == 'NovelAI' and isinstance(img.info.get('Comment'), str) + except Exception: + return False diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/sd_webui.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/sd_webui.py new file mode 100644 index 0000000000000000000000000000000000000000..88c11a51a3dc0509da33a572ffd427c4e271cd0c --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/sd_webui.py @@ -0,0 +1,35 @@ +from PIL import Image + +from scripts.iib.tool import ( + parse_generation_parameters, + read_sd_webui_gen_info_from_image, +) +from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams + + +class SdWebUIParser: + def __init__(self): + pass + + @classmethod + def parse(clz, img: Image, file_path): + if not clz.test(img, file_path): + raise Exception("The input image does not match the current parser.") + info = read_sd_webui_gen_info_from_image(img, file_path) + if not info: + return ImageGenerationInfo() + info += ", Source Identifier: Stable Diffusion web UI" + params = parse_generation_parameters(info) + return ImageGenerationInfo( + info, + ImageGenerationParams( + meta=params["meta"], pos_prompt=params["pos_prompt"], extra=params + ), + ) + + @classmethod + def test(clz, img: Image, file_path: str): + try: + return True + except Exception as e: + return False diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/stable_swarm_ui.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/stable_swarm_ui.py new file mode 100644 index 0000000000000000000000000000000000000000..8e41e043371f20b9c8844f3c9f143d0944c25a43 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/parsers/stable_swarm_ui.py @@ -0,0 +1,61 @@ +from PIL import Image + +import piexif +import piexif.helper +from scripts.iib.tool import parse_generation_parameters, replace_punctuation +from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams +from PIL.ExifTags import TAGS +import json + + +class StableSwarmUIParser: + def __init__(self): + pass + + @classmethod + def get_exif_data(clz, image: Image) -> str: + items = image.info or {} + + if "exif" in items: + exif = piexif.load(items["exif"]) + exif_bytes = ( + (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b"") + ) + + unicode_start = exif_bytes.find(b"UNICODE") + if unicode_start == -1: + raise ValueError("'UNICODE' markup isn't found") + + unicode_data = exif_bytes[unicode_start + len("UNICODE") + 1 :] + geninfo = unicode_data.decode("utf-16") + return geninfo + + @classmethod + def parse(clz, img: Image, file_path): + if not clz.test(img, file_path): + raise Exception("The input image does not match the current parser.") + exif_data = json.loads(clz.get_exif_data(img))["sui_image_params"] + prompt = exif_data.pop("prompt") + negativeprompt = exif_data.pop("negativeprompt") + steps = exif_data.pop("steps") + meta_kv = [f"Steps: {steps}", "Source Identifier: StableSwarmUI"] + for key, value in exif_data.items(): + value = replace_punctuation(str(value)) + meta_kv.append(f"{key}: {value}") + meta = ", ".join(meta_kv) + info = "\n".join([prompt, f"Negative prompt: {negativeprompt}", meta]) + params = parse_generation_parameters(info) + return ImageGenerationInfo( + info, + ImageGenerationParams( + meta=params["meta"], pos_prompt=params["pos_prompt"], extra=params + ), + ) + + @classmethod + def test(clz, img: Image, file_path: str): + try: + exif = clz.get_exif_data(img) + return exif.find("sui_image_params") != -1 + except Exception as e: + return False diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/plugin.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..fbcb7ce4e1c3168835777cfaf46dc6e4c9188532 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/plugin.py @@ -0,0 +1,36 @@ +import os +import importlib.util +import sys +from scripts.iib.tool import cwd + +def load_plugins(plugin_dir): + if not os.path.exists(plugin_dir): + return [] + plugins = [] + for filename in os.listdir(plugin_dir): + main_module_path = os.path.join(plugin_dir, filename, 'main.py') + if not os.path.exists(main_module_path): + continue + spec = importlib.util.spec_from_file_location('main', main_module_path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + plugins.append(module) + return plugins + +plugin_insts = [] +plugin_inst_map = {} +# 使用插件 +try: + plugin_dir = os.path.normpath(os.path.join(cwd, 'plugins')) + plugins = load_plugins(plugin_dir) + sys.path.append(plugin_dir) + for plugin in plugins: + try: + res = plugin.Main() + plugin_insts.append(res) + plugin_inst_map[res.source_identifier] = res + print(f'IIB loaded plugin: {res.name}') + except Exception as e: + print(f'Error running plugin {plugin.__class__.__name__}: {e}') +except Exception as e: + print(f'Error loading plugins: {e}') \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/seq.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/seq.py new file mode 100644 index 0000000000000000000000000000000000000000..a7c609c81c87b1bfa1f374ffb56aa49052cdb813 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/seq.py @@ -0,0 +1,21 @@ +class Seq: + def __init__(self, iterable): + self.iterable = iterable + + def map(self, func): + return Seq(func(item) for item in self.iterable) + + def filter(self, predicate): + return Seq(item for item in self.iterable if predicate(item)) + + def to_list(self): + return list(self.iterable) + + def __iter__(self): + return iter(self.iterable) + + def __repr__(self): + return f"Seq({repr(self.iterable)})" + +def seq(iterable): + return Seq(iterable) \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/tool.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..1779b56523486c4a7d793155066fc163f47b7b94 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/tool.py @@ -0,0 +1,746 @@ +import ctypes +from datetime import datetime +import os +import platform +import re +import tempfile +import subprocess +from typing import Dict, List +import sys +import piexif +import piexif.helper +import json +import zipfile +from PIL import Image +import shutil + + +sd_img_dirs = [ + "outdir_txt2img_samples", + "outdir_img2img_samples", + "outdir_save", + "outdir_extras_samples", + "outdir_grids", + "outdir_img2img_grids", + "outdir_samples", + "outdir_txt2img_grids", +] + + +is_dev = os.getenv("APP_ENV") == "dev" +is_nuitka = "__compiled__" in globals() +is_pyinstaller_bundle = bool(getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS')) +is_exe_ver = is_nuitka or is_pyinstaller_bundle + +cwd = os.getcwd() if is_exe_ver else os.path.normpath(os.path.join(__file__, "../../../")) +is_win = platform.system().lower().find("windows") != -1 + + + + +try: + from dotenv import load_dotenv + + load_dotenv(os.path.join(cwd, ".env")) +except Exception as e: + print(e) + + + +def backup_db_file(db_file_path): + + if not os.path.exists(db_file_path): + return + max_backup_count = int(os.environ.get('IIB_DB_FILE_BACKUP_MAX', '8')) + if max_backup_count < 1: + return + backup_folder = os.path.join(cwd,'iib_db_backup') + current_time = datetime.now() + timestamp = current_time.strftime('%Y-%m-%d %H-%M-%S') + backup_filename = f"iib.db_{timestamp}" + os.makedirs(backup_folder, exist_ok=True) + backup_filepath = os.path.join(backup_folder, backup_filename) + shutil.copy2(db_file_path, backup_filepath) + backup_files = os.listdir(backup_folder) + pattern = r"iib\.db_(\d{4}-\d{2}-\d{2} \d{2}-\d{2}-\d{2})" + backup_files_with_time = [(f, re.search(pattern, f).group(1)) for f in backup_files if re.search(pattern, f)] + sorted_backup_files = sorted(backup_files_with_time, key=lambda x: datetime.strptime(x[1], '%Y-%m-%d %H-%M-%S')) + + if len(sorted_backup_files) > max_backup_count: + files_to_remove_count = len(sorted_backup_files) - max_backup_count + for i in range(files_to_remove_count): + file_to_remove = os.path.join(backup_folder, sorted_backup_files[i][0]) + os.remove(file_to_remove) + + print(f"\033[92mIIB Database file has been successfully backed up to the backup folder.\033[0m") + +def get_sd_webui_conf(**kwargs): + try: + from modules.shared import opts + + return opts.data + except: + pass + try: + sd_conf_path = kwargs.get("sd_webui_config") + with codecs.open(sd_conf_path, "r", "utf-8") as f: + obj = json.loads(f.read()) + if kwargs.get("sd_webui_path_relative_to_config"): + for dir in sd_img_dirs: + if obj[dir] and not os.path.isabs(obj[dir]): + obj[dir] = os.path.normpath( + os.path.join(sd_conf_path, "../", obj[dir]) + ) + return obj + except: + pass + return {} + +def normalize_paths(paths: List[str], base = cwd): + """ + Normalize a list of paths, ensuring that each path is an absolute path with no redundant components. + + Args: + paths (List[str]): A list of paths to be normalized. + + Returns: + List[str]: A list of normalized paths. + """ + res: List[str] = [] + for path in paths: + # Skip empty or blank paths + if not path or len(path.strip()) == 0: + continue + # If the path is already an absolute path, use it as is + if os.path.isabs(path): + abs_path = path + # Otherwise, make the path absolute by joining it with the current working directory + else: + abs_path = os.path.join(base, path) + # If the absolute path exists, add it to the result after normalizing it + if os.path.exists(abs_path): + res.append(os.path.normpath(abs_path)) + return res + +def to_abs_path(path): + if not os.path.isabs(path): + path = os.path.join(os.getcwd(), path) + return os.path.normpath(path) + + +def get_valid_img_dirs( + conf, + keys=sd_img_dirs, +): + # 获取配置项 + paths = [conf.get(key) for key in keys] + + # 判断路径是否有效并转为绝对路径 + abs_paths = [] + for path in paths: + if not path or len(path.strip()) == 0: + continue + if os.path.isabs(path): # 已经是绝对路径 + abs_path = path + else: # 转为绝对路径 + abs_path = os.path.join(os.getcwd(), path) + if os.path.exists(abs_path): # 判断路径是否存在 + abs_paths.append(os.path.normpath(abs_path)) + + return abs_paths + + +def human_readable_size(size_bytes): + """ + Converts bytes to a human-readable format. + """ + # define the size units + units = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") + # calculate the logarithm of the input value with base 1024 + size = int(size_bytes) + if size == 0: + return "0B" + i = 0 + while size >= 1024 and i < len(units) - 1: + size /= 1024 + i += 1 + # round the result to two decimal points and return as a string + return "{:.2f} {}".format(size, units[i]) + + +def get_windows_drives(): + drives = [] + bitmask = ctypes.windll.kernel32.GetLogicalDrives() + for letter in range(65, 91): + if bitmask & 1: + drive_name = chr(letter) + ":/" + drives.append(drive_name) + bitmask >>= 1 + return drives + + +pattern = re.compile(r"(\d+\.?\d*)([KMGT]?B)", re.IGNORECASE) + + +def convert_to_bytes(file_size_str): + match = re.match(pattern, file_size_str) + if match: + size_str, unit_str = match.groups() + size = float(size_str) + unit = unit_str.upper() + if unit == "KB": + size *= 1024 + elif unit == "MB": + size *= 1024**2 + elif unit == "GB": + size *= 1024**3 + elif unit == "TB": + size *= 1024**4 + return int(size) + else: + raise ValueError(f"Invalid file size string '{file_size_str}'") + +def get_video_type(file_path): + video_extensions = ['.mp4', '.m4v', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.ts'] + file_extension = file_path[file_path.rfind('.'):].lower() + + if file_extension in video_extensions: + return file_extension[1:] + else: + return None + +def is_image_file(filename: str) -> bool: + if not isinstance(filename, str): + return False + + extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.avif', '.jpe'] + extension = filename.split('.')[-1].lower() + return f".{extension}" in extensions + +def is_video_file(filename: str) -> bool: + return isinstance(get_video_type(filename), str) + +def is_valid_media_path(path): + """ + 判断给定的路径是否是图像文件 + """ + abs_path = os.path.abspath(path) # 转为绝对路径 + if not os.path.exists(abs_path): # 判断路径是否存在 + return False + if not os.path.isfile(abs_path): # 判断是否是文件 + return False + return is_image_file(abs_path) or is_video_file(abs_path) + +def is_media_file(file_path): + return is_image_file(file_path) or is_video_file(file_path) + +def create_zip_file(file_paths: List[str], zip_file_name: str, compress = False): + """ + 将文件打包成一个压缩包 + + Args: + file_paths: 文件路径的列表 + zip_file_name: 压缩包的文件名 + + Returns: + 无返回值 + """ + with zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED) as zip_file: + for file_path in file_paths: + if os.path.isfile(file_path): + zip_file.write(file_path, os.path.basename(file_path)) + elif os.path.isdir(file_path): + for root, _, files in os.walk(file_path): + for file in files: + full_path = os.path.join(root, file) + zip_file.write(full_path, os.path.relpath(full_path, file_path)) + +def get_temp_path(): + """获取跨平台的临时文件目录路径""" + temp_path = None + try: + # 尝试获取系统环境变量中的临时文件目录路径 + temp_path = ( + os.environ.get("TMPDIR") or os.environ.get("TMP") or os.environ.get("TEMP") + ) + except Exception as e: + print("获取系统环境变量临时文件目录路径失败,错误信息:", e) + + # 如果系统环境变量中没有设置临时文件目录路径,则使用 Python 的 tempfile 模块创建临时文件目录 + if not temp_path: + try: + temp_path = tempfile.gettempdir() + except Exception as e: + print("使用 Python 的 tempfile 模块创建临时文件目录失败,错误信息:", e) + + # 确保临时文件目录存在 + if not os.path.exists(temp_path): + try: + os.makedirs(temp_path) + except Exception as e: + print("创建临时文件目录失败,错误信息:", e) + + return temp_path + + +_temp_path = get_temp_path() + + +def get_cache_dir(): + return os.getenv("IIB_CACHE_DIR") or _temp_path + +def get_secret_key_required(): + try: + from modules.shared import cmd_opts + return bool(cmd_opts.gradio_auth) + except: + return False + +is_secret_key_required = get_secret_key_required() + +def get_enable_access_control(): + ctrl = os.getenv("IIB_ACCESS_CONTROL") + if ctrl == "enable": + return True + if ctrl == "disable": + return False + try: + from modules.shared import cmd_opts + + return ( + cmd_opts.share or cmd_opts.ngrok or cmd_opts.listen or cmd_opts.server_name + ) + except: + pass + return False + + +enable_access_control = get_enable_access_control() + + +def get_locale(): + import locale + + env_lang = os.getenv("IIB_SERVER_LANG") + if env_lang in ["zh", "en"]: + return env_lang + lang, _ = locale.getdefaultlocale() + return "zh" if lang and lang.startswith("zh") else "en" + + +locale = get_locale() + + +def get_formatted_date(timestamp: float) -> str: + return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S") + + +def get_modified_date(folder_path: str): + return get_formatted_date(os.path.getmtime(folder_path)) + + +def get_created_date(folder_path: str): + return get_formatted_date(os.path.getctime(folder_path)) + +is_st_birthtime_available = True + +def get_created_date_by_stat(stat: os.stat_result): + global is_st_birthtime_available + try: + if is_st_birthtime_available: + return get_formatted_date(stat.st_birthtime) + else: + return get_formatted_date(stat.st_ctime) + except Exception as e: + is_st_birthtime_available = False + return get_formatted_date(stat.st_ctime) + +def birthtime_sort_key_fn(x): + stat = x.stat() + global is_st_birthtime_available + try: + if is_st_birthtime_available and hasattr(stat, "st_birthtime"): + return stat.st_birthtime + else: + return stat.st_ctime + except: + is_st_birthtime_available = False + return stat.st_ctime + +def unique_by(seq, key_func=lambda x: x): + seen = set() + return [x for x in seq if not (key := key_func(x)) in seen and not seen.add(key)] + + +def find(lst, comparator): + return next((item for item in lst if comparator(item)), None) + + +def findIndex(lst, comparator): + return next((i for i, item in enumerate(lst) if comparator(item)), -1) + +def unquote(text): + if len(text) == 0 or text[0] != '"' or text[-1] != '"': + return text + + try: + return json.loads(text) + except Exception: + return text + +def get_img_geninfo_txt_path(path: str): + txt_path = re.sub(r"\.\w+$", ".txt", path) + if os.path.exists(txt_path): + return txt_path + +def is_img_created_by_comfyui(img: Image): + prompt = img.info.get('prompt') + return prompt and (img.info.get('workflow') or ("class_type" in prompt)) # ermanitu + +def is_img_created_by_comfyui_with_webui_gen_info(img: Image): + return is_img_created_by_comfyui(img) and img.info.get('parameters') + +def get_comfyui_exif_data(img: Image): + prompt = img.info.get('prompt') + if not prompt: + return {} + meta_key = '3' + data: Dict[str, any] = json.loads(prompt) + for i in data.keys(): + try: + if data[i]["class_type"].startswith("KSampler"): + meta_key = i + break + except: + pass + meta = {} + KSampler_entry = data[meta_key]["inputs"] + #print(KSampler_entry) # for testing + + # As a workaround to bypass parsing errors in the parser. + # https://github.com/jiw0220/stable-diffusion-image-metadata/blob/00b8d42d4d1a536862bba0b07c332bdebb2a0ce5/src/index.ts#L130 + meta["Steps"] = KSampler_entry.get("steps", "Unknown") + meta["Sampler"] = KSampler_entry["sampler_name"] + meta["Model"] = data[KSampler_entry["model"][0]]["inputs"].get("ckpt_name") + meta["Source Identifier"] = "ComfyUI" + def get_text_from_clip(idx: str) : + inputs = data[idx]["inputs"] + text = inputs["text"] if "text" in inputs else inputs["t5xxl"] + if isinstance(text, list): # type:CLIPTextEncode (NSP) mode:Wildcards + text = data[text[0]]["inputs"]["text"] + return text.strip() + + in_node = data[str(KSampler_entry["positive"][0])] + if in_node["class_type"] != "FluxGuidance": + pos_prompt = get_text_from_clip(KSampler_entry["positive"][0]) + else: + pos_prompt = get_text_from_clip(in_node["inputs"]["conditioning"][0]) + + neg_prompt = get_text_from_clip(KSampler_entry["negative"][0]) + pos_prompt_arr = unique_by(parse_prompt(pos_prompt)["pos_prompt"]) + return { + "meta": meta, + "pos_prompt": pos_prompt_arr, + "pos_prompt_raw": pos_prompt, + "neg_prompt_raw" : neg_prompt + } + +def comfyui_exif_data_to_str(data): + res = data["pos_prompt_raw"] + "\nNegative prompt: " + data["neg_prompt_raw"] + "\n" + meta_arr = [] + for k,v in data["meta"].items(): + meta_arr.append(f'{k}: {v}') + return res + ", ".join(meta_arr) + +def read_sd_webui_gen_info_from_image(image: Image, path="") -> str: + """ + Reads metadata from an image file. + + Args: + image (PIL.Image.Image): The image object to read metadata from. + path (str): Optional. The path to the image file. Used to look for a .txt file with additional metadata. + + Returns: + str: The metadata as a string. + """ + items = image.info or {} + geninfo = items.pop("parameters", None) + if "exif" in items: + exif = piexif.load(items["exif"]) + exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b"") + + try: + exif_comment = piexif.helper.UserComment.load(exif_comment) + except ValueError: + exif_comment = exif_comment.decode("utf8", errors="ignore") + + if exif_comment: + items["exif comment"] = exif_comment + geninfo = exif_comment + + if not geninfo and path: + try: + txt_path = get_img_geninfo_txt_path(path) + if txt_path: + with open(txt_path) as f: + geninfo = f.read() + except Exception as e: + pass + + return geninfo + + +re_param_code = r'\s*([\w ]+):\s*("(?:\\"[^,]|\\"|\\|[^\"])+"|[^,]*)(?:,|$)' +re_param = re.compile(re_param_code) +re_imagesize = re.compile(r"^(\d+)x(\d+)$") +re_lora_prompt = re.compile("", re.IGNORECASE) +re_lora_extract = re.compile(r"([\w_\s.]+)(?:\d+)?") +re_lyco_prompt = re.compile("", re.IGNORECASE) +re_parens = re.compile(r"[\\/\[\](){}]+") +re_lora_white_symbol= re.compile(r">\s+") + + +def lora_extract(lora: str): + """ + 提取yoshino yoshino(2a79aa5adc4a) + """ + res = re_lora_extract.match(lora) + return res.group(1) if res else lora + + +def parse_prompt(x: str): + x = re.sub(r'\sBREAK\s', ' , BREAK , ', x) + x = re.sub(re_lora_white_symbol, "> , ", x) + x = x.replace(",", ",").replace("-", " ").replace("_", " ") + x = re.sub(re_parens, "", x) + tag_list = [x.strip() for x in x.split(",")] + res = [] + lora_list = [] + lyco_list = [] + for tag in tag_list: + if len(tag) == 0: + continue + idx_colon = tag.find(":") + if idx_colon != -1: + if re.search(re_lora_prompt, tag): + lora_res = re.search(re_lora_prompt, tag) + lora_list.append( + {"name": lora_res.group(1), "value": float(lora_res.group(2))} + ) + elif re.search(re_lyco_prompt, tag): + lyco_res = re.search(re_lyco_prompt, tag) + lyco_list.append( + {"name": lyco_res.group(1), "value": float(lyco_res.group(2))} + ) + else: + tag = tag[0:idx_colon] + if len(tag): + res.append(tag.lower()) + else: + res.append(tag.lower()) + return {"pos_prompt": res, "lora": lora_list, "lyco": lyco_list} + + +def parse_generation_parameters(x: str): + res = {} + prompt = "" + negative_prompt = "" + done_with_prompt = False + if not x: + return {"meta": {}, "pos_prompt": [], "lora": [], "lyco": []} + + *lines, lastline = x.strip().split("\n") + if len(re_param.findall(lastline)) < 3: + lines.append(lastline) + lastline = "" + if len(lines) == 1 and lines[0].startswith("Postprocess"): # 把上面改成<2应该也可以,当时不敢动 + lastline = lines[ + 0 + ] # 把Postprocess upscale by: 4, Postprocess upscaler: R-ESRGAN 4x+ Anime6B 推到res解析 + lines = [] + for i, line in enumerate(lines): + line = line.strip() + if line.startswith("Negative prompt:"): + done_with_prompt = True + line = line[16:].strip() + + if done_with_prompt: + negative_prompt += ("" if negative_prompt == "" else "\n") + line + else: + prompt += ("" if prompt == "" else "\n") + line + + for k, v in re_param.findall(lastline): + try: + if len(v) == 0: + res[k] = v + continue + if v[0] == '"' and v[-1] == '"': + v = unquote(v) + + m = re_imagesize.match(v) + if m is not None: + res[f"{k}-1"] = m.group(1) + res[f"{k}-2"] = m.group(2) + else: + res[k] = v + except Exception: + print(f"Error parsing \"{k}: {v}\"") + + prompt_parse_res = parse_prompt(prompt) + lora = prompt_parse_res["lora"] + for k in res: + k_s = str(k) + if k_s.startswith("AddNet Module") and str(res[k]).lower() == "lora": + model = res[k_s.replace("Module", "Model")] + value = res.get(k_s.replace("Module", "Weight A"), "1") + lora.append({"name": lora_extract(model), "value": float(value)}) + return { + "meta": res, + "pos_prompt": unique_by(prompt_parse_res["pos_prompt"]), + "lora": unique_by(lora, lambda x: x["name"].lower()), + "lyco": unique_by(prompt_parse_res["lyco"], lambda x: x["name"].lower()), + } + + +tags_translate: Dict[str, str] = {} +try: + import codecs + + with codecs.open(os.path.join(cwd, "tags-translate.csv"), "r", "utf-8") as tag: + tags_translate_str = tag.read() + for line in tags_translate_str.splitlines(): + en, mapping = line.split(",") + tags_translate[en.strip()] = mapping.strip() +except Exception as e: + pass + + +def open_folder(folder_path, file_path=None): + folder = os.path.realpath(folder_path) + if file_path: + file = os.path.join(folder, file_path) + if os.name == "nt": + subprocess.run(["explorer", "/select,", file]) + elif sys.platform == "darwin": + subprocess.run(["open", "-R", file]) + elif os.name == "posix": + subprocess.run(["xdg-open", file]) + else: + if os.name == "nt": + subprocess.run(["explorer", folder]) + elif sys.platform == "darwin": + subprocess.run(["open", folder]) + elif os.name == "posix": + subprocess.run(["xdg-open", folder]) + + +def open_file_with_default_app(file_path): + system = platform.system() + if system == 'Darwin': # macOS + subprocess.call(['open', file_path]) + elif system == 'Windows': # Windows + subprocess.call(file_path, shell=True) + elif system == 'Linux': # Linux + subprocess.call(['xdg-open', file_path]) + else: + raise OSError(f'Unsupported operating system: {system}') + +def omit(d, keys): + return {k: v for k, v in d.items() if k not in keys} + + +def get_current_commit_hash(): + try: + result = subprocess.run(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, cwd=cwd) + if result.returncode == 0: + return result.stdout.strip() + else: + return None + except Exception: + return None + +def get_current_tag(): + try: + result = subprocess.run(['git', 'describe', '--tags', '--abbrev=0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, cwd=cwd) + if result.returncode == 0: + return result.stdout.strip() + else: + return None + except Exception: + return None + + +def replace_punctuation(input_string): + return input_string.replace(',', ' ').replace('\n', ' ') + + +def case_insensitive_get(d, key, default=None): + for k, v in d.items(): + if k.lower() == key.lower(): + return v + return default + +def build_sd_webui_style_img_gen_info(prompt, negative_prompt = 'None', meta = {}): + res = f"{prompt}\nNegative prompt: {negative_prompt}\n" + for k, v in meta.items(): + res += f"{k}: {v}, " + return res + +def map_dict_keys(value_dict, map_dict=None): + if map_dict is None: + return value_dict + else: + return {map_dict.get(key, key): value for key, value in value_dict.items()} + + +def get_file_info_by_path(fullpath: str, is_under_scanned_path = True): + stat = os.stat(fullpath) + date = get_formatted_date(stat.st_mtime) + name = os.path.basename(fullpath) + created_time = get_created_date_by_stat(stat) + if os.path.isfile(fullpath): + bytes = stat.st_size + size = human_readable_size(bytes) + return { + "type": "file", + "date": date, + "size": size, + "name": name, + "bytes": bytes, + "created_time": created_time, + "fullpath": fullpath, + "is_under_scanned_path": is_under_scanned_path, + } + + elif os.path.isdir(fullpath): + return { + "type": "dir", + "date": date, + "created_time": created_time, + "size": "-", + "name": name, + "is_under_scanned_path": is_under_scanned_path, + "fullpath": fullpath, + } + return {} + + +def get_frame_at_second(video_path, second): + import av + with av.open(video_path) as container: + time_base = container.streams.video[0].time_base + frame_container_pts = round( second / time_base) + + container.seek(frame_container_pts, backward=True, stream=container.streams.video[0]) + frame = next(container.decode(video=0)) + return frame + +def get_data_file_path(filename): + if hasattr(sys, '_MEIPASS'): + # Running in a PyInstaller bundle + base_path = os.path.join(sys._MEIPASS) + else: + # Running in a normal Python environment + base_path = os.path.join(os.path.dirname(__file__)) + + return os.path.normpath(os.path.join(base_path, "../../", filename)) \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/video_cover_gen.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/video_cover_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2fd8e8cd72cf0da18030d4497caee5ef8d5597 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib/video_cover_gen.py @@ -0,0 +1,59 @@ +import hashlib +import os +from typing import List +from scripts.iib.tool import get_formatted_date, get_cache_dir, is_video_file +from concurrent.futures import ThreadPoolExecutor +import time + + +def generate_video_covers(dirs,verbose=False): + start_time = time.time() + import imageio.v3 as iio + + cache_base_dir = get_cache_dir() + + def process_video(item): + if item.is_dir(): + verbose and print(f"Processing directory: {item.path}") + for sub_item in os.scandir(item.path): + process_video(sub_item) + return + if not os.path.exists(item.path) or not is_video_file(item.path): + return + + try: + path = os.path.normpath(item.path) + stat = item.stat() + t = get_formatted_date(stat.st_mtime) + hash_dir = hashlib.md5((path + t).encode("utf-8")).hexdigest() + cache_dir = os.path.join(cache_base_dir, "iib_cache", "video_cover", hash_dir) + cache_path = os.path.join(cache_dir, "cover.webp") + + # 如果缓存文件存在,则直接返回该文件 + if os.path.exists(cache_path): + print(f"Video cover already exists: {path}") + return + + frame = iio.imread( + path, + index=16, + plugin="pyav", + ) + + os.makedirs(cache_dir, exist_ok=True) + iio.imwrite(cache_path, frame, extension=".webp") + verbose and print(f"Video cover generated: {path}") + except Exception as e: + print(f"Error generating video cover: {path}") + print(e) + + with ThreadPoolExecutor() as executor: + for dir_path in dirs: + folder_listing: List[os.DirEntry] = os.scandir(dir_path) + for item in folder_listing: + executor.submit(process_video, item) + + print("Video covers generated successfully.") + end_time = time.time() + execution_time = end_time - start_time + print(f"Execution time: {execution_time} seconds") \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib_setup.py b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..930aaef034f7540be26d4c7e66fd30bbffa9c77e --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/scripts/iib_setup.py @@ -0,0 +1,86 @@ +from scripts.iib.api import infinite_image_browsing_api, send_img_path +from modules import script_callbacks, generation_parameters_copypaste as send +from scripts.iib.tool import locale +from scripts.iib.tool import read_sd_webui_gen_info_from_image +from PIL import Image +from scripts.iib.logger import logger + +from fastapi import FastAPI +import gradio as gr +from modules.shared import cmd_opts + +""" +api函数声明和启动分离方便另外一边被外部调用 +""" + + +def on_ui_tabs(): + + with gr.Blocks(analytics_enabled=False) as view: + with gr.Row(): + with gr.Column(): + gr.HTML("", elem_id="iib_top") + gr.HTML("error", elem_id="infinite_image_browsing_container_wrapper") + # 以下是使用2个组件模拟粘贴过程 + img = gr.Image( + type="pil", + elem_id="iib_hidden_img", + ) + + def on_img_change(): + send_img_path["value"] = "" # 真正收到图片改变才允许放行 + + img.change(on_img_change) + + img_update_trigger = gr.Button( + "button", elem_id="iib_hidden_img_update_trigger" + ) + + # 修改文本和图像,等待修改完成后前端触发粘贴按钮 + # 有时在触发后收不到回调,可能是在解析params。txt时除了问题删除掉就行了 + def img_update_func(): + try: + path = send_img_path.get("value") + # logger.info("img_update_func %s", path) + img = Image.open(path) + info = read_sd_webui_gen_info_from_image(img, path) + return img, info + except Exception as e: + logger.error("img_update_func err %s",e) + + img_file_info = gr.Textbox(elem_id="iib_hidden_img_file_info") + img_update_trigger.click(img_update_func, outputs=[img, img_file_info]) + for tab in ["txt2img", "img2img", "inpaint", "extras"]: + btn = gr.Button(f"Send to {tab}", elem_id=f"iib_hidden_tab_{tab}") + # 注册粘贴 + send.register_paste_params_button( + send.ParamBinding( + paste_button=btn, + tabname=tab, + source_image_component=img, + source_text_component=img_file_info, + ) + ) + + return ( + ( + view, + "无边图像浏览" if locale == "zh" else "Infinite image browsing", + "infinite-image-browsing", + ), + ) + +def on_app_started(_: gr.Blocks, app: FastAPI) -> None: + # 第一个参数是SD-WebUI传进来的gr.Blocks,但是不需要使用 + DEFAULT_BASE = "/infinite_image_browsing" + fe_public_path = None + subpath = vars(cmd_opts).get("subpath") + + if subpath: + base = "/" + subpath + "/" + DEFAULT_BASE + fe_public_path = base.replace('//', '/') + infinite_image_browsing_api(app, fe_public_path = fe_public_path) + + +script_callbacks.on_ui_tabs(on_ui_tabs) +script_callbacks.on_app_started(on_app_started) diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/style.css b/extensions-builtin/sd-webui-infinite-image-browsing-main/style.css new file mode 100644 index 0000000000000000000000000000000000000000..3a937d686bd254d8c2ae8733515db7dfe1f8b008 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/style.css @@ -0,0 +1,3 @@ +[id^="iib_hidden_"] { + display: none !important; +} \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/.eslintrc.cjs b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/.eslintrc.cjs new file mode 100644 index 0000000000000000000000000000000000000000..89d44a57eeb9a34541cea9f4f469657222c64ed1 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/.eslintrc.cjs @@ -0,0 +1,31 @@ +/* eslint-disable no-undef */ + +// require('@rushstack/eslint-patch/modern-module-resolution') + +module.exports = { + ignorePatterns: [ + 'dist/', + // 其他忽略规则 + ], + root: true, + extends: [ + 'plugin:vue/vue3-essential', + 'eslint:recommended', + '@vue/eslint-config-typescript', + ], + parserOptions: { + ecmaVersion: 'latest' + }, + rules: { + 'vue/multi-word-component-names': ['error', { ignores: ['index', 'index.vue'] }], + 'no-console': 'off', + 'quote-props': ['error', 'as-needed'], + quotes: ['error', 'single'], + 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', + '@typescript-eslint/explicit-module-boundary-types': 'off', + '@typescript-eslint/no-non-null-assertion': 'off', + '@typescript-eslint/no-explicit-any': 'off', + indent: 'off', + '@typescript-eslint/indent': ['error', 2] + } +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/.gitignore b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..234f2f1beb6f684af9f47861d3a04652e31f23e4 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/.gitignore @@ -0,0 +1,22 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/.prettierrc.json b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/.prettierrc.json new file mode 100644 index 0000000000000000000000000000000000000000..66e23359c3dabfe3929b4e2fa049c41037afb15f --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/.prettierrc.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://json.schemastore.org/prettierrc", + "semi": false, + "tabWidth": 2, + "singleQuote": true, + "printWidth": 100, + "trailingComma": "none" +} \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/.vscode/extensions.json b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/.vscode/extensions.json new file mode 100644 index 0000000000000000000000000000000000000000..c0a6e5a48110e472b09d68afa2a030af6ab3208b --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/.vscode/extensions.json @@ -0,0 +1,3 @@ +{ + "recommendations": ["Vue.volar", "Vue.vscode-typescript-vue-plugin"] +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/README.md b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4b8e0d35c8d9f86718ce422ed43a8729586ead2b --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/README.md @@ -0,0 +1,47 @@ +# vue + +This template should help get you started developing with Vue 3 in Vite. + +## Recommended IDE Setup + +[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin). + +## Type Support for `.vue` Imports in TS + +TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin) to make the TypeScript language service aware of `.vue` types. + +If the standalone TypeScript plugin doesn't feel fast enough to you, Volar has also implemented a [Take Over Mode](https://github.com/johnsoncodehk/volar/discussions/471#discussioncomment-1361669) that is more performant. You can enable it by the following steps: + +1. Disable the built-in TypeScript Extension + 1) Run `Extensions: Show Built-in Extensions` from VSCode's command palette + 2) Find `TypeScript and JavaScript Language Features`, right click and select `Disable (Workspace)` +2. Reload the VSCode window by running `Developer: Reload Window` from the command palette. + +## Customize configuration + +See [Vite Configuration Reference](https://vitejs.dev/config/). + +## Project Setup + +```sh +yarn +``` + +### Compile and Hot-Reload for Development + +```sh +yarn dev +``` + + +### Compile and Minify for Production, Deliver to Production Mode Resources + +```sh +yarn build +``` + +### Lint with [ESLint](https://eslint.org/) + +```sh +yarn lint +``` diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/build.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/build.ts new file mode 100644 index 0000000000000000000000000000000000000000..7854c3acff230297b3eba6d1eb86957badd4b883 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/build.ts @@ -0,0 +1,27 @@ +import { execSync } from 'child_process' +import { readFile, rm, writeFile } from 'fs/promises' +import { exit } from 'process' + +const main = async () => { + try { + console.log(execSync('vue-tsc && vite build').toString('utf8')) + } catch (error: any) { + if (error.stdout && error.stderr) { + console.log(error.stdout.toString('utf8')) + console.error(error.stderr.toString('utf8')) + exit(2) + } else { + throw error + } + } + try { + await rm('../javascript/index.js') + // eslint-disable-next-line no-empty + } catch (error) { + + } + const html = (await readFile('dist/index.html')).toString() + const js = (await readFile('index.tpl.js')).toString().replace('__built_html__', html) + await writeFile('../javascript/index.js', js) +} +main() diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/components.d.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/components.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dbf049d408e5a0d58f5d4846315dd5dbf81e441d --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/components.d.ts @@ -0,0 +1,57 @@ +/* eslint-disable */ +/* prettier-ignore */ +// @ts-nocheck +// Generated by unplugin-vue-components +// Read more: https://github.com/vuejs/core/pull/3399 +import '@vue/runtime-core' + +export {} + +declare module '@vue/runtime-core' { + export interface GlobalComponents { + AAlert: typeof import('ant-design-vue/es')['Alert'] + ABadge: typeof import('ant-design-vue/es')['Badge'] + ABreadcrumb: typeof import('ant-design-vue/es')['Breadcrumb'] + ABreadcrumbItem: typeof import('ant-design-vue/es')['BreadcrumbItem'] + AButton: typeof import('ant-design-vue/es')['Button'] + ACheckbox: typeof import('ant-design-vue/es')['Checkbox'] + ACol: typeof import('ant-design-vue/es')['Col'] + ACollapse: typeof import('ant-design-vue/es')['Collapse'] + ACollapsePanel: typeof import('ant-design-vue/es')['CollapsePanel'] + ADrawer: typeof import('ant-design-vue/es')['Drawer'] + ADropdown: typeof import('ant-design-vue/es')['Dropdown'] + AForm: typeof import('ant-design-vue/es')['Form'] + AFormItem: typeof import('ant-design-vue/es')['FormItem'] + AImage: typeof import('ant-design-vue/es')['Image'] + AInput: typeof import('ant-design-vue/es')['Input'] + AInputGroup: typeof import('ant-design-vue/es')['InputGroup'] + AInputNumber: typeof import('ant-design-vue/es')['InputNumber'] + AMenu: typeof import('ant-design-vue/es')['Menu'] + AMenuDivider: typeof import('ant-design-vue/es')['MenuDivider'] + AMenuItem: typeof import('ant-design-vue/es')['MenuItem'] + AModal: typeof import('ant-design-vue/es')['Modal'] + ARadioButton: typeof import('ant-design-vue/es')['RadioButton'] + ARadioGroup: typeof import('ant-design-vue/es')['RadioGroup'] + ARow: typeof import('ant-design-vue/es')['Row'] + ASelect: typeof import('ant-design-vue/es')['Select'] + ASkeleton: typeof import('ant-design-vue/es')['Skeleton'] + ASlider: typeof import('ant-design-vue/es')['Slider'] + ASpin: typeof import('ant-design-vue/es')['Spin'] + ASubMenu: typeof import('ant-design-vue/es')['SubMenu'] + ASwitch: typeof import('ant-design-vue/es')['Switch'] + ATabPane: typeof import('ant-design-vue/es')['TabPane'] + ATabs: typeof import('ant-design-vue/es')['Tabs'] + ATag: typeof import('ant-design-vue/es')['Tag'] + ATextarea: typeof import('ant-design-vue/es')['Textarea'] + ATooltip: typeof import('ant-design-vue/es')['Tooltip'] + BaseFileListInfo: typeof import('./src/components/BaseFileListInfo.vue')['default'] + ChangeIndicator: typeof import('./src/components/ChangeIndicator.vue')['default'] + ContextMenu: typeof import('./src/components/ContextMenu.vue')['default'] + FileItem: typeof import('./src/components/FileItem.vue')['default'] + HistoryRecord: typeof import('./src/components/HistoryRecord.vue')['default'] + MultiSelectKeep: typeof import('./src/components/MultiSelectKeep.vue')['default'] + NumInput: typeof import('./src/components/numInput.vue')['default'] + RouterLink: typeof import('vue-router')['RouterLink'] + RouterView: typeof import('vue-router')['RouterView'] + } +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/Checkbox-6eb6dd6a.js b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/Checkbox-6eb6dd6a.js new file mode 100644 index 0000000000000000000000000000000000000000..4f32c1810c5e146a29f5dc8be1aab26178f63d1f --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/Checkbox-6eb6dd6a.js @@ -0,0 +1 @@ +import{d as E,bx as $,r as f,m as M,_ as T,a as c,al as W,h as m,c as v,P as z}from"./index-bd4c24ce.js";var G=["prefixCls","name","id","type","disabled","readonly","tabindex","autofocus","value","required"],H={prefixCls:String,name:String,id:String,type:String,defaultChecked:{type:[Boolean,Number],default:void 0},checked:{type:[Boolean,Number],default:void 0},disabled:Boolean,tabindex:{type:[Number,String]},readonly:Boolean,autofocus:Boolean,value:z.any,required:Boolean};const L=E({compatConfig:{MODE:3},name:"Checkbox",inheritAttrs:!1,props:$(H,{prefixCls:"rc-checkbox",type:"checkbox",defaultChecked:!1}),emits:["click","change"],setup:function(a,d){var t=d.attrs,h=d.emit,x=d.expose,o=f(a.checked===void 0?a.defaultChecked:a.checked),i=f();M(function(){return a.checked},function(){o.value=a.checked}),x({focus:function(){var e;(e=i.value)===null||e===void 0||e.focus()},blur:function(){var e;(e=i.value)===null||e===void 0||e.blur()}});var l=f(),g=function(e){if(!a.disabled){a.checked===void 0&&(o.value=e.target.checked),e.shiftKey=l.value;var r={target:c(c({},a),{},{checked:e.target.checked}),stopPropagation:function(){e.stopPropagation()},preventDefault:function(){e.preventDefault()},nativeEvent:e};a.checked!==void 0&&(i.value.checked=!!a.checked),h("change",r),l.value=!1}},C=function(e){h("click",e),l.value=e.shiftKey};return function(){var n,e=a.prefixCls,r=a.name,s=a.id,p=a.type,b=a.disabled,K=a.readonly,P=a.tabindex,B=a.autofocus,S=a.value,N=a.required,_=T(a,G),q=t.class,D=t.onFocus,j=t.onBlur,w=t.onKeydown,A=t.onKeypress,F=t.onKeyup,y=c(c({},_),t),O=Object.keys(y).reduce(function(k,u){return(u.substr(0,5)==="aria-"||u.substr(0,5)==="data-"||u==="role")&&(k[u]=y[u]),k},{}),R=W(e,q,(n={},m(n,"".concat(e,"-checked"),o.value),m(n,"".concat(e,"-disabled"),b),n)),V=c(c({name:r,id:s,type:p,readonly:K,disabled:b,tabindex:P,class:"".concat(e,"-input"),checked:!!o.value,autofocus:B,value:S},O),{},{onChange:g,onClick:C,onFocus:D,onBlur:j,onKeydown:w,onKeypress:A,onKeyup:F,required:N});return v("span",{class:R},[v("input",c({ref:i},V),null),v("span",{class:"".concat(e,"-inner")},null)])}}});export{L as V}; diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/FileItem-3771a510.js b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/FileItem-3771a510.js new file mode 100644 index 0000000000000000000000000000000000000000..18289462a40c2c4fe1b63c507350a16ac1cf71bc --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/FileItem-3771a510.js @@ -0,0 +1,3 @@ +var vt=Object.defineProperty;var mt=(i,t,e)=>t in i?vt(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var ee=(i,t,e)=>(mt(i,typeof t!="symbol"?t+"":t,e),e);import{d as X,u as Ye,E as V,al as qe,h as K,c as A,ao as yt,cZ as bt,r as j,bc as At,X as H,cW as St,P as $e,c5 as kt,A as W,c_ as ce,L as ge,ak as ke,bf as It,cB as _t,bW as Ct,c$ as wt,cY as Et,d0 as Tt,d1 as Ge,bw as Pt,d2 as ae,d3 as Ot,aF as Dt,d4 as Nt,B as $t,d5 as zt,n as pe,m as se,aP as Mt,q as Ze,$ as Ie,c3 as Xe,aH as Qt,d6 as et,d7 as Bt,N as Ft,v as Rt,aN as tt,aO as nt,ax as it,S as a,a0 as R,d8 as Lt,d9 as jt,da as Ht,b$ as Vt,db as xt,ar as Ut,T as h,aE as te,Y as S,a1 as k,a6 as J,c0 as ze,c1 as Jt,dc as Wt,a5 as rt,ae as Y,V as I,W as y,a2 as Q,aj as st,cH as Kt,cG as Yt,M as ot,U as u,Z as lt,cD as qt,dd as Me,ad as Gt,de as Zt,cE as Xt,cm as en,df as tn,dg as de,dh as nn}from"./index-bd4c24ce.js";import{h as Qe,g as rn,i as sn}from"./functionalCallableComp-8b0d9f43.js";import{i as on}from"./_isIterateeCall-eeca32c3.js";import{D as G,a as ve}from"./index-afbe1fb8.js";/* empty css */var ln=function(){return{prefixCls:String,checked:{type:Boolean,default:void 0},onChange:{type:Function},onClick:{type:Function},"onUpdate:checked":Function}},an=X({compatConfig:{MODE:3},name:"ACheckableTag",props:ln(),setup:function(t,e){var n=e.slots,r=e.emit,o=Ye("tag",t),p=o.prefixCls,d=function(E){var w=t.checked;r("update:checked",!w),r("change",!w),r("click",E)},v=V(function(){var b;return qe(p.value,(b={},K(b,"".concat(p.value,"-checkable"),!0),K(b,"".concat(p.value,"-checkable-checked"),t.checked),b))});return function(){var b;return A("span",{class:v.value,onClick:d},[(b=n.default)===null||b===void 0?void 0:b.call(n)])}}});const me=an;var un=new RegExp("^(".concat(yt.join("|"),")(-inverse)?$")),cn=new RegExp("^(".concat(bt.join("|"),")$")),dn=function(){return{prefixCls:String,color:{type:String},closable:{type:Boolean,default:!1},closeIcon:$e.any,visible:{type:Boolean,default:void 0},onClose:{type:Function},"onUpdate:visible":Function,icon:$e.any}},Z=X({compatConfig:{MODE:3},name:"ATag",props:dn(),slots:["closeIcon","icon"],setup:function(t,e){var n=e.slots,r=e.emit,o=e.attrs,p=Ye("tag",t),d=p.prefixCls,v=p.direction,b=j(!0);At(function(){t.visible!==void 0&&(b.value=t.visible)});var E=function(s){s.stopPropagation(),r("update:visible",!1),r("close",s),!s.defaultPrevented&&t.visible===void 0&&(b.value=!1)},w=V(function(){var l=t.color;return l?un.test(l)||cn.test(l):!1}),T=V(function(){var l;return qe(d.value,(l={},K(l,"".concat(d.value,"-").concat(t.color),w.value),K(l,"".concat(d.value,"-has-color"),t.color&&!w.value),K(l,"".concat(d.value,"-hidden"),!b.value),K(l,"".concat(d.value,"-rtl"),v.value==="rtl"),l))});return function(){var l,s,c,m=t.icon,N=m===void 0?(l=n.icon)===null||l===void 0?void 0:l.call(n):m,O=t.color,$=t.closeIcon,g=$===void 0?(s=n.closeIcon)===null||s===void 0?void 0:s.call(n):$,f=t.closable,C=f===void 0?!1:f,M=function(){return C?g?A("span",{class:"".concat(d.value,"-close-icon"),onClick:E},[g]):A(kt,{class:"".concat(d.value,"-close-icon"),onClick:E},null):null},F={backgroundColor:O&&!w.value?O:void 0},B=N||null,_=(c=n.default)===null||c===void 0?void 0:c.call(n),L=B?A(H,null,[B,A("span",null,[_])]):_,P="onClick"in o,z=A("span",{class:T.value,style:F},[L,M()]);return P?A(St,null,{default:function(){return[z]}}):z}}});Z.CheckableTag=me;Z.install=function(i){return i.component(Z.name,Z),i.component(me.name,me),i};const fn=Z;G.Button=ve;G.install=function(i){return i.component(G.name,G),i.component(ve.name,ve),i};var hn={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M908.1 353.1l-253.9-36.9L540.7 86.1c-3.1-6.3-8.2-11.4-14.5-14.5-15.8-7.8-35-1.3-42.9 14.5L369.8 316.2l-253.9 36.9c-7 1-13.4 4.3-18.3 9.3a32.05 32.05 0 00.6 45.3l183.7 179.1-43.4 252.9a31.95 31.95 0 0046.4 33.7L512 754l227.1 119.4c6.2 3.3 13.4 4.4 20.3 3.2 17.4-3 29.1-19.5 26.1-36.9l-43.4-252.9 183.7-179.1c5-4.9 8.3-11.3 9.3-18.3 2.7-17.5-9.5-33.7-27-36.3z"}}]},name:"star",theme:"filled"};const gn=hn;function Be(i){for(var t=1;t{const r=Ct();ge(r),ne.has(r)||(ne.set(r,ke(i(r,n??(t==null?void 0:t())))),It(()=>{ne.delete(r)}));const o=ne.get(r);return ge(o),{state:o,toRefs(){return _t(o)}}}}}var $n={icon:{tag:"svg",attrs:{viewBox:"0 0 1024 1024",focusable:"false"},children:[{tag:"path",attrs:{d:"M715.8 493.5L335 165.1c-14.2-12.2-35-1.2-35 18.5v656.8c0 19.7 20.8 30.7 35 18.5l380.8-328.4c10.9-9.4 10.9-27.6 0-37z"}}]},name:"caret-right",theme:"outlined"};const zn=$n;function Le(i){for(var t=1;t{const i=j([]);return{selectdFiles:i,addFiles:e=>{i.value=Et([...i.value,...e])}}});class oe{constructor(t,e=Tt.CREATED_TIME_DESC){ee(this,"root");ee(this,"execQueue",[]);ee(this,"walkerInitPromsie");this.entryPath=t,this.sortMethod=e,this.root={children:[],info:{name:this.entryPath,size:"-",bytes:0,created_time:"",is_under_scanned_path:!0,date:"",type:"dir",fullpath:this.entryPath}},this.walkerInitPromsie=new Promise(n=>{Qe([this.entryPath]).then(async r=>{this.root.info=r[this.entryPath],await this.fetchChildren(this.root),n()})})}reset(){return this.root.children=[],this.fetchChildren(this.root)}get images(){const t=e=>e.children.map(n=>{if(n.info.type==="dir")return t(n);if(ae(n.info.name))return n.info}).filter(n=>n).flat(1);return t(this.root)}get isCompleted(){return this.execQueue.length===0}async fetchChildren(t){const{files:e}=await rn(t.info.fullpath);return t.children=Ge(e,this.sortMethod).map(n=>({info:n,children:[]})),this.execQueue.shift(),this.execQueue.unshift(...t.children.filter(n=>n.info.type==="dir").map(n=>({fn:()=>this.fetchChildren(n),...n}))),t}async next(){await this.walkerInitPromsie;const t=_n(this.execQueue);if(!t)return null;const e=await t.fn();return this.execQueue=this.execQueue.slice(),this.root={...this.root},e}async isExpired(){const t=[this.root.info],e=r=>{for(const o of r.children)o.info.type==="dir"&&(t.push(o.info),e(o))};e(this.root);const n=await Qe(t.map(r=>r.fullpath));for(const r of t)if(!Pt(r,n[r.fullpath]))return!0;return!1}async seamlessRefresh(t,e=j(!1)){const n=performance.now(),r=new oe(this.entryPath,this.sortMethod);for(await r.walkerInitPromsie;!r.isCompleted&&r.images.length
'};e.configure=function(s){var c,m;for(c in s)m=s[c],m!==void 0&&s.hasOwnProperty(c)&&(n[c]=m);return this},e.status=null,e.set=function(s){var c=e.isStarted();s=r(s,n.minimum,1),e.status=s===1?null:s;var m=e.render(!c),N=m.querySelector(n.barSelector),O=n.speed,$=n.easing;return m.offsetWidth,d(function(g){n.positionUsing===""&&(n.positionUsing=e.getPositioningCSS()),v(N,p(s,O,$)),s===1?(v(m,{transition:"none",opacity:1}),m.offsetWidth,setTimeout(function(){v(m,{transition:"all "+O+"ms linear",opacity:0}),setTimeout(function(){e.remove(),g()},O)},O)):setTimeout(g,O)}),this},e.isStarted=function(){return typeof e.status=="number"},e.start=function(){e.status||e.set(0);var s=function(){setTimeout(function(){e.status&&(e.trickle(),s())},n.trickleSpeed)};return n.trickle&&s(),this},e.done=function(s){return!s&&!e.status?this:e.inc(.3+.5*Math.random()).set(1)},e.inc=function(s){var c=e.status;return c?c>1?void 0:(typeof s!="number"&&(c>=0&&c<.2?s=.1:c>=.2&&c<.5?s=.04:c>=.5&&c<.8?s=.02:c>=.8&&c<.99?s=.005:s=0),c=r(c+s,0,.994),e.set(c)):e.start()},e.trickle=function(){return e.inc()},function(){var s=0,c=0;e.promise=function(m){return!m||m.state()==="resolved"?this:(c===0&&e.start(),s++,c++,m.always(function(){c--,c===0?(s=0,e.done()):e.set((s-c)/s)}),this)}}(),e.getElement=function(){var s=e.getParent();if(s){var c=Array.prototype.slice.call(s.querySelectorAll(".nprogress")).filter(function(m){return m.parentElement===s});if(c.length>0)return c[0]}return null},e.getParent=function(){if(n.parent instanceof HTMLElement)return n.parent;if(typeof n.parent=="string")return document.querySelector(n.parent)},e.render=function(s){if(e.isRendered())return e.getElement();E(document.documentElement,"nprogress-busy");var c=document.createElement("div");c.id="nprogress",c.className="nprogress",c.innerHTML=n.template;var m=c.querySelector(n.barSelector),N=s?"-100":o(e.status||0),O=e.getParent(),$;return v(m,{transition:"all 0 linear",transform:"translate3d("+N+"%,0,0)"}),n.showSpinner||($=c.querySelector(n.spinnerSelector),$&&l($)),O!=document.body&&E(O,"nprogress-custom-parent"),O.appendChild(c),c},e.remove=function(){e.status=null,w(document.documentElement,"nprogress-busy"),w(e.getParent(),"nprogress-custom-parent");var s=e.getElement();s&&l(s)},e.isRendered=function(){return!!e.getElement()},e.getPositioningCSS=function(){var s=document.body.style,c="WebkitTransform"in s?"Webkit":"MozTransform"in s?"Moz":"msTransform"in s?"ms":"OTransform"in s?"O":"";return c+"Perspective"in s?"translate3d":c+"Transform"in s?"translate":"margin"};function r(s,c,m){return sm?m:s}function o(s){return(-1+s)*100}function p(s,c,m){var N;return n.positionUsing==="translate3d"?N={transform:"translate3d("+o(s)+"%,0,0)"}:n.positionUsing==="translate"?N={transform:"translate("+o(s)+"%,0)"}:N={"margin-left":o(s)+"%"},N.transition="all "+c+"ms "+m,N}var d=function(){var s=[];function c(){var m=s.shift();m&&m(c)}return function(m){s.push(m),s.length==1&&c()}}(),v=function(){var s=["Webkit","O","Moz","ms"],c={};function m(g){return g.replace(/^-ms-/,"ms-").replace(/-([\da-z])/gi,function(f,C){return C.toUpperCase()})}function N(g){var f=document.body.style;if(g in f)return g;for(var C=s.length,M=g.charAt(0).toUpperCase()+g.slice(1),F;C--;)if(F=s[C]+M,F in f)return F;return g}function O(g){return g=m(g),c[g]||(c[g]=N(g))}function $(g,f,C){f=O(f),g.style[f]=C}return function(g,f){var C=arguments,M,F;if(C.length==2)for(M in f)F=f[M],F!==void 0&&f.hasOwnProperty(M)&&$(g,M,F);else $(g,C[1],C[2])}}();function b(s,c){var m=typeof s=="string"?s:T(s);return m.indexOf(" "+c+" ")>=0}function E(s,c){var m=T(s),N=m+c;b(m,c)||(s.className=N.substring(1))}function w(s,c){var m=T(s),N;b(s,c)&&(N=m.replace(" "+c+" "," "),s.className=N.substring(1,N.length-1))}function T(s){return(" "+(s&&s.className||"")+" ").replace(/\s+/gi," ")}function l(s){s&&s.parentNode&&s.parentNode.removeChild(s)}return e})})(ct);var Yn=ct.exports;const gs=Dt(Yn);function ps({fetchNext:i}={}){const{scroller:t,sortedFiles:e,sortMethod:n,currLocation:r,stackViewEl:o,canLoadNext:p,previewIdx:d,props:v,walker:b,getViewableAreaFiles:E}=le().toRefs(),{state:w}=le(),T=j(!1),l=j(q.defaultGridCellWidth),s=V(()=>l.value+16),c=44,{width:m}=Nt(o),N=V(()=>~~(m.value/s.value)),O=ke(new Map),$=V(()=>{const B=s.value;return{first:B+(l.value<=160?0:c),second:B}}),g=j(!1),f=async()=>{var B;if(!(g.value||v.value.mode!=="walk"||!p.value))try{g.value=!0,await((B=b.value)==null?void 0:B.next())}finally{g.value=!1}},C=async(B=!1)=>{const _=t.value,L=()=>B?d.value:(_==null?void 0:_.$_endIndex)??0,P=()=>{const z=e.value.length,x=50;return z?i?L()>z-x:L()>z-x&&p.value:!0};for(;P();){await Ze(30);const z=await(i??f)();if(typeof z=="boolean"&&!z)return}};w.useEventListen("loadNextDir",$t(async(B=!1)=>{await C(B),v.value.mode==="walk"&&M()})),w.useEventListen("viewableAreaFilesChange",()=>{const B=E.value(),_=B.filter(P=>P.is_under_scanned_path&&ae(P.name)).map(P=>P.fullpath);qn.fetchImageTags(_);const L=B.filter(P=>P.is_under_scanned_path&&P.type==="dir"&&!O.has(P.fullpath)).map(P=>P.fullpath);L.length&&zt(L).then(P=>{for(const z in P)if(Object.prototype.hasOwnProperty.call(P,z)){const x=P[z];O.set(z,x)}})}),w.useEventListen("refresh",async()=>{w.eventEmitter.emit("viewableAreaFilesChange")});const M=pe(()=>w.eventEmitter.emit("viewableAreaFilesChange"),300);se(r,M);const F=pe(async()=>{await C(),M()},150);return{gridItems:N,sortedFiles:e,sortMethodConv:Mt,moreActionsDropdownShow:T,gridSize:s,sortMethod:n,onScroll:F,loadNextDir:f,loadNextDirLoading:g,canLoadNext:p,itemSize:$,cellWidth:l,dirCoverCache:O}}const vs=new Map,q=Ie(),ms=Kn(),qn=Xe(),ys=Qt(),bs=new BroadcastChannel("iib-image-transfer-bus"),{eventEmitter:As,useEventListen:Ss}=et(),{useHookShareState:le}=Nn((i,{images:t})=>{const e=j({tabIdx:-1,paneIdx:-1}),n=V(()=>Ft(r.value)),r=j([]),o=V(()=>{var f;return r.value.map(C=>C.curr).slice((f=q.conf)!=null&&f.is_win&&e.value.mode!=="scanned-fixed"?1:0)}),p=V(()=>Rt(...o.value)),d=V(()=>{var f,C;return e.value.mode==="scanned-fixed"?((C=(f=r.value)==null?void 0:f[0])==null?void 0:C.curr)??"":e.value.mode==="walk"?e.value.path??"":r.value.length===1?"/":p.value}),v=j(q.defaultSortingMethod),b=j(e.value.mode=="walk"?new oe(e.value.path,v.value):void 0);se([()=>e.value.mode,()=>e.value.path,v],async([f,C,M])=>{var F;f==="walk"?(b.value=new oe(C,M),r.value=[{files:[],curr:C}],await Ze(),await((F=b.value)==null?void 0:F.reset()),$.eventEmitter.emit("loadNextDir")):b.value=void 0});const E=ke(new Set);se(n,()=>E.clear());const w=V(()=>{var F;if(t.value)return t.value;if(b.value)return b.value.images.filter(B=>!E.has(B.fullpath));if(!n.value)return[];const f=((F=n.value)==null?void 0:F.files)??[],C=v.value;return Ge((B=>q.onlyFoldersAndImages?B.filter(_=>_.type==="dir"||ae(_.name)):B)(f),C).filter(B=>!E.has(B.fullpath))}),T=j([]),l=j(-1),s=V(()=>b.value?!b.value.isCompleted:!1),c=j(!1),m=j(!1),N=j(),O=()=>{var f,C,M;return(M=(C=(f=q.tabList)==null?void 0:f[e.value.tabIdx])==null?void 0:C.panes)==null?void 0:M[e.value.paneIdx]},$=et();$.useEventListen("selectAll",()=>{console.log(`select all 0 -> ${w.value.length}`),T.value=On(0,w.value.length)});const g=()=>{const f=N.value;if(f){const C=Math.max(f.$_startIndex-10,0);return w.value.slice(C,f.$_endIndex+10)}return[]};return{previewing:m,spinning:c,canLoadNext:s,multiSelectedIdxs:T,previewIdx:l,basePath:o,currLocation:d,currPage:n,stack:r,sortMethod:v,sortedFiles:w,scroller:N,stackViewEl:j(),props:e,getPane:O,walker:b,deletedFiles:E,getViewableAreaFiles:g,...$}},()=>({images:j()}));function ks(){const{eventEmitter:i,multiSelectedIdxs:t,sortedFiles:e}=le().toRefs();return{onSelectAll:()=>i.value.emit("selectAll"),onReverseSelect:()=>{t.value=e.value.map((p,d)=>d).filter(p=>!t.value.includes(p))},onClearAllSelected:()=>{t.value=[]}}}const Is=()=>{const{stackViewEl:i}=le().toRefs(),t=j(-1);return Bt(i,e=>{var r;let n=e.target;for(;n.parentElement;)if(n=n.parentElement,n.tagName.toLowerCase()==="li"&&n.classList.contains("file-item-trigger")){const o=(r=n.dataset)==null?void 0:r.idx;o&&Number.isSafeInteger(+o)&&(t.value=+o);return}}),{showMenuIdx:t}};function Gn(){var i=window.navigator.userAgent,t=i.indexOf("MSIE ");if(t>0)return parseInt(i.substring(t+5,i.indexOf(".",t)),10);var e=i.indexOf("Trident/");if(e>0){var n=i.indexOf("rv:");return parseInt(i.substring(n+3,i.indexOf(".",n)),10)}var r=i.indexOf("Edge/");return r>0?parseInt(i.substring(r+5,i.indexOf(".",r)),10):-1}let ie;function ye(){ye.init||(ye.init=!0,ie=Gn()!==-1)}var ue={name:"ResizeObserver",props:{emitOnMount:{type:Boolean,default:!1},ignoreWidth:{type:Boolean,default:!1},ignoreHeight:{type:Boolean,default:!1}},emits:["notify"],mounted(){ye(),it(()=>{this._w=this.$el.offsetWidth,this._h=this.$el.offsetHeight,this.emitOnMount&&this.emitSize()});const i=document.createElement("object");this._resizeObject=i,i.setAttribute("aria-hidden","true"),i.setAttribute("tabindex",-1),i.onload=this.addResizeHandlers,i.type="text/html",ie&&this.$el.appendChild(i),i.data="about:blank",ie||this.$el.appendChild(i)},beforeUnmount(){this.removeResizeHandlers()},methods:{compareAndNotify(){(!this.ignoreWidth&&this._w!==this.$el.offsetWidth||!this.ignoreHeight&&this._h!==this.$el.offsetHeight)&&(this._w=this.$el.offsetWidth,this._h=this.$el.offsetHeight,this.emitSize())},emitSize(){this.$emit("notify",{width:this._w,height:this._h})},addResizeHandlers(){this._resizeObject.contentDocument.defaultView.addEventListener("resize",this.compareAndNotify),this.compareAndNotify()},removeResizeHandlers(){this._resizeObject&&this._resizeObject.onload&&(!ie&&this._resizeObject.contentDocument&&this._resizeObject.contentDocument.defaultView.removeEventListener("resize",this.compareAndNotify),this.$el.removeChild(this._resizeObject),this._resizeObject.onload=null,this._resizeObject=null)}}};const Zn=Lt();tt("data-v-b329ee4c");const Xn={class:"resize-observer",tabindex:"-1"};nt();const ei=Zn((i,t,e,n,r,o)=>(a(),R("div",Xn)));ue.render=ei;ue.__scopeId="data-v-b329ee4c";ue.__file="src/components/ResizeObserver.vue";function re(i){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?re=function(t){return typeof t}:re=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},re(i)}function ti(i,t){if(!(i instanceof t))throw new TypeError("Cannot call a class as a function")}function Ue(i,t){for(var e=0;ei.length)&&(t=i.length);for(var e=0,n=new Array(t);e2&&arguments[2]!==void 0?arguments[2]:{},n,r,o,p=function(v){for(var b=arguments.length,E=new Array(b>1?b-1:0),w=1;w1){var b=d.find(function(w){return w.isIntersecting});b&&(v=b)}if(r.callback){var E=v.isIntersecting&&v.intersectionRatio>=r.threshold;if(E===r.oldResult)return;r.oldResult=E,r.callback(E,v)}},this.options.intersection),it(function(){r.observer&&r.observer.observe(r.el)})}}},{key:"destroyObserver",value:function(){this.observer&&(this.observer.disconnect(),this.observer=null),this.callback&&this.callback._clear&&(this.callback._clear(),this.callback=null)}},{key:"threshold",get:function(){return this.options.intersection&&typeof this.options.intersection.threshold=="number"?this.options.intersection.threshold:0}}]),i}();function ft(i,t,e){var n=t.value;if(n)if(typeof IntersectionObserver>"u")console.warn("[vue-observe-visibility] IntersectionObserver API is not available in your browser. Please install this polyfill: https://github.com/w3c/IntersectionObserver/tree/master/polyfill");else{var r=new ui(i,n,e);i._vue_visibilityState=r}}function ci(i,t,e){var n=t.value,r=t.oldValue;if(!dt(n,r)){var o=i._vue_visibilityState;if(!n){ht(i);return}o?o.createObserver(n,e):ft(i,{value:n},e)}}function ht(i){var t=i._vue_visibilityState;t&&(t.destroyObserver(),delete i._vue_visibilityState)}var di={beforeMount:ft,updated:ci,unmounted:ht},fi={itemsLimit:1e3},hi=/(auto|scroll)/;function gt(i,t){return i.parentNode===null?t:gt(i.parentNode,t.concat([i]))}var fe=function(t,e){return getComputedStyle(t,null).getPropertyValue(e)},gi=function(t){return fe(t,"overflow")+fe(t,"overflow-y")+fe(t,"overflow-x")},pi=function(t){return hi.test(gi(t))};function We(i){if(i instanceof HTMLElement||i instanceof SVGElement){for(var t=gt(i.parentNode,[]),e=0;e{this.$_prerender=!1,this.updateVisibleItems(!0),this.ready=!0})},activated(){const i=this.$_lastUpdateScrollPosition;typeof i=="number"&&this.$nextTick(()=>{this.scrollToPosition(i)})},beforeUnmount(){this.removeListeners()},methods:{addView(i,t,e,n,r){const o=jt({id:bi++,index:t,used:!0,key:n,type:r}),p=Ht({item:e,position:0,nr:o});return i.push(p),p},unuseView(i,t=!1){const e=this.$_unusedViews,n=i.nr.type;let r=e.get(n);r||(r=[],e.set(n,r)),r.push(i),t||(i.nr.used=!1,i.position=-9999)},handleResize(){this.$emit("resize"),this.ready&&this.updateVisibleItems(!1)},handleScroll(i){if(!this.$_scrollDirty){if(this.$_scrollDirty=!0,this.$_updateTimeout)return;const t=()=>requestAnimationFrame(()=>{this.$_scrollDirty=!1;const{continuous:e}=this.updateVisibleItems(!1,!0);e||(clearTimeout(this.$_refreshTimout),this.$_refreshTimout=setTimeout(this.handleScroll,this.updateInterval+100))});t(),this.updateInterval&&(this.$_updateTimeout=setTimeout(()=>{this.$_updateTimeout=0,this.$_scrollDirty&&t()},this.updateInterval))}},handleVisibilityChange(i,t){this.ready&&(i||t.boundingClientRect.width!==0||t.boundingClientRect.height!==0?(this.$emit("visible"),requestAnimationFrame(()=>{this.updateVisibleItems(!1)})):this.$emit("hidden"))},updateVisibleItems(i,t=!1){const e=this.itemSize,n=this.gridItems||1,r=this.itemSecondarySize||e,o=this.$_computedMinItemSize,p=this.typeField,d=this.simpleArray?null:this.keyField,v=this.items,b=v.length,E=this.sizes,w=this.$_views,T=this.$_unusedViews,l=this.pool,s=this.itemIndexByKey;let c,m,N,O,$;if(!b)c=m=O=$=N=0;else if(this.$_prerender)c=O=0,m=$=Math.min(this.prerender,v.length),N=null;else{const _=this.getScroll();if(t){let z=_.start-this.$_lastUpdateScrollPosition;if(z<0&&(z=-z),e===null&&z_.start&&(De=U),U=~~((x+De)/2);while(U!==Ne);for(U<0&&(U=0),c=U,N=E[b-1].accumulator,m=U;mb&&(m=b)),O=c;Ob&&(m=b),O<0&&(O=0),$>b&&($=b),N=Math.ceil(b/n)*e}}m-c>fi.itemsLimit&&this.itemsLimitError(),this.totalSize=N;let g;const f=c<=this.$_endIndex&&m>=this.$_startIndex;if(f)for(let _=0,L=l.length;_=m)&&this.unuseView(g));const C=f?null:new Map;let M,F,B;for(let _=c;_=P.length)&&(g=this.addView(l,_,M,L,F),this.unuseView(g,!0),P=T.get(F)),g=P[B],C.set(F,B+1)),w.delete(g.nr.key),g.nr.used=!0,g.nr.index=_,g.nr.key=L,g.nr.type=F,w.set(L,g),z=!0;else if(!g.nr.used&&(g.nr.used=!0,g.nr.index=_,z=!0,P)){const x=P.indexOf(g);x!==-1&&P.splice(x,1)}g.item=M,z&&(_===v.length-1&&this.$emit("scroll-end"),_===0&&this.$emit("scroll-start")),e===null?(g.position=E[_-1].accumulator,g.offset=0):(g.position=Math.floor(_/n)*e,g.offset=_%n*r)}return this.$_startIndex=c,this.$_endIndex=m,this.emitUpdate&&this.$emit("update",c,m,O,$),clearTimeout(this.$_sortTimer),this.$_sortTimer=setTimeout(this.sortViews,this.updateInterval+300),{continuous:f}},getListenerTarget(){let i=We(this.$el);return window.document&&(i===window.document.documentElement||i===window.document.body)&&(i=window),i},getScroll(){const{$el:i,direction:t}=this,e=t==="vertical";let n;if(this.pageMode){const r=i.getBoundingClientRect(),o=e?r.height:r.width;let p=-(e?r.top:r.left),d=e?window.innerHeight:window.innerWidth;p<0&&(d+=p,p=0),p+d>o&&(d=o-p),n={start:p,end:p+d}}else e?n={start:i.scrollTop,end:i.scrollTop+i.clientHeight}:n={start:i.scrollLeft,end:i.scrollLeft+i.clientWidth};return n},applyPageMode(){this.pageMode?this.addListeners():this.removeListeners()},addListeners(){this.listenerTarget=this.getListenerTarget(),this.listenerTarget.addEventListener("scroll",this.handleScroll,Se?{passive:!0}:!1),this.listenerTarget.addEventListener("resize",this.handleResize)},removeListeners(){this.listenerTarget&&(this.listenerTarget.removeEventListener("scroll",this.handleScroll),this.listenerTarget.removeEventListener("resize",this.handleResize),this.listenerTarget=null)},scrollToItem(i){let t;const e=this.gridItems||1;this.itemSize===null?t=i>0?this.sizes[i-1].accumulator:0:t=Math.floor(i/e)*this.itemSize,this.scrollToPosition(t)},scrollToPosition(i){const t=this.direction==="vertical"?{scroll:"scrollTop",start:"top"}:{scroll:"scrollLeft",start:"left"};let e,n,r;if(this.pageMode){const o=We(this.$el),p=o.tagName==="HTML"?0:o[t.scroll],d=o.getBoundingClientRect(),b=this.$el.getBoundingClientRect()[t.start]-d[t.start];e=o,n=t.scroll,r=i+p+b}else e=this.$el,n=t.scroll,r=i;e[n]=r},itemsLimitError(){throw setTimeout(()=>{console.log("It seems the scroller element isn't scrolling, so it tries to render all the items at once.","Scroller:",this.$el),console.log("Make sure the scroller has a fixed height (or width) and 'overflow-y' (or 'overflow-x') set to 'auto' so it can scroll correctly and only render the items visible in the scroll viewport.")}),new Error("Rendered items limit reached")},sortViews(){this.pool.sort((i,t)=>i.nr.index-t.nr.index)}}};const Ai={key:0,ref:"before",class:"vue-recycle-scroller__slot"},Si={key:1,ref:"after",class:"vue-recycle-scroller__slot"};function ki(i,t,e,n,r,o){const p=Vt("ResizeObserver"),d=xt("observe-visibility");return Ut((a(),h("div",{class:Y(["vue-recycle-scroller",{ready:r.ready,"page-mode":e.pageMode,[`direction-${i.direction}`]:!0}]),onScrollPassive:t[0]||(t[0]=(...v)=>o.handleScroll&&o.handleScroll(...v))},[i.$slots.before?(a(),h("div",Ai,[te(i.$slots,"before")],512)):S("v-if",!0),(a(),R(ze(e.listTag),{ref:"wrapper",style:rt({[i.direction==="vertical"?"minHeight":"minWidth"]:r.totalSize+"px"}),class:Y(["vue-recycle-scroller__item-wrapper",e.listClass])},{default:k(()=>[(a(!0),h(H,null,J(r.pool,v=>(a(),R(ze(e.itemTag),Jt({key:v.nr.id,style:r.ready?{transform:`translate${i.direction==="vertical"?"Y":"X"}(${v.position}px) translate${i.direction==="vertical"?"X":"Y"}(${v.offset}px)`,width:e.gridItems?`${i.direction==="vertical"&&e.itemSecondarySize||e.itemSize}px`:void 0,height:e.gridItems?`${i.direction==="horizontal"&&e.itemSecondarySize||e.itemSize}px`:void 0}:null,class:["vue-recycle-scroller__item-view",[e.itemClass,{hover:!e.skipHover&&r.hoverKey===v.nr.key}]]},Wt(e.skipHover?{}:{mouseenter:()=>{r.hoverKey=v.nr.key},mouseleave:()=>{r.hoverKey=null}})),{default:k(()=>[te(i.$slots,"default",{item:v.item,index:v.nr.index,active:v.nr.used})]),_:2},1040,["style","class"]))),128)),te(i.$slots,"empty")]),_:3},8,["style","class"])),i.$slots.after?(a(),h("div",Si,[te(i.$slots,"after")],512)):S("v-if",!0),A(p,{onNotify:o.handleResize},null,8,["onNotify"])],34)),[[d,o.handleVisibilityChange]])}pt.render=ki;pt.__file="src/components/RecycleScroller.vue";const Ke=X({__name:"ContextMenu",props:{file:{},idx:{},selectedTag:{},isSelectedMutilFiles:{type:Boolean}},emits:["contextMenuClick"],setup(i,{emit:t}){const e=i,n=Ie(),r=V(()=>{var o;return(((o=n.conf)==null?void 0:o.all_custom_tags)??[]).reduce((p,d)=>[...p,{...d,selected:!!e.selectedTag.find(v=>v.id===d.id)}],[])});return(o,p)=>{const d=st,v=Kt,b=Yt,E=ot;return a(),R(E,{onClick:p[0]||(p[0]=w=>t("contextMenuClick",w,o.file,o.idx))},{default:k(()=>{var w;return[A(d,{key:"deleteFiles"},{default:k(()=>[I(y(o.$t("deleteSelected")),1)]),_:1}),A(d,{key:"openWithDefaultApp"},{default:k(()=>[I(y(o.$t("openWithDefaultApp")),1)]),_:1}),A(d,{key:"saveSelectedAsJson"},{default:k(()=>[I(y(o.$t("saveSelectedAsJson")),1)]),_:1}),o.file.type==="dir"?(a(),h(H,{key:0},[A(d,{key:"openInNewTab"},{default:k(()=>[I(y(o.$t("openInNewTab")),1)]),_:1}),A(d,{key:"openOnTheRight"},{default:k(()=>[I(y(o.$t("openOnTheRight")),1)]),_:1}),A(d,{key:"openWithWalkMode"},{default:k(()=>[I(y(o.$t("openWithWalkMode")),1)]),_:1})],64)):S("",!0),o.file.type==="file"?(a(),h(H,{key:1},[Q(ae)(o.file.name)?(a(),h(H,{key:0},[A(d,{key:"viewGenInfo"},{default:k(()=>[I(y(o.$t("viewGenerationInfo")),1)]),_:1}),A(v),((w=Q(n).conf)==null?void 0:w.launch_mode)!=="server"?(a(),h(H,{key:0},[A(d,{key:"send2txt2img"},{default:k(()=>[I(y(o.$t("sendToTxt2img")),1)]),_:1}),A(d,{key:"send2img2img"},{default:k(()=>[I(y(o.$t("sendToImg2img")),1)]),_:1}),A(d,{key:"send2inpaint"},{default:k(()=>[I(y(o.$t("sendToInpaint")),1)]),_:1}),A(d,{key:"send2extras"},{default:k(()=>[I(y(o.$t("sendToExtraFeatures")),1)]),_:1}),A(b,{key:"sendToThirdPartyExtension",title:o.$t("sendToThirdPartyExtension")},{default:k(()=>[A(d,{key:"send2controlnet-txt2img"},{default:k(()=>[I("ControlNet - "+y(o.$t("t2i")),1)]),_:1}),A(d,{key:"send2controlnet-img2img"},{default:k(()=>[I("ControlNet - "+y(o.$t("i2i")),1)]),_:1}),A(d,{key:"send2outpaint"},{default:k(()=>[I("openOutpaint")]),_:1})]),_:1},8,["title"])],64)):S("",!0),A(d,{key:"send2BatchDownload"},{default:k(()=>[I(y(o.$t("sendToBatchDownload")),1)]),_:1}),A(b,{key:"copy2target",title:o.$t("copyTo")},{default:k(()=>[(a(!0),h(H,null,J(Q(n).quickMovePaths,T=>(a(),R(d,{key:`copy-to-${T.dir}`},{default:k(()=>[I(y(T.zh),1)]),_:2},1024))),128))]),_:1},8,["title"]),A(b,{key:"move2target",title:o.$t("moveTo")},{default:k(()=>[(a(!0),h(H,null,J(Q(n).quickMovePaths,T=>(a(),R(d,{key:`move-to-${T.dir}`},{default:k(()=>[I(y(T.zh),1)]),_:2},1024))),128))]),_:1},8,["title"]),A(v),o.isSelectedMutilFiles?(a(),h(H,{key:1},[A(b,{key:"batch-add-tag",title:o.$t("batchAddTag")},{default:k(()=>[A(d,{key:"add-custom-tag"},{default:k(()=>[I("+ "+y(o.$t("addNewCustomTag")),1)]),_:1}),(a(!0),h(H,null,J(r.value,T=>(a(),R(d,{key:`batch-add-tag-${T.id}`},{default:k(()=>[I(y(T.name),1)]),_:2},1024))),128))]),_:1},8,["title"]),A(b,{key:"batch-remove-tag",title:o.$t("batchRemoveTag")},{default:k(()=>[(a(!0),h(H,null,J(r.value,T=>(a(),R(d,{key:`batch-remove-tag-${T.id}`},{default:k(()=>[I(y(T.name),1)]),_:2},1024))),128))]),_:1},8,["title"])],64)):(a(),R(b,{key:"toggle-tag",title:o.$t("toggleTag")},{default:k(()=>[A(d,{key:"add-custom-tag"},{default:k(()=>[I("+ "+y(o.$t("addNewCustomTag")),1)]),_:1}),(a(!0),h(H,null,J(r.value,T=>(a(),R(d,{key:`toggle-tag-${T.id}`},{default:k(()=>[I(y(T.name)+" ",1),T.selected?(a(),R(Q(at),{key:0})):(a(),R(Q(ut),{key:1}))]),_:2},1024))),128))]),_:1},8,["title"])),A(v),A(d,{key:"openFileLocationInNewTab"},{default:k(()=>[I(y(o.$t("openFileLocationInNewTab")),1)]),_:1}),A(d,{key:"openWithLocalFileBrowser"},{default:k(()=>[I(y(o.$t("openWithLocalFileBrowser")),1)]),_:1})],64)):S("",!0),A(v),A(d,{key:"rename"},{default:k(()=>[I(y(o.$t("rename")),1)]),_:1}),A(d,{key:"previewInNewWindow"},{default:k(()=>[I(y(o.$t("previewInNewWindow")),1)]),_:1}),A(d,{key:"download"},{default:k(()=>[I(y(o.$t("download")),1)]),_:1}),A(d,{key:"copyPreviewUrl"},{default:k(()=>[I(y(o.$t("copySourceFilePreviewLink")),1)]),_:1}),A(d,{key:"copyFilePath"},{default:k(()=>[I(y(o.$t("copyFilePath")),1)]),_:1})],64)):S("",!0)]}),_:1})}}}),D=i=>(tt("data-v-4ea1ffe2"),i=i(),nt(),i),Ii={class:"changeIndicatorWrapper"},_i={key:0,class:"changeIndicatorsLeft changeIndicators"},Ci={key:0,class:"promptChangeIndicator changeIndicator"},wi={key:1,class:"negpromptChangeIndicator changeIndicator"},Ei={key:2,class:"seedChangeIndicator changeIndicator"},Ti={key:3,class:"stepsChangeIndicator changeIndicator"},Pi={key:4,class:"cfgChangeIndicator changeIndicator"},Oi={key:5,class:"sizeChangeIndicator changeIndicator"},Di={key:6,class:"modelChangeIndicator changeIndicator"},Ni={key:7,class:"samplerChangeIndicator changeIndicator"},$i={key:8,class:"otherChangeIndicator changeIndicator"},zi={class:"hoverOverlay"},Mi=D(()=>u("strong",null,"This file",-1)),Qi=D(()=>u("br",null,null,-1)),Bi=D(()=>u("br",null,null,-1)),Fi={key:0},Ri=D(()=>u("td",null,[u("span",{class:"promptChangeIndicator"},"+ Prompt")],-1)),Li={key:1},ji=D(()=>u("td",null,[u("span",{class:"negpromptChangeIndicator"},"- Prompt")],-1)),Hi={key:2},Vi=D(()=>u("td",null,[u("span",{class:"seedChangeIndicator"},"Seed")],-1)),xi={key:3},Ui=D(()=>u("td",null,[u("span",{class:"stepsChangeIndicator"},"Steps")],-1)),Ji={key:4},Wi=D(()=>u("td",null,[u("span",{class:"cfgChangeIndicator"},"Cfg Scale")],-1)),Ki={key:5},Yi=D(()=>u("td",null,[u("span",{class:"sizeChangeIndicator"},"Size")],-1)),qi={key:6},Gi=D(()=>u("td",null,[u("span",{class:"modelChangeIndicator"},"Model")],-1)),Zi=D(()=>u("br",null,null,-1)),Xi={key:7},er=D(()=>u("td",null,[u("span",{class:"samplerChangeIndicator"},"Sampler")],-1)),tr=D(()=>u("br",null,null,-1)),nr=D(()=>u("br",null,null,-1)),ir={key:0},rr=D(()=>u("span",{class:"otherChangeIndicator"},"Other",-1)),sr=D(()=>u("br",null,null,-1)),or=D(()=>u("br",null,null,-1)),lr={key:1,class:"changeIndicatorsRight changeIndicators"},ar={key:0,class:"promptChangeIndicator changeIndicator"},ur={key:1,class:"negpromptChangeIndicator changeIndicator"},cr={key:2,class:"seedChangeIndicator changeIndicator"},dr={key:3,class:"stepsChangeIndicator changeIndicator"},fr={key:4,class:"cfgChangeIndicator changeIndicator"},hr={key:5,class:"sizeChangeIndicator changeIndicator"},gr={key:6,class:"modelChangeIndicator changeIndicator"},pr={key:7,class:"samplerChangeIndicator changeIndicator"},vr={key:8,class:"otherChangeIndicator changeIndicator"},mr={class:"hoverOverlay"},yr=D(()=>u("strong",null,"This file",-1)),br=D(()=>u("br",null,null,-1)),Ar=D(()=>u("br",null,null,-1)),Sr={key:0},kr=D(()=>u("td",null,[u("span",{class:"promptChangeIndicator"},"+ Prompt")],-1)),Ir={key:1},_r=D(()=>u("td",null,[u("span",{class:"negpromptChangeIndicator"},"- Prompt")],-1)),Cr={key:2},wr=D(()=>u("td",null,[u("span",{class:"seedChangeIndicator"},"Seed")],-1)),Er={key:3},Tr=D(()=>u("td",null,[u("span",{class:"stepsChangeIndicator"},"Steps")],-1)),Pr={key:4},Or=D(()=>u("td",null,[u("span",{class:"cfgChangeIndicator"},"Cfg Scale")],-1)),Dr={key:5},Nr=D(()=>u("td",null,[u("span",{class:"sizeChangeIndicator"},"Size")],-1)),$r={key:6},zr=D(()=>u("td",null,[u("span",{class:"modelChangeIndicator"},"Model")],-1)),Mr=D(()=>u("br",null,null,-1)),Qr={key:7},Br=D(()=>u("td",null,[u("span",{class:"samplerChangeIndicator"},"Sampler")],-1)),Fr=D(()=>u("br",null,null,-1)),Rr=D(()=>u("br",null,null,-1)),Lr={key:0},jr=D(()=>u("span",{class:"otherChangeIndicator"},"Other",-1)),Hr=D(()=>u("br",null,null,-1)),Vr=D(()=>u("br",null,null,-1)),xr=X({__name:"ChangeIndicator",props:{genDiffToPrevious:{},genDiffToNext:{},genInfo:{}},setup(i){function t(n){const r=["prompt","negativePrompt","seed","steps","cfgScale","size","Model","others"],o=Object.keys(n).filter(p=>!r.includes(p));return Object.fromEntries(o.map(p=>[p,n[p]]))}function e(n){return Object.keys(t(n)).length>0}return(n,r)=>(a(),h("div",Ii,[n.genDiffToPrevious.empty?S("",!0):(a(),h("div",_i,["prompt"in n.genDiffToPrevious.diff?(a(),h("div",Ci,"P+")):S("",!0),"negativePrompt"in n.genDiffToPrevious.diff?(a(),h("div",wi,"P-")):S("",!0),"seed"in n.genDiffToPrevious.diff?(a(),h("div",Ei,"Se")):S("",!0),"steps"in n.genDiffToPrevious.diff?(a(),h("div",Ti,"St")):S("",!0),"cfgScale"in n.genDiffToPrevious.diff?(a(),h("div",Pi,"Cf")):S("",!0),"size"in n.genDiffToPrevious.diff?(a(),h("div",Oi,"Si")):S("",!0),"Model"in n.genDiffToPrevious.diff?(a(),h("div",Di,"Mo")):S("",!0),"Sampler"in n.genDiffToPrevious.diff?(a(),h("div",Ni,"Sa")):S("",!0),e(n.genDiffToPrevious.diff)?(a(),h("div",$i,"Ot")):S("",!0)])),u("div",zi,[u("small",null,[A(Q(je)),Mi,I(" vs "+y(n.genDiffToPrevious.otherFile)+" ",1),Qi,Bi,u("table",null,["prompt"in n.genDiffToPrevious.diff?(a(),h("tr",Fi,[Ri,u("td",null,y(n.genDiffToPrevious.diff.prompt)+" tokens changed",1)])):S("",!0),"negativePrompt"in n.genDiffToPrevious.diff?(a(),h("tr",Li,[ji,u("td",null,y(n.genDiffToPrevious.diff.negativePrompt)+" tokens changed",1)])):S("",!0),"seed"in n.genDiffToPrevious.diff?(a(),h("tr",Hi,[Vi,u("td",null,[u("strong",null,y(n.genDiffToPrevious.diff.seed[0]),1),I(" vs "+y(n.genDiffToPrevious.diff.seed[1]),1)])])):S("",!0),"steps"in n.genDiffToPrevious.diff?(a(),h("tr",xi,[Ui,u("td",null,[u("strong",null,y(n.genDiffToPrevious.diff.steps[0]),1),I(" vs "+y(n.genDiffToPrevious.diff.steps[1]),1)])])):S("",!0),"cfgScale"in n.genDiffToPrevious.diff?(a(),h("tr",Ji,[Wi,u("td",null,[u("strong",null,y(n.genDiffToPrevious.diff.cfgScale[0]),1),I(" vs "+y(n.genDiffToPrevious.diff.cfgScale[1]),1)])])):S("",!0),"size"in n.genDiffToPrevious.diff?(a(),h("tr",Ki,[Yi,u("td",null,[u("strong",null,y(n.genDiffToPrevious.diff.size[0]),1),I(" vs "+y(n.genDiffToPrevious.diff.size[1]),1)])])):S("",!0),"Model"in n.genDiffToPrevious.diff?(a(),h("tr",qi,[Gi,u("td",null,[u("strong",null,y(n.genDiffToPrevious.diff.Model[0]),1),Zi,I(" vs "+y(n.genDiffToPrevious.diff.Model[1]),1)])])):S("",!0),"Sampler"in n.genDiffToPrevious.diff?(a(),h("tr",Xi,[er,u("td",null,[u("strong",null,y(n.genDiffToPrevious.diff.Sampler[0]),1),tr,I(" vs "+y(n.genDiffToPrevious.diff.Sampler[1]),1)])])):S("",!0)]),nr,e(n.genDiffToPrevious.diff)?(a(),h("div",ir,[rr,I(" props that changed:"),sr,or,u("ul",null,[(a(!0),h(H,null,J(t(n.genDiffToPrevious.diff),(o,p)=>(a(),h("li",null,y(p),1))),256))])])):S("",!0)])]),n.genDiffToNext.empty?S("",!0):(a(),h("div",lr,["prompt"in n.genDiffToNext.diff?(a(),h("div",ar,"P+")):S("",!0),"negativePrompt"in n.genDiffToNext.diff?(a(),h("div",ur,"P-")):S("",!0),"seed"in n.genDiffToNext.diff?(a(),h("div",cr,"Se")):S("",!0),"steps"in n.genDiffToNext.diff?(a(),h("div",dr,"St")):S("",!0),"cfgScale"in n.genDiffToNext.diff?(a(),h("div",fr,"Cf")):S("",!0),"size"in n.genDiffToNext.diff?(a(),h("div",hr,"Si")):S("",!0),"Model"in n.genDiffToNext.diff?(a(),h("div",gr,"Mo")):S("",!0),"Sampler"in n.genDiffToNext.diff?(a(),h("div",pr,"Sa")):S("",!0),e(n.genDiffToNext.diff)?(a(),h("div",vr,"Ot")):S("",!0)])),u("div",mr,[u("small",null,[A(Q(je)),yr,I(" vs "+y(n.genDiffToNext.otherFile)+" ",1),br,Ar,u("table",null,["prompt"in n.genDiffToNext.diff?(a(),h("tr",Sr,[kr,u("td",null,y(n.genDiffToNext.diff.prompt)+" tokens changed",1)])):S("",!0),"negativePrompt"in n.genDiffToNext.diff?(a(),h("tr",Ir,[_r,u("td",null,y(n.genDiffToNext.diff.negativePrompt)+" tokens changed",1)])):S("",!0),"seed"in n.genDiffToNext.diff?(a(),h("tr",Cr,[wr,u("td",null,[u("strong",null,y(n.genDiffToNext.diff.seed[0]),1),I(" vs "+y(n.genDiffToNext.diff.seed[1]),1)])])):S("",!0),"steps"in n.genDiffToNext.diff?(a(),h("tr",Er,[Tr,u("td",null,[u("strong",null,y(n.genDiffToNext.diff.steps[0]),1),I(" vs "+y(n.genDiffToNext.diff.steps[1]),1)])])):S("",!0),"cfgScale"in n.genDiffToNext.diff?(a(),h("tr",Pr,[Or,u("td",null,[u("strong",null,y(n.genDiffToNext.diff.cfgScale[0]),1),I(" vs "+y(n.genDiffToNext.diff.cfgScale[1]),1)])])):S("",!0),"size"in n.genDiffToNext.diff?(a(),h("tr",Dr,[Nr,u("td",null,[u("strong",null,y(n.genDiffToNext.diff.size[0]),1),I(" vs "+y(n.genDiffToNext.diff.size[1]),1)])])):S("",!0),"Model"in n.genDiffToNext.diff?(a(),h("tr",$r,[zr,u("td",null,[u("strong",null,y(n.genDiffToNext.diff.Model[0]),1),Mr,I(" vs "+y(n.genDiffToNext.diff.Model[1]),1)])])):S("",!0),"Sampler"in n.genDiffToNext.diff?(a(),h("tr",Qr,[Br,u("td",null,[u("strong",null,y(n.genDiffToNext.diff.Sampler[0]),1),Fr,I(" vs "+y(n.genDiffToNext.diff.Sampler[1]),1)])])):S("",!0)]),Rr,e(n.genDiffToNext.diff)?(a(),h("div",Lr,[jr,I(" props that changed:"),Hr,Vr,u("ul",null,[(a(!0),h(H,null,J(t(n.genDiffToNext.diff),(o,p)=>(a(),h("li",null,y(p),1))),256))])])):S("",!0)])])]))}});const Ur=lt(xr,[["__scopeId","data-v-4ea1ffe2"]]),Jr=["data-idx"],Wr={key:1,class:"more"},Kr={class:"float-btn-wrap"},Yr={key:1,class:"tags-container"},qr=["url"],Gr={class:"play-icon"},Zr=["src"],Xr={key:0,class:"tags-container"},es={key:4,class:"preview-icon-wrap"},ts={key:1,class:"dir-cover-container"},ns=["src"],is={key:5,class:"profile"},rs=["title"],ss={class:"basic-info"},os={style:{"margin-right":"4px"}},he=160,ls=X({__name:"FileItem",props:{file:{},idx:{},selected:{type:Boolean,default:!1},showMenuIdx:{},cellWidth:{},fullScreenPreviewImageUrl:{},enableRightClickMenu:{type:Boolean,default:!0},enableCloseIcon:{type:Boolean,default:!1},isSelectedMutilFiles:{type:Boolean},genInfo:{},enableChangeIndicator:{type:Boolean},extraTags:{},coverFiles:{},getGenDiff:{},getGenDiffWatchDep:{}},emits:["update:showMenuIdx","fileItemClick","dragstart","dragend","previewVisibleChange","contextMenuClick","close-icon-click"],setup(i,{emit:t}){const e=i;qt(l=>({da9c1018:l.$props.cellWidth+"px"}));const n=Ie(),r=Xe(),o=j(),p=j(),d=pe(()=>{const{getGenDiff:l,file:s,idx:c}=e;l&&(p.value=l(s.gen_info_obj,c,1,s),o.value=l(s.gen_info_obj,c,-1,s))},200+100*Math.random());se(()=>{var l;return(l=e.getGenDiffWatchDep)==null?void 0:l.call(e,e.idx)},()=>{d()},{immediate:!0,deep:!0});const v=V(()=>r.tagMap.get(e.file.fullpath)??[]),b=V(()=>{const l=n.gridThumbnailResolution;return n.enableThumbnail?Me(e.file,[l,l].join("x")):Gt(e.file)}),E=V(()=>{var l;return(((l=n.conf)==null?void 0:l.all_custom_tags)??[]).reduce((s,c)=>[...s,{...c,selected:!!v.value.find(m=>m.id===c.id)}],[])}),w=V(()=>E.value.find(l=>l.type==="custom"&&l.name==="like")),T=()=>{ge(w.value),t("contextMenuClick",{key:`toggle-tag-${w.value.id}`},e.file,e.idx)};return(l,s)=>{const c=G,m=st,N=ot,O=nn,$=fn;return a(),R(c,{trigger:["contextmenu"],visible:Q(n).longPressOpenContextMenu?typeof l.idx=="number"&&l.showMenuIdx===l.idx:void 0,"onUpdate:visible":s[8]||(s[8]=g=>typeof l.idx=="number"&&t("update:showMenuIdx",g?l.idx:-1))},{overlay:k(()=>[l.enableRightClickMenu?(a(),R(Ke,{key:0,file:l.file,idx:l.idx,"selected-tag":v.value,onContextMenuClick:s[7]||(s[7]=(g,f,C)=>t("contextMenuClick",g,f,C)),"is-selected-mutil-files":l.isSelectedMutilFiles},null,8,["file","idx","selected-tag","is-selected-mutil-files"])):S("",!0)]),default:k(()=>{var g;return[(a(),h("li",{class:Y(["file file-item-trigger grid",{clickable:l.file.type==="dir",selected:l.selected}]),"data-idx":l.idx,key:l.file.name,draggable:"true",onDragstart:s[4]||(s[4]=f=>t("dragstart",f,l.idx)),onDragend:s[5]||(s[5]=f=>t("dragend",f,l.idx)),onClickCapture:s[6]||(s[6]=f=>t("fileItemClick",f,l.file,l.idx))},[u("div",null,[l.enableCloseIcon?(a(),h("div",{key:0,class:"close-icon",onClick:s[0]||(s[0]=f=>t("close-icon-click"))},[A(Q(Zt))])):S("",!0),l.enableRightClickMenu?(a(),h("div",Wr,[A(c,null,{overlay:k(()=>[A(Ke,{file:l.file,idx:l.idx,"selected-tag":v.value,onContextMenuClick:s[1]||(s[1]=(f,C,M)=>t("contextMenuClick",f,C,M)),"is-selected-mutil-files":l.isSelectedMutilFiles},null,8,["file","idx","selected-tag","is-selected-mutil-files"])]),default:k(()=>[u("div",Kr,[A(Q(Xt))])]),_:1}),l.file.type==="file"?(a(),R(c,{key:0},{overlay:k(()=>[E.value.length>1?(a(),R(N,{key:0,onClick:s[2]||(s[2]=f=>t("contextMenuClick",f,l.file,l.idx))},{default:k(()=>[(a(!0),h(H,null,J(E.value,f=>(a(),R(m,{key:`toggle-tag-${f.id}`},{default:k(()=>[I(y(f.name)+" ",1),f.selected?(a(),R(Q(at),{key:0})):(a(),R(Q(ut),{key:1}))]),_:2},1024))),128))]),_:1})):S("",!0)]),default:k(()=>{var f,C;return[u("div",{class:Y(["float-btn-wrap",{"like-selected":(f=w.value)==null?void 0:f.selected}]),onClick:T},[(C=w.value)!=null&&C.selected?(a(),R(Q(Rn),{key:0})):(a(),R(Q(Vn),{key:1}))],2)]}),_:1})):S("",!0)])):S("",!0),Q(en)(l.file.name)?(a(),h("div",{key:l.file.fullpath,class:Y(`idx-${l.idx} item-content`)},[l.enableChangeIndicator&&p.value&&o.value?(a(),R(Ur,{key:0,"gen-diff-to-next":p.value,"gen-diff-to-previous":o.value},null,8,["gen-diff-to-next","gen-diff-to-previous"])):S("",!0),A(O,{src:b.value,fallback:Q(Dn),preview:{src:l.fullScreenPreviewImageUrl,onVisibleChange:(f,C)=>t("previewVisibleChange",f,C)}},null,8,["src","fallback","preview"]),v.value&&l.cellWidth>he?(a(),h("div",Yr,[(a(!0),h(H,null,J(l.extraTags??v.value,f=>(a(),R($,{key:f.id,color:Q(r).getColor(f)},{default:k(()=>[I(y(f.name),1)]),_:2},1032,["color"]))),128))])):S("",!0)],2)):Q(tn)(l.file.name)?(a(),h("div",{key:3,class:Y(`idx-${l.idx} item-content video`),url:Q(de)(l.file),style:rt({"background-image":`url('${l.file.cover_url??Q(de)(l.file)}')`}),onClick:s[3]||(s[3]=f=>Q(sn)(l.file,C=>t("contextMenuClick",{key:`toggle-tag-${C}`},l.file,l.idx)))},[u("div",Gr,[u("img",{src:Q(Wn),style:{width:"40px",height:"40px"}},null,8,Zr)]),v.value&&l.cellWidth>he?(a(),h("div",Xr,[(a(!0),h(H,null,J(v.value,f=>(a(),R($,{key:f.id,color:Q(r).getColor(f)},{default:k(()=>[I(y(f.name),1)]),_:2},1032,["color"]))),128))])):S("",!0)],14,qr)):(a(),h("div",es,[l.file.type==="file"?(a(),R(Q(bn),{key:0,class:"icon center"})):(g=l.coverFiles)!=null&&g.length&&l.cellWidth>160?(a(),h("div",ts,[(a(!0),h(H,null,J(l.coverFiles,f=>(a(),h("img",{class:"dir-cover-item",src:f.media_type==="image"?Q(Me)(f):Q(de)(f),key:f.fullpath},null,8,ns))),128))])):(a(),R(Q(In),{key:2,class:"icon center"}))])),l.cellWidth>he?(a(),h("div",is,[u("div",{class:"name line-clamp-1",title:l.file.name},y(l.file.name),9,rs),u("div",ss,[u("div",os,y(l.file.type)+" "+y(l.file.size),1),u("div",null,y(l.file.date),1)])])):S("",!0)])],42,Jr))]}),_:1},8,["visible"])}}});const _s=lt(ls,[["__scopeId","data-v-b0176b12"]]);export{_s as F,gs as N,Ke as _,ps as a,Is as b,ks as c,pt as d,Ss as e,ys as f,q as g,As as h,ms as i,bs as j,Kn as k,On as r,vs as s,qn as t,le as u}; diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/FileItem-5efde21f.css b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/FileItem-5efde21f.css new file mode 100644 index 0000000000000000000000000000000000000000..a3f7c4dfaf1a5998e5688a7e79ba29631333ae95 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/FileItem-5efde21f.css @@ -0,0 +1 @@ +.vue-recycle-scroller{position:relative}.vue-recycle-scroller.direction-vertical:not(.page-mode){overflow-y:auto}.vue-recycle-scroller.direction-horizontal:not(.page-mode){overflow-x:auto}.vue-recycle-scroller.direction-horizontal{display:flex}.vue-recycle-scroller__slot{flex:auto 0 0}.vue-recycle-scroller__item-wrapper{flex:1;box-sizing:border-box;overflow:hidden;position:relative}.vue-recycle-scroller.ready .vue-recycle-scroller__item-view{position:absolute;top:0;left:0;will-change:transform}.vue-recycle-scroller.direction-vertical .vue-recycle-scroller__item-wrapper{width:100%}.vue-recycle-scroller.direction-horizontal .vue-recycle-scroller__item-wrapper{height:100%}.vue-recycle-scroller.ready.direction-vertical .vue-recycle-scroller__item-view{width:100%}.vue-recycle-scroller.ready.direction-horizontal .vue-recycle-scroller__item-view{height:100%}.resize-observer[data-v-b329ee4c]{position:absolute;top:0;left:0;z-index:-1;width:100%;height:100%;border:none;background-color:transparent;pointer-events:none;display:block;overflow:hidden;opacity:0}.resize-observer[data-v-b329ee4c] object{display:block;position:absolute;top:0;left:0;height:100%;width:100%;overflow:hidden;pointer-events:none;z-index:-1}.ant-tag{box-sizing:border-box;margin:0 8px 0 0;color:#000000d9;font-size:14px;font-variant:tabular-nums;line-height:1.5715;list-style:none;font-feature-settings:"tnum";display:inline-block;height:auto;padding:0 7px;font-size:12px;line-height:20px;white-space:nowrap;background:#fafafa;border:1px solid #d9d9d9;border-radius:2px;opacity:1;transition:all .3s}.ant-tag,.ant-tag a,.ant-tag a:hover{color:#000000d9}.ant-tag>a:first-child:last-child{display:inline-block;margin:0 -8px;padding:0 8px}.ant-tag-close-icon{margin-left:3px;color:#00000073;font-size:10px;cursor:pointer;transition:all .3s}.ant-tag-close-icon:hover{color:#000000d9}.ant-tag-has-color{border-color:transparent}.ant-tag-has-color,.ant-tag-has-color a,.ant-tag-has-color a:hover,.ant-tag-has-color .anticon-close,.ant-tag-has-color .anticon-close:hover{color:#fff}.ant-tag-checkable{background-color:transparent;border-color:transparent;cursor:pointer}.ant-tag-checkable:not(.ant-tag-checkable-checked):hover{color:#d03f0a}.ant-tag-checkable:active,.ant-tag-checkable-checked{color:#fff}.ant-tag-checkable-checked{background-color:#d03f0a}.ant-tag-checkable:active{background-color:#ab2800}.ant-tag-hidden{display:none}.ant-tag-pink{color:#c41d7f;background:#fff0f6;border-color:#ffadd2}.ant-tag-pink-inverse{color:#fff;background:#eb2f96;border-color:#eb2f96}.ant-tag-magenta{color:#c41d7f;background:#fff0f6;border-color:#ffadd2}.ant-tag-magenta-inverse{color:#fff;background:#eb2f96;border-color:#eb2f96}.ant-tag-red{color:#cf1322;background:#fff1f0;border-color:#ffa39e}.ant-tag-red-inverse{color:#fff;background:#f5222d;border-color:#f5222d}.ant-tag-volcano{color:#d4380d;background:#fff2e8;border-color:#ffbb96}.ant-tag-volcano-inverse{color:#fff;background:#fa541c;border-color:#fa541c}.ant-tag-orange{color:#d46b08;background:#fff7e6;border-color:#ffd591}.ant-tag-orange-inverse{color:#fff;background:#fa8c16;border-color:#fa8c16}.ant-tag-yellow{color:#d4b106;background:#feffe6;border-color:#fffb8f}.ant-tag-yellow-inverse{color:#fff;background:#fadb14;border-color:#fadb14}.ant-tag-gold{color:#d48806;background:#fffbe6;border-color:#ffe58f}.ant-tag-gold-inverse{color:#fff;background:#faad14;border-color:#faad14}.ant-tag-cyan{color:#08979c;background:#e6fffb;border-color:#87e8de}.ant-tag-cyan-inverse{color:#fff;background:#13c2c2;border-color:#13c2c2}.ant-tag-lime{color:#7cb305;background:#fcffe6;border-color:#eaff8f}.ant-tag-lime-inverse{color:#fff;background:#a0d911;border-color:#a0d911}.ant-tag-green{color:#389e0d;background:#f6ffed;border-color:#b7eb8f}.ant-tag-green-inverse{color:#fff;background:#52c41a;border-color:#52c41a}.ant-tag-blue{color:#096dd9;background:#e6f7ff;border-color:#91d5ff}.ant-tag-blue-inverse{color:#fff;background:#1890ff;border-color:#1890ff}.ant-tag-geekblue{color:#1d39c4;background:#f0f5ff;border-color:#adc6ff}.ant-tag-geekblue-inverse{color:#fff;background:#2f54eb;border-color:#2f54eb}.ant-tag-purple{color:#531dab;background:#f9f0ff;border-color:#d3adf7}.ant-tag-purple-inverse{color:#fff;background:#722ed1;border-color:#722ed1}.ant-tag-success{color:#52c41a;background:#f6ffed;border-color:#b7eb8f}.ant-tag-processing{color:#d03f0a;background:#fff1e6;border-color:#f7ae83}.ant-tag-error{color:#ff4d4f;background:#fff2f0;border-color:#ffccc7}.ant-tag-warning{color:#faad14;background:#fffbe6;border-color:#ffe58f}.ant-tag>.anticon+span,.ant-tag>span+.anticon{margin-left:7px}.ant-tag.ant-tag-rtl{margin-right:0;margin-left:8px;direction:rtl;text-align:right}.ant-tag-rtl .ant-tag-close-icon{margin-right:3px;margin-left:0}.ant-tag-rtl.ant-tag>.anticon+span,.ant-tag-rtl.ant-tag>span+.anticon{margin-right:7px;margin-left:0}.changeIndicators[data-v-4ea1ffe2]{position:absolute;display:flex;flex-direction:column;height:100%;align-items:center;justify-content:center;opacity:.6}.changeIndicatorsRight[data-v-4ea1ffe2]{position:absolute;right:0}.changeIndicator[data-v-4ea1ffe2]{margin-left:-4px;width:16px;height:16px;border-radius:2px;border:1px solid rgba(255,255,255,.2);background-color:gray;line-height:16px;margin-bottom:2px;text-align:center;font-size:6pt;font-weight:600;color:#000;z-index:9999;pointer-events:auto;box-shadow:0 0 4px #00000080}.changeIndicatorsRight .changeIndicator[data-v-4ea1ffe2]{margin-right:-4px;border-top-right-radius:8px;border-bottom-right-radius:8px;text-align:left;padding-left:2px}.changeIndicatorsLeft .changeIndicator[data-v-4ea1ffe2]{border-top-left-radius:8px;border-bottom-left-radius:8px;text-align:right;padding-right:2px}.changeIndicatorWrapper[data-v-4ea1ffe2]{top:0;position:absolute;user-select:none;width:100%;height:100%;z-index:999999;pointer-events:none}.hoverOverlay[data-v-4ea1ffe2]{display:none;background-color:#000c;color:#fff;border:1px solid gray;padding:10px 20px;border-radius:5px;z-index:100;opacity:1;font-size:8pt;line-height:1.2;overflow:hidden}.hoverOverlay ul[data-v-4ea1ffe2]{list-style:none;padding:0}.hoverOverlay ul li[data-v-4ea1ffe2]{display:inline-block;padding-left:4px;padding-right:4px;border:1px solid gray;border-radius:2px;margin:1px;font-weight:200}.changeIndicators[data-v-4ea1ffe2]:hover{opacity:1}.changeIndicators:hover+div.hoverOverlay[data-v-4ea1ffe2]{display:block;position:absolute;top:0;left:0;width:100%;height:100%}table tr td:first-child span[data-v-4ea1ffe2]{padding:1px 3px;display:inline-block;width:100%}table tr td[data-v-4ea1ffe2]:first-child{padding-right:10px;vertical-align:top}.otherChangeIndicator[data-v-4ea1ffe2]{background-color:#8b5b8e;color:#efefef}.stepsChangeIndicator[data-v-4ea1ffe2]{background-color:#577ab8;color:#efefef}.seedChangeIndicator[data-v-4ea1ffe2]{background-color:#649da3;color:#121}.negpromptChangeIndicator[data-v-4ea1ffe2]{background-color:#d8a390;color:#2f2f2f}.modelChangeIndicator[data-v-4ea1ffe2]{background-color:#d68679;color:#efefef}.promptChangeIndicator[data-v-4ea1ffe2]{background-color:#8fba99;color:#121}.cfgChangeIndicator[data-v-4ea1ffe2]{background-color:#d4c98f;color:#121}.sizeChangeIndicator[data-v-4ea1ffe2]{background-color:#678a6c;color:#efefef}.center[data-v-b0176b12]{display:flex;justify-content:center;align-items:center}.item-content[data-v-b0176b12]{position:relative}.item-content.video[data-v-b0176b12]{background-color:var(--zp-border);border-radius:8px;overflow:hidden;width:var(--da9c1018);height:var(--da9c1018);background-size:cover;background-position:center;cursor:pointer}.item-content .play-icon[data-v-b0176b12]{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);border-radius:100%;display:flex}.item-content .tags-container[data-v-b0176b12]{position:absolute;right:8px;bottom:8px;display:flex;width:calc(100% - 16px);flex-wrap:wrap-reverse;flex-direction:row-reverse}.item-content .tags-container>*[data-v-b0176b12]{margin:0 0 4px 4px;font-size:14px;line-height:1.6}.close-icon[data-v-b0176b12]{position:absolute;top:0;right:0;transform:translate(50%,-50%) scale(1.5);cursor:pointer;z-index:100;border-radius:100%;overflow:hidden;line-height:1;background-color:var(--zp-primary-background)}.file[data-v-b0176b12]{padding:8px 16px;margin:8px;display:flex;align-items:center;background:var(--zp-primary-background);border-radius:8px;box-shadow:0 0 4px var(--zp-secondary-variant-background);position:relative}.file:hover .more[data-v-b0176b12]{opacity:1}.file .more[data-v-b0176b12]{opacity:0;transition:all .3s ease;position:absolute;top:4px;right:4px;z-index:100;display:flex;align-items:center;justify-content:center;flex-direction:column;line-height:1em}.file .more .float-btn-wrap[data-v-b0176b12]{font-size:1.5em;cursor:pointer;font-size:500;padding:4px;border-radius:100vh;color:#fff;background:var(--zp-icon-bg);margin-bottom:4px}.file .more .float-btn-wrap.like-selected[data-v-b0176b12]{color:#df0505}.file.grid[data-v-b0176b12]{padding:0;display:inline-block;box-sizing:content-box;box-shadow:unset;background-color:var(--zp-secondary-background)}.file.grid[data-v-b0176b12] .icon{font-size:8em}.file.grid[data-v-b0176b12] .profile{padding:0 4px}.file.grid[data-v-b0176b12] .profile .name{font-weight:500;padding:0}.file.grid[data-v-b0176b12] .profile .basic-info{display:flex;justify-content:space-between;flex-direction:row;margin:0;font-size:.7em}.file.grid[data-v-b0176b12] .profile .basic-info *{white-space:nowrap;overflow:hidden}.file.grid[data-v-b0176b12] .ant-image,.file.grid[data-v-b0176b12] .preview-icon-wrap{border:1px solid var(--zp-secondary);background-color:var(--zp-secondary-variant-background);border-radius:8px;overflow:hidden}.file.grid[data-v-b0176b12] img:not(.dir-cover-item),.file.grid[data-v-b0176b12] .dir-cover-container,.file.grid[data-v-b0176b12] .preview-icon-wrap>[role=img]{height:var(--da9c1018);width:var(--da9c1018);object-fit:contain}.file.clickable[data-v-b0176b12]{cursor:pointer}.file.selected[data-v-b0176b12]{outline:#0084ff solid 2px}.file .name[data-v-b0176b12]{flex:1;padding:8px;word-break:break-all}.file .basic-info[data-v-b0176b12]{overflow:hidden;display:flex;flex-direction:column;align-items:flex-end}.file .dir-cover-container[data-v-b0176b12]{top:0;display:flex;flex-wrap:wrap;padding:4px}.file .dir-cover-container>img[data-v-b0176b12]{width:calc(50% - 8px);height:calc(50% - 8px);margin:4px;object-fit:cover;border-radius:8px;overflow:hidden} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/ImgSliPagePane-5f5e28b7.css b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/ImgSliPagePane-5f5e28b7.css new file mode 100644 index 0000000000000000000000000000000000000000..ddc617c2c2d49f4cf0add4ca65bac3a276c545ea --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/ImgSliPagePane-5f5e28b7.css @@ -0,0 +1 @@ +.img-sli-container[data-v-ec71de83]{position:relative;overflow-y:auto;height:calc(100vh - 40px)} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/ImgSliPagePane-967c320a.js b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/ImgSliPagePane-967c320a.js new file mode 100644 index 0000000000000000000000000000000000000000..ea76744f1f2155d67525e2937ddad1e2b33e0856 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/ImgSliPagePane-967c320a.js @@ -0,0 +1 @@ +import{d as t,S as a,T as s,c as n,cS as _,Z as c}from"./index-bd4c24ce.js";const o={class:"img-sli-container"},i=t({__name:"ImgSliPagePane",props:{paneIdx:{},tabIdx:{},left:{},right:{}},setup(l){return(e,r)=>(a(),s("div",o,[n(_,{left:e.left,right:e.right},null,8,["left","right"])]))}});const p=c(i,[["__scopeId","data-v-ec71de83"]]);export{p as default}; diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/MatchedImageGrid-2b7a400a.css b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/MatchedImageGrid-2b7a400a.css new file mode 100644 index 0000000000000000000000000000000000000000..8fb6dbf7e71a0cd1f22329d158237c6d236a96da --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/MatchedImageGrid-2b7a400a.css @@ -0,0 +1 @@ +.container[data-v-b42a9a06]{background:var(--zp-secondary-background);position:relative}.container .action-bar[data-v-b42a9a06]{display:flex;align-items:center;user-select:none;gap:4px;padding:4px}.container .action-bar>*[data-v-b42a9a06]{flex-wrap:wrap}.container .file-list[data-v-b42a9a06]{list-style:none;padding:8px;overflow:auto;height:calc(var(--pane-max-height) - 40px);width:100%}.container .no-res-hint[data-v-b42a9a06]{height:var(--pane-max-height);display:flex;align-items:center;flex-direction:column;justify-content:center}.container .no-res-hint .hint[data-v-b42a9a06]{font-size:1.6em;margin-bottom:2em;text-align:center} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/MatchedImageGrid-948fe1f2.js b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/MatchedImageGrid-948fe1f2.js new file mode 100644 index 0000000000000000000000000000000000000000..f8d8b07953249dc0029c784f232d9e11a4df5de2 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/MatchedImageGrid-948fe1f2.js @@ -0,0 +1 @@ +import{d as re,m as F,ax as ce,$ as pe,S as p,T as I,c as s,a2 as e,a1 as n,a4 as R,U as d,J as me,W as o,V as u,a0 as V,ad as ue,Y as k,ae as z,ag as ge,R as fe,ai as G,aN as ve,aO as he,bz as Ie,Z as ke}from"./index-bd4c24ce.js";import{S as _e}from"./index-0c3c532d.js";import{L as Ce,R as we,f as Se,M as be}from"./MultiSelectKeep-09d43067.js";import{c as xe,d as ye,F as Me}from"./FileItem-3771a510.js";import{c as Ae,u as Te}from"./hook-5a401311.js";import{a as $e}from"./functionalCallableComp-8b0d9f43.js";import"./shortcut-16a42bc1.js";import"./Checkbox-6eb6dd6a.js";/* empty css */import"./index-dfa3dc65.js";import"./index-afbe1fb8.js";import"./_isIterateeCall-eeca32c3.js";const De=r=>(ve("data-v-b42a9a06"),r=r(),he(),r),Fe={class:"hint"},Re={class:"action-bar"},Ve=De(()=>d("div",{style:{padding:"16px 0 512px"}},null,-1)),ze={key:1},Ge={class:"no-res-hint"},Be={class:"hint"},Ne={key:2,class:"preview-switch"},Ue=re({__name:"MatchedImageGrid",props:{tabIdx:{},paneIdx:{},selectedTagIds:{},id:{}},setup(r){const g=r,f=Ae(t=>Ie(g.selectedTagIds,t)),{queue:B,images:i,onContextMenuClickU:_,stackViewEl:N,previewIdx:c,previewing:C,onPreviewVisibleChange:U,previewImgMove:w,canPreview:S,itemSize:b,gridItems:J,showGenInfo:m,imageGenInfo:x,q:E,multiSelectedIdxs:v,onFileItemClick:L,scroller:y,showMenuIdx:h,onFileDragStart:O,onFileDragEnd:P,cellWidth:K,onScroll:M,saveAllFileAsJson:W,props:q,saveLoadedFileAsJson:Q,changeIndchecked:Y,seedChangeChecked:Z,getGenDiff:j,getGenDiffWatchDep:H}=Te(f);F(()=>g.selectedTagIds,async()=>{var t;await f.reset(),await ce(),(t=y.value)==null||t.scrollToItem(0),M()},{immediate:!0}),F(()=>g,async t=>{q.value=t},{deep:!0,immediate:!0});const X=pe(),{onClearAllSelected:ee,onSelectAll:te,onReverseSelect:le}=xe();return(t,l)=>{const se=be,ne=ge,ae=fe,A=G,ie=G,oe=_e;return p(),I("div",{class:"container",ref_key:"stackViewEl",ref:N},[s(se,{show:!!e(v).length||e(X).keepMultiSelect,onClearAllSelected:e(ee),onSelectAll:e(te),onReverseSelect:e(le)},null,8,["show","onClearAllSelected","onSelectAll","onReverseSelect"]),s(oe,{size:"large",spinning:!e(B).isIdle},{default:n(()=>{var T,$;return[s(ae,{visible:e(m),"onUpdate:visible":l[1]||(l[1]=a=>R(m)?m.value=a:null),width:"70vw","mask-closable":"",onOk:l[2]||(l[2]=a=>m.value=!1)},{cancelText:n(()=>[]),default:n(()=>[s(ne,{active:"",loading:!e(E).isIdle},{default:n(()=>[d("div",{style:{width:"100%","word-break":"break-all","white-space":"pre-line","max-height":"70vh",overflow:"auto"},onDblclick:l[0]||(l[0]=a=>e(me)(e(x)))},[d("div",Fe,o(t.$t("doubleClickToCopy")),1),u(" "+o(e(x)),1)],32)]),_:1},8,["loading"])]),_:1},8,["visible"]),d("div",Re,[s(A,{onClick:e(Q)},{default:n(()=>[u(o(t.$t("saveLoadedImageAsJson")),1)]),_:1},8,["onClick"]),s(A,{onClick:e(W)},{default:n(()=>[u(o(t.$t("saveAllAsJson")),1)]),_:1},8,["onClick"])]),(T=e(i))!=null&&T.length?(p(),V(e(ye),{key:0,ref_key:"scroller",ref:y,class:"file-list",items:e(i),"item-size":e(b).first,"key-field":"fullpath","item-secondary-size":e(b).second,gridItems:e(J),onScroll:e(M)},{after:n(()=>[Ve]),default:n(({item:a,index:D})=>[s(Me,{idx:D,file:a,"cell-width":e(K),"show-menu-idx":e(h),"onUpdate:showMenuIdx":l[3]||(l[3]=de=>R(h)?h.value=de:null),onDragstart:e(O),onDragend:e(P),onFileItemClick:e(L),"full-screen-preview-image-url":e(i)[e(c)]?e(ue)(e(i)[e(c)]):"",selected:e(v).includes(D),onContextMenuClick:e(_),onPreviewVisibleChange:e(U),"is-selected-mutil-files":e(v).length>1,"enable-change-indicator":e(Y),"seed-change-checked":e(Z),"get-gen-diff":e(j),"get-gen-diff-watch-dep":e(H)},null,8,["idx","file","cell-width","show-menu-idx","onDragstart","onDragend","onFileItemClick","full-screen-preview-image-url","selected","onContextMenuClick","onPreviewVisibleChange","is-selected-mutil-files","enable-change-indicator","seed-change-checked","get-gen-diff","get-gen-diff-watch-dep"])]),_:1},8,["items","item-size","item-secondary-size","gridItems","onScroll"])):e(f).load&&t.selectedTagIds.and_tags.length===1&&!(($=t.selectedTagIds.folder_paths_str)!=null&&$.trim())?(p(),I("div",ze,[d("div",Ge,[d("p",Be,o(t.$t("tagSearchNoResultsMessage")),1),s(ie,{onClick:l[4]||(l[4]=a=>e($e)()),type:"primary"},{default:n(()=>[u(o(t.$t("rebuildImageIndex")),1)]),_:1})])])):k("",!0),e(C)?(p(),I("div",Ne,[s(e(Ce),{onClick:l[5]||(l[5]=a=>e(w)("prev")),class:z({disable:!e(S)("prev")})},null,8,["class"]),s(e(we),{onClick:l[6]||(l[6]=a=>e(w)("next")),class:z({disable:!e(S)("next")})},null,8,["class"])])):k("",!0)]}),_:1},8,["spinning"]),e(C)&&e(i)&&e(i)[e(c)]?(p(),V(Se,{key:0,file:e(i)[e(c)],idx:e(c),onContextMenuClick:e(_)},null,8,["file","idx","onContextMenuClick"])):k("",!0)],512)}}});const He=ke(Ue,[["__scopeId","data-v-b42a9a06"]]);export{He as default}; diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/MultiSelectKeep-09d43067.js b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/MultiSelectKeep-09d43067.js new file mode 100644 index 0000000000000000000000000000000000000000..83744ef33e32651f0a6734be2249850a8171e9c6 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/MultiSelectKeep-09d43067.js @@ -0,0 +1,6 @@ +import{bf as Ot,c as u,A as ie,cm as R,y as oe,z as j,m as he,x as je,cn as rt,co as Tt,c6 as Ge,R as ye,ai as pe,cp as jt,r as te,N as We,cq as Lt,G as ct,ad as fe,cr as Wt,cs as qt,V as A,ac as Ut,ct as qe,O as _e,K as Bt,cu as Nt,J as de,cv as Ht,cw as Xt,cl as Jt,cx as Vt,cy as Gt,q as Ue,cz as Yt,cA as Be,o as zt,ax as Zt,$ as Ye,I as be,ak as Kt,E as Q,cB as Qt,n as ze,cC as Rt,Q as Ne,d as xt,cD as en,c3 as tn,S as $,T as E,a2 as c,Y as X,U as M,a0 as le,a1 as z,cE as dt,X as K,W as O,a6 as re,a5 as Me,ae as Se,a4 as ke,cF as Fe,a3 as nn,aj as an,cG as ln,cH as on,M as sn,aL as un,cI as rn,cJ as cn,aN as dn,aO as gn,Z as Ct}from"./index-bd4c24ce.js";import{u as we,e as He,g as H,f as gt,h as ce,r as fn,t as Pe,i as pn,s as ft,j as Oe,_ as hn}from"./FileItem-3771a510.js";import{M as Et,c as Mt,m as Xe,b as Je,d as vn,e as mn,f as $n}from"./functionalCallableComp-8b0d9f43.js";import{C as yn,g as bn,t as wn}from"./shortcut-16a42bc1.js";/* empty css */import{_ as _n}from"./index-dfa3dc65.js";import{D as kn}from"./index-afbe1fb8.js";const ve=(...e)=>{document.addEventListener(...e),Ot(()=>document.removeEventListener(...e))};var On={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M464 144H160c-8.8 0-16 7.2-16 16v304c0 8.8 7.2 16 16 16h304c8.8 0 16-7.2 16-16V160c0-8.8-7.2-16-16-16zm-52 268H212V212h200v200zm452-268H560c-8.8 0-16 7.2-16 16v304c0 8.8 7.2 16 16 16h304c8.8 0 16-7.2 16-16V160c0-8.8-7.2-16-16-16zm-52 268H612V212h200v200zM464 544H160c-8.8 0-16 7.2-16 16v304c0 8.8 7.2 16 16 16h304c8.8 0 16-7.2 16-16V560c0-8.8-7.2-16-16-16zm-52 268H212V612h200v200zm452-268H560c-8.8 0-16 7.2-16 16v304c0 8.8 7.2 16 16 16h304c8.8 0 16-7.2 16-16V560c0-8.8-7.2-16-16-16zm-52 268H612V612h200v200z"}}]},name:"appstore",theme:"outlined"};const Ln=On;function pt(e){for(var t=1;t{const e=Array.from(document.querySelectorAll(".ant-image-preview-wrap")).find(t=>t.style.display!=="none");e?(console.log("closeImageFullscreenPreview success"),ta(e)):console.log("closeImageFullscreenPreview not found")};function ta(e){if(!(e instanceof HTMLElement))throw new Error("The provided value is not an HTMLElement.");const t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0,target:e});e.dispatchEvent(t)}const na=(e,t)=>{const n=t.querySelector(`.idx-${e} .ant-image-img`);n?n.click():console.log("openImageFullscreenPreview error: not found",e,t)};function dl(e){const{previewIdx:t,eventEmitter:n,canLoadNext:a,previewing:o,sortedFiles:s,scroller:w,props:x}=we().toRefs(),{state:y}=we();let _=null;const k=(L,g)=>{var r;o.value=L,_!=null&&!L&&g&&((r=w.value)==null||r.scrollToItem(_),_=null)},I=()=>{if(!F("next")){if(e!=null&&e.loadNext)return e.loadNext();x.value.mode==="walk"&&a.value&&(oe.info(j("loadingNextFolder")),n.value.emit("loadNextDir",!0))}};ve("keydown",L=>{var g;if(o.value){let r=t.value;if(["ArrowDown","ArrowRight"].includes(L.key))for(r++;s.value[r]&&!R(s.value[r].name);)r++;else if(["ArrowUp","ArrowLeft"].includes(L.key))for(r--;s.value[r]&&!R(s.value[r].name);)r--;if(R((g=s.value[r])==null?void 0:g.name)??""){t.value=r;const C=w.value;C&&!(r>=C.$_startIndex&&r<=C.$_endIndex)&&(_=r)}I()}});const b=L=>{var r;let g=t.value;if(L==="next")for(g++;s.value[g]&&!R(s.value[g].name);)g++;else if(L==="prev")for(g--;s.value[g]&&!R(s.value[g].name);)g--;if(R((r=s.value[g])==null?void 0:r.name)??""){t.value=g;const C=w.value;C&&!(g>=C.$_startIndex&&g<=C.$_endIndex)&&(_=g)}I()},F=L=>{var r;let g=t.value;if(L==="next")for(g++;s.value[g]&&!R(s.value[g].name);)g++;else if(L==="prev")for(g--;s.value[g]&&!R(s.value[g].name);)g--;return R((r=s.value[g])==null?void 0:r.name)};return He("removeFiles",async()=>{o.value&&!y.sortedFiles[t.value]&&xe()}),{previewIdx:t,onPreviewVisibleChange:k,previewing:o,previewImgMove:b,canPreview:F}}function Ie(e){return typeof e=="function"||Object.prototype.toString.call(e)==="[object Object]"&&!jt(e)}function gl(){const{currLocation:e,sortedFiles:t,currPage:n,multiSelectedIdxs:a,eventEmitter:o,walker:s}=we().toRefs(),w=()=>{a.value=[]};return ve("click",()=>{H.keepMultiSelect||w()}),ve("blur",()=>{H.keepMultiSelect||w()}),he(n,w),{onFileDragStart:(k,I)=>{const b=je(t.value[I]);gt.fileDragging=!0,console.log("onFileDragStart set drag file ",k,I,b);const F=[b];let L=b.type==="dir";if(a.value.includes(I)){const r=a.value.map(C=>t.value[C]);F.push(...r),L=r.some(C=>C.type==="dir")}const g={includeDir:L,loc:e.value||"search-result",path:rt(F,"fullpath").map(r=>r.fullpath),nodes:rt(F,"fullpath"),__id:"FileTransferData"};k.dataTransfer.setData("text/plain",JSON.stringify(g))},onDrop:async k=>{if(s.value)return;const I=Tt(k);if(!I)return;const b=e.value;if(I.loc===b)return;const F=Ge(),L=async()=>F.pushAction(async()=>{await Mt(I.path,b),o.value.emit("refresh"),ye.destroyAll()}),g=()=>F.pushAction(async()=>{await Xe(I.path,b),ce.emit("removeFiles",{paths:I.path,loc:I.loc}),o.value.emit("refresh"),ye.destroyAll()});ye.confirm({title:j("confirm")+"?",width:"60vw",content:()=>{let r,C,D;return u("div",null,[u("div",null,[`${j("moveSelectedFilesTo")} ${b}`,u("ol",{style:{maxHeight:"50vh",overflow:"auto"}},[I.path.map(S=>u("li",null,[S.split(/[/\\]/).pop()]))])]),u(Et,null,null),u("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end"},class:"actions"},[u(pe,{onClick:ye.destroyAll},Ie(r=j("cancel"))?r:{default:()=>[r]}),u(pe,{type:"primary",loading:!F.isIdle,onClick:L},Ie(C=j("copy"))?C:{default:()=>[C]}),u(pe,{type:"primary",loading:!F.isIdle,onClick:g},Ie(D=j("move"))?D:{default:()=>[D]})])])},maskClosable:!0,wrapClassName:"hidden-antd-btns-modal"})},multiSelectedIdxs:a,onFileDragEnd:()=>{gt.fileDragging=!1}}}function fl({openNext:e}){const t=te(!1),n=te(""),{sortedFiles:a,previewIdx:o,multiSelectedIdxs:s,stack:w,currLocation:x,spinning:y,previewing:_,stackViewEl:k,eventEmitter:I,props:b,deletedFiles:F}=we().toRefs(),L=ct;He("removeFiles",({paths:S,loc:l})=>{L(l)!==L(x.value)||!We(w.value)||(S.forEach(p=>F.value.add(p)),S.filter(R).forEach(p=>F.value.add(p.replace(/\.\w+$/,".txt"))))}),He("addFiles",({files:S,loc:l})=>{if(L(l)!==L(x.value))return;const m=We(w.value);m&&m.files.unshift(...S)});const g=Ge(),r=async(S,l,m)=>{o.value=m,H.fullscreenPreviewInitialUrl=fe(l);const p=s.value.indexOf(m);if(S.shiftKey){if(p!==-1)s.value.splice(p,1);else{s.value.push(m),s.value.sort((q,G)=>q-G);const N=s.value[0],J=s.value[s.value.length-1];s.value=fn(N,J+1)}S.stopPropagation()}else S.ctrlKey||S.metaKey?(p!==-1?s.value.splice(p,1):s.value.push(m),S.stopPropagation()):await e(l)},C=async(S,l,m)=>{var se,ee,$e;const p=fe(l),N=x.value,J={IIB_container_id:parent.IIB_container_id},q=()=>{let f=[];return s.value.includes(m)?f=s.value.map(v=>a.value[v]):f.push(l),f},G=async f=>{if(!y.value)try{y.value=!0,await Vt(l.fullpath),Oe.postMessage({...J,event:"click_hidden_button",btnEleId:"iib_hidden_img_update_trigger"}),await Gt(),Oe.postMessage({...J,event:"click_hidden_button",btnEleId:`iib_hidden_tab_${f}`})}catch(v){console.error(v),oe.error("发送图像失败,请携带console的错误消息找开发者")}finally{y.value=!1}},Y=`${S.key}`;if(Y.startsWith("toggle-tag-")){const f=+Y.split("toggle-tag-")[1],{is_remove:v}=await Wt({tag_id:f,img_path:l.fullpath}),U=(ee=(se=H.conf)==null?void 0:se.all_custom_tags.find(T=>T.id===f))==null?void 0:ee.name;await Pe.refreshTags([l.fullpath]),oe.success(j(v?"removedTagFromImage":"addedTagToImage",{tag:U}));return}else if(Y==="add-custom-tag")Je();else if(Y.startsWith("batch-add-tag-")||Y.startsWith("batch-remove-tag-")){const f=+Y.split("-tag-")[1],v=Y.includes("add")?"add":"remove",U=q().map(T=>T.fullpath);await qt({tag_id:f,img_paths:U,action:v}),await Pe.refreshTags(U),oe.success(j(v==="add"?"addCompleted":"removeCompleted"));return}else if(Y.startsWith("copy-to-")){const f=Y.split("copy-to-")[1],v=q(),U=v.map(T=>T.fullpath);await Mt(U,f,!0),ce.emit("addFiles",{files:v,loc:f}),oe.success(j("copySuccess"));return}else if(Y.startsWith("move-to-")){const f=Y.split("move-to-")[1],v=q(),U=v.map(T=>T.fullpath);await Xe(U,f,!0),ce.emit("removeFiles",{paths:U,loc:x.value}),ce.emit("addFiles",{files:v,loc:f}),oe.success(j("moveSuccess"));return}switch(S.key){case"previewInNewWindow":return window.open(p);case"copyFilePath":return de(l.fullpath);case"saveSelectedAsJson":return Jt(q());case"openWithDefaultApp":return Xt(l.fullpath);case"download":{const f=q();Ht(f.map(v=>fe(v,!0)));break}case"copyPreviewUrl":return de(parent.document.location.origin+p);case"rename":{let f=await vn(l.fullpath);f=ct(f);const v=Pe.tagMap;v.set(f,v.get(l.fullpath)??[]),v.delete(l.fullpath),l.fullpath=f,l.name=f.split(/[\\/]/).pop()??"";return}case"send2txt2img":return G("txt2img");case"send2img2img":return G("img2img");case"send2inpaint":return G("inpaint");case"send2extras":return G("extras");case"send2savedDir":{const f=H.quickMovePaths.find(T=>T.key==="outdir_save");if(!f)return oe.error(j("unknownSavedDir"));const v=Nt(f.dir,($e=H.conf)==null?void 0:$e.sd_cwd),U=q();await Xe(U.map(T=>T.fullpath),v,!0),ce.emit("removeFiles",{paths:U.map(T=>T.fullpath),loc:x.value}),ce.emit("addFiles",{files:U,loc:v});break}case"send2controlnet-img2img":case"send2controlnet-txt2img":{const f=S.key.split("-")[1];Oe.postMessage({...J,event:"send_to_control_net",type:f,url:fe(l)});break}case"send2outpaint":{n.value=await g.pushAction(()=>qe(l.fullpath)).res;const[f,v]=(n.value||"").split(` +`);Oe.postMessage({...J,event:"send_to_outpaint",url:fe(l),prompt:f,negPrompt:v.slice(17)});break}case"openWithWalkMode":{ft.set(N,w.value);const f=H.tabList[b.value.tabIdx],v={type:"local",key:_e(),path:l.fullpath,name:j("local"),stackKey:N,mode:"walk"};f.panes.push(v),f.key=v.key;break}case"openFileLocationInNewTab":case"openInNewTab":{const f=H.tabList[b.value.tabIdx],v={type:"local",key:_e(),path:S.key==="openInNewTab"?l.fullpath:Bt(l.fullpath),name:j("local"),mode:"scanned-fixed"};f.panes.push(v),f.key=v.key;break}case"openOnTheRight":{ft.set(N,w.value);let f=H.tabList[b.value.tabIdx+1];f||(f={panes:[],key:"",id:_e()},H.tabList[b.value.tabIdx+1]=f);const v={type:"local",key:_e(),path:l.fullpath,name:j("local"),stackKey:N};f.panes.push(v),f.key=v.key;break}case"send2BatchDownload":{pn.addFiles(q());break}case"viewGenInfo":{t.value=!0,n.value=await g.pushAction(()=>qe(l.fullpath)).res;break}case"openWithLocalFileBrowser":{await Ut(l.fullpath);break}case"deleteFiles":{const f=q(),v=async()=>{const U=f.map(T=>T.fullpath);if(await mn(U),oe.success(j("deleteSuccess")),_.value){const T=fe(l)===H.fullscreenPreviewInitialUrl,ge=o.value===a.value.length-1;if((T||ge)&&(xe(),await Ue(100),T&&a.value.length>1)){const Ee=o.value;Ue(0).then(()=>na(Ee,k.value))}}ce.emit("removeFiles",{paths:U,loc:x.value})};if(f.length===1&&H.ignoredConfirmActions.deleteOneOnly)return v();await new Promise(U=>{ye.confirm({title:j("confirmDelete"),maskClosable:!0,width:"60vw",content:()=>u("div",null,[u("ol",{style:{maxHeight:"50vh",overflow:"auto"}},[f.map(T=>u("li",null,[T.fullpath.split(/[/\\]/).pop()]))]),u(Et,null,null),u(yn,{checked:H.ignoredConfirmActions.deleteOneOnly,"onUpdate:checked":T=>H.ignoredConfirmActions.deleteOneOnly=T},{default:()=>[j("deleteOneOnlySkipConfirm"),A(" ("),j("resetOnGlobalSettingsPage"),A(")")]})]),async onOk(){await v(),U()}})});break}}return{}},{isOutside:D}=Lt(k);return ve("keydown",S=>{var m,p,N;const l=bn(S);if(_.value){l==="Esc"&&xe();const J=(m=Object.entries(H.shortcut).find(q=>q[1]===l&&q[1]))==null?void 0:m[0];if(J){S.stopPropagation(),S.preventDefault();const q=o.value,G=a.value[q];switch(J){case"delete":return C({key:"deleteFiles"},G,q);case"download":return C({key:"download"},G,q);default:{const Y=(p=/^toggle_tag_(.*)$/.exec(J))==null?void 0:p[1],se=(N=H.conf)==null?void 0:N.all_custom_tags.find(ee=>ee.name===Y);if(se)return C({key:`toggle-tag-${se.id}`},G,q);if(J.startsWith("copy_to_")){const ee=J.split("copy_to_")[1];return C({key:`copy-to-${ee}`},G,q)}if(J.startsWith("move_to_")){const ee=J.split("move_to_")[1];return C({key:`move-to-${ee}`},G,q)}}}}}else!D.value&&["Ctrl + KeyA","Cmd + KeyA"].includes(l)&&(S.preventDefault(),S.stopPropagation(),I.value.emit("selectAll"))}),{onFileItemClick:r,onContextMenuClick:C,showGenInfo:t,imageGenInfo:n,q:g}}const Ae=new Map,pl=()=>{const{useEventListen:e,sortedFiles:t,getViewableAreaFiles:n}=we().toRefs(),a=te(H.defaultChangeIndchecked),o=te(H.defaultSeedChangeChecked),s=async()=>{if(await Ue(100),!a.value)return;const y=n.value().filter(k=>R(k.fullpath)&&!k.gen_info_obj);if(!y.length)return;const _=await Yt(y.map(k=>k.fullpath).filter(k=>!Ae.has(k)));y.forEach(k=>{const I=_[k.fullpath]||Ae.get(k.fullpath)||"";Ae.set(k.fullpath,I),k.gen_info_obj=Be(I),k.gen_info_raw=I})};e.value("viewableAreaFilesChange",s);const w=y=>{const _=t.value;return[y,o.value,_[y-1],_[y],_[y+1]]};function x(y,_,k,I){const b={diff:{},empty:!0,ownFile:"",otherFile:""};if(_+k<0||_+k>=t.value.length||t.value[_]==null||!("gen_info_obj"in t.value[_])||!("gen_info_obj"in t.value[_+k]))return b;const F=y,L=t.value[_+k].gen_info_obj;if(L==null)return b;const g=["hashes","resources"];b.diff={},b.ownFile=I.name,b.otherFile=t.value[_+k].name,b.empty=!1,o.value||g.push("seed");for(const r in F)if(!g.includes(r)){if(!(r in L)){b.diff[r]="+";continue}if(F[r]!=L[r])if(r.includes("rompt")&&F[r]!=""&&L[r]!=""){const C=F[r].split(","),D=L[r].split(",");let S=0;for(const l in C)C[l]!=D[l]&&S++;b.diff[r]=S}else b.diff[r]=[F[r],L[r]]}return b}return{getGenDiff:x,changeIndchecked:a,seedChangeChecked:o,getRawGenParams:()=>s(),getGenDiffWatchDep:w}};function aa(e,t,n,a){let o=0,s=0,w=typeof(a==null?void 0:a.width)=="number"?a.width:0,x=typeof(a==null?void 0:a.height)=="number"?a.height:0,y=typeof(a==null?void 0:a.left)=="number"?a.left:0,_=typeof(a==null?void 0:a.top)=="number"?a.top:0,k=!1;const I=l=>{l.stopPropagation(),l.preventDefault(),!(!e.value||!t.value)&&(o=l instanceof MouseEvent?l.clientX:l.touches[0].clientX,s=l instanceof MouseEvent?l.clientY:l.touches[0].clientY,w=e.value.offsetWidth,x=e.value.offsetHeight,t.value.offsetLeft,t.value.offsetTop,document.documentElement.addEventListener("mousemove",b),document.documentElement.addEventListener("touchmove",b),document.documentElement.addEventListener("mouseup",F),document.documentElement.addEventListener("touchend",F))},b=l=>{if(!e.value||!t.value)return;let m=w+((l instanceof MouseEvent?l.clientX:l.touches[0].clientX)-o),p=x+((l instanceof MouseEvent?l.clientY:l.touches[0].clientY)-s);e.value.offsetLeft+m>window.innerWidth&&(m=window.innerWidth-e.value.offsetLeft),e.value.offsetTop+p>window.innerHeight&&(p=window.innerHeight-e.value.offsetTop),e.value.style.width=`${m}px`,e.value.style.height=`${p}px`,a!=null&&a.onResize&&a.onResize(m,p)},F=()=>{document.documentElement.removeEventListener("mousemove",b),document.documentElement.removeEventListener("touchmove",b),document.documentElement.removeEventListener("mouseup",F),document.documentElement.removeEventListener("touchend",F)},L=l=>{l.stopPropagation(),l.preventDefault(),!(!e.value||!n.value)&&(k=!0,y=e.value.offsetLeft,_=e.value.offsetTop,o=l instanceof MouseEvent?l.clientX:l.touches[0].clientX,s=l instanceof MouseEvent?l.clientY:l.touches[0].clientY,document.documentElement.addEventListener("mousemove",g),document.documentElement.addEventListener("touchmove",g),document.documentElement.addEventListener("mouseup",r),document.documentElement.addEventListener("touchend",r))},g=l=>{if(!e.value||!n.value||!k)return;const m=y+((l instanceof MouseEvent?l.clientX:l.touches[0].clientX)-o),p=_+((l instanceof MouseEvent?l.clientY:l.touches[0].clientY)-s);m<0?e.value.style.left="0px":m+e.value.offsetWidth>window.innerWidth?e.value.style.left=`${window.innerWidth-e.value.offsetWidth}px`:e.value.style.left=`${m}px`,p<0?e.value.style.top="0px":p+e.value.offsetHeight>window.innerHeight?e.value.style.top=`${window.innerHeight-e.value.offsetHeight}px`:e.value.style.top=`${p}px`,a!=null&&a.onDrag&&a.onDrag(m,p)},r=()=>{k=!1,document.documentElement.removeEventListener("mousemove",g),document.documentElement.removeEventListener("touchmove",g),document.documentElement.removeEventListener("mouseup",r),document.documentElement.removeEventListener("touchend",r)},C=()=>{if(!e.value||!t.value)return;let l=e.value.offsetLeft,m=e.value.offsetTop,p=e.value.offsetWidth,N=e.value.offsetHeight;l+p>window.innerWidth&&(l=window.innerWidth-p,l<0&&(l=0,p=window.innerWidth)),m+N>window.innerHeight&&(m=window.innerHeight-N,m<0&&(m=0,N=window.innerHeight)),e.value.style.left=`${l}px`,e.value.style.top=`${m}px`,e.value.style.width=`${p}px`,e.value.style.height=`${N}px`},D=()=>{!e.value||!a||(typeof a.width=="number"&&(e.value.style.width=`${a.width}px`),typeof a.height=="number"&&(e.value.style.height=`${a.height}px`),typeof a.left=="number"&&(e.value.style.left=`${a.left}px`),typeof a.top=="number"&&(e.value.style.top=`${a.top}px`),C(),window.addEventListener("resize",C))},S=()=>{document.documentElement.removeEventListener("mousemove",b),document.documentElement.removeEventListener("touchmove",b),document.documentElement.removeEventListener("mouseup",F),document.documentElement.removeEventListener("touchend",F),document.documentElement.removeEventListener("mousemove",g),document.documentElement.removeEventListener("touchmove",g),document.documentElement.removeEventListener("mouseup",r),document.documentElement.removeEventListener("touchend",r),window.removeEventListener("resize",C)};return zt(D),Ot(S),he(()=>a==null?void 0:a.disbaled,async l=>{await Zt(),l!==void 0&&(l?S():D())}),he(()=>[e.value,t.value,n.value],([l,m,p])=>{l&&m&&(m.addEventListener("mousedown",I),m.addEventListener("touchstart",I)),l&&p&&(p.addEventListener("mousedown",L),p.addEventListener("touchstart",L))}),{handleResizeMouseDown:I,handleDragMouseDown:L}}let _t=null;const la=()=>{var y,_;const e=Ye(),t=be(Ne+"fullscreen_layout",{enable:!1,panelWidth:384,alwaysOn:!0}),n=Kt(_t??((_=(y=e.conf)==null?void 0:y.app_fe_setting)==null?void 0:_.fullscreen_layout)??je(t.value)),a="--iib-lr-layout-info-panel-width",o=Q(()=>n.alwaysOn&&n.enable?n.panelWidth:0);he(n,k=>{t.value=je(k),kt(n,a,o),oa(n),_t=n},{deep:!0}),zt(()=>kt(n,a,o));const{enable:s,panelWidth:w,alwaysOn:x}=Qt(n);return{state:n,isLeftRightLayout:s,panelwidtrhStyleVarName:a,lrLayoutInfoPanelWidth:w,lrMenuAlwaysOn:x}},oa=ze(e=>Rt("fullscreen_layout",e),300),kt=ze((e,t,n)=>{e.enable?(document.body.classList.add("fullscreen-lr-layout"),document.documentElement.style.setProperty(t,`${e.panelWidth}px`),document.documentElement.style.setProperty("--iib-lr-layout-container-offset",`${n.value}px`)):(document.documentElement.style.removeProperty(t),document.documentElement.style.removeProperty("--iib-lr-layout-container-offset"),document.body.classList.remove("fullscreen-lr-layout"))},300);/*! +author:kooboy_li@163.com +MIT licensed +*/let St=19968,ia=(40896-St)/2,Ve="",Le=",",sa=(()=>{let e=[];for(let t=33;t<127;t++)t!=34&&t!=92&&t!=45&&e.push(String.fromCharCode(t));return e.join(Ve)})(),lt={a:{yi:"!]#R$!$q(3(p)[*2*g+6+d.C.q0[0w1L2<717l8B8E9?:8;V;[;e;{<)<+.>4??@~A`BbC:CGC^CiDMDjDkF!H/H;JaL?M.M2MoNCN|OgO|P$P)PBPyQ~R%R.S.T;Tk^l$lt?uJv$vMyE|R}a-!}-#&-#8-#L-#b-$Q-%?-+q-,6-,8",yu:"#V$l%S&9&I('(7(=)))m*#*$*B+2+F+v,0,b,i.W0.1F232L2a3(384>6P8n;';i;y<1>(>)>]@iB&X&m&s'2'X'd'f(9(c(i(j)@)l+'+M.).+1y1{2=3K4c6&6'6)606<6B6`9`9{:a`?`AgCLCuD%D2F2GyH&H1I;K~LkLuM&MYO0O3O9P8PbPcQqR5S2SCU0U~V%XYY&Z}[G^P`7cUc}dEeNgOj$j)l?m:n4p,sOuRv.y'{/|i}1~P-$B-%Y-)|-)}-*K-+G-+H-,m-.@-.M-/|-0y-2D-2c-4W-4`-4h-7a-7p-9c-9i",shang:")Y6V9cJvR8UqXJXa])asbQc,s,uSvz-#+-.;",xia:"#Y#w&,&;'''I)1.u/j7=:[<'B[ByCtL'NmNyQOR([0`(cLh[iRkVt/t_u4uezFzM|W|{~d-&)-*4-.}-0a-5;-8S",han:"#,.m/h:l

MFrGXJqNrOUPCPqPrQ|]@`+`2h1lBlZnXp*r;rWrkz9{4{B}x-#c-#y-$;-$l-$y-%Q-%n-(i-(x-)i-/!-3*-5B-9V",wan:"#=$0&o.]0F4@5X5b6*628u9pk@,JhR`b$b`knmtujz'z0}<-#+-'I-*Q-16-7m",san:"3T3q3w3x7~uJuwzA-'n-([-,s",ji:"#r%''l'y)3)d)o*Z+'+9+G+M+T+Z+^+g+x._.c/R090d1S1W2;43484J4R5C5w6)6C6`7f7s878H8t8w9J9X9Z9{;8;<;B;C=(=2>6?YA$B+CHD0D8DbE:EQF2I*I|JEJnKKL)L:LkLzMdN'N5N:NiQ6QyRrUWVcVnWPWQWtX6XEXYXuY(ZAZ|[/]O]e^F^J^U^~`)b#b0c*ckc}dee!e$e9e>eyf+fXfrg)hFhriMjZlrqmr)sRt%uov3vevw|@};}N}g~!~+~F~{-!&-!u-#N-$%-&a-'u-(,-*x-+]-,W-.?-.V-._-.d-.g-/+-0$-0H-1%-1/-10-1^-1o-2/-2@-3'-4)-4o-5>-5H-5U-6,-6J-7/-7P-9e-9g-9h-9i-9j-:l",bu:"0$192,FKJgT=UYZ^e+hhjmm8mFoGpGp}sjw]w{-'7-'E-/m-3#-4.-6=",fou:"4I:L:O:Q~1-3:",mian:"!G!d#4$U$W$]3Y5X6A6_6o9g9w@qB/CkG!H_Q;-!L-!M-!P-/_-7y-7z-8'-8,-8q-8r",gai:"):5=5LD,ErI!J1Z'_/`TaYaac!lnpcw[|O}1",chou:"!+#n$N+0/y0}2:4e5/6#9jB*B.GNLfUmZ+^3^5_4e%e4fWkan]nbo.o6oU}u~$~*-.X-/>",zhuan:"%H'S'V.K0k1B1H1r2?7Z+7+f,8.#.|0K0p2O>#DNE1P.ccd]eMlpt8y>-0&",ju:"!Z$L$w%R*W,c,l/e1~3&3J8#:t=#=`=k@FBGC0DlD}FeGAIaIkJbMrN[OVP`RDTlU|W>Y`[$^Z`Ua*ccc{dWd]dae#e@eFeff8fSg*ga@'@2@KA%C|DQO+O]O^PvR!REScU'UfZw]m`l`na'i[l_m;p-4F-6'-63-91",shi:"!E!Q!e#?$p%$&+'$([(](q*^.&/5/n0[1w204zQQR9VYW2W@W^X2XNYxY{ZI[:[<[v]X^l^{^}_p`DaDbmgqi8ixjdk!kNkpl(lkntoMo^ocoeofp5ppq%q&q*q4qbr=t9x/-&^-&_-&}-'<-'@-(*-(8-)!-)H-+,-/<-0?-0d-0o-0p-2:-2O-3+-38-57-6M-9C-9E",qiu:"*6*7+a0r3k4D5]6j>7CaCeF`HEJXMhNgNjONP;QMQ_RfSWUUX?XUXqXrajc$d'jpjskXl]n@o.oup:r?-#5-#6-$8-/'-/k-0W-0X-1,-2Z-4v-7&-9U-:Y-:Z-:]",bing:"!n)F*4+/,>.75@DsOcZ7l`puqar||>-!:-!q-#,-#G-''-'C-(D-/O",ye:"$>$E(0,a6g=;@?HfSb[]_]lUlfn(oip=rmtDtTtevTx?-!O-!R-$5-%N-'F-'e-(T-*o-4Y-61",cong:"$'&Y1>8==g=l=p=vDIE=I2JUK0LsRZZk]$a}a~sKtBuKu_-*)-*V-+Y",dong:"&&.r0b5D?7?C@JD|G;I#KwQ([&jV~^-)T-/=-0)-4g-5/-6T-9,",si:"'?(b)^)g)p*+.+>0KxL+NLP7PiQnReS&W_`tp1pvp{qTqnr8r`tIuzyB-&6-&R-&^-&c-&s-&{-(:-)L-)q-*8-+.-0.-5j-6`-9N-:o",cheng:"#0$,$P&W*O*[*w+A+{,O,v/l5[7#:`?}FQOoS(UKZV_#cHcJk#m$nhrxtkuxv@vWx=xB|2-!A-$h-'w-)o-*>-+B-/u",diu:"r2xL-&&",liang:"3A3D3{6K@0CRF{Q%Up[,_Oe1h!h2hCiBiHojss-!=-)h-.J-.O",you:"(r)O*I7o8W;L;f=5=M>VDKFoFsFwG/KaOOOSPSQLY8ZN_;`qh%hMjWjnk6kPlYmEn3n>ncodp~r3x&x<-),-.y-/1-1p-1z-7N-8P-9D",yan:"##%F%L&%&F&T&v(Z,j/u1?2$5t7V;!;h?<@@AsCVCYCZD3FmGpH.JlN_PVQAT$UxV9WUX/XkXmXnY?Z3[U^1^C^E_e_~`B`C`RbDbPc;g/g7kIm#mNmsn5nHnsnyoPoVo`x+z7zkzmzn{A{`{e|}}2}b-%'-%,-%B-%v-'0-(#-)~-*$-*F-*j-*s-+C-.4-.H-.Y-0V-3$-3*-3B-3n-5#-5G-5u-7K-7r-8T-8W-8_-8`-8a-8d-8j-9L-9Q-9w-:1-:N",sang:"'EVNts-%2-%{",gun:"#<&#'U6F6z9dJ>JpTFTwUu]4h:?B@}AbB3BwECHxJ1NwOrP'U9UPXM[X[hhLhmq`tetlu.xSyUzTzU{W}4-!S-!s-#F-#`-#j-%f-(A-*%-+t-.3-/K-/U-1u-3T-3z-6g",ya:"#B%C&{'I*{,a.g=UDEKqO;T1WEWGY.^[g=i!j4lUp=s=v7x;}f-3C-3c-4U-6O-6V-9o-:;",pan:"!&!>!?!H!o'L'x2A76=F>R?$AIH+m/V2T4{6b99>j@`BnEkK*O:OBP^R2RKSzTKTNTO[@e^f>ohparHtQv5wbyF-3_-9@",jie:"#S%@&{(.*d+=.G0e4J5,599D;k=(@/CfD,G#G`J[LzOFP&P:PTQ=SKSQSqT/TITPTlU4U7UPVQXOXSX}Z%ZWZh]/^K^~_5ckdve=j^qGtNtXz,|1}.-!m-!u-$U-%c-&v-+i-.l-/@-2&-4{-5$",feng:"!@%N'40m5v7R:3C$FdHnN.PFSaWI[R^c`?b.c5k'n+n;r[u5uXxs-!$-!4-&%-&J-&L-(w-3(-3,-3F-8)",guan:"!'$b$j$k(W)B,Y/f0E6:9&:]:gBVFqIEWSW{X+X.a?bifMh?kmsUu>w7zOzS{,{2}{-'K-(N-0q-1N-1j-2e-2z-6D-7A",kuang:"!Y!z$Y%1%r%w(G+}/O/z5'538V8vZ-8>",chuan:",40jA7BYB`BhBxEvale[hIkJp%wQ-5+",chan:"&6'W)K)q1N6D7$8*8A8[8_:6;xCODJIHKQQ2RGR_R{S1UeW!W`X3ZMZy]B^+^7_N_bfbi|n2n6o@rTr]uWw3xYz%ze{7{g-#Q-%D-%~-(%-(S-+Z",lin:"$B&['t0:393O5{8!S]SrU;VsD5E4GTO$WNYk`LdDdNgjozp?wr~~-!a-&.-.D-.`-/&-/0-1t-1v-1}-9=",dan:"!K%$%5)r,S0N1h4V8A=A=B=H=~>q@9ATAVH*JDOkPUTLV?VoXGX~ZK_'a|bBc3f{mHn&nKn~~t-$I-'G-'s-)*-)a-,C-3Z-8H-8b-8i",wei:"#o$M%}&0'#'D'M6/6p6r7+8y9f;6>n@gC+D!DOE+FCGBH)I&I(I4INJ]K$KJL7LdMDN0PwQ$QDQHR?T3T6V`WkX$Z)[#[^^*^4_I_^e;fefig@hbj>kg?:?k@N?#@!@D@E@nA3C!CWC}D*DFE'E,E]EpFFF|GKHKHjJXKsNSODOGOXOwPIPMQEQIQWTETsTvU.V(V6ViW+WKWMXpYS[C^H`Va4a{b4bXc(c7cRd=dZegh*hPhRiAiLlIm(m*mmnQowo|pFqZYZZ]U_6_9d9fYj6j~lWm)mep)rQrbrctvwkxc{y|U}6~?~C~`~m-!Z-*'-+R-/j-0j-3i-4/-4@-5,-5f-6j-6s-7)-9G-9W-9X",tuo:"%U%V&z0L2J4v?{@$F_H6MUTbT~Y'Yc^QdHdQnVq+r`x1{{|;|<-&d-(.-(z-({-)1-)J-)K-*:-*e-*p-+$-+3-.b-/%-/[-0b-3O-4,-6_-8}-9$-9?",zhe:"#'%+%E'P2f2|_@eB>CADvFAI0I>J:L]M:M~TgWHWfY/Ya[|[}^6_ngmi6k`kll*l9r!tdwhxRzv}!-!j-%=-&9-&T-'(-'=-*&-0u-1I-2f-3;-3]-5F-5Y-7+-9T-:%",zhi:"!7!t$s%=(J(i(k(s(y)2)I)Z*2*>*A*T*^*c+(+)+J+Y,G/k4Q4b5T5W5s6~7^7|9(98;(<0=E=Q=b=}>L>|?+?QA4^4g=0D{OPOZX]Yb[(]G]W^ng=o;t*xHzI{N~J-&t-/9-/a-1{-22-9]-9`",hu:"(1(~.j0Z1M3!3^545r757G?0AMCtCxD5C_{u-$*-'1-(A-1!-1d-2i",yue:"$S%!(a){0^0|242S2_373H4<8sAlM{O,O.ZaZc_>cid2dCdFfZgApDqBw2whw}zczd{[-,V-6:-6B-8Y-:^-:m",lao:"&)'n,71s3<5>9M~CXE%F$H(JWMaOQP%Yg^jgrh>mAqa-$^-(w-/(-1w",pang:"!o'A1+=/>R?$?=A/B|QmWsd@jf~6~|-0k-2g-:K-:M",guai:"0,;%",sheng:"!D!^...t7*7q859e=[=x?*E(KM]^aMb1q2t2|#|Y|u-4_-9B",hao:"*:.,25-%|-0i",mie:"!`(D1G1dJxL>SNS~W]vt-1e-3M",nie:"1&294(4,=G=|B)B0E!GDMlSX^=e)e?eAezforAs$sJu*vfw9wByVyY{&|c}(-%L-%x-:#",xi:"!>#6$3$d%/&(&g'J's(!)P)n*l+7,,,n313z434i5j6H7?7W81878g979U;V;n<2<5<6>c>d@>A6BABBB}FUG]HeI9IbIwJ+JVKzL2NdPjQoQqRYRqSiT!U)UzW9WFWiWlX7XfXjXlZH[K[m]5]F_@`.`/`W`_a(cCcGcfcwesf)fulGlplwm&m4m_n:oIokp2p7pbqLqMqvsYu+ufv&w6wSxJy,z[{5{b}9}?}P}U~#~2~q-!%-&?-'2-'`-'r-(1-(C-*C-*O-*{-.)-/x-0_-1+-1J-2X-2q-46-6*-8I-9O",xiang:"!;)*+50U5Q6Y8b9u:U;E;J<4APC{HGHvLTaU4UI`]a$a]bxdRjGl{m/q#qOrXu,x$x>y`-$a-$e-%c-%d-)B-+5-3J-3q-4(-7i",mao:"!M#i$i*:/66e:uqcsVx,y%-,B-,O-4|",mai:"?W?XF>K^LgS{aKaxj(l+~g~h-!'-5{-7t-7u",luan:";D?dAzA{L=NDW~o{r7w@-4'-6G-6h-:y",ru:"/M7F8G:1>AEgIYJ6KlLhQJSHU:VGW,inlEm`oSr+x_-%E-&!-1]-3)-3K-3x",xue:"$?,(A=C@E@IGLKStTnXd[p_[coe,hdibig~/-!_-#M-18-2k-6%-6^",sha:"%4&G052u4O8F8~<<WIYIuTJU!Zt`m`pgNlNlypHu7wcyZ~0-!d-.x",qian:"'K.(/~0A0t1'2*2D2R2p6+7[8J8q:G;h>b@vA~CnD(EIElF:I%IjK>KLNNO&O8P}VR[*[u]u_q`!`&gSh;i~kjk~p9pEpOq;q?r6sPtYukvqwPwgwtwvx+{x-#U-$z-*+-*/-*=-+U-,y-,z-0x-37-4M-6z-8G-8M",suo:"#*1Z1^4Z797U:?;cFaFbJ7P{VJcuk)tatju3u9xi-/b",gan:"!3%)*1*t.Y/x1*1}3%4s91>GCmE#T>Y^bJbTcAcTcti}nE-+e-.Q-1T-2w-3*-:i",gui:"!q#o$.$C%x%})0)s,E/?1K1T?NERJ;N%P/R*RpUgEi#lilxuyvlzY{P|M~#-#K-*;-.7-.:-.=-/S-1F-1U-2%-2r-34-:Y-:]",jue:"$Z$l$o%6,%525S8#9NA^D=KiKtNnO6RwRxU!WWWbX%X5X>XBXZXiY4Zj]N^f_}a0c[chd7h7x8D9V:4AQCyFOFPNxV}Zm]c_QazkFkHl.uqv!vF}*}/}G}H}w-#$-#r-+|-,/",gen:"CQEHdc",xie:"';(f*&3c4k5+595I5h6g6v7&8>8T92:B:M<3>l?T?V?ZA&LRLTM0Q7QKS+S@SBStTRV*V^W4XKXOXS[B[y^<_Z_mflfnl,lU-!i-!v-#1-#D-#h-$#-%c-/S-2%-9Z-9q-9t-9~-:b",zhai:"%X)3,92qP*Q,Znh5iGj+jM-.N",kang:"%<+U2v3tg1lJpgugwmz={L-17",da:"!W.u/(/S84;H=Xs]Q]fa`d0dhe3gvh_hfi;i?lvnkoHo]p#q]v*xW-'%-(B-*h-+;-/Q-1>-20-3|-5k-5s-78-:a",hai:"5L?Aj9l/lnnro<-'!-'~-)Z-)b-+>-+p",heng:"?J?mMZT9vc-3o-4$-6e",peng:"%c&'&S'+'Z+,.V1+1@5@8P>~AACgE%FdJRMkRiRjU3eSgbh:s9v{zL-$+-$0-):-*A-,X-,b-,q-4K-6y",mu:"!1#N%]+V7`7n:@?.C5DeF~G%O=e/qKqPx!~3~G-#9",ting:"/s5l%>&?qC)FnI7PWQ8ZJ[El=rUxKz`~K-!~-$g-%e-9F",qin:"$j$k*'*Q.d5c=>>MD1DAGZG^GkMRO8Q}RJS7TVWJWrZQc]pXpkriwix{}c-!]-$~-)f-+E-/c-33-4L",qing:"&/&Z'i046+60:ZDaHzQ#Wr[%]%_Agph+i7m;>t?fA!BuC,DrGWH=I'J{L4MmO^U+U,U6VrW5ZL[d]Rd8d_eKf@m3pxq5qFrVtow0wxw|x(yT-'4-'^-(E-(V-(d-(g-).-)[-*^-+)-+~-,$-/0-1=-1}-42-6k",lian:"'K+D2+2P2V6w7b8k94;s{M-#!",ren:"(o*,*e+#4A4U5)5y8x9$>?@AD)E}FGGDTUU2Y!ZC^I^Vg&gFi&p/p;pRqp-!W-![-#[-#w-&i-'#-(2-.^-3{",shen:"!U![$8$r$u%j)#)9,12e2g3T3U3q3w4l96:p:~>i>m?t@BFkHwH}JGK!LCPGPHUNX)Y1YHZ*[2^)_%_L_S_VfylPqRrj-$W-)W-.m-/z-0@-0|-1)-2N-4A-8b",ze:"#R#}$n(+*p/,0J1I=0BsKAS?Vz[(].a@b7b]c:jO-&t-6.-9s-:,",jin:"!#$j$k%M)8)G.U.m/J4W4`6L70:/B6F&F;GcGkJYM!TWW%WzXsTwGy2-!^-'m-(Y-)$-7D-88-::",pu:"$5*k+j0$8LBTBUFXGGGaH~IsIt[D]]_|bEfInprtupv=xbyqyu|[-/m",reng:"(_DGiu|z",zong:"&Y'h+?3P3]4$5z6E6Q6n6x7(7M7X7e7t9%9nz?!?MB'CwE5E7ENE`F4GHHuJbL;NsXHYOYP[I_caFa[bzb~cZcpd(h3hQiJmbp&pmsGtRtuy=yO-$s-$t-,I-/{-0r-2P-4e-9)-9f-9i-9u-:D",zai:"#^7HGHb+g|i9n^",ta:"(d)i2~VAZr]wdBe7etfFfOfpkdkiq+sBt]tex1{'{5{;{={R{o-!s-#*-#B-/?-0t-2d",xian:"!:!O#5$<&#(F(h)X*3+D/D0V2k3B4%4|5A5c5t6,6]7J7r8Z8c8q90:%;];d;h?&@oAnA~B;BvDSDwFzG,LOM'M*MpOKO_O}PJT+T0V_W:WRX,ZXZo[O]d`>awbKb^cYdgd}f;fhgBhHnfo'oPqvr#r$rFrqs0o334=4P4f5i8o8{;z*]+m.?/Q/i345D5N5`9PA@EjJPO1T,Z,cFj|ndq:qYqjxC-')-/L-2*",dai:"0,1n4x7%9AC?OMQ]TdW=Yd^xa7aLbqdff'gCgLg[i%jIk4p0~z-!0-)E-/>-3I-8N-8e",ling:"%d)D*M++.5/+4p6@9];K;U<.=KBqD[GiJJJmL%M|OiT(TcUjYVdLgZh/n8oWpts0x)zN|q~;~O~]~a~c-!2-$L-%`-)C-/$-05-2C-3L-6Y-7E-7q-9z-9{-:A-:T",chao:"!k,h,r2u6?9b;5J@mA+DTGMH!UlUqZfs&sWy+z'z(z0zh{1{a-#d-.0-02-1X-2H-2T-92-:d",sa:"8g?^HDK{LYY@fnpQuwwS}A-!c-!s-&,-&P-)&",fan:"%0(M/1/40i2A2d6R7i8$;o<[AIBcBfE0KNLPM>N!SOVqXva=bcfXo:-+g",wo:"#l&A,R,_6}>I@OAlB!G*HQLgP[Qbe:-(p-:4-:I-:L",jian:"!%#9#`$<$D$I&N&b','r'}(&(<(X+D.p/9/g0#0/0Q181k262I3_5U6Z788(899v:9$>S@fB4BoCICSCTETE~G-#O-#X-'A-'S-(7-(k-,h-0Y-0`-0h-1(-28-2h-37-40-4R-5@-71-7F-7I-7J-7W",fen:"#|%A*9./2x3=3r4S9';M;q;~ARD4IxKmO?O@TGY,`^`ff|hjnOpUvY}K~5-'W-'}-(c-(r-.w-1M-2Q-35-85-8n-9.-9:",bin:"%A8I::A)AiNc`X`cahailKvjya~l-$p-%G-%k-,'-,1-,E-,_-,p-.!",di:"!u#/%W')'.'{)<)_*U.v/*1=2c4+6c:);X;@WDXD_FMG9G_ICJMJrJwJ|M6Q+QVR-0>-69",fang:"!I!n(l4Y9*>TBjD;O!Y;^ed@lLp@siwn|,-,?-.v-1s-3E-51",pei:">Q?(JBSwUrUsauc2hyiPnBn{s5y7|%|f~M-)#",diao:"$#&a,C,k.B1]5FJML|NhOaXxZ8Zv_M`ro~p_r!r:s*s[vawUxExR}v~D-.c-//-0%-2L-2{-3&-4O-9>",dun:"!^?gD'G!O'O(R/RO`ahShWiNu6zlzqzw{<{D{Q{c~4-#?-#{-%(-'f-)(-)4-.r-0g-0z-2V-36-3G-9<",xin:"!=(F?zBID7FkLZSyVtY3Y-%T-%U-*[-,w-.G-.W-1_",tang:"$f'@)f0{3V3j3o;l=)@zA4J4LJQSR$RAcMc~eef&g+m]o=tiu)uTv'wDx[yWyd{1}:-#I-']-'h-5:-96",huo:"!V$S$^(*)>)S*Y*_*`+|,W10=$=4AuCJG.IhMTSI[g`0a:4<%<@?R?U@.AEANAhG{THVmd#uQ}Y-$|",che:"$;%I&?&@=JFjP@gFA}EKFRFcK:LmRBTDW6Y7Zz[Q[o^;_V`$arb;c`cad>dKeagKimjHmDo@pAt(|C|o~H-5T-7]-9l-9m-:=",xun:"!x$Q*p,^4;8MAjEnF:KLKSL[LaMcRzS%XwY#Y)Yt^R^T_+j%jajlkclsmzoTv`-%A-(}-)U-+%-1?-1H-24-5A",chi:"!]!y$).X.y/A0+02133,5W<#<$>?2?D@SE9E|GeO%OHORR;U/U0UkVMYFZ9Zq[t`8aRcBc^d+dfeGj@jBkKkfkrkyl7q7q^qusx~9-&l-(4-(|-+&-.R-3Y-4!-4r-4w-4y-5]-6Z-8(-8C-9k-9v-:<",xuan:"!m!x#d$['5)k0R5?7J7d7w9K-+4",bai:"+&.;3;3M51L^W3b:b_-#k",gu:"!/$J'B)A*~+P.z010?0u3g75:r:v;Q>K@(AfE)G>GhJ,LSOdOjSeXFYR^h`%a]bxgdgehYi,iXk,nYprpws]wwy.}h-%@-%W-'Y-(Q-+`-/;-0'-2I-3^-5?-6S-7%-9*-9+",ni:"!h#P*G2m73=i>$>}@pABA{DqLpOLP.Q!XXZt`~d`h.jhmCpnx3}L~X-(e-0,-2J-7`-:+",ban:"*E2s5!9;>PBgBkQ*QvVKd[iciipPqEwfzx|$-!h-$F-%Z-.n-35",zhou:"!+#U$x&y062.2@2C3+384:777o8p9:B>o?#B^F@GoI$LfY][a]y^r_4_Manc0gkg{h,i0inCqg~Q-);-)`-)t-*r-+[-0(-3~-6f",qu:"$L'o(}.2.F/@2U3?4o5#<1u?/AxDlG:HhKbM}O[OfOpQdRDRlSkSpT'T:U&WxX!X&X=YeYjZj^tcjcld%d*fqf}g2gWw-#)",ga:"g=onsfwH-.A",dian:"&p'v,j1iIiKRPXdXeVewq!x%|8~@-!E-%3-%4-%z-*g-8Q-:8",tian:"!:#;'1'H,j4w6D>v@:BRBXGvWmX9atnTr#rFsXx%xM{%{n-!>-!G-'$-3f-5J-5S-8:",bi:"#L#M'!(w)L*@*C+;.n.o/E/Y0(0)1/1<2r2y4M4m6>7Q8@8};7<,=a>a>r@lA[BlC|E*F.FJG~H:J*>1>2GdYf^ucScxorpC&CqD^FyHSK}Tjh$la-#&-$)-,Z-/`",zuo:"(|*S+!+n/,/p4*7{?'D{F^H`HaJ?Th[(nWp||7-&t",ti:"!g#e')'?)Z)|*v/8285f6|9Y9y:{DXF!KgLIUzV&V'[qd)d2eJemexf~g8jxk=kLo&rDt)xy-%$-%r-*2-+m-,0-,L-,]-,a-/^-0B-2U-4;-4w-4y-5L-5M-5i-6r",zhan:"$H&b.33*6=9oGQLMN2N`NaOeWyYQZ/]h]l^B`#cghUhgiSl0n|zK~V-%~-&*-&N-&e-'|-*b-*l-.Z-1S-2y-37-60-7=-8i-:h",he:"&c()*(0z2i3@4?8r-:`",she:"'y(`BJBKBLJuNpOgP(S5Y>^dagakc'cDg~{!{^-#h-)u-7l",die:"!g!t&w5M9GpB5C6D~PmQ`R@V,V]YU[7_WcbdOdXdreigojNz+-#1-0S-2R-3d",gou:"/01%2)3g6t:&DhO[U#VBWwX;YNY~_(`ob5bgk_pMqHwl}k-#A-#m",kou:"!P!Z#r$$,P.2/W1OD+K=KFp$-5K",ning:"$P=R>!DpLevm-,~-64",yong:"%p&>A]DcIPP=Yre2e]l@mJmio9rHuVyh}n}~-%*-%s-'x-/y-0w-15-2A-2o-5`",wa:"%K,),?,E,`=N@r@xOyTuW1lc-#W-#^-#t-8w",ka:"?8U@qV",bao:",<.~6h?,DgGYHcK`L4MJN^OJTeUdV4V5Vf`ib*d8q/w%x.zs~>-!6-&x-&|-(9-)/-+j-,M-/7-1~-3/-3A-6Q-9r-:B",huai:"=7N3N8VDVSeE-:f",ming:"!C!w#zEDJ'R,WuZ0m^n_q}xT-3.-6L",hen:"Y|-!y",quan:"$b%u/K0B5<6$7:9mEqI3NAP|SlXLZ#_)dkeIgzi=o5qxv%xO{#-#_-%M-&$-)V-*3-,e-0L-2^-9}",tiao:"!~(t),,J,g/!3/4.5F=S?PCdD^H0J@JMJNPnWdZ8Zv_McqdwjCr!rdtyxR-#%-,G-/o-1&-2;-9y-:C",xing:"!D#Z&$0Y0g6J@YApBFEuF7FhHrP9T#XVX_[_lMluo+pBqZqwrhwZx6|D|S-'V-(/-)p-+D-/5-0D",kan:"!N$=$g%?'^.QG&T%h8ho{4{q-%)-.+-:R-:X",lai:"#8#F/X0%2/2MG'H%MSW7Zqaob,c&c4k.mBsgxd-$q-$w-)y-0*-4B-4f-8%",kua:"50?>B~Z=d9dlq~-+s",gong:"'91*44474=8o;z>[OBXQXba6bZfzg$gtrG-!z-,T-:L-:Q-:W-:u",mi:"!s#p$A(w)')w*C1d2b2}3p407c;>;F?bClH{J#K'K/L}N#N6PaU*WZW[WcX1Z.[j[l_g_rjXo4oXoYo_r,z/-!K-66-7X-7Y-7j-82-9&",an:"!(!.;)?I@XEzGlHWHgJSUxZS[N_d`k`{r1s:x]zy}+~=-!w-!x-$1-(l-/E-4I-4u-6v-8c",lu:"!)#Q$_%|&L&d'])E)J*}+[+o071X1v2!2#2G2H3I6S8^9q:f?9A,AtBmBzCFCMCND.G@JcJeJtKcM[NSYXh[~aVb|d$dseCf#gxh^h|i/i>iTk5nwpis2sascu8uMumvGw&w+yr|A|t~x-%J-%_-)+-)r-*N-,3-.q-.t-00-1i-1r-1y-3w-4E-4P-6!-6>-6U-7;-7C-7M-7b-8l",mou:"!|7n:@Oq[[_Ue6t=-#9-3y-8!",cun:".N2nA>lS",lv:"$()(*r+~0`5Z5~6S7_7j9q:*@wA(A8A;HkM,NKV=VZm'rJw#xDz_{T-*u-+*-5a",zhen:"!X!b!c!}%Y'%)5)T)b+I.A0X264N4w5Y7D7L9,:2=I?%B9H5I5IWJ&LnTpUSWaYKZb^pa2afbWc%g^hZi4iqkOnNoxq$r~s`tOu$u%wJyS|0|_~L-)D-,o-1f-3@-6R-8d",ce:"/%/U/^/t0G1W36F/H3HPJA",chai:")&>HCjEJNzS9T[Xz`jp4wY",nong:")v*j+q8C?cAXL,V~]iioipoL-,{-9a",hou:"#c$t0q3Z@AGFyHCKyL2LtNBNMP{DoU1UbVTdPllnm-+o-/R-:p",jun:"&].=/`0<0CFlGCI1O/PeTXWhaeg?m1p^qfr&t'wj|Q}^}l-$j-'8-(J-)m-+F-/]-2?-43-44-47-7U-7^-7d-:Y-:]",zu:"(x*J+10H4}95GqHbIkYm^kd6eLtdu2u;yk|6-!f",hun:"!F#O#W#]F6I8JyXT[=_2hczo{d-'>-(L-.C-9J",su:"';+1+3+],X1U3.324X7K7U:?>,>/@{DWFwJsM+M]MiXWYE[r^o_lcyf(k$khksnZrR-':-*_-+L-/i-1@-5p-6~",pai:"0'1z1|IOhBjLtV",biao:"'c,!1D@3A,A1AoJoM=T@UoVa[3]#b?seuZw$ycz#-&&-&+-&5-&D-&E-&F-&H-&O-&W-&X-*~-+@-+W-,;-2j-7Q",fei:"%[//1!6M9aO>e>r>z>{@GDFGjH$KhP_PuRuUtZp_GaObsvEyP|g~T-!/-!H-!I-&Y-&[-&]-'H-(j-*!-*,-0+-2F-9;",bei:"&i&r)`0'3f>wA[DfJ9M8PAU'V;ZLZwa1bVgch@iDlbm5mQqWrPv[wd|=-!l-#,-#C-+k-4N-6x",dao:")=)H)x+B+K005F8hbdm?n~o,oJqQsMx#y8-$x",chui:"&U0D@8GPsFtny0|n-$u-:_",kong:"%.&V,/0@;gg,sA-#(-4[",juan:"!{#2#H5J5V7Z9S:|;=?w@7AaG[K3SfUM^&mTrZras6u0vHy5yXzt}^}l-#'-&k-'.-6m-:w",luo:"%T&!&='n/>0M2]5>8f9M:n;@@)@UAwF8H9HYJ5N9OrRHS6UvW~X'Z1dbf`g'kAl:uEw>y/yf}s-$f-('-)_-*P-*k-+=-+X-/K-4#-6)",song:"&P.@===yGOY0Z]^b_?jcu1-$@-%[-'[-)e-,c",leng:"#>&h++L@eD",ben:"/&<(DxRuaUblk/sIy&",cai:"#T677P8aGSK+U>a5b[dxeQob",ying:"!R$v&C&|(P)c+_2K2^6U7/8`9^:>:X:Y:c=?A:ASDzEAF7F9G0G1H@HAHBHZJKLqMwOmQ0QPQiR0S8SgVPWv[i]M]|adbHc@g:j/m2twv8vky?~_-##-$.-$i-%g-%o-%p-1V-3g-4q-5*-53-5o-5~-67-6C-74-7>",ruan:"&u(>6^U?sA7C~G3G}HRITJZQgSUb(hKn}o/sL|T-0#-0Q-4i-4~-6{",ruo:"0P1#DnI}mP-0e-0{-5<",dang:"!,#s%2'((2/[1f2&CDF3GbKuN(S)UCW&]b^A_kd&kEvWxB{9~A-8[",huang:"'w+e0f1q7O>=C1F#H|Q@RtSuYv[V[f_Xd,kWt3txu}yI},-$,-'P-*.-0T-1A-2]-5q-86-87",duan:"${'&.I1`2X6a:#IMK(QfRI]1a*g3kxu]yN|F~x-#J-+}-,*-5a",sou:"#v2BC;IQJ(L_M?Qum[o3t~uAyH-&:-&<-&S-'c-(R-*<",yuan:"!9!f)V.i0F6f7':.;m>CD3DYE?I?I_InLGLdO5PRPzQFQXQrT&TYUiUuV3VF[xa3bYh]iQj=k@kgl8lRnPphs'u(|^-%1-)9-*G-.o-30-3U-4V-5%-54-6K-6]-6}-8s-9!-90-95",rong:"+Q+S5E7@9C;^>FEFEfF5J/QhQwQxSDVEghthyb-)R",jiang:"(43u3|5P8:9L:F<>=.A2EaH^ILK.LAQjRM[w]=^W`6ngo>oF|H-#P-%5-12-2_",bang:"&<'A+%5_749B@uC8IcO!O*OvPt[s_olQlVt^y^-#3-,#",shan:"#:'m)K)q+W.s7g7}:D;p;r?pALATBaD&DtR}S,TCWjY%[b]r^ObFc?cVd^gGlAn#p!qtvBwRz4z5z;{@|P|X-'q-*J-+V-/l-1C-1D-2s-2y",que:"&5&E&g'6'7(1(N:P:RI]O6c}z}{*{l{p}a-4Q-6t",nuo:"+<+u3e3y4&5JiKWL.M4N*N+N7N@SPZ:^(^zhxnoqls?vPvvw:yz~<-!*-$O-$_-%7-%}-1Y-6<-9R",zao:",y,~1R3sC#LlMPOC]`d1f4fNk%ktoCwA",cao:"3m>9C=C[EwJ_R:VbV|n)uc-*D-94",ao:"!T'Y}I-*S-+S-0~-2b-5X-8{",cou:"@ThJiK",chuang:"'_,H,L,q{+{E",piao:"$+).1D7a:;_tmuuCuUye-#!-%;-%y-'i-(Z-,t-,u-1*-2m",zun:"8':^U5]Pk|qqv+-1B-2u-4n-5|",deng:"$7'q.M/H1pCCW|`:f9l>mxv6yx}E",tie:"=VH8OhaPbndXq'qzv>vRx'-&z-'Q-*i",seng:"-,v",zhuang:"3:3nF)F]UBUZ",min:"!B%9&`.}/<1l6O6d:,:wDiSSb'pqs7tEzEzZ{K{S-1$-2n-3P-8q-8r",sai:"2'@cb6c9-%#-0_-2X",tai:"0+27>h>yB8BeD]GeLjdIl[nSpfw^-&/-)E-+7-/6-2$",lan:"17212Q4/8K8i9x;+I2F7I@sAHM9N?R1Z@[`l1~u-)S-*B-*v-0s-97",long:"!p$a%n&=(R(S,u.!.6/;1*162N=P>'?6E'[,A6;9l;1;;-&@-&C-&U-'b-(W-)M-)c-*@-*d-+T-.9-0m-5=-5_-7.-76-7[",shou:"6.9h@yC2uA-(_-:s",ran:"7v>ZDZIFOEOYTST`Tz-,A-,K",gang:"%.&q/{639!:N:W:x>Ep+s)ttwe",gua:"506}:z;%>xU^|cnedr#rFxM-&'-&1-*9-3k-6c",zui:"#G)C+15&8d;$KjRdXHi]nInqo!s$s8",qia:"%{'I?1HyU4dUnU-!{-+z",mei:"!L!_#)#a({)]+X0h3p;I;T?S?r@PE&FfI@QGTZdMg0mOnlrKtUtZyMyQ~N-#^-.>-.F-5(-7(-8V-8h",zhun:"+$,56(>UT8YAZ{_Pj.",du:"#K#b*f.T.^1,>DCsFBR&SZSmUyWqZd^$^D_E`3b%bNc)mMo(sDs|v}yL{!{^-!Y-#V-#s-#u-*E-,,-8]-8k",kai:"II`7gysvtbt{vCxGxvy@z<{({U-&;",hua:"%;&K'B3S8/BWD9D:GgIKK[MzR#XKZ&Ze[4[>]A]o_&`0p(p)rbsdunxN-*]-+<-5m-8=",bie:"FTNFObRmVuf6-19-2l-8|-:[",pao:"%e(@(O,!?|H>M=TeTfV>dDdTgfq/x.-!N-!o-7Q-7S-7|",geng:"56575d6m7,9Q;j;uAbArG?HYM3PfQ4Q[SRi_i`l6v|z$-#0-,k-0F",pou:"0$UO",tuan:"1H4'V8a%u<-5V-6#",zuan:"1B2Y808N8U8e:Kb3fjftq)vxw?w~",keng:"%t&3&RZOr>t1uOxg|&",gao:"#R#g)4)6)e*m+N+O/v0~3i7E:5;O;TA'B,GILrMHZ[_:m+ryu#xny]-#o-'_-,4-,5-5R-5v-93",lang:"&7*n/dC(F{IXJ.JHPOQlZEg%lzl~m.rLu&xzz^{]-)h",weng:"#q:b;}=rJ0L(Qstg-56-7,-9_",tao:")?58617A7N9W9kG|PoUhX{Yn[{^MdwhXjPjenzs+|r-!k-!t-#@-#l-#|-&w-'d-'y-)P-)x-9/",nao:"%z&q'*?a@&@ZAkP6R~YZ]Ju|x@zJ{O-.'",zang:";S?_AmAyB$I,K@M#abambLbUb}rC-)A-++-,.",suan:"(z.b/m0;1BI^nn",nian:"':*5*P1Y3*C/K6evf5f[h=iCiS-/4-0;-1x-2K-4%-8B",shuai:"7>:4RNTH",mang:"!5!6&<&D.ZCvEXEiG4G5M_OvRaSAlDp.rsx:-)g",rou:"*!2w3X>3?l@aHdQC]tekhEt$-#2-#f-*7-0R-4t",cen:"+W.m1A",shuang:"(V7;CPuh}z~b-*M-*y-+^-5c-6A-7B",po:"%g%i/70I3'7i<,IlK,jLn%n[o1oKotq9uswMwz|=-$K-%a-)7-,N-.E",a:"@@s@x}|:",tun:"AYAeC~OlVL`G`IgJ~Z-&h-(0-.j-1q-8J",hang:".k/T5*9HBiDHOAT#UAa9j3lJ-$C-%]-.i",shun:"!x$&$1$9BZKo-$:-%S-,g",ne:"!vY6^]",chuo:"'j0^6?8&9bd!e'e`Q`b`va/hpj9k3l/lsn9tCvSyJy{{:{r}i}{-*|-,|-/n-0A-0K-2>-3?-4+-7<",ken:"&#>8>Y>fUFV$`S`wsh-:?-:E",chuai:"A0ACeb",pa:"/bm|roxk-.6-1K",nin:"?[",kun:"#7&H);*s+*5oGEPpUEUJUgV.`wo%sCy*z]zj{Y-)w-,<-,=-,D-0/-2G-4^-5'-6w",qun:"0<;_;`UVU^e.k&-7U",ri:"TMp/p;pd-)%-+(",lve:"+4rgrlxr",zhui:"&U((.h66729r:'@C@|[!b>c6j_o#s>sQvdy1})}Y-)s-+J-4Z",sao:"$O7m8<:A:HAdR4-&<-*#-*I-+Q-,:-0l-1R-2a",en:"J!",zou:"0&6GG=[)_CcNcOlem@mcn.|h-*H-+1-/w-06-2E-83-:.-:7-:n",nv:"2h=TSvSxp8wW",nuan:"-'M",shuo:"$m&+'$0cIvZaZc_>qttmv~x*",niu:"4H9.FxpTwq-!`",rao:"+i8)9FF,KdVvk}}B-'v-(>",niang:"nuoRoZ",shui:"#I)7*q*z@1U[ZaZcZg_>_KzG",nve:"&ONJ",niao:"@%E>K1T^UGVO-2{-6H",kuan:",s,tAqw(-,&-,2",cuan:",',Q,s,t,z1)1[fLfsrZw;yv",te:"?vRgr{xe",zen:"]V_y",zei:"S;a_bv-0M-1Q-2+",zhua:"2(AU-,Y",shuan:"5<@]z3{?",zhuai:"#1dmi'",nou:";v=,tfv;",shai:"/Z121J1e2[[K",sen:"Ve",run:"$1AOz@zQ{F",ei:"ZH_@",gei:"5C9J",miu:"7n:@]+_w",neng:"?LR'",fiao:"WL",shei:"Zg",zhei:"j:",nun:"-84"},m:{yi:"-:~-:<-:;-:4-:3-:#-:!-9~-9T-92-8u-8R-8N-8I-8+-8(-7O-7M-74-6l-6c-6L-5z-5)-40-2U-2Q-2>-11-0o-/_-..-,o-,B-,3-+q-+[-+<-)X-(o-(5-'w-'k-'=-'#-&6-$'-!?~=}E}1|x{Zz|zzxix6x.x%wKw,v%uPs_rurorEr8r)pppdpXojoioVnxn_,^g]|]{]`]/[!Z=Y5XVVTTgT_T7T1SxSsR~RyR;QwQ0Q!PDP6NbN^N,MZMSLXLIL6L$J9I}IUIIHMG?EaEHE4D!CwCFBkBTBEB9B5@2?Y?K?I>K>H>'=a=R;m:~:48c8!7,5g4q3&2}2Y1j1f1`1M1/1'0t.O.K,_,,*x*f(c'G&.&&%b%Y%G%$$b$6$/#x#T!9",ding:"-:}-8q-)?-%!vipfkGiydzY2Ik6u+B&^&[%_",zheng:"-:}-9O-7L-0#{1{,yjuvsRm*lNlIi;eheZe8e4e3d/`x_v]3[+ZSY8Y2XlVFTYT#Q1C@A!4W3w07.),]%*#C",kao:"-:|n{k][#TbL>>R3p/,",qiao:"-:|-:(-6A-5v-4=-3(-2[-.@-,2-$H-$5-!q-!=y/y$xkx4rSm+m!k]k%j:iSi(hqbvaT_wVuV6V$T%KgGaF^FKFGEpDSBCBBB;8<2b1C1>.}#e",yu:"-:|-:p-9^-9P-9J-9H-80-7t-75-6'-5g-5b-5H-4U-3F-2l-20-1F-+K-)O-)+-(J-%a-$p-$K-$9-!7}]}W}5{7zizNzEvyvwv9v3tytjtetcsqsos@rsq|pyp+p%oQn6m%l8kyklk8jfgvguf%eGdWbtb(aLaKa:`1_1^:]e]d]KZOZ!YmXiTDS`SUS7RpQyNvLAKsJKJJJ;IAH|HmHVDVD:D*D#D!CrC[CDC,B*@K=Q<><<<1;h;_:v9G908=7M7I7A535#2{2R1b1:1(0;/q.(.&,1+G+9+7)n)h)F))(+&*%!$M$D$=#V!A!0",qi:"-:{-:r-9{-9E-9;-99-82-8$-5f-5(-3D-2{-1:-0G-.j-(Y-(A-(.-'v-'C-&%-%m-%I-%F-%E-%:-$D-#N-!Z-!B}$zvyHwbw;w1u~t[tFn;n3n$m~l^kkiBg/dpdTcKbJ4GyGJEW8l1T",xia:"-:y-:s-9u-6I-5e-3w-+T-*+-(v-'m-%n-!!}({Mwtwpm/logkeB_3YST)P~M-1A-/j-/i-*P-*J-(^-&C-&9-$k}[{Xtrrbp,n8lJl%dqbm_c_L]cZ(VLV%T]R_R^QRQQPOK9IJCH@l@^@?=k=Z=?y>]=x<`;t;(9.9(857&6{6d5m3D/;.j+?(>(!&8%{%t%4$X$,#H#>#'!w",bu:"-:q-7F-,M-*w-*t-(d-'K-&D{B{?{6zPtOm#izh'gfd,bi[rY}Y{YfQHM,C>C;C:'=",fou:"-:q-(cvCBj4H",mian:"-:o-42-1d-0w-,S-,H-$`tktQsZqpq#aDNWJ^E=D~@p?|;k;,7G/o",gai:"-:n-9w-6e-+u-+t|'uYm@dy^AW%T`QYNaHZGNGM:M8|'{&6!,",chou:"-:m-:l-8m-5_-4=-2A-(m~{t/r!iKhld$b3aS_%[_Y%W~N?N=LJJkI|E?B_0h/O.s.p&3&!%l#v!m",zhuan:"-:k-7o-3G-3+-2y-.I-)n-%+~EzRyPreq;<`,E%g#(",ju:"-:j-:?-9m-7n-62-5`-5S-4x-4j-2l-19-0%-.Z-.:-,.-+n-)H-'d-$|{/ztx_uct_tNt$o{nvnqnOnMmqmil`jYj9j7g+e%d:-(h-(c-%5-!.-!,~|~X}2|L{2xhvCs7*6e4n2x.Q.G,n)Q'(%k%h%@$p#R!U",shi:"-:h-:g-9q-9l-9N-9M-8t-8_-7R-6k-6]-1X-0m-,^-,:-+_-+6-++-*>-);-()-'{-',-%.-#t-#7-!W-!>{>z|y{xn=}:{:s:W:5:'9v7C7?6n4=4%28.3.+.#,0)$&3$}",qiu:"-:f-:^-8m-6#-)u-)9-&+~*|FyTsQl4j2j1cFc&]rWkO%KIHeF8BpAn@s@b?J=o;^:l:k:j2D/T.k+D*'([!P!(",bing:"-:e-:W-8h-8b-6u-5B-4T-3Y-1;-0a-0[{mp1ngnZhbhah&cm[vY,W5R0QpN/MQLQLLJnJbGXE:@~4E)r%,",ye:"-:d-9z-9.-9&-4e-2_-0U-)7-(u-'%-$W-#,-!]{:zIxqxdwgoVm$jxjw[hZzZ!YyY;X:X6UhUcUUUSURQUPxP@P?P,OmOkMYMXIQHsHpCXBh>i-,u-,G-,/-'I|/{)y&u^tXr*mSm>lKl?eNc3_H^LZhXL^>J=,7[6?1e=_=G<8:?7f7d6/05/f*6*2)c%x!'",diu:"-:_-:[",liang:"-:]-:Y-9)-5x-5[-5>-5%-1G-0B-&J-%y-%7-$Ly2bWY7Q*KJIwG%~n}bvRuAq=pZo8o6m1lyh[hZh(d]d$c|cqbY`,^xXkTaS4OVM;LAKGK=H{GFD}DJ@8@(?V?>=g;C:b976B/j/i/O.b.D,?,>+Z+Q&g&d%O%!",yan:"-:X-9d-5]-4]-4O-3;-1u-1Z-1Y-.a-.[-+:-*O-*F-*/-*$-){-)z-'%-&=-&2-%'-$N-$G-!L~~~a~Q~5{GzAydy7xLx@wMw>vPv>uFu@titfrgr?r9qwqfqWpKmhlEl'kuktk0jUjKjJjIjGgM-9<-9:-7m-5K-0W-.$-*H-*G-*A-*?-(s-(H-&n-&'-%;}L}@}9{j{5zbxTuBu3t%q2n,lVlUhKh?[`[ZZZY:XLN'KlIsIFA0A,}>k:c9s84684l0$/w&C&/&,!*",zhong:"-:P-8A-83-7x-4Z-0j-/C-$Tz8ysx$vMvHs^o)i)eqe0dddYS`MKC2@=?G4w2k.T$F!>",jie:"-:N-8i-8<-5$-4~-4W-4!-3j-2]-/@-/?-/)-,r-,a-*j-*i-(e-&c-%d-%H-$m-$8-#q~zzKz7vevOuit>sasVsCs(qSpIoJnpnln*m|lCkvkbjrjqjgjbhihIeEbr^S^;]_[,YZY+X{XwX?W_UmUOUJS9RINXNJL0KxKoI~I1HqHgHfH8EOB,>j>;:z9b882?/'.6+0)H)8&K&J%g%]%M%##D!~",feng:"-:M-8:-5L-4N-2Y-0]-0&-0!-/{-/y-%p{Rz9z5w}w9v7odoYl}l|l5W4MkKPI.E[?m?h=S;Y;#:R8e5Z4i3V3*2g1h/1,O)u%C$B",guan:"-:L-58-1=-0l-*vphb@b?af`LXqW*SRJ+G*D(B2>wRWQkP#L)?N>=0X.X.U",chuan:"-:K-7o-3G-2t-.K-$]}Tz3jFjDPMIRIDCbA?@i,H+<)7",chan:"-:J-91-2y-2R-1~-1/-/:-.k-.J-.*-*~-%$-$F-!n~P~@xBszr>q3l>kJkCkBjXh{hpgWdu^r^lXsX+W;VqVhU#S9RYJsJXDEB#=v:^967o7n71655d5B2V1I,#&v&u",lin:"-:I-9U-2g-0e-00-0/-)v-(l-%PxDlbk,gIgHc=bob)_=_6[MVGS?Q+PGN!FIEmEDQ>L#JuJfJ3J,IoGcDh@j=|=h.h)e)N",zhu:"-:G-:B-9]-7d-7G-7?-6Z-.&-,t-,n-#T-!z~4|=xpx3qVq!ploNnWnIl*i>[[[WT&StS;OqO1O0O.N>M#LzLFGWFmF,DhDbD^D0BH?&>Q;b7t7Z6s5x5>4V4A3y2^2@1+0x0?,K*K%B$J",ba:"-:F-8l-7`-1E-)^-)@-(b-&M-&I|_{[x>wCv0mumIj,fq]o]I]6]#[GZ)O+M'D,5?4R0+.m+@%N#/#!",dan:"-:D-8~-7{-7H-2r-2J-/V-,,-+G-*~-*{-'f-&2-%C-%B-$v-$F-!m-!b~[vTsjiofTfOfEb$aga>_q_P]4[VXuV@V?UjRiM/BeBSA*@)>rc>C=n=$;S;N;0:N:08?837i6R6G5|4]4>4$2]2O2F1]0u02/$.r,[,P,I*~)h);'f&H%!$N#X#U",jing:"-:A-9C-9+-9'-5r-5%-3A-2O-1N-0K-0C-/9-.~-,y-,k-,[|i|g|cyIvQt:t8t+pojAh|fdfZeeeWb/___NUoT+S&S%Q:Q3PIP0KZJpEvBsBn@I@H>m>%=><87]6#,r,'(^(B(<%($u",li:"-:@-6_-5u-5k-5Z-3s-2&-1z-08-/Q-/=-.o-.G-.'-.%-,l-,&-*L-*I-*:-*.-*!-)|-)Z-)X-(z-(2-&U-&0-%g-$C~g~`~A~>|`yrxEu+tat#rjqYq,nAmkm5m.lzjag@b]bXbRbB`l^&]q]gWYU@U3TsTlSpP_P>P%O&NmN^MqMSLnLcLYLUK!JoJdJMG1ECDuDjD_D8D.C/C+?k?[?Z=Y=U=/:/8z7@6C6$5H0a0U/>/=/#.z,~,u*V*$)z(t(_'x'u'l'W%R%F$l#P#A!Y",pie:"-:>rVV]V[PHAD8>",fu:"-:=-9c-8[-8#-7z-73-5y-5m-5j-5U-46-3v-0d-/|-/J-.R-+h-(=-(6-'[-'S-&E-!s|<|!{]wvwWvVvRuru'tDt,sbr5qJq/pmp3oWmgmFi~ifi7hzh;fwfkeje?c{ct^w]l]J]&]%[Y[QZ+YfV7S}SLS)ORN+M]MGM)M'L1KWJ2IYIPHKA:>~>Y=W-8%-6;-5|-4k-2k-2:-1q-.T-,|-,C-+y-+/-*V-(U-(T-(J-(?-(+-&)-%K-#v}4|^zLykxvvxv4u%tjthsurTownkn9n+lmkzk_j6hFgQfudbd`d@c'b[bZbKat_]^[]e]d]]Z4WGTTS7RoROQENvNtNoM&K#FLCVC=B3@[@Z@S?{>T>*=V;^:,874(3C322*1w/V/A+3*4*3(|(P')$h",tuo:"-:6-8X-77-6h-6.-'a-'G-%[-%$|Sz;v8sNrRmck'gzet]i]`[H[F[EZMYuV1NgN^MTM8ITI+GbFBF0AvA_@d?`?_?^-)C-(W-'v-'8|||{|T|:z~z{yFy@x$v%uNtsrGp&m7l0j+iridiahyh5h3ggf5eYeKe4e3dmdUcU`6`*_$^{^E]Y]F]E[u[HZtZpZ]Y{XvWpWVW2V{VvVtUKUJU>TjSMRwRgQ`Q/NOMyMcM2LqLhL6K~K7JjIuI]I*H+GHF_D|DnCAC6BiAJ@t@O@N?v?T?3>V>34`1_/9,x,^(R'w'[&3%c%;%7${$z$k$E",zha:"-:0-48-.N-.=-*C-(w-'X-'?-&K-$j-$O-$Aw/pNd6]s[m[XZdX4WIW#O2M7M1M0LvLlI?H4Fv;X:67u5#4@2N/p&d%.!M!H",hu:"-:/-:'-9j-9F-5E-0Z-+U-+L-'h-'W-%n-%Z-$_-$4-$1-#>-#2~k}v|;x1x0x,uGt4sEr]r[oxm[iphxfxfgdFd*d)cGa{^V^6^4^3^/^.^,^']y]9[xWWW$SXRFR-'$-&N-%z-#p-!}uSr`ljk/cY_f_eYtVZO:L=G5F!=O='8%7a3{/^./*<$f#c",yin:"-:+-7}-6^-0t-0;-*c-(j-(V-%o-$d-!T-!+~l~+~$}`}$|&{w{YzXz:w_u=t0t&p:n}lnlLlfya@`i`B_u_t_0SMO[L:KKEkE@E1DKCwC_BYBGA5>l>d>U<5;~:}:i9}9V6^6]4).],|,j*I(U$7#k#_#:",ping:"-:*-5i-0]-/z-/s-'u|Qz1u/ngnZmTi[iJi4heh&`0_zMfEU?6>6=A[KMbLw",sheng:"-:%-:$-4H-.X-.Q-,?-+0-(9}=x{x7u*k}_VS[RGQJQIOeMuIyG~E{BzBF?%;k;@:q7G2u/M.N*h)i&y&s&`!'",hao:"-:!-65-3k-2)-)6-'j-&_-#k-!t-!Y-!#~xxRvacOblRDR'QBPePaPWP7J!A~Ao=]-'6-&/-%]-$X-$:-!p-![~T~8y?xWwnw'tgs;rCr@nsncn`nRnHkgk9jpj`jZiqiOeceOe9djd_dEcscgcZcKc/bqbeb8ay`r`p_s_r^V^6^4^3]_]O]HW%R:QKQ9Q6PEOzNON)MdLZKSIdIGG{GUFkFRE|EjCzCuCmCMCJA4@e>X>S=f<[;i:+9h9)8p8/8,7N3e3R3K343&2Y2+2)2%1q1P1O1N0}0P/E/?/*.{.t.#+p*r)|(#'h$1!k",xiang:"-9x-9,-9(-6}-3*-1}-,4-,$-*0-(x-&r-%L~Ww~uXk5j)h7gqe'abQXP5LWH^F1DH;!8:*E'g'T",shu:"-9s-61-5g-55-54-1|-1F-)Y-'3yNyGu[tGq4oNoCnWnIg}gxdWchcgcIbt^X].Z.Z#Y>WBU9T'S|PvPtP*OhO1O0O.N[NBMtL`JtFuFYEpBuBKAaA`?c&=L/3,E,B*n*d&f%0$8",mao:"-9k-1,-1(-0|-0z-*dzLwksLmOkzi?a=_?^(S/QvPrN4M@I'B!AcAW?9;F/Y/#,J)E#$",mai:"-9i-7I-,{-,*-*}-#${Kx5",luan:"-9h-9Y-9V-*^}C}Bvmu0qXq:q$m)jOZ[TvOuL2D69K5J59#4#3",ru:"-9f-6K-2C-1K-(N-#{-!$vkv[s7qyq)jciX]kZgUTP+NzL(E0@W>7;Q9u6b+^",xue:"-9e-.x-(Q-!9|Bxbq>q+mmmMjzf=ckT/SlKvFc?!>u9j7>5y1&.B%L%<",sha:"-9b-4c-3?-2H-/,-.t-*+-%t-%^-%H-%4-$R-$0iCgkZEZDW$<%81806O5S4B2Z/J/B/2+%!l",suo:"-9_-9=-3]-&8-%x-$&-#j-#gu&s(as^$ZEZDW:PjKaJz:E9y+|)w)v)!(]",gan:"-9Z-8S-7J-5&-0=-/u-'c|Ro'o%o#o!hfh_dqa5U~T]T6R_NuMDKLH6FNEd@??;<:8f7_7/55+;*w'#%?!T",gui:"-9X-6q-3{-/(-/&-.7-.5-+Q-+J-+I-+F-*%}3{zv2u;s?rhrIp|k$jpj`iLhLh,gmf;cMVxVVTiThRCQ2O%M9L.KeIeI`GTGAG_k_Z^b]7Z`Y~Y9V^V;TnSgKTF7F6D[CvAG@:?!5P2|1d1>0S0G000/+z+M+)+'*](n(G%L$3",liao:"-9R-2|-!rrLovomo[>90%*F",chu:"-9K-5N-3d-3R-2K-2!-0$-/m-/Y-/I-,t-*)-!o{$x!s>n5hjgXcj`g_SWxW$VoTNS=NEIjI&HoHQF|E}EsESE#DsDdCzCG?@9r9q6x4N/+*+(,&;",kui:"-9I-3{-/4-+I-+F-$U-$;-!xwow4s/rBo*mQjVjHb]a.a,_y^BXgQdPyI2I0E&BV:S7x2l.q!/",yun:"-9G-7r-3q-1p-+}-+x-(0-&^-$^}xwEvsvEqOb}aca4a)`c]2[yRNQTP}MwHWF@BmBaA&A%@0=3=!:!7W2h2:202(2$1b.Y+(&P",sui:"-9A-5#-&F-#U{3wytvr1nwn4kpRqEWC1C0Ab=H9[7+6z5}2C1g0~(/'p",gen:"-9@-9?-&pX=X'L7",xie:"-9=-9!-7[-4J-4A-4/-39-1{-0s-0c-,w-,+-+'-+!-*k-*Z-)7-$(-!C~e{ry_wrw8w1u)sOq]opnenVnNm$jrgJeFcT`z`p_BZ~ZWZ8X9WnWMV*UiUFT}SWRePXMZLIK@JwI,HOH?H/FlC]?K>p>A;P9h7B695{5!4Q4P3b3E2,0w0s0O,C+k+e)8",zhai:"-9;-6B-4f-4*-3E-*K-*C-&c~zw{p{os[u[2YxW/UwU>SiSfH#EL#t",tou:"-98-4'-4&{$wNv'sqs@aK]*T0SQ",wang:"-97-8v-87-1JvYo7o1o0o/eoeiefe[dldJa}]>RTQ(OEODO=N1JD@J6;+E",kang:"-96-8)-+X}|rmkKg|dG`8]f](G=8_4d.a",da:"-95-.N-+f-'f-'R-&m-#~-!J{hxrw[v*d'ag_q]nWZVJ@f?}:<4Y0p&@&4$#",jiao:"-94-6n-6D-2q-2j-2I-.B-.6-,6-)B-(<-$H-#M-#K-#?-#(-!^-!=~IuUu1r=r6qcm+m(k1k%k!e.e+cJbl_~_i_KZjZTZ5X&W9VlVCV(ToTJT?T,SwSuSgSSQbPgP2LOIpG!>!:l:k9Y8w8<7b5[5C443,2b1>1*.9+l*X(5#e!v!^!V",hai:"-93-'V-'0-$#-#h~ey]vOq;pL[!A3=N3[,C",heng:"-90-&B-%QuJcXcLbaVKL/FiF&<|42*B",peng:"-90-5,-3J-.F-+o-!~zgyqyYfUe|cyc+`%[tZ?Z6YkXpWvW4OTKCJLIlIWGGFn?6t}sxk~hVhJh)gBg?g;dzZT8T.O)O(NfN^MrMTMSM&KuIRAh?`?^&D$i",men:"-8{-8G-53d8bcbCaz_9_&]VYgS^PZIh@>3=1,+((W",ren:"-8z-8y-8s-8U-8F-88-/d-/cx;vSu`n:n2d|dwdv]XO,NiLPLMK6J7/]",shen:"-8t-7V-6i-6/-5d-1Q-)l-)k-)j-)i-(V-'i-&}z^u|u>ttsys.qmp_pHorn7lui(fp`t`b]b]4WPTFR4P9P3M:J7J(IHHRA9@+=D<0n:(9U7C5[!e",jin:"-8o-8j-8d-7}-6<-35-2^-2=-01-,y-,k-,[-*X-*'-%o-!F~y{Fzkz6yE=q=M:I9$6~6g3h2M0i*Y)y)K(z(d(@(*",pu:"-8n-3$-+k-!S}^}O}<{BzPy(]p[rY{V0UvTeTdQ;PiPPP&O*M,FZE_AS=`:17k6T614r3a+v(C$m",reng:"-8g]m",zong:"-8f-5:-4y-43-3KzFpikxkrkNeJcdaraVY^XXX(W&Q|O>MxJQIKG28L8D8#3+1n1c0{,b,R%E#w",fo:"-8e-8;-73|IJl",lun:"-8c-7i-6S-4u}l}Y{.t*lSlRb9[{YMJa?j<6:3",cang:"-8a-89-7h-5;-3e-07-+OkeDW<];o:Y9g9_8a7;/G+J(!&Y&7",zai:"-8`-3V-2G-1!-&v}8pOl.]j]>L3>f;>:.4|4{3~&Y&7",ta:"-8^-6E-3^-#~-!&~Kz$yyy6vep}lc[HZXW`V&HCG}EqA[?}u.t`tZs~r~rOrNr9q`pUo;o:nBmylxlhjthhgCfhf+dI_a_X_R_'ZPYQXsWnWiVhVXVSU6U'QlQNPKNFMhGiFFEtDRC~ArA@>S=E=7:]:C7Q6*574*0l.=,s,G+f+c+U+O*|*s*T*,'3$c#b#Z",cha:"-8X-6Q-4D-/,-.t-)e-$A-$$~s{yvbu?o|m}kqj3]a]OZ7Z.XZX5WJW1NsM0LvK?I?GjEB@k,<%s",hong:"-8W-)w-).-(X-(K-(;-&{-%}-$)~i{kvXu6pqpjn=j[fvfBa*``XeVNQ[@E?y?<>@=b=S;J;B:R8J7U5(3|31+>+4'T",tong:"-8V-7/-6R-4Z-2h-,/-(}-&|-#Z}o|/mNm>m3h:f(c%`P`)Z1Q]PwwuqtKqdmdmVlQjhekYffd9]bDaxT:RBQtPcIiATX7s5L",fan:"-8E-0)-0(-0'-,1-+R-)a-!hy%v_tDr;r:iwhwdi_h]l[ARvRtNpMLKXJrJAG,FD@w@g?4955t5_3n2E15.l.[(A&O&/&,!.",miao:"-8D-,m-)v-$?vDscrPh>gtgSX^NP<#;A+K",yang:"-8C-7<-6{-3[-15-,f-,@-*g-'Z|J{xwTukswmrl6l3e`d4cEaA`m^}]T[lXRUz>`8N6A4y4D4.2B+6*O)4%Q$|$@#F",ang:"-8C-*gn.RLQoN0!5",wo:"-8?-4s-4L-*l-(/-'&-%q-$atCtBsfi8^TZYYbYSXKV#SRN8I>@1=#YqXmXjX7WmV!UGU'R{PpO_MoM(LEK3JgIfIJICI)HEG]FhFCEKE2DLC&BMBLA]>a>$OYOSN.K&J*J)F)A>@66}5i4v391=16+{+.",bin:"-86-3S-2EpAe}W?UNShJnImGXE:B^BO@r9I6q6Q6M6,+.(j((",di:"-85-7@-5a-4F-3:-*D-'}-&t-&$-%R-%&-#O-!(}0|h|d|@{Q{L{8zMyFy;x|w?tqsmrimUkIjoi`hBg:fofjeld#`7]g[g[=YFX]XGW2TLT!R[NfN(MrM3KAK:JCHiG7AI=g<};T9f9=3F/K.V+=*5'1%c##",fang:"-84-4}-+^|r{Qzcv5er^%TZS:S(RER6N/@<@'8*4c1@/!+m",wen:"-8,-/X-(M-(C-(&-%Jy`vNf)dfde]:X.WRSmQsKNHWH)C$B`@>;z;R:*4s+1*8(}(&$;$.",xin:"-8*-7f-5d-5G-!3-!0~%vSCR9N@N%D$C^4a3$",ai:"-8&-2W-09-)h-'!-&q-&5-%Y-$'-#]-#E-!;{SzIyfxUtgtUrxr'kaa9_7_,ZNYaT&T$QqP^P.CxClB.:%9t6U3.03(k(;#]!s!j!]",xiu:"-7~-5c-5V-''-$/~|p@mfmPh2N~G09~9F8I4+*P*#(N",xu:"-7~-7Y-6Y-6!-49-0x-,F-,E-*Y-)T-)+-'p-$e-$Q-#7-!o-!W}7{Wy,x+v&uxspsArFhHeXckcKc:b(`g^YY4XMTKT@RbRZR!QcP{O^OOLGI9GfC|CtCiCOCKBw@5@4>?=t<>;+;):P9r998W8B433W2H0m+t*N*?&;%T",tang:"-7y-5+-4M-3l-3U-1v-.2-&.-${-#.|XzpyukdilaA^cW^V~OsJFH%F{F<@P/:f8U6y6Y6+525127+_#@",hui:"-7u-7#-2u-1{-+H-+.-'/-&j-$[-#=-!f-!U-!D~p~,~&}u}Fz]xztEsgr7q]onn?n>i*gmg7g5f6f4f3e,e*cDcCcVEQSQCP|PQO]KeIOI3GRF4EiEZEQDqBVB>B=B7@n?D>h>g=y;+:S9X897x796y6:5,5)3t3q3k2h0y0q+h*9)G(=(2$~$)",kuai:"-7u-6@-2M-/p-&f-!8}:|ez&y'jEgMdXUkRrO]Cq=y79.*+g(2",cui:"-7s-5?-3N-04-%I-%>y8lYlWkhdSbE`TV|IxH*GHAg<48P6a331g)p(b%I$L!d",che:"-7n-5`-4I-,%-'y-&*|?vln|nGene/]QY.XcVsV>V<7`3r3b3E0C",chen:"-7h-4_-3e-2'-#|~ZyWyAw]pGoBdRa>[aY]THS~QAP$L[K_K'J(HUG3D]@+@*2n05)l%P$?$$",xun:"-7g-6O-4.-,Q-,A-,)-,(-+5-'3-!k-!P~u|y{=yixYxAw#uHqKq9o`oOmEj@j&j#g=ebe>c]`uXUTfRcP(NqL_KbF`BvB@Au@Y>5=r=l8+7y6V583O2h1{1D130j0Y0Q.5+b*H(L&T",chi:"-7c-7M-6b-6P-5E-3@-,W-,K-+_-*]-)<-)3-))-(:-&W-$z-$I-#l-!g-!=|@|)yLw/vBs6n|fsf$eweve6cBc9`X`7_|_2]`[f[!ZvZ/W+TxTCSNNcMPM3G1ChC6C4BX@T?Y;:8g4~4;3U1K.O'A$Y$U$E$2#G",xuan:"-7b-2N-/.-)o-)'-'(-$Y-$Mz)wsv&sWrqr.p]f[cobMaQaI_I^nX_SyS'RAR,QeQ$Q#PNK@HxHwEf?#;I8d4M3x2e+L*s*)*&)B(Z'~%/#E#<",nu:"-7a-3r-,svjq?ilfed1Wo",bai:"-7`-6z-(1-&:hJ[?[>ZwYeX}WAUfUCTAMFLN,n'D#*#)",gu:"-7_-3T-2e-0F-)I-'s-'N-&<-&;-%G-#y-#@}gzfx#uhrUq@o&lXl=j5j4d*`~]_]9TSNaM.K-27-+8-(%|Nzsznv/v)t'Y'R$*#[",zhou:"-7W-6M-2X-0{-'|-'z-'Q-'5-%X-$i-!G~{v.t/pgjCiceIY%QnQLQ8)<3;[5U3G2o0D(K(8#9",ci:"-7T-7B-6m-47-17-/+-/'-'t-'r-%@|*q}j3h<`hN|MILHD&C??56Z*p*k'E'6%=!{",beng:"-7S-#w-#+{R{#zgyXw!lBkYX0>v)d)[',&k&j$a",ga:"-7Q-'M-#A-#/-!4wIwDoEo>o.RaOM+C",dian:"-7K-7:-3m-18-**~M|P{lyBxfw6v~t6t!kXj]jNjMh@ao^!YOTrTWT9I_GqG_FPF5B?-(7-%`ylybwYvit=nodgc2b:Y#WPQ?LSB{?U-72-66-4E-'L-&,-#!|lmtmsj;h0d6YTV4R%M7M&)e",ti:"-7;-5N-5'-4R-/!-.n-*;-%H-$y-$3~w~rw?smsPnmnYnVl2foeCe6bnbjb#b!aU^)ZHY*X]XGU>OaONL$JxJCCQB]=0;T8O*5)A'r",zhan:"-7:-4>-2y-*s-!IrQnamRl>l)kCkBk.j|d+b0^M^?^5W|SJSGS0RsMjLiL-&t-%H-$j{szSmDl/kIi3c}cPa`^IZbX:QwP!M2HsGUBcAK?I0*/}/n'_&#%q%j%i",gou:"-71-3p-0y-+z-)H-'p-%W|C{uwdwcuTs0mnfM[CX%VcN6M^Gm?q:925.C*o%2",kou:"-71-0f-.C-,g-)J-)DpCp8fId3]^[|VpTV9@",ning:"-70-6>-4a-29-0.-'H-!)r%q!p2p)p'p!ot[4UMM5F/E5?17J6k.<+a&i",yong:"-7*-5t-3M-,U-,T-'T-$t-$+-!:{Oz!yCxcrlkUg{gAe{ceb{bzapaC`w`n`:[6XTU}M4LaGQ@}>x=9:p947:5T/{/i&p&l%)#S#8",wa:"-7)-/n-,e-(/-'P-'&-&x-%h-%A-#y-#nu5tbt3sGnCije[ZaWUTq>.:;8h'V'D'>&A",ka:"-7&-*r-'O-'M-'4-$u{g",bao:"-7%-5h-21-/>-.e-.]-,!-+{-+s~ozPzOz@sBqBpcpMp$ohoee&d:[w[kPPP1P&M]614J2<0_.u.h*G",huai:"-7#-',|mx^xIe_dC_:^oGhDX<25z",ming:"-6x-0g-06-(|-'guEs&`aXxR@PhOFH<>0:7,8",hen:"-6s-&p-!3eac6[0.:$y",quan:"-6p-1H-/.-.#-,5-,#-%%}X}Q{4w5u:t;q[m?jRf`c0b_b%['Y`WKNxJ:I[H_GLFjD>?F>F:a5841/I/H/7.o.n.m.O)2&I%'",tiao:"-6o-%Xr#pWmjmWh4cRZfSQRdQjOLO'NYK.Fo",xing:"-6j-5.-1<-/U-&g|0{auft{t5qljAh`f*cxb>aZUYR/P4Nl>ZG<9;H9<8o6o6l5n5G1z0B,a+T'h",an:"-6W-5J-4<-2D-*P-*J-')-%e-$x{b{&z_sYpwn@n8mXm:hXg~ZnXNQ.PnL'L&A1>M.g*w$V",lu:"-6V-33-1C-.H-,N-,<-*q-*o-!N~q~_};|G|5yVyUxMtVmChGgZgFf9f8^7XzW)V)UzUAU/O{MpLeJ#G&FyEuDvDaARAM>sb._,A$C",jiong:"-69-3'-1.-1$-0}}z|K{;]~]}?M=J7e4t4I3c2T2S1W1.",tui:"-6.-6(-3&y'tmo$ftfodrY(F>24",nan:"-6+-*|-$r~'~#v=tzstrb^e[sXfPqN*M6H}:d29&a&?",xiao:"-6*-5v-5R-3a-.x-,d-'j-'1-&l-&P-$}-$1-#D-#?-#&-!|-!v~c~J~CuUtHqGpPpJoKlGh/fFcJ_iX;V:TPT/SoSnQVQ'P;MiMaLOK+DOCYCLBAB4>B===8M=5;9*7)`$V$O!r",guang:"-5~-2}-1h-'@{~uIhXhTgOZsVKL+>28)5/4b4_4^3s.d+Y*U",ku:"-5}-/3-&Q-$6~R}PzrhDh+gN]dZiZ5OPMgL!I%3N.>$9",jun:"-5{-2T-0q-(n-(G|u{NuHollq_;Z3U5TzQPKMJH@F=l6V3G1B*1&'!Q!K!J",zu:"-5w-5?-+1-+$-&S-%rlYlAd(S#M1Ix0'*e",hun:"-5s-4o}_t9t'o9dMaz`oYDR?Q~JYJRBf=u>=4:&9z828&+F*L(F&r",lia:"-5[-5>",pai:"-5Q-&sg9eP[NY?JU?p>+;j;8/t.w,q",biao:"-5O-36-2/yJtIryi%f!VfNhLjFzEG<.9C66511o0c,k#|",fei:"-5M-.m-+M-*4-(i-%8w%vZt@t?nXh8gpgPbH]xSdQxQ%P:OPNLLxJVH5FOF)Di?Wq>O>N;y8^6F3{/(,T+P*M#y#5!Y",song:"-4q-3I-0D-)'u8pulDk^kOgydYdAb`a3a$`D_MZ#XXW0NK%J`HyEF-#*-!K~Oz%x#s{sXs9s%quqqq_q%kcj[jWhCgDexdha/_AVwV_U0U&R]R.Q:PwO?MHKpK]J{HvHdFbDMDI=_;E:U:K9d9O8K8F6j6i6N6=6&5~5o5j5M5A2w2r2_1x1)0b*:)*(y(S'i'5'%#j#;!B!;",ruan:"-4[zJxQsiVWOUE0):'}",chun:"-4Y-&7sda^RPR(PlOONDIBGrFQE(=T<,:[9N8u/6)C",ruo:"-4S-)[sskPf]Z:YUI8;y3'0^",dang:"-4M-2P-1V-/k-!1}*{fx]swpkl6kdf:aAZUUsTpKiEYD5@|8:7E5D*;(J(6'?%}",huang:"-4@-1L-/w-$PzDz.xtw&s[pEl9jBi0e@clcQa_a#`dXTQgQfPBOEHbH7D{@9:x9i8)4:2c2.1J0X+w)((E#i!}!g!Z",duan:"-4+-.Uz+s`SFS[$XOVUU8U*TwR1Q&PYKrEy6E5K't'k'c",za:"-4$-+Z-'b-'X-'2-$c-!c~B~:~5i}]s[$NyKr?r?a",lou:"-4#-38-.}-$7-#ByMu4tRo{n[kjkEg_`5X)W'HaG#:O9&8~1i'2$5#o#n",sou:"-3z-0J-)Q-)N-#z-#R-#QgsghZ#YvWlW>W0V:U`UBJ/DgCn:#,5#s",yuan:"-3u-1n-1)-0h-.z-*3-*1-)y-(0-&^-$Y-!<}{}t}Z}R}N}M}D{t{_yawlv6v(sSs:s)qhpepH0ErDk@/P>#;L9A8M.|,&&B%y%n%m",bang:"-3n{^ypiNi5h~hme|Z?YrWvS2KEJTJSH@=j/m++",shan:"-3h-3)-2R-/F-/<-.a-.E-*~-$q-$F-#H}'{Gy+y*ulubr2nDj|i(f+]zZ;Y3XuXsWaVhV?UySvQ8NrL|LlIVFSEhCI@`7|7p7O5F4B2Z211~.4*b%U%1",que:"-3f-*_-*W{Pyty$lgbNa+`KX!T8T.JBH$@j4e0|)O#q!N",nuo:"-3Q-1w-$ftxa6_#_!ZLXnWoWbWLK0HJF2Am",can:"-3P-2F-)l-)k-)j-)i-$D-#H~:r(q3amah`W`V`U_[XsVqVhO_BtBg;/784z1!0L(9",lei:"-3O-24-1t-,J-)q-#1|(z0xOx?rrU|U;G'E]DyDxD/?$>I=+JO7F5&2>1#(](7#&#%",cao:"-3L-#GnGk@`v`k`^_DVAUqOgOfG:8x",ao:"-3H-/n-*&-#X-#W|H|4xnxkv}vyvwsDs2rZmxmakAjnga`O_@]I]![DVuUeTBM*K=?>9;7M741m1^0Z,!+~(Y",cou:"-3D-0:Hl;1",chuang:"-3B-/b-/K-/5-.s-.i-.L-$T-!dhvhMd=`|W7O|;z;+:t8(+1*c)o)j)=$R!D",sai:"-2V-#b-#)-!/yod%a2XaAxAb",tai:"-2B-0_-)=}e|Mw[wXwOvzqvqCdodQdB`e[pU]SpR]MeE>@f@D@C>{:=4G4F1$*f",lan:"-2?-1@-)}-%P-!'~3|hx`xXt(qgqaqUmwkwhgb)_8_'^p[5X/UXU(TmSaS_PpLbHXDDD2D1=^9L8i7K6W5`5W5=5<46121%0n0d0I0@0>($'j",meng:"-2;-0k-,Lwaw`qEo2hnh*_._+^qXtUaP)O9K$F;EAANAF:A6h,Z+]'/&X#B!#",qiong:"-28-*fr.pza]`!K}F(3(3%2L1}*))J(G's'f",lie:"-25-0N-/O-,z-,w-,`-'<-&G{D{CuDjaj=djZeZ_YiUEL;JMA{>_=p403f2A1$0a0[.x,h,V+k+[",teng:"-2%i+9]8r1e%6%&",long:"-2#-'J-&]~^|7|6xHxGo2n=k6j_j^g.e([9U.QmOxO8LgKDGYDU>t:g9T9%5w0N*Z'n#f",rang:"-1}-,$~Nx[xC^mU$5b0K+S'X",xiong:"-1m-1j-/q-+v-+p-&zwsdLc?Sy@;>42w2r2#2!",chong:"-1l-0Y-#L{*p`oflelde0dc`+_dXT2NB6[6G5|5u$P",rui:"-1g-1e-1`-)LxFas]0M~KVF.@G)'&t",ke:"-1f-/*-.w-,]-,R-+;-)>-'o-'0-$!|Dzqx4u#p^oUmomIkvknjqc4bra6U4U0!/N//*j%>$O",tu:"-1c-1]-0H-/o-(y-&3-%?}n}c}J}I}A}?zezZyvxipvnUlskikFh.gVeVc}bsZ.YYX@W2K?EL@R=C=::r7u(i$r$>",nei:"-1I-1*-&TtvA(=w::8Q7V631r1[*a)~)%(v(?&S&>&%%r$(#d",shou:"-13-)`-)V-%l-!o{ox)x&pxo[]v]uYITcTN,",mei:"-0I~j|vz>yRv#sks]sTs4r

-+b-+(-(_-(.-&h-#%{@wGuWs}s|rJrDlaWTV}V+NAMvKfIgGKFX9a7c,7&]&+%~",bie:"-/A-/;fGe2`#M'M!$!#I",pao:"-/>-+i-'^~o|2w=hA]$[P?.4J4H3d06.M'^%A!S",geng:"-/7-&A{TzHlrh=ZIOlK4IX=X2p&M",shua:"-//-%j",cuo:"-.y-.p-*5wukWkSh!ZKY&WuV4(o$j$'",kei:"-.woU",la:"-.v-%3-$n~L|8[RXFXEWnUEU2R`MOI6DT:T0['o$A",pou:"-.l-'_-&[{]twtO]+]&Z+YGJS/<",tuan:"-.I~!}~}K}HyPy&f7`>[}XIVmGLE;;.:m8t2[,F%v%p",zuan:"-.)XOTt",keng:"-,x-([|t|kvIZCXlVgBF/C",gao:"-,Z-(I-(>wRlpWjNHGxGwGdG>E~E3Dm,)!y!t",lang:"-,V-&J-$~{Jy[r{llgiSeOIOHO;KRHHG4Cp=[3Y,z*%(s",weng:"-,@-#oyxv{kfU!Pd9o'N'&",tao:"-+m-)E-'+-%DwPwMw*r}i/fl`j[oYBWXL,JkGtE?><=)'v",cen:"-)l-)k-)j-)i{Un#kH@?=1",shuang:"-)byOqeq^`NDB>t8R5w5^0&",po:"-)8-&M-#6~]|ZvztMoZmlmZg9W]TXR+O*E%?E>q>o>D;*:J8;6F3v,9*l!`",a:"-(s-'o-%O-$0",tun:"-(k-(7-%L-!`}}|snFhNdP_mRQPFOC@x=335",hang:"-([{dwSvIj)dGS8NML/@.",shun:"-(ZHnF?",ne:"-(R-(8-(%-&T]0%a",chuo:"-(Q-&@-%=~Hu!t~t.ssqVa|^2Z}UuCClMi@i$fDf@b1`Y_4XyW6TMMzJ$I:GOD{=#gKfVfSfC^P^N^>[zWQW!VySKMlIvGkFdEJ:)8{4[1s/|/z,f,.*{(p%m",pen:"-('-$E-$=-!6CN;'6}'Q!=",pin:"-&~~Yuatnrvq{[AZ{H]@_/c+!)r",ha:"-&wvz",yo:"-&`-%c-$B",o:"-&X-$a-!H-!%",n:"-&)-#a",huan:"-%v-$Z-$Y~G}D{_zWw@w2r.q[pYp0okm8l!h]bVaH_I^iYpXQUnU1KyK2GBD%CPCB>1=c<~;c8V7D734/3>2I.[.;,3+R*})9(1'b$d$:",ken:"-%V{qxjc*_CX~*I",chuai:"-%=XIW}Ch",pa:"-%/vLisihd.]oX|NC@r8608)P#!",se:"-%,-$,yogK_WY%X`W~J/J.Hl",nv:"vkc7OM@!",nuan:"vcPo;`:m2X2W",shuo:"v]a'WhT'S|OKGnCn>>470W+p",niu:"v?q=dKd0]S]![DN?@8@!4u/e/d.W",rao:"u2rA]PU?KkFJ",niang:"t|r&qb",shui:"t]iTZMYuA$A#@{=.=*",nve:"t)%S$%",nen:"sirarYc^",niao:"s!r+qsnwFq9x",kuan:"pBp#ooK)CoCfCd",cuan:"jPV'U*T~TwDtD7BU@o6E5K1S0<",te:"dsdr`R/F/9",zen:"d5VU",zei:"^H",den:"][]C",zhua:"],ZYV#ER0:09",shuan:"[&L^GL{let t=0,n=1;for(let a=e.length;a--;)t+=n*sa.indexOf(e.charAt(a)),n*=91;return t},Ft=(e,t)=>{let n,a,o,s,w;for(n in e)if(e.hasOwnProperty(n))for(a=e[n].match(ua),o=0;o(dn("data-v-bdff5e8a"),e=e(),gn(),e),pa={key:0},ha={class:"container"},va={class:"action-bar"},ma=["title"],$a=["title"],ya=["title"],ba=["src"],wa={key:0,class:"icon",style:{cursor:"pointer"}},_a={key:2,"flex-placeholder":""},ka={key:3,class:"action-bar"},Oa={key:0,class:"gen-info"},La={class:"info-tags"},za={class:"info-tag"},xa={class:"name"},Ca=["title"],Ea={class:"name"},Ma=["title","onDblclick"],Sa={key:0,class:"tags-container"},Fa={style:{display:"inline-block",width:"32px"}},Pa=["onClick"],Ia=["onClick"],Aa={class:"lr-layout-control"},Da={class:"ctrl-item"},Ta={class:"ctrl-item"},ja={class:"ctrl-item"},Wa=me(()=>M("br",null,null,-1)),qa=me(()=>M("h3",null,"Prompt",-1)),Ua=["innerHTML"],Ba=me(()=>M("br",null,null,-1)),Na=me(()=>M("h3",null,"Negative Prompt",-1)),Ha=["innerHTML"],Xa=me(()=>M("br",null,null,-1)),Ja=me(()=>M("h3",null,"Params",-1)),Va={style:{"font-weight":"600","text-transform":"capitalize"}},Ga=["onDblclick"],Ya=["onDblclick"],Za=["title"],Ka=xt({__name:"fullScreenContextMenu",props:{file:{},idx:{}},emits:["contextMenuClick"],setup(e,{emit:t}){const n=e;en(i=>({"5fcd4629":c(m)?0:"46px",a6e55e48:c(l)+"px","0cfa8da0":`calc(100vw - ${c(l)}px)`}));const a=Ye(),o=tn(),s=te(),w=Q(()=>o.tagMap.get(n.file.fullpath)??[]),x=te(""),y=Ge(),_=te(""),k=Q(()=>_.value.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")),I=Q(()=>k.value.split(` +`)),b=Q(()=>Be(k.value)),F=Q(()=>{let i=Be(k.value);return delete i.prompt,delete i.negativePrompt,i});he(()=>{var i;return(i=n==null?void 0:n.file)==null?void 0:i.fullpath},async i=>{i&&(y.tasks.forEach(d=>d.cancel()),y.pushAction(()=>qe(i)).res.then(d=>{_.value=d}))},{immediate:!0});const L=be("iib@fullScreenContextMenu.prompt-tab","structedData"),g=te(),r=te(),C={left:100,top:100,width:512,height:384,expanded:!0},D=be("fullScreenContextMenu.vue-drag",C);D.value&&(D.value.left<0||D.value.top<0)&&(D.value={...C});const{isLeftRightLayout:S,lrLayoutInfoPanelWidth:l,lrMenuAlwaysOn:m}=la(),p=S;aa(s,g,r,{disbaled:p,...D.value,onDrag:ze(function(i,d){D.value={...D.value,left:i,top:d}},300),onResize:ze(function(i,d){D.value={...D.value,width:i,height:d}},300)});const N=te(!1),{isOutside:J}=Lt(Q(()=>!p.value||m.value?null:N.value?s.value:We(document.querySelectorAll(".iib-tab-edge-trigger"))));he(J,wn(i=>{N.value=!i},300));function q(i){return i.parentNode}function G(i){if(!i)return"";const d=[],ae="BREAK",B=i.replace(/>\s/g,"> ,").replace(/\sBREAK\s/g,","+ae+",").split(/[\n,]+/).map(W=>W.trim()).filter(W=>W);let P=!1;for(let W=0;WBREAK
');continue}const Z=B[W];P||(P=Z.includes("("));const ue=["tag"];P&&ue.push("has-parentheses"),Z.length<32&&ue.push("short-tag"),d.push(`${Z}`),P&&(P=!Z.includes(")"))}return d.join(a.showCommaInInfoPanel?",":" ")}ve("load",i=>{const d=i.target;d.className==="ant-image-preview-img"&&(x.value=`${d.naturalWidth} x ${d.naturalHeight}`)},{capture:!0});const Y=Q(()=>{const i=[{name:j("fileSize"),val:n.file.size}];return x.value&&i.push({name:j("resolution"),val:x.value}),i}),se=()=>{const i="Negative prompt:",d=_.value.includes(i)?_.value.split(i)[0]:I.value[0]??"";de(Fe(d.trim()))},ee=()=>document.body.requestFullscreen(),$e=i=>{de(typeof i=="object"?JSON.stringify(i,null,4):i)},f=i=>{i.key.startsWith("Arrow")?(i.stopPropagation(),i.preventDefault(),document.dispatchEvent(new KeyboardEvent("keydown",i))):i.key==="Escape"&&document.fullscreenElement&&document.exitFullscreen()};ve("dblclick",i=>{var d;((d=i.target)==null?void 0:d.className)==="ant-image-preview-img"&&xe()});const v=Q(()=>p.value||D.value.expanded),U=be(Ne+"contextShowFullPath",!1),T=Q(()=>U.value?n.file.fullpath:n.file.name),ge=be(Ne+"tagA2ZClassify",!1),Ee=Q(()=>{var ae;const i=(ae=a.conf)==null?void 0:ae.all_custom_tags.map(B=>{var W,Z;return{char:((W=B.display_name)==null?void 0:W[0])||((Z=B.name)==null?void 0:Z[0]),...B}}).reduce((B,P)=>{var Z;let W="#";if(/[a-z]/i.test(P.char))W=P.char.toUpperCase();else if(/[\u4e00-\u9fa5]/.test(P.char))try{W=((Z=/^\[?(\w)/.exec(fa(P.char)+""))==null?void 0:Z[1])??"#"}catch(ue){console.log("err",ue)}return W=W.toUpperCase(),B[W]||(B[W]=[]),B[W].push(P),B},{});return Object.entries(i??{}).sort((B,P)=>B[0].charCodeAt(0)-P[0].charCodeAt(0))});return(i,d)=>{var st;const ae=kn,B=pe,P=an,W=ln,Z=on,ue=sn,Pt=pe,ot=_n,It=$n,At=un,it=rn,Dt=cn;return $(),E("div",{ref_key:"el",ref:s,class:Se(["full-screen-menu",{"unset-size":!c(D).expanded,lr:c(p),"always-on":c(m),"mouse-in":N.value}]),onWheelCapture:d[13]||(d[13]=nn(()=>{},["stop"])),onKeydownCapture:f},[c(p)?($(),E("div",pa)):X("",!0),M("div",ha,[M("div",va,[c(p)?X("",!0):($(),E("div",{key:0,ref_key:"dragHandle",ref:r,class:"icon",style:{cursor:"grab"},title:c(j)("dragToMovePanel")},[u(c(An))],8,ma)),c(p)?X("",!0):($(),E("div",{key:1,class:"icon",style:{cursor:"pointer"},onClick:d[0]||(d[0]=h=>c(D).expanded=!c(D).expanded),title:c(j)("clickToToggleMaximizeMinimize")},[v.value?($(),le(c(Wn),{key:0})):($(),le(c(Nn),{key:1}))],8,$a)),M("div",{style:{display:"flex","flex-direction":"column","align-items":"center",cursor:"grab"},class:"icon",title:c(j)("fullscreenview"),onClick:ee},[M("img",{src:c(ea),style:{width:"21px",height:"21px","padding-bottom":"2px"},alt:""},null,8,ba)],8,ya),u(ae,{"get-popup-container":q},{overlay:z(()=>[u(hn,{file:i.file,idx:i.idx,"selected-tag":w.value,onContextMenuClick:d[1]||(d[1]=(h,V,ne)=>t("contextMenuClick",h,V,ne))},null,8,["file","idx","selected-tag"])]),default:z(()=>[c(D).expanded?X("",!0):($(),E("div",wa,[u(c(dt))]))]),_:1}),v.value?($(),E("div",_a)):X("",!0),v.value?($(),E("div",ka,[u(ae,{trigger:["hover"],"get-popup-container":q},{overlay:z(()=>[u(ue,{onClick:d[2]||(d[2]=h=>t("contextMenuClick",h,i.file,i.idx))},{default:z(()=>{var h;return[((h=c(a).conf)==null?void 0:h.launch_mode)!=="server"?($(),E(K,{key:0},[u(P,{key:"send2txt2img"},{default:z(()=>[A(O(i.$t("sendToTxt2img")),1)]),_:1}),u(P,{key:"send2img2img"},{default:z(()=>[A(O(i.$t("sendToImg2img")),1)]),_:1}),u(P,{key:"send2inpaint"},{default:z(()=>[A(O(i.$t("sendToInpaint")),1)]),_:1}),u(P,{key:"send2extras"},{default:z(()=>[A(O(i.$t("sendToExtraFeatures")),1)]),_:1}),u(W,{key:"sendToThirdPartyExtension",title:i.$t("sendToThirdPartyExtension")},{default:z(()=>[u(P,{key:"send2controlnet-txt2img"},{default:z(()=>[A("ControlNet - "+O(i.$t("t2i")),1)]),_:1}),u(P,{key:"send2controlnet-img2img"},{default:z(()=>[A("ControlNet - "+O(i.$t("i2i")),1)]),_:1}),u(P,{key:"send2outpaint"},{default:z(()=>[A("openOutpaint")]),_:1})]),_:1},8,["title"])],64)):X("",!0),u(P,{key:"send2BatchDownload"},{default:z(()=>[A(O(i.$t("sendToBatchDownload")),1)]),_:1}),u(W,{key:"copy2target",title:i.$t("copyTo")},{default:z(()=>[($(!0),E(K,null,re(c(a).quickMovePaths,V=>($(),le(P,{key:`copy-to-${V.dir}`},{default:z(()=>[A(O(V.zh),1)]),_:2},1024))),128))]),_:1},8,["title"]),u(W,{key:"move2target",title:i.$t("moveTo")},{default:z(()=>[($(!0),E(K,null,re(c(a).quickMovePaths,V=>($(),le(P,{key:`move-to-${V.dir}`},{default:z(()=>[A(O(V.zh),1)]),_:2},1024))),128))]),_:1},8,["title"]),u(Z),u(P,{key:"deleteFiles"},{default:z(()=>[A(O(i.$t("deleteSelected")),1)]),_:1}),u(P,{key:"previewInNewWindow"},{default:z(()=>[A(O(i.$t("previewInNewWindow")),1)]),_:1}),u(P,{key:"copyPreviewUrl"},{default:z(()=>[A(O(i.$t("copySourceFilePreviewLink")),1)]),_:1}),u(P,{key:"copyFilePath"},{default:z(()=>[A(O(i.$t("copyFilePath")),1)]),_:1})]}),_:1})]),default:z(()=>[u(B,null,{default:z(()=>[A(O(c(j)("openContextMenu")),1)]),_:1})]),_:1}),u(Pt,{onClick:d[3]||(d[3]=h=>t("contextMenuClick",{key:"download"},n.file,n.idx))},{default:z(()=>[A(O(i.$t("download")),1)]),_:1}),_.value?($(),le(B,{key:0,onClick:d[4]||(d[4]=h=>c(de)(_.value))},{default:z(()=>[A(O(i.$t("copyPrompt")),1)]),_:1})):X("",!0),_.value?($(),le(B,{key:1,onClick:se},{default:z(()=>[A(O(i.$t("copyPositivePrompt")),1)]),_:1})):X("",!0)])):X("",!0)]),v.value?($(),E("div",Oa,[M("div",La,[M("span",za,[M("span",xa,O(i.$t("fileName")),1),M("span",{class:"value",title:T.value,onDblclick:d[5]||(d[5]=h=>c(de)(T.value))},O(T.value),41,Ca),M("span",{style:{margin:"0 8px",cursor:"pointer"},title:"Click to expand full path",onClick:d[6]||(d[6]=h=>U.value=!c(U))},[u(c(dt))])]),($(!0),E(K,null,re(Y.value,h=>($(),E("span",{class:"info-tag",key:h.name},[M("span",Ea,O(h.name),1),M("span",{class:"value",title:h.val,onDblclick:V=>c(de)(h.val)},O(h.val),41,Ma)]))),128))]),(st=c(a).conf)!=null&&st.all_custom_tags?($(),E("div",Sa,[M("div",{class:"sort-tag-switch",onClick:d[7]||(d[7]=h=>ge.value=!c(ge))},[c(ge)?($(),le(c(xn),{key:1})):($(),le(c(Rn),{key:0}))]),M("div",{class:"tag",onClick:d[8]||(d[8]=(...h)=>c(Je)&&c(Je)(...h)),style:Me({"--tag-color":"var(--zp-luminous)"})},"+ "+O(i.$t("add")),5),c(ge)?($(!0),E(K,{key:0},re(Ee.value,([h,V])=>($(),E("div",{key:h,class:"tag-alpha-item"},[M("h4",Fa,O(h)+" : ",1),M("div",null,[($(!0),E(K,null,re(V,ne=>($(),E("div",{class:Se(["tag",{selected:w.value.some(ut=>ut.id===ne.id)}]),onClick:ut=>t("contextMenuClick",{key:`toggle-tag-${ne.id}`},i.file,i.idx),key:ne.id,style:Me({"--tag-color":c(o).getColor(ne)})},O(ne.name),15,Pa))),128))])]))),128)):($(!0),E(K,{key:1},re(c(a).conf.all_custom_tags,h=>($(),E("div",{class:Se(["tag",{selected:w.value.some(V=>V.id===h.id)}]),onClick:V=>t("contextMenuClick",{key:`toggle-tag-${h.id}`},i.file,i.idx),key:h.id,style:Me({"--tag-color":c(o).getColor(h)})},O(h.name),15,Ia))),128))])):X("",!0),M("div",Aa,[M("div",Da,[A(O(i.$t("experimentalLRLayout"))+": ",1),u(ot,{checked:c(p),"onUpdate:checked":d[9]||(d[9]=h=>ke(p)?p.value=h:null),size:"small"},null,8,["checked"])]),c(p)?($(),E(K,{key:0},[M("div",Ta,[A(O(i.$t("width"))+": ",1),u(It,{value:c(l),"onUpdate:value":d[10]||(d[10]=h=>ke(l)?l.value=h:null),style:{width:"64px"},step:16,min:128,max:1024},null,8,["value"])]),u(At,{title:i.$t("alwaysOnTooltipInfo")},{default:z(()=>[M("div",ja,[A(O(i.$t("alwaysOn"))+": ",1),u(ot,{checked:c(m),"onUpdate:checked":d[11]||(d[11]=h=>ke(m)?m.value=h:null),size:"small"},null,8,["checked"])])]),_:1},8,["title"])],64)):X("",!0)]),u(Dt,{activeKey:c(L),"onUpdate:activeKey":d[12]||(d[12]=h=>ke(L)?L.value=h:null)},{default:z(()=>[u(it,{key:"structedData",tab:i.$t("structuredData")},{default:z(()=>[M("div",null,[b.value.prompt?($(),E(K,{key:0},[Wa,qa,M("code",{innerHTML:G(b.value.prompt??"")},null,8,Ua)],64)):X("",!0),b.value.negativePrompt?($(),E(K,{key:1},[Ba,Na,M("code",{innerHTML:G(b.value.negativePrompt??"")},null,8,Ha)],64)):X("",!0)]),Object.keys(F.value).length?($(),E(K,{key:0},[Xa,Ja,M("table",null,[($(!0),E(K,null,re(F.value,(h,V)=>($(),E("tr",{key:V,class:"gen-info-frag"},[M("td",Va,O(V),1),typeof h=="object"?($(),E("td",{key:0,style:{cursor:"pointer"},onDblclick:ne=>$e(h)},[M("code",null,O(h),1)],40,Ga)):($(),E("td",{key:1,style:{cursor:"pointer"},onDblclick:ne=>$e(c(Fe)(h))},O(c(Fe)(h)),41,Ya))]))),128))])],64)):X("",!0)]),_:1},8,["tab"]),u(it,{key:"sourceText",tab:i.$t("sourceText")},{default:z(()=>[M("code",null,O(_.value),1)]),_:1},8,["tab"])]),_:1},8,["activeKey"])])):X("",!0)]),c(D).expanded&&!c(p)?($(),E("div",{key:1,class:"mouse-sensor",ref_key:"resizeHandle",ref:g,title:c(j)("dragToResizePanel")},[u(c(Sn))],8,Za)):X("",!0)],34)}}});const hl=Ct(Ka,[["__scopeId","data-v-bdff5e8a"]]),Qa={key:0,class:"float-panel"},Ra={key:0,class:"select-actions"},el={key:1},tl=xt({__name:"MultiSelectKeep",props:{show:{type:Boolean}},emits:["selectAll","reverseSelect","clearAllSelected"],setup(e,{emit:t}){const n=Ye(),a=()=>{t("clearAllSelected"),n.keepMultiSelect=!1},o=()=>{n.keepMultiSelect=!0};return(s,w)=>{const x=pe;return s.show?($(),E("div",Qa,[c(n).keepMultiSelect?($(),E("div",Ra,[u(x,{size:"small",onClick:w[0]||(w[0]=y=>t("selectAll"))},{default:z(()=>[A(O(s.$t("select-all")),1)]),_:1}),u(x,{size:"small",onClick:w[1]||(w[1]=y=>t("reverseSelect"))},{default:z(()=>[A(O(s.$t("rerverse-select")),1)]),_:1}),u(x,{size:"small",onClick:w[2]||(w[2]=y=>t("clearAllSelected"))},{default:z(()=>[A(O(s.$t("clear-all-selected")),1)]),_:1}),u(x,{size:"small",onClick:a},{default:z(()=>[A(O(s.$t("exit")),1)]),_:1})])):($(),E("div",el,[u(x,{size:"small",type:"primary",onClick:o},{default:z(()=>[A(O(s.$t("keep-multi-selected")),1)]),_:1})]))])):X("",!0)}}});const vl=Ct(tl,[["__scopeId","data-v-b6f9a67c"]]);export{rl as L,vl as M,cl as R,gl as a,fl as b,dl as c,pl as d,hl as f,ve as u}; diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/MultiSelectKeep-0ed20b3a.css b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/MultiSelectKeep-0ed20b3a.css new file mode 100644 index 0000000000000000000000000000000000000000..e3f69ad2dc2f6672782e14d380e824a533c4e351 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/MultiSelectKeep-0ed20b3a.css @@ -0,0 +1 @@ +.full-screen-menu[data-v-bdff5e8a]{position:fixed;z-index:9999;background:var(--zp-primary-background);padding:8px 16px;box-shadow:0 0 4px var(--zp-secondary);border-radius:4px}.full-screen-menu .tags-container[data-v-bdff5e8a]{margin:4px 0}.full-screen-menu .tags-container .tag[data-v-bdff5e8a]{margin-right:4px;margin-bottom:4px;padding:2px 16px;border-radius:4px;display:inline-block;cursor:pointer;font-weight:700;transition:.5s all ease;border:2px solid var(--tag-color);color:var(--tag-color);background:var(--zp-primary-background);user-select:none}.full-screen-menu .tags-container .tag.selected[data-v-bdff5e8a]{background:var(--tag-color);color:#fff}.full-screen-menu .container[data-v-bdff5e8a]{height:100%;display:flex;overflow:hidden;flex-direction:column}.full-screen-menu .gen-info[data-v-bdff5e8a]{flex:1;word-break:break-all;white-space:pre-line;overflow:auto;z-index:1;padding-top:4px;position:relative}.full-screen-menu .gen-info code[data-v-bdff5e8a]{font-size:.9em;display:block;padding:4px;background:var(--zp-primary-background);border-radius:4px;margin-right:20px;white-space:pre-wrap;word-break:break-word;line-height:1.78em}.full-screen-menu .gen-info code[data-v-bdff5e8a] .short-tag{word-break:break-all;white-space:nowrap}.full-screen-menu .gen-info code[data-v-bdff5e8a] span.tag{background:var(--zp-secondary-variant-background);color:var(--zp-primary);padding:2px 4px;border-radius:6px;margin-right:6px;margin-top:4px;line-height:1.3em;display:inline-block}.full-screen-menu .gen-info code[data-v-bdff5e8a] .has-parentheses.tag{background:rgba(255,100,100,.14)}.full-screen-menu .gen-info code[data-v-bdff5e8a] span.tag:hover{background:rgba(120,0,0,.15)}.full-screen-menu .gen-info table[data-v-bdff5e8a]{font-size:1em;border-radius:4px;border-collapse:separate;margin-bottom:3em}.full-screen-menu .gen-info table tr td[data-v-bdff5e8a]:first-child{white-space:nowrap}.full-screen-menu .gen-info table td[data-v-bdff5e8a]{padding-right:14px;padding-left:4px;border-bottom:1px solid var(--zp-secondary);border-collapse:collapse}.full-screen-menu .gen-info .info-tags .info-tag[data-v-bdff5e8a]{display:inline-block;overflow:hidden;border-radius:4px;margin-right:8px;border:2px solid var(--zp-primary)}.full-screen-menu .gen-info .info-tags .name[data-v-bdff5e8a]{background-color:var(--zp-primary);color:var(--zp-primary-background);padding:4px;border-bottom-right-radius:4px}.full-screen-menu .gen-info .info-tags .value[data-v-bdff5e8a]{padding:4px}.full-screen-menu.unset-size[data-v-bdff5e8a]{width:unset!important;height:unset!important}.full-screen-menu .mouse-sensor[data-v-bdff5e8a]{position:absolute;bottom:0;right:0;transform:rotate(90deg);cursor:se-resize;z-index:1;background:var(--zp-primary-background);border-radius:2px}.full-screen-menu .mouse-sensor>*[data-v-bdff5e8a]{font-size:18px;padding:4px}.full-screen-menu .action-bar[data-v-bdff5e8a]{display:flex;align-items:center;user-select:none;gap:4px}.full-screen-menu .action-bar .icon[data-v-bdff5e8a]{font-size:1.5em;padding:2px 4px;border-radius:4px}.full-screen-menu .action-bar .icon[data-v-bdff5e8a]:hover{background:var(--zp-secondary-variant-background)}.full-screen-menu .action-bar>*[data-v-bdff5e8a]{flex-wrap:wrap}.full-screen-menu.lr[data-v-bdff5e8a]{top:var(--5fcd4629)!important;right:0!important;bottom:0!important;left:100vw!important;height:unset!important;width:var(--a6e55e48)!important;transition:left ease .3s}.full-screen-menu.lr.always-on[data-v-bdff5e8a],.full-screen-menu.lr.mouse-in[data-v-bdff5e8a]{left:var(--0cfa8da0)!important}.tag-alpha-item[data-v-bdff5e8a]{display:flex;margin-top:4px}.tag-alpha-item h4[data-v-bdff5e8a]{width:32px;flex-shrink:0}.sort-tag-switch[data-v-bdff5e8a]{display:inline-block;padding-right:16px;padding-left:8px;cursor:pointer;user-select:none}.sort-tag-switch span[data-v-bdff5e8a]{transition:all ease .3s;transform:scale(1.2)}.sort-tag-switch:hover span[data-v-bdff5e8a]{transform:scale(1.3)}.lr-layout-control[data-v-bdff5e8a]{display:flex;align-items:center;gap:16px;padding:4px 8px;flex-wrap:wrap;border-radius:2px;border-left:3px solid var(--zp-luminous);background-color:var(--zp-secondary-background)}.lr-layout-control .ctrl-item[data-v-bdff5e8a]{display:flex;align-items:center;gap:4px;flex-wrap:nowrap}.select-actions[data-v-b6f9a67c]>:not(:last-child){margin-right:4px}.float-panel[data-v-b6f9a67c]{position:absolute;bottom:32px;right:32px;background:var(--zp-primary-background);border-radius:4px;z-index:1000;padding:8px;box-shadow:0 0 4px var(--zp-secondary)} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/SubstrSearch-45f76b80.js b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/SubstrSearch-45f76b80.js new file mode 100644 index 0000000000000000000000000000000000000000..e3d594ce7bdcaea21a2c30211a680f599e419b3f --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/SubstrSearch-45f76b80.js @@ -0,0 +1 @@ +import{c as s,A as Me,d as ze,r as k,o as De,c7 as X,m as Fe,B as Ve,ax as Be,y as Ue,z as Ee,C as Y,c8 as He,$ as Pe,S as g,T as A,a1 as t,a2 as e,U as u,V as i,W as o,a0 as b,Y as _,a3 as V,cj as Te,ae as R,a4 as Z,J as Ge,ad as Ke,X as Ne,R as ee,ah as je,ai as te,cc as Je,ag as Le,aN as qe,aO as We,ck as Qe,ce as Xe,Z as Ye}from"./index-bd4c24ce.js";import{S as Ze}from"./index-0c3c532d.js";/* empty css */import"./index-dbe83aae.js";import{c as et,d as tt,F as st}from"./FileItem-3771a510.js";import{M as at,L as lt,R as nt,f as ot}from"./MultiSelectKeep-09d43067.js";import{c as it,u as rt}from"./hook-5a401311.js";import{f as O,H as se,_ as dt,a as ut}from"./searchHistory-9695d8f0.js";import"./functionalCallableComp-8b0d9f43.js";/* empty css */import"./_isIterateeCall-eeca32c3.js";import"./index-afbe1fb8.js";import"./shortcut-16a42bc1.js";import"./Checkbox-6eb6dd6a.js";import"./index-dfa3dc65.js";var ct={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"defs",attrs:{},children:[{tag:"style",attrs:{}}]},{tag:"path",attrs:{d:"M952 474H829.8C812.5 327.6 696.4 211.5 550 194.2V72c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v122.2C327.6 211.5 211.5 327.6 194.2 474H72c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h122.2C211.5 696.4 327.6 812.5 474 829.8V952c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V829.8C696.4 812.5 812.5 696.4 829.8 550H952c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8zM512 756c-134.8 0-244-109.2-244-244s109.2-244 244-244 244 109.2 244 244-109.2 244-244 244z"}},{tag:"path",attrs:{d:"M512 392c-32.1 0-62.1 12.4-84.8 35.2-22.7 22.7-35.2 52.7-35.2 84.8s12.5 62.1 35.2 84.8C449.9 619.4 480 632 512 632s62.1-12.5 84.8-35.2C619.4 574.1 632 544 632 512s-12.5-62.1-35.2-84.8A118.57 118.57 0 00512 392z"}}]},name:"aim",theme:"outlined"};const pt=ct;function ae(c){for(var p=1;p(qe("data-v-5145f12c"),c=c(),We(),c),mt={style:{"padding-right":"16px"}},ht=U(()=>u("div",null,null,-1)),_t=["title"],yt=["src"],bt={class:"search-bar"},kt={class:"form-name"},wt={class:"search-bar last actions"},St={class:"hint"},Ct={key:0,style:{margin:"64px 16px 32px",padding:"8px",background:"var(--zp-secondary-variant-background)","border-radius":"16px"}},xt={style:{margin:"16px 32px 16px"}},It={style:{"padding-right":"16px"}},$t=U(()=>u("div",null,null,-1)),At=U(()=>u("div",{style:{padding:"16px 0 512px"}},null,-1)),Rt={key:2,class:"preview-switch"},Ot=ze({__name:"SubstrSearch",props:{tabIdx:{},paneIdx:{},searchScope:{}},setup(c){const p=c,d=k(!1),f=k(""),h=k(!1),w=k(p.searchScope??""),C=k(!1),E=k(0),M=it(l=>{const a={cursor:l,regexp:d.value?f.value:"",surstr:d.value?"":f.value,path_only:h.value,folder_paths:(w.value??"").split(/,|\n/).map(r=>r.trim()).filter(r=>r)};return Qe(a)}),{queue:S,images:m,onContextMenuClickU:H,stackViewEl:le,previewIdx:x,previewing:P,onPreviewVisibleChange:ne,previewImgMove:T,canPreview:G,itemSize:K,gridItems:oe,showGenInfo:I,imageGenInfo:N,q:ie,multiSelectedIdxs:z,onFileItemClick:re,scroller:j,showMenuIdx:D,onFileDragStart:de,onFileDragEnd:ue,cellWidth:ce,onScroll:J,saveAllFileAsJson:pe,saveLoadedFileAsJson:fe,props:ve,changeIndchecked:ge,seedChangeChecked:me,getGenDiff:he,getGenDiffWatchDep:_e}=rt(M),v=k();De(async()=>{v.value=await X(),v.value.img_count&&v.value.expired&&await L(),p.searchScope&&await $()}),Fe(()=>p,async l=>{ve.value=l},{deep:!0,immediate:!0});const L=Ve(()=>S.pushAction(async()=>(await Xe(),v.value=await X(),v.value)).res),q=l=>{f.value=l.substr,w.value=l.folder_paths_str,d.value=l.isRegex,C.value=!1,$()},$=async()=>{E.value++,O.value.add({substr:f.value,folder_paths_str:w.value,isRegex:d.value}),await M.reset({refetch:!0}),await Be(),J(),j.value.scrollToItem(0),m.value.length||Ue.info(Ee("fuzzy-search-noResults"))};Y("returnToIIB",async()=>{const l=await S.pushAction(He).res;v.value.expired=l.expired}),Y("searchIndexExpired",()=>v.value&&(v.value.expired=!0));const ye=()=>{d.value=!d.value},be=Pe(),{onClearAllSelected:ke,onSelectAll:we,onReverseSelect:Se}=et();return(l,a)=>{const r=dt,y=ut,Ce=ee,xe=je,W=te,Ie=Je,F=te,$e=Le,Ae=ee,Re=Ze;return g(),A(Ne,null,[s(Ce,{visible:C.value,"onUpdate:visible":a[0]||(a[0]=n=>C.value=n),width:"70vw","mask-closable":"",onOk:a[1]||(a[1]=n=>C.value=!1)},{default:t(()=>[s(se,{records:e(O),onReuseRecord:q},{default:t(({record:n})=>[u("div",mt,[s(y,null,{default:t(()=>[s(r,{span:4},{default:t(()=>[i(o(l.$t("historyRecordsSubstr"))+":",1)]),_:1}),s(r,{span:20},{default:t(()=>[i(o(n.substr),1)]),_:2},1024)]),_:2},1024),n.folder_paths_str?(g(),b(y,{key:0},{default:t(()=>[s(r,{span:4},{default:t(()=>[i(o(l.$t("searchScope"))+":",1)]),_:1}),s(r,{span:20},{default:t(()=>[i(o(n.folder_paths_str),1)]),_:2},1024)]),_:2},1024)):_("",!0),s(y,null,{default:t(()=>[s(r,{span:4},{default:t(()=>[i(o(l.$t("historyRecordsisRegex"))+":",1)]),_:1}),s(r,{span:20},{default:t(()=>[i(o(n.isRegex),1)]),_:2},1024)]),_:2},1024),s(y,null,{default:t(()=>[s(r,{span:4},{default:t(()=>[i(o(l.$t("time"))+":",1)]),_:1}),s(r,{span:20},{default:t(()=>[i(o(n.time),1)]),_:2},1024)]),_:2},1024),ht])]),_:1},8,["records"])]),_:1},8,["visible"]),u("div",{class:"container",ref_key:"stackViewEl",ref:le},[s(at,{show:!!e(z).length||e(be).keepMultiSelect,onClearAllSelected:e(ke),onSelectAll:e(we),onReverseSelect:e(Se)},null,8,["show","onClearAllSelected","onSelectAll","onReverseSelect"]),v.value?(g(),A("div",{key:0,class:"search-bar",onKeydown:a[6]||(a[6]=V(()=>{},["stop"]))},[s(xe,{value:f.value,"onUpdate:value":a[2]||(a[2]=n=>f.value=n),placeholder:l.$t("fuzzy-search-placeholder")+" "+l.$t("regexSearchEnabledHint"),disabled:!e(S).isIdle,onKeydown:Te($,["enter"]),"allow-clear":""},null,8,["value","placeholder","disabled","onKeydown"]),u("div",{class:R(["regex-icon",{selected:h.value}]),onKeydown:a[3]||(a[3]=V(()=>{},["stop"])),onClick:a[4]||(a[4]=n=>h.value=!h.value),title:l.$t("pathOnly")},[s(e(vt))],42,_t),u("div",{class:R(["regex-icon",{selected:d.value}]),onKeydown:a[5]||(a[5]=V(()=>{},["stop"])),onClick:ye,title:"Use Regular Expression"},[u("img",{src:e(gt)},null,8,yt)],34),v.value.expired||!v.value.img_count?(g(),b(W,{key:0,onClick:e(L),loading:!e(S).isIdle,type:"primary"},{default:t(()=>[i(o(v.value.img_count===0?l.$t("generateIndexHint"):l.$t("UpdateIndex")),1)]),_:1},8,["onClick","loading"])):(g(),b(W,{key:1,type:"primary",onClick:$,loading:!e(S).isIdle||e(M).loading,disabled:!f.value&&!w.value},{default:t(()=>[i(o(l.$t("search")),1)]),_:1},8,["loading","disabled"]))],32)):_("",!0),u("div",bt,[u("div",kt,o(l.$t("searchScope")),1),s(Ie,{"auto-size":{maxRows:8},value:w.value,"onUpdate:value":a[7]||(a[7]=n=>w.value=n),placeholder:l.$t("specifiedSearchFolder")},null,8,["value","placeholder"])]),u("div",wt,[e(m).length?(g(),b(F,{key:0,onClick:e(fe)},{default:t(()=>[i(o(l.$t("saveLoadedImageAsJson")),1)]),_:1},8,["onClick"])):_("",!0),e(m).length?(g(),b(F,{key:1,onClick:e(pe)},{default:t(()=>[i(o(l.$t("saveAllAsJson")),1)]),_:1},8,["onClick"])):_("",!0),s(F,{onClick:a[8]||(a[8]=n=>C.value=!0)},{default:t(()=>[i(o(l.$t("history")),1)]),_:1})]),s(Re,{size:"large",spinning:!e(S).isIdle},{default:t(()=>[s(Ae,{visible:e(I),"onUpdate:visible":a[10]||(a[10]=n=>Z(I)?I.value=n:null),width:"70vw","mask-closable":"",onOk:a[11]||(a[11]=n=>I.value=!1)},{cancelText:t(()=>[]),default:t(()=>[s($e,{active:"",loading:!e(ie).isIdle},{default:t(()=>[u("div",{style:{width:"100%","word-break":"break-all","white-space":"pre-line","max-height":"70vh",overflow:"auto"},onDblclick:a[9]||(a[9]=n=>e(Ge)(e(N)))},[u("div",St,o(l.$t("doubleClickToCopy")),1),i(" "+o(e(N)),1)],32)]),_:1},8,["loading"])]),_:1},8,["visible"]),E.value===0&&!e(m).length&&e(O).getRecords().length?(g(),A("div",Ct,[u("h2",xt,o(l.$t("restoreFromHistory")),1),s(se,{records:e(O),onReuseRecord:q},{default:t(({record:n})=>[u("div",It,[s(y,null,{default:t(()=>[s(r,{span:4},{default:t(()=>[i(o(l.$t("historyRecordsSubstr"))+":",1)]),_:1}),s(r,{span:20},{default:t(()=>[i(o(n.substr),1)]),_:2},1024)]),_:2},1024),n.folder_paths_str?(g(),b(y,{key:0},{default:t(()=>[s(r,{span:4},{default:t(()=>[i(o(l.$t("searchScope"))+":",1)]),_:1}),s(r,{span:20},{default:t(()=>[i(o(n.folder_paths_str),1)]),_:2},1024)]),_:2},1024)):_("",!0),s(y,null,{default:t(()=>[s(r,{span:4},{default:t(()=>[i(o(l.$t("historyRecordsisRegex"))+":",1)]),_:1}),s(r,{span:20},{default:t(()=>[i(o(n.isRegex),1)]),_:2},1024)]),_:2},1024),s(y,null,{default:t(()=>[s(r,{span:4},{default:t(()=>[i(o(l.$t("time"))+":",1)]),_:1}),s(r,{span:20},{default:t(()=>[i(o(n.time),1)]),_:2},1024)]),_:2},1024),$t])]),_:1},8,["records"])])):_("",!0),e(m)?(g(),b(e(tt),{key:1,ref_key:"scroller",ref:j,class:"file-list",items:e(m),"item-size":e(K).first,"key-field":"fullpath","item-secondary-size":e(K).second,gridItems:e(oe),onScroll:e(J)},{after:t(()=>[At]),default:t(({item:n,index:Q})=>[s(st,{idx:Q,file:n,"show-menu-idx":e(D),"onUpdate:showMenuIdx":a[12]||(a[12]=Oe=>Z(D)?D.value=Oe:null),onFileItemClick:e(re),"full-screen-preview-image-url":e(m)[e(x)]?e(Ke)(e(m)[e(x)]):"","cell-width":e(ce),selected:e(z).includes(Q),onContextMenuClick:e(H),onDragstart:e(de),onDragend:e(ue),"enable-change-indicator":e(ge),"seed-change-checked":e(me),"get-gen-diff":e(he),"get-gen-diff-watch-dep":e(_e),"is-selected-mutil-files":e(z).length>1,onPreviewVisibleChange:e(ne)},null,8,["idx","file","show-menu-idx","onFileItemClick","full-screen-preview-image-url","cell-width","selected","onContextMenuClick","onDragstart","onDragend","enable-change-indicator","seed-change-checked","get-gen-diff","get-gen-diff-watch-dep","is-selected-mutil-files","onPreviewVisibleChange"])]),_:1},8,["items","item-size","item-secondary-size","gridItems","onScroll"])):_("",!0),e(P)?(g(),A("div",Rt,[s(e(lt),{onClick:a[13]||(a[13]=n=>e(T)("prev")),class:R({disable:!e(G)("prev")})},null,8,["class"]),s(e(nt),{onClick:a[14]||(a[14]=n=>e(T)("next")),class:R({disable:!e(G)("next")})},null,8,["class"])])):_("",!0)]),_:1},8,["spinning"]),e(P)&&e(m)&&e(m)[e(x)]?(g(),b(ot,{key:1,file:e(m)[e(x)],idx:e(x),onContextMenuClick:e(H)},null,8,["file","idx","onContextMenuClick"])):_("",!0)],512)],64)}}});const Jt=Ye(Ot,[["__scopeId","data-v-5145f12c"]]);export{Jt as default}; diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/SubstrSearch-d173de8d.css b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/SubstrSearch-d173de8d.css new file mode 100644 index 0000000000000000000000000000000000000000..becbd193cc0402be6bdd2967d4e2196bf90111c9 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/SubstrSearch-d173de8d.css @@ -0,0 +1 @@ +[data-v-5145f12c] .float-panel{position:fixed}.regex-icon[data-v-5145f12c]{user-select:none;padding:4px;margin:0 4px;cursor:pointer;border:1px solid var(--zp-border);border-radius:4px}.regex-icon img[data-v-5145f12c]{height:1.5em}.regex-icon[data-v-5145f12c]:hover{background:var(--zp-border)}.regex-icon.selected[data-v-5145f12c]{background:var(--primary-color-1);border:1px solid var(--primary-color)}.search-bar[data-v-5145f12c]{padding:8px 8px 0;display:flex}.search-bar.last[data-v-5145f12c]{padding-bottom:8px}.search-bar .form-name[data-v-5145f12c]{flex-shrink:0;padding:4px 8px}.search-bar .actions>*[data-v-5145f12c]{margin-right:4px}.container[data-v-5145f12c]{background:var(--zp-secondary-background);position:relative}.container .file-list[data-v-5145f12c]{list-style:none;padding:8px;height:100%;overflow:auto;height:var(--pane-max-height);width:100%} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/TagSearch-2739a812.css b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/TagSearch-2739a812.css new file mode 100644 index 0000000000000000000000000000000000000000..b956c80109e4c9c11a6a75cec36657af70b1f30a --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/TagSearch-2739a812.css @@ -0,0 +1 @@ +@charset "UTF-8";.ant-collapse{box-sizing:border-box;margin:0;padding:0;color:#000000d9;font-size:14px;font-variant:tabular-nums;line-height:1.5715;list-style:none;font-feature-settings:"tnum";background-color:#fafafa;border:1px solid #d9d9d9;border-bottom:0;border-radius:2px}.ant-collapse>.ant-collapse-item{border-bottom:1px solid #d9d9d9}.ant-collapse>.ant-collapse-item:last-child,.ant-collapse>.ant-collapse-item:last-child>.ant-collapse-header{border-radius:0 0 2px 2px}.ant-collapse>.ant-collapse-item>.ant-collapse-header{position:relative;display:flex;flex-wrap:nowrap;align-items:flex-start;padding:12px 16px;color:#000000d9;line-height:1.5715;cursor:pointer;transition:all .3s,visibility 0s}.ant-collapse>.ant-collapse-item>.ant-collapse-header .ant-collapse-arrow{display:inline-block;margin-right:12px;font-size:12px;vertical-align:-1px}.ant-collapse>.ant-collapse-item>.ant-collapse-header .ant-collapse-arrow svg{transition:transform .24s}.ant-collapse>.ant-collapse-item>.ant-collapse-header .ant-collapse-extra{margin-left:auto}.ant-collapse>.ant-collapse-item>.ant-collapse-header:focus{outline:none}.ant-collapse>.ant-collapse-item .ant-collapse-header-collapsible-only{cursor:default}.ant-collapse>.ant-collapse-item .ant-collapse-header-collapsible-only .ant-collapse-header-text{cursor:pointer}.ant-collapse>.ant-collapse-item.ant-collapse-no-arrow>.ant-collapse-header{padding-left:12px}.ant-collapse-icon-position-right>.ant-collapse-item>.ant-collapse-header{position:relative;padding:12px 40px 12px 16px}.ant-collapse-icon-position-right>.ant-collapse-item>.ant-collapse-header .ant-collapse-arrow{position:absolute;top:50%;right:16px;left:auto;margin:0;transform:translateY(-50%)}.ant-collapse-content{color:#000000d9;background-color:#fff;border-top:1px solid #d9d9d9}.ant-collapse-content>.ant-collapse-content-box{padding:16px}.ant-collapse-content-hidden{display:none}.ant-collapse-item:last-child>.ant-collapse-content{border-radius:0 0 2px 2px}.ant-collapse-borderless{background-color:#fafafa;border:0}.ant-collapse-borderless>.ant-collapse-item{border-bottom:1px solid #d9d9d9}.ant-collapse-borderless>.ant-collapse-item:last-child,.ant-collapse-borderless>.ant-collapse-item:last-child .ant-collapse-header{border-radius:0}.ant-collapse-borderless>.ant-collapse-item>.ant-collapse-content{background-color:transparent;border-top:0}.ant-collapse-borderless>.ant-collapse-item>.ant-collapse-content>.ant-collapse-content-box{padding-top:4px}.ant-collapse-ghost{background-color:transparent;border:0}.ant-collapse-ghost>.ant-collapse-item{border-bottom:0}.ant-collapse-ghost>.ant-collapse-item>.ant-collapse-content{background-color:transparent;border-top:0}.ant-collapse-ghost>.ant-collapse-item>.ant-collapse-content>.ant-collapse-content-box{padding-top:12px;padding-bottom:12px}.ant-collapse .ant-collapse-item-disabled>.ant-collapse-header,.ant-collapse .ant-collapse-item-disabled>.ant-collapse-header>.arrow{color:#00000040;cursor:not-allowed}.ant-collapse-rtl{direction:rtl}.ant-collapse-rtl .ant-collapse>.ant-collapse-item>.ant-collapse-header{padding:12px 40px 12px 16px}.ant-collapse-rtl.ant-collapse>.ant-collapse-item>.ant-collapse-header .ant-collapse-arrow{margin-right:0;margin-left:12px}.ant-collapse-rtl.ant-collapse>.ant-collapse-item>.ant-collapse-header .ant-collapse-arrow svg{transform:rotate(180deg)}.ant-collapse-rtl.ant-collapse>.ant-collapse-item>.ant-collapse-header .ant-collapse-extra{margin-right:auto;margin-left:0}.ant-collapse-rtl.ant-collapse>.ant-collapse-item.ant-collapse-no-arrow>.ant-collapse-header{padding-right:12px;padding-left:0}.small-alpha-slider{height:10px!important}.small-alpha-slider .small-bar{height:10px!important;width:10px!important}.small-alpha-slider .small-bar div{width:12px!important;height:12px!important;border-radius:5px!important;transform:translate(-6px,-2px);margin-top:1px!important}.bee-alpha-slider{position:relative;margin-bottom:15px;width:100%;height:14px;box-shadow:2px 0 8px #00000014;border-radius:15px}.bee-alpha-slider.is-vertical{width:14px;height:100%;display:inline-block;transform:rotate(180deg)}.bee-alpha-slider.transparent{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.bee-alpha-slider__bar{position:relative;width:100%;height:100%;border-radius:15px}.bee-alpha-slider__bar-pointer{position:absolute;width:14px;height:14px}.bee-alpha-slider__bar-handle{width:14px;height:14px;border-radius:6px;transform:translate(-7px,-2px);background-color:#f8f8f8;margin-top:2px;box-shadow:0 1px 4px #0000005e;cursor:pointer}.bee-alpha-slider__bar-handle.vertical{transform:translateY(-7px);margin-top:0}.bee-compact{margin-bottom:15px;width:auto;box-shadow:3px 0 5px #00000014;display:inline-block}.bee-compact__row{position:relative;width:100%;margin:0}.bee-compact__row>*{display:inline-block;vertical-align:middle}.bee-compact__color_cube{width:100%;height:100%}.bee-compact__color_cube.transparent:before{content:"";position:absolute;top:0;left:0;width:100%;height:100%;background:white}.bee-compact__color_cube.transparent:after{content:"";position:absolute;top:100%;left:0;transform:rotate(-45deg);transform-origin:0 0;width:35px;height:1px;background:red}.bee-compact__color_cube.advance{background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAdCAYAAAC9pNwMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABqVJREFUeNrEl11yHDUQx1ua2Zlde2M7jqESqnjg45kjcBwOwQG4BY+8cwWK17xBUUARICQhTmI7tte7Ozs7o+bXLTleuACpKNJqJP3789+doKoSPxfVGxFZioS1iK5Yd0nCJko9iLTVVvZSlCOp5FBF7vP5RFTelyDHvmYvMPPtiP19fu+HIHPetrllX2TLMJAOgEehti3ZY/Axap51ZB5ZDEnGMUoCNCmDbRv+2Q4CDJ5Mymj4OmE0CNj6b5WJlkel3xkiGXjOc0imDH/JDid1AXQEfKgccHg3lN+uhh+v2WkkOvCUnT3GjP2WOfrJzjUNPq/ugPUej1TiwME3+DfVUhWkEQF6LZraJxsp6xHLIzW/DNyAW75PGJVrOxbQFSeWzOsdjQ/tZHTxtSgdzAimMfOAdbas7crUvIWAqZg5+gg8FBzYTOygbo1tAb1xTYMs/q1xAFgnvBx5JrKO2X9pzJrJhr+b5BaY8vjG3O+w7HFnypkZ+zP3K8AWL7FHiRsJappe4knA9fo/pj7WrIrdshBs8cukcu0ljhK2lZt1Q8B1msMj5WCQKoibd8q8p1J8i6aWJnrJCcDljDX2Cm8Jn2WJC9PtIHpYeowza125Dc3c6CQ1MbEdooxoPQw54Ak9jigaKcAMk9ddgUi68ZxMmNbNG8hTXXjOZrPf+vg4C+RpRRJqO0ps8FxtzhoJLiSIHCWtLi9u5LiZyqKv0UvlHmaccukoVjJLFu2YUy946FRidS7beCXN9i3gKzd1Yo53ps7ppTnqEYD0mYNldpuxnvIo2nZb/L+ay9tulA/sJpE/Tfchj1H2kW2KpsFYSK4YgI1vZDJe57XmIAu642N5kCxUJfQ8bA48IKpWGNKi/T7rPWRMBMkp5lhz5mUlV0O+fGAGC5XMkTzoG349I/D+Qis0jpeZBt0CXaZGnwtwdcS7A/4ycOIi3bNI0pzfxoVHQYYDIu+A9djJ5bKX+c2BVKnHS5Xcw8QTecWlXxi/khgvYMFzHlp4/g74WREshg3zpuS9mfowShxyrnv6wFS2Dl12QUDwaO54xIWTKZem8up7M0ojn5BzdftEdPMzII9ljE8kVde8Z5y89PSJYcACAJhWTigFOO1rpqRbWs0pKjp4Nkl6OMiGQiFnKsOnLQNqJNe33yV5iFml/4YLfzB+wwpvuNoT+eq0F+JWYtp50MlXLBvUAkLlXXbdloHkUsREDsc6y9LDvs2pTNJD6eM5+x/KAslqWK/pOo/WEIvw3PC3q8rZz3IzWBqqp2CpTvjAACIVyFhLMQmlwXPU9gYrC+lCZs0VtPkc0Jfc+Va+XK/lK3Pr10XhF8ToAjf1VKktAH0hd3srqesSMmCJaiNwJB/IzNviF9Uor8NnndSkyRBfExbPpdHfKRg/yqH8JCPxdvbZVE6+6GTzmCD9Af45RfhzLGZZtEaIVQVdDpLwVByAHeIu8DXWGTySUil8wSNw6fMoliZnfHsqfXiC2M+gjJXX7wuEOvm4gWUBa9h4xrAAtwy6hHyWo1QQGc9gDkD7sAt8VjqETSnUHaArd0Gupc8ZBv4n4ymUfiEPxEu4/A3eyayX+x+ZZjjoIEl6D+2zrJJgyOoKf68RCKJXOpt4B3xZQNclwVeSbXVd2hXzKXlpqsC3c0ttyR3La6rTW2yyP1dpSbdowUtBji1+aAioxTZXD+ORZcrs+A5YF9kWnnfWeJUSZgnswKeZ7FNHkaeXgjTmowVhkhuQ1pQxCE1aik2A16OVVwtvayxmW6fdeDNKKcs79Zhy5eaFwIOXsxu3grolVsUVS0y0pAKN3tpMStdlheJajZ1V5rxWHxoJjR6crr51frlg59K73AFWf7h3gs8BlWtpsHpqwrioa6nJj5lphgim1C3XdPGuuZm2hYIB90QCrKqxDnPkm81hN6pvAyqElRdvN3exjdXeYGQS8oXGmjgoICQjhUh6jdSYmvQdpakSFArIfg6bqiqZW6t3N6HaNbUX7M4Lt4NK8bX3SblJM9Mas+65xuodpVFRj58HfLyAdPZjftCittnLXaHWKQdczNE4trkfK8GFiT3RVqU523gaBbeC04/3zW3pp0yJWFqfofjZejBfw3bGE3WNO8jrmLtDt5ahVyHt+DiUDv/WtFpAQ+4MrDFvC3Bb+uXiI2f1TXGURfesNPc11mjacki1dK/JKTnsUmYGLnnM/2MycWRt7dCtedrSyhqPe39tPBecjV3rrTWDweqzSl2hsfVwM3lX+UL+f0CuTv/Hn38EGAAvCnNy1JKVIQAAAABJRU5ErkJggg==)}.bee-compact__color_cube .alpha{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.bee-compact__color-cube--wrap{position:relative;width:25px;height:25px;cursor:pointer;overflow:hidden}.bee-compact__color-cube--wrap:hover{transform:scale(1.2);z-index:299;transition:transform .2s}.bee-colorPicker__record{display:flex;align-items:center;margin-top:20px}.bee-colorPicker__record .text{width:48px;margin-right:10px;text-align:right;font-size:12px;color:#666}.bee-colorPicker__record .color-list{width:auto;display:flex;position:relative;margin:0}.bee-colorPicker__record .color-list .color-item{position:relative;width:25px;height:25px;cursor:pointer;overflow:hidden;display:inline-block;vertical-align:middle;margin-right:1px;box-shadow:3px 0 5px #00000014}.bee-colorPicker__record .color-list .color-item__round{border-radius:50%}.bee-colorPicker__record .color-list .color-item.transparent{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.bee-colorPicker__record .color-list .color-item:hover{transform:scale(1.2);z-index:299;transition:transform .2s}.bee-colorPicker__record .color-list .color-item__display{width:100%;height:100%}.small-hue-slider{height:10px!important}.small-hue-slider .small-bar{height:10px!important;width:10px!important}.small-hue-slider .small-bar div{width:12px!important;height:12px!important;border-radius:5px!important;transform:translate(-6px,-2px);margin-top:1px!important}.bee-hue-colorPicker{position:relative;margin-bottom:15px;width:100%;height:14px;box-shadow:2px 0 8px #00000014;border-radius:15px}.bee-hue-colorPicker.is-vertical{width:14px;height:100%;display:inline-block;transform:rotate(180deg)}.bee-hue-colorPicker.transparent{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.bee-hue-colorPicker__inner{position:relative;width:100%;height:100%;border-radius:15px;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMkAAAAdCAYAAAAAaUg8AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAKtJREFUeNrs09EKgjAUgOGzEFfv/7CVBceiLiJiLnf7fSAbDoUj/iWnyKgRcXxf9Wtt7Vvntf8854jLY3uN19qzf67nH/e2nmmdZ8xjg2x+sI533qf9g4wM/3GvLPumOHVMWf/4SiWWsUG6/6bG+/NWDgE0iQREAiIBkYBIQCQgEhAJiAQQCYgERAIiAZGASEAkIBJAJCASEAmIBEQCIgGRgEgAkYBIYNAqwAD5oWo3bpsiKwAAAABJRU5ErkJggg==);background-size:100%}.bee-hue-colorPicker__inner-pointer{position:absolute;width:14px;height:14px}.bee-hue-colorPicker__inner-handle{width:14px;height:14px;border-radius:6px;transform:translate(-7px,-2px);background-color:#f8f8f8;margin-top:2px;box-shadow:0 1px 4px #0000005e;cursor:pointer}.bee-hue-colorPicker__inner-handle.vertical{transform:translate(-1px,-7px);margin-top:0}.small-light-slider{height:10px!important}.small-light-slider .small-bar{height:10px!important;width:10px!important}.small-light-slider .small-bar div{width:12px!important;height:12px!important;border-radius:5px!important;transform:translate(-6px,-2px);margin-top:1px!important}.bee-light-colorPicker{position:relative;margin-bottom:15px;width:100%;height:14px;box-shadow:2px 0 8px #00000014;border-radius:15px}.bee-light-colorPicker.is-vertical{width:14px;height:100%;display:inline-block;transform:rotate(180deg)}.bee-light-colorPicker.transparent{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.bee-light-colorPicker__inner{position:relative;width:100%;height:100%;border-radius:15px}.bee-light-colorPicker__inner-pointer{position:absolute;width:14px;height:14px}.bee-light-colorPicker__inner-handle{width:14px;height:14px;border-radius:6px;transform:translate(-7px,-2px);background-color:#f8f8f8;margin-top:2px;box-shadow:0 1px 4px #0000005e;cursor:pointer}.bee-light-colorPicker__inner-handle.vertical{transform:translateY(-7px);margin-top:0}.bee-saturation{position:relative;margin-bottom:15px;width:100%;height:125px}.bee-saturation__chrome{border-top-left-radius:5px;border-top-right-radius:5px;border-color:transparent}.bee-saturation__hidden{overflow:hidden}.bee-saturation__white,.bee-saturation__black{position:absolute;top:0;left:0;right:0;bottom:0}.bee-saturation__black{background:linear-gradient(0deg,#000,transparent)}.bee-saturation__white{background:linear-gradient(90deg,#fff,hsla(0,0%,100%,0))}.bee-saturation__cursor{position:absolute}.bee-saturation__cursor div{transform:translate(-5px,-5px);box-shadow:0 1px 4px #0000005e;width:10px;height:10px;border:1px solid white;border-radius:50%;cursor:pointer}.inputs-controls{display:flex;font-size:16px;margin-bottom:5px}.inputs-controls .formatBtn{position:relative;display:inline-flex;justify-content:center;align-items:center;padding:1px;border:0;text-align:center;cursor:pointer;background-color:transparent;font-weight:700;outline:none;margin-right:5px}.inputs-controls .formatBtn:hover{color:#1a3aff}.inputs-controls .format-group{display:flex;flex-grow:1}.inputs-controls .format-group input{padding:5px;margin:0 3px;min-width:0;text-align:center;border-width:0 0 1px 0;-webkit-appearance:none;appearance:none;-moz-appearance:textfield;outline:none;flex:1}.inputs-controls .format-group input::-webkit-outer-spin-button,.inputs-controls .format-group input::-webkit-inner-spin-button{-webkit-appearance:none!important;margin:0}.bee-fk-colorPicker{position:relative;box-sizing:border-box;border-radius:3px;box-shadow:0 0 10px #00000026;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-color:#fff;width:249px;padding-bottom:10px}.bee-fk-colorPicker__inner{padding:12px}.bee-fk-colorPicker__header{margin-bottom:12px;z-index:999;text-align:left}.bee-fk-colorPicker__header .back{border:solid black;border-width:0 1px 1px 0;display:inline-block;padding:4px;margin-left:2px;transform:rotate(135deg);-webkit-transform:rotate(135deg)}.bee-fk-colorPicker__display{position:relative;width:100%;margin:0;text-align:left}.bee-fk-colorPicker__display .transparent{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.bee-fk-colorPicker__display .current-color{margin-right:10px;width:50px;height:24px;box-shadow:3px 0 5px #00000014;position:relative;cursor:pointer;overflow:hidden;display:inline-block;vertical-align:middle}.bee-fk-colorPicker__display .current-color .color-cube{width:100%;height:100%}.bee-fk-colorPicker__display .hexColor-prefix{position:relative;padding:0 4px;font-size:14px;display:inline-block;vertical-align:middle}.bee-fk-colorPicker__display input{width:25px;text-align:center;outline:0;border-top:0;border-right:0;border-left:none;display:inline-block;vertical-align:middle;padding-bottom:3px;border-bottom:1px solid #e3e2e8}.bee-fk-colorPicker__display .hexColor-input{width:64px}.bee-fk-colorPicker__display .action{float:right;vertical-align:middle}.bee-fk-colorPicker__display .action .clear-btn{border-color:transparent;color:#409eff;background:transparent;padding-left:0;padding-right:0;display:inline-block;vertical-align:middle;cursor:pointer}.bee-fk-colorPicker__display .action .copy-btn{border-color:transparent;color:#13ce66cc;background:transparent;padding-left:0;padding-right:0;display:inline-block;margin-left:10px;vertical-align:middle;cursor:pointer}.bee-ele-colorPicker{position:relative;box-sizing:border-box;border-radius:3px;box-shadow:0 0 10px #00000026;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-color:#fff;padding:10px;width:300px}.bee-ele-colorPicker .bee-ele-row{display:flex}.bee-ele-colorPicker .bee-ele-row .bee-ele-saturation{width:280px;height:180px}.bee-ele-colorPicker .bee-ele-row .bee-ele-hue{margin-left:10px;height:180px}.bee-chrome-colorPicker{position:relative;box-sizing:border-box;border-radius:3px;box-shadow:0 0 10px #00000026;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-color:#fff;width:250px;padding-bottom:20px}.bee-chrome-colorPicker-body{padding:0 12px;background-color:#fff}.bee-chrome-colorPicker-body .chrome-controls{display:flex}.bee-chrome-colorPicker-body .chrome-controls .chrome-color-wrap{position:relative;width:36px;height:36px;border-radius:50%;overflow:hidden;z-index:1}.bee-chrome-colorPicker-body .chrome-controls .chrome-color-wrap .current-color{width:100%;height:100%}.bee-chrome-colorPicker-body .chrome-controls .chrome-sliders{flex:1;margin-left:10px}.bee-color-wrap{margin-right:10px;width:50px;height:24px;box-shadow:3px 0 5px #00000014;position:relative;cursor:pointer;overflow:hidden;display:inline-block;vertical-align:middle}.bee-color-wrap.transparent{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.bee-color-wrap.round{width:22px;height:22px;border-radius:50%;border:1px solid #d8d8d8}.bee-color-wrap .current-color{width:100%;height:100%}.vc-alpha-slider[data-v-18925ba6]{position:relative;margin-bottom:15px;width:100%;height:14px;box-shadow:2px 0 8px #00000014;border-radius:15px}.vc-alpha-slider.is-vertical[data-v-18925ba6]{width:14px;height:100%;display:inline-block;transform:rotate(180deg)}.vc-alpha-slider.transparent[data-v-18925ba6]{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.vc-alpha-slider__bar[data-v-18925ba6]{position:relative;width:100%;height:100%;border-radius:15px}.vc-alpha-slider__bar-pointer[data-v-18925ba6]{position:absolute;width:14px;height:14px}.vc-alpha-slider__bar-handle[data-v-18925ba6]{width:14px;height:14px;border-radius:6px;transform:translate(-7px,-2px);background-color:#f8f8f8;margin-top:2px;box-shadow:0 1px 4px #0000005e;cursor:pointer}.vc-alpha-slider__bar-handle.vertical[data-v-18925ba6]{transform:translateY(-7px);margin-top:0}.vc-alpha-slider.small-slider[data-v-18925ba6]{height:10px!important}.vc-alpha-slider.small-slider .small-bar[data-v-18925ba6]{height:10px!important;width:10px!important}.vc-alpha-slider.small-slider .small-bar div[data-v-18925ba6]{width:12px!important;height:12px!important;border-radius:5px!important;transform:translate(-6px,-2px);margin-top:1px!important}.vc-compact[data-v-b969fd48]{margin-bottom:15px;width:auto;box-shadow:3px 0 5px #00000014;display:inline-block}.vc-compact__row[data-v-b969fd48]{position:relative;width:100%;margin:0;height:27px}.vc-compact__row>*[data-v-b969fd48]{display:inline-block;vertical-align:middle}.vc-compact__color_cube[data-v-b969fd48]{width:100%;height:100%}.vc-compact__color_cube.transparent[data-v-b969fd48]:before{content:"";position:absolute;top:0;left:0;width:100%;height:100%;background:white}.vc-compact__color_cube.transparent[data-v-b969fd48]:after{content:"";position:absolute;top:100%;left:0;transform:rotate(-45deg);transform-origin:0 0;width:35px;height:1px;background:red}.vc-compact__color_cube.advance[data-v-b969fd48]{background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAdCAYAAAC9pNwMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABqVJREFUeNrEl11yHDUQx1ua2Zlde2M7jqESqnjg45kjcBwOwQG4BY+8cwWK17xBUUARICQhTmI7tte7Ozs7o+bXLTleuACpKNJqJP3789+doKoSPxfVGxFZioS1iK5Yd0nCJko9iLTVVvZSlCOp5FBF7vP5RFTelyDHvmYvMPPtiP19fu+HIHPetrllX2TLMJAOgEehti3ZY/Axap51ZB5ZDEnGMUoCNCmDbRv+2Q4CDJ5Mymj4OmE0CNj6b5WJlkel3xkiGXjOc0imDH/JDid1AXQEfKgccHg3lN+uhh+v2WkkOvCUnT3GjP2WOfrJzjUNPq/ugPUej1TiwME3+DfVUhWkEQF6LZraJxsp6xHLIzW/DNyAW75PGJVrOxbQFSeWzOsdjQ/tZHTxtSgdzAimMfOAdbas7crUvIWAqZg5+gg8FBzYTOygbo1tAb1xTYMs/q1xAFgnvBx5JrKO2X9pzJrJhr+b5BaY8vjG3O+w7HFnypkZ+zP3K8AWL7FHiRsJappe4knA9fo/pj7WrIrdshBs8cukcu0ljhK2lZt1Q8B1msMj5WCQKoibd8q8p1J8i6aWJnrJCcDljDX2Cm8Jn2WJC9PtIHpYeowza125Dc3c6CQ1MbEdooxoPQw54Ak9jigaKcAMk9ddgUi68ZxMmNbNG8hTXXjOZrPf+vg4C+RpRRJqO0ps8FxtzhoJLiSIHCWtLi9u5LiZyqKv0UvlHmaccukoVjJLFu2YUy946FRidS7beCXN9i3gKzd1Yo53ps7ppTnqEYD0mYNldpuxnvIo2nZb/L+ay9tulA/sJpE/Tfchj1H2kW2KpsFYSK4YgI1vZDJe57XmIAu642N5kCxUJfQ8bA48IKpWGNKi/T7rPWRMBMkp5lhz5mUlV0O+fGAGC5XMkTzoG349I/D+Qis0jpeZBt0CXaZGnwtwdcS7A/4ycOIi3bNI0pzfxoVHQYYDIu+A9djJ5bKX+c2BVKnHS5Xcw8QTecWlXxi/khgvYMFzHlp4/g74WREshg3zpuS9mfowShxyrnv6wFS2Dl12QUDwaO54xIWTKZem8up7M0ojn5BzdftEdPMzII9ljE8kVde8Z5y89PSJYcACAJhWTigFOO1rpqRbWs0pKjp4Nkl6OMiGQiFnKsOnLQNqJNe33yV5iFml/4YLfzB+wwpvuNoT+eq0F+JWYtp50MlXLBvUAkLlXXbdloHkUsREDsc6y9LDvs2pTNJD6eM5+x/KAslqWK/pOo/WEIvw3PC3q8rZz3IzWBqqp2CpTvjAACIVyFhLMQmlwXPU9gYrC+lCZs0VtPkc0Jfc+Va+XK/lK3Pr10XhF8ToAjf1VKktAH0hd3srqesSMmCJaiNwJB/IzNviF9Uor8NnndSkyRBfExbPpdHfKRg/yqH8JCPxdvbZVE6+6GTzmCD9Af45RfhzLGZZtEaIVQVdDpLwVByAHeIu8DXWGTySUil8wSNw6fMoliZnfHsqfXiC2M+gjJXX7wuEOvm4gWUBa9h4xrAAtwy6hHyWo1QQGc9gDkD7sAt8VjqETSnUHaArd0Gupc8ZBv4n4ymUfiEPxEu4/A3eyayX+x+ZZjjoIEl6D+2zrJJgyOoKf68RCKJXOpt4B3xZQNclwVeSbXVd2hXzKXlpqsC3c0ttyR3La6rTW2yyP1dpSbdowUtBji1+aAioxTZXD+ORZcrs+A5YF9kWnnfWeJUSZgnswKeZ7FNHkaeXgjTmowVhkhuQ1pQxCE1aik2A16OVVwtvayxmW6fdeDNKKcs79Zhy5eaFwIOXsxu3grolVsUVS0y0pAKN3tpMStdlheJajZ1V5rxWHxoJjR6crr51frlg59K73AFWf7h3gs8BlWtpsHpqwrioa6nJj5lphgim1C3XdPGuuZm2hYIB90QCrKqxDnPkm81hN6pvAyqElRdvN3exjdXeYGQS8oXGmjgoICQjhUh6jdSYmvQdpakSFArIfg6bqiqZW6t3N6HaNbUX7M4Lt4NK8bX3SblJM9Mas+65xuodpVFRj58HfLyAdPZjftCittnLXaHWKQdczNE4trkfK8GFiT3RVqU523gaBbeC04/3zW3pp0yJWFqfofjZejBfw3bGE3WNO8jrmLtDt5ahVyHt+DiUDv/WtFpAQ+4MrDFvC3Bb+uXiI2f1TXGURfesNPc11mjacki1dK/JKTnsUmYGLnnM/2MycWRt7dCtedrSyhqPe39tPBecjV3rrTWDweqzSl2hsfVwM3lX+UL+f0CuTv/Hn38EGAAvCnNy1JKVIQAAAABJRU5ErkJggg==)}.vc-compact__color_cube .alpha[data-v-b969fd48]{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.vc-compact__color-cube--wrap[data-v-b969fd48]{position:relative;width:27px;height:27px;cursor:pointer;overflow:hidden}.vc-compact__color-cube--wrap[data-v-b969fd48]:hover{transform:scale(1.2);z-index:299;transition:transform .2s}.vc-saturation[data-v-7f0cdcdf]{position:relative;margin-bottom:15px;width:100%;height:125px}.vc-saturation__chrome[data-v-7f0cdcdf]{border-top-left-radius:5px;border-top-right-radius:5px;border-color:transparent}.vc-saturation__hidden[data-v-7f0cdcdf]{overflow:hidden}.vc-saturation__white[data-v-7f0cdcdf],.vc-saturation__black[data-v-7f0cdcdf]{position:absolute;top:0;left:0;right:0;bottom:0}.vc-saturation__black[data-v-7f0cdcdf]{background:linear-gradient(0deg,#000,transparent)}.vc-saturation__white[data-v-7f0cdcdf]{background:linear-gradient(90deg,#fff,hsla(0,0%,100%,0))}.vc-saturation__cursor[data-v-7f0cdcdf]{position:absolute}.vc-saturation__cursor div[data-v-7f0cdcdf]{transform:translate(-5px,-5px);box-shadow:0 1px 4px #0000005e;width:10px;height:10px;border:1px solid white;border-radius:50%;cursor:pointer}.vc-hue-slider[data-v-e1a08576]{position:relative;margin-bottom:15px;width:100%;height:14px;box-shadow:2px 0 8px #00000014;border-radius:15px}.vc-hue-slider.is-vertical[data-v-e1a08576]{width:14px;height:100%;display:inline-block;transform:rotate(180deg)}.vc-hue-slider.transparent[data-v-e1a08576]{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.vc-hue-slider__bar[data-v-e1a08576]{position:relative;width:100%;height:100%;border-radius:15px;background:linear-gradient(to right,rgb(255,0,0) 0%,rgb(255,255,0) 16.66%,rgb(0,255,0) 33.33%,rgb(0,255,255) 50%,rgb(0,0,255) 66.66%,rgb(255,0,255) 83.33%,rgb(255,0,0) 100%);background:-webkit-linear-gradient(left,rgb(255,0,0) 0%,rgb(255,255,0) 16.66%,rgb(0,255,0) 33.33%,rgb(0,255,255) 50%,rgb(0,0,255) 66.66%,rgb(255,0,255) 83.33%,rgb(255,0,0) 100%);background:-moz-linear-gradient(left,rgb(255,0,0) 0%,rgb(255,255,0) 16.66%,rgb(0,255,0) 33.33%,rgb(0,255,255) 50%,rgb(0,0,255) 66.66%,rgb(255,0,255) 83.33%,rgb(255,0,0) 100%);background:-ms-linear-gradient(left,rgb(255,0,0) 0%,rgb(255,255,0) 16.66%,rgb(0,255,0) 33.33%,rgb(0,255,255) 50%,rgb(0,0,255) 66.66%,rgb(255,0,255) 83.33%,rgb(255,0,0) 100%)}.vc-hue-slider__bar-pointer[data-v-e1a08576]{position:absolute;width:14px;height:14px}.vc-hue-slider__bar-handle[data-v-e1a08576]{width:14px;height:14px;border-radius:6px;transform:translate(-7px,-2px);background-color:#f8f8f8;margin-top:2px;box-shadow:0 1px 4px #0000005e;cursor:pointer}.vc-hue-slider__bar-handle.vertical[data-v-e1a08576]{transform:translateY(-7px);margin-top:0}.vc-hue-slider.small-slider[data-v-e1a08576]{height:10px!important}.vc-hue-slider.small-slider .small-bar[data-v-e1a08576]{height:10px!important;width:10px!important}.vc-hue-slider.small-slider .small-bar div[data-v-e1a08576]{width:12px!important;height:12px!important;border-radius:5px!important;transform:translate(-6px,-2px);margin-top:1px!important}.vc-lightness-slider[data-v-94a50a9e]{position:relative;margin-bottom:15px;width:100%;height:14px;box-shadow:2px 0 8px #00000014;border-radius:15px}.vc-lightness-slider.is-vertical[data-v-94a50a9e]{width:14px;height:100%;display:inline-block;transform:rotate(180deg)}.vc-lightness-slider.transparent[data-v-94a50a9e]{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.vc-lightness-slider__bar[data-v-94a50a9e]{position:relative;width:100%;height:100%;border-radius:15px}.vc-lightness-slider__bar-pointer[data-v-94a50a9e]{position:absolute;width:14px;height:14px}.vc-lightness-slider__bar-handle[data-v-94a50a9e]{width:14px;height:14px;border-radius:6px;transform:translate(-7px,-2px);background-color:#f8f8f8;margin-top:2px;box-shadow:0 1px 4px #0000005e;cursor:pointer}.vc-lightness-slider__bar-handle.vertical[data-v-94a50a9e]{transform:translateY(-7px);margin-top:0}.vc-lightness-slider.small-slider[data-v-94a50a9e]{height:10px!important}.vc-lightness-slider.small-slider .small-bar[data-v-94a50a9e]{height:10px!important;width:10px!important}.vc-lightness-slider.small-slider .small-bar div[data-v-94a50a9e]{width:12px!important;height:12px!important;border-radius:5px!important;transform:translate(-6px,-2px);margin-top:1px!important}.vc-colorPicker__record[data-v-0f657238]{display:flex;align-items:center;margin-top:15px}.vc-colorPicker__record .text[data-v-0f657238]{width:48px;margin-right:10px;text-align:right;font-size:12px;color:#666}.vc-colorPicker__record .color-list[data-v-0f657238]{width:100%;display:flex;position:relative;margin:0;gap:2px}.vc-colorPicker__record .color-list .color-item[data-v-0f657238]{position:relative;flex:1;max-width:26px;height:26px;border-radius:2px;cursor:pointer;overflow:hidden;display:inline-block;vertical-align:middle;box-shadow:3px 0 5px #0000001a}.vc-colorPicker__record .color-list .color-item__round[data-v-0f657238]{border-radius:50%}.vc-colorPicker__record .color-list .color-item.transparent[data-v-0f657238]{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.vc-colorPicker__record .color-list .color-item[data-v-0f657238]:hover{transform:scale(1.2);z-index:299;transition:transform .2s}.vc-colorPicker__record .color-list .color-item__display[data-v-0f657238]{width:100%;height:100%}.vc-display[data-v-7334ac20]{height:28px;display:flex;align-items:center;gap:8px}.vc-display .vc-current-color[data-v-7334ac20]{width:50px;height:100%;box-shadow:3px 0 5px #00000014;border-radius:2px;position:relative;cursor:pointer;overflow:hidden;display:inline-block;vertical-align:middle}.vc-display .vc-current-color.vc-transparent[data-v-7334ac20]{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.vc-display .vc-current-color .color-cube[data-v-7334ac20]{width:100%;height:100%;text-align:center}.vc-display .vc-color-input[data-v-7334ac20]{height:100%;flex:1;flex-shrink:0;box-sizing:border-box;position:relative}.vc-display .vc-color-input input[data-v-7334ac20]{padding:0;border:0;outline:none;cursor:pointer;font-size:14px;text-align:center;box-sizing:border-box;background-color:#c8c8c840;color:#666;border-radius:2px;height:100%;width:100%}.vc-display .vc-rgb-input[data-v-7334ac20]{flex:1;font-size:12px;color:#666;text-align:center}.vc-display .vc-rgb-input input[data-v-7334ac20]{padding:4px 0;margin-bottom:2px;border:0;outline:none;cursor:pointer;font-size:14px;text-align:center;background-color:#c8c8c840;color:#666;border-radius:2px;width:100%}.vc-display .vc-alpha-input[data-v-7334ac20]{width:48px;height:100%;border:none;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;border-radius:2px;font-size:14px;background-color:#c8c8c840;padding:0 2px}.vc-display .vc-alpha-input>input[data-v-7334ac20]{width:100%;height:100%;padding:0;text-align:center;background-color:transparent;font-size:inherit}.vc-display .vc-alpha-input__inner[data-v-7334ac20]{padding:10px 12px;border-radius:4px;color:#000;font-size:14px;line-height:20px;outline:none;border:none;display:block;box-sizing:border-box;cursor:pointer}.vc-display .vc-input-toggle[data-v-7334ac20]{cursor:pointer;font-size:12px;line-height:12px;width:24px;border-radius:4px;padding:2px}.vc-display .vc-input-toggle[data-v-7334ac20]:hover{background-color:#efefef}.vc-display .vc-input-toggle[data-v-7334ac20]:before{height:0;width:0;margin:auto auto 2px;content:"";display:block;border-bottom:4px solid #888;border-left:4px solid transparent;border-right:4px solid transparent}.vc-display .vc-input-toggle[data-v-7334ac20]:after{height:0;width:0;margin:2px auto auto;content:"";display:block;border-top:4px solid #888;border-left:4px solid transparent;border-right:4px solid transparent}.vc-display .copy-text[data-v-7334ac20]{font-size:12px;line-height:28px;text-align:center;transform:scale(.8);display:inline-block}.vc-fk-colorPicker[data-v-48e3c224]{position:relative;box-sizing:border-box;border-radius:3px;user-select:none;background-color:initial}.vc-fk-colorPicker__inner[data-v-48e3c224]{position:relative}.vc-fk-colorPicker__header[data-v-48e3c224]{z-index:999;text-align:left}.vc-fk-colorPicker__header .back[data-v-48e3c224]{border:2px solid rgba(150,150,150,.6);border-width:0 2px 2px 0;display:inline-block;padding:4px;margin-left:2px;margin-bottom:12px;transform:rotate(135deg)}.vc-fk-colorPicker__display[data-v-48e3c224]{position:relative;width:100%;margin:0;text-align:left}.vc-fk-colorPicker__display .transparent[data-v-48e3c224]{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.vc-fk-colorPicker__display .current-color[data-v-48e3c224]{margin-right:10px;width:50px;height:24px;box-shadow:3px 0 5px #00000014;position:relative;cursor:pointer;overflow:hidden;display:inline-block;vertical-align:middle}.vc-fk-colorPicker__display .current-color .color-cube[data-v-48e3c224]{width:100%;height:100%}.vc-fk-colorPicker__display .hexColor-prefix[data-v-48e3c224]{position:relative;padding:0 4px;font-size:14px;display:inline-block;vertical-align:middle}.vc-fk-colorPicker__display input[data-v-48e3c224]{width:25px;text-align:center;outline:0;border-top:0;border-right:0;border-left:none;display:inline-block;vertical-align:middle;padding-bottom:3px;border-bottom:1px solid #e3e2e8}.vc-fk-colorPicker__display .hexColor-input[data-v-48e3c224]{width:64px}.vc-fk-colorPicker__display .action[data-v-48e3c224]{float:right;vertical-align:middle}.vc-fk-colorPicker__display .action .clear-btn[data-v-48e3c224]{border-color:transparent;color:#409eff;background:transparent;padding-left:0;padding-right:0;display:inline-block;vertical-align:middle;cursor:pointer}.vc-fk-colorPicker__display .action .copy-btn[data-v-48e3c224]{border-color:transparent;color:#13ce66cc;background:transparent;padding-left:0;padding-right:0;display:inline-block;margin-left:10px;vertical-align:middle;cursor:pointer}.vc-chrome-colorPicker[data-v-2611d66c]{position:relative;box-sizing:border-box;border-radius:3px;user-select:none;background-color:initial}.vc-chrome-colorPicker-body[data-v-2611d66c]{position:relative}.vc-chrome-colorPicker-body .chrome-controls[data-v-2611d66c]{display:flex}.vc-chrome-colorPicker-body .chrome-controls .chrome-color-wrap[data-v-2611d66c]{position:relative;width:36px;height:36px;border-radius:50%;overflow:hidden;z-index:1}.vc-chrome-colorPicker-body .chrome-controls .chrome-color-wrap.transparent[data-v-2611d66c]{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.vc-chrome-colorPicker-body .chrome-controls .chrome-color-wrap .current-color[data-v-2611d66c]{width:100%;height:100%}.vc-chrome-colorPicker-body .chrome-controls .chrome-sliders[data-v-2611d66c]{flex:1;margin-left:10px}.bee-angle{transform:rotate(90deg)}.bee-angle>*{display:inline-block;vertical-align:middle}.bee-angle.zero-right{transform:rotate(180deg)}.bee-angle.zero-bottom{transform:rotate(270deg)}.bee-angle__round{position:relative;width:16px;height:16px;border:1px solid #666;border-radius:50%;cursor:pointer;display:inline-block;vertical-align:middle}.bee-angle__round:before{content:"";position:absolute;top:50%;left:0;transform:translateY(-50%);width:50%;height:1px;background-color:#666}.vc-gradient-picker[data-v-c4d6d6ea]{position:relative}.vc-gradient-picker__header[data-v-c4d6d6ea]{margin-bottom:12px;z-index:999;text-align:left;display:flex;justify-content:space-between;align-items:center}.vc-gradient-picker__header .back[data-v-c4d6d6ea]{border:2px solid rgba(150,150,150,.65);border-width:0 2px 2px 0;display:inline-block;padding:4px;margin-left:2px;transform:rotate(135deg);margin-right:8px}.vc-gradient-picker .vc-gradient__types[data-v-c4d6d6ea]{display:flex;width:100%;justify-content:space-between}.vc-gradient-picker .vc-gradient__types .vc-gradient-wrap__types[data-v-c4d6d6ea]{display:flex;background-color:#c8c8c840;border-radius:4px;overflow:hidden;align-items:center}.vc-gradient-picker .vc-gradient__types .vc-gradient__type[data-v-c4d6d6ea]{padding:4px 8px;color:#666;cursor:pointer;font-size:12px}.vc-gradient-picker .vc-gradient__types .vc-gradient__type.active[data-v-c4d6d6ea]{color:#000;background-color:#c8c8c8cc}.vc-gradient-picker__body[data-v-c4d6d6ea]{margin-bottom:12px;display:-ms-flexbox;display:flex;align-items:center}.vc-gradient-picker__body .vc-color-range[data-v-c4d6d6ea]{flex:1}.vc-gradient-picker__body .vc-color-range__container[data-v-c4d6d6ea]{position:relative;height:16px;border-radius:5px}.vc-gradient-picker__body .vc-color-range__container .vc-background[data-v-c4d6d6ea]{height:100%;border-radius:4px;box-shadow:inset 0 0 0 1px #0000000f}.vc-gradient-picker__body .vc-color-range__container .vc-gradient__stop__container[data-v-c4d6d6ea]{position:absolute;width:100%;top:0;height:100%;left:0}.vc-gradient-picker__body .vc-color-range__container .vc-gradient__stop__container .vc-gradient__stop[data-v-c4d6d6ea]{position:absolute;top:-2px;width:14px;height:16px;overflow:hidden;border:2px solid #fff;border-radius:2px;cursor:pointer;box-shadow:0 0 2px 1px #00000059;box-sizing:content-box;transform:translate(-9px)}.vc-gradient-picker__body .vc-color-range__container .vc-gradient__stop__container .vc-gradient__stop--inner[data-v-c4d6d6ea]{display:inline-block;height:100%}.vc-gradient-picker__body .vc-color-range__container .vc-gradient__stop__container .vc-gradient__stop--current[data-v-c4d6d6ea]{position:relative;z-index:1;box-shadow:0 0 2px 2px #2253f4,0 0 1px 1px #2253f480}.vc-gradient-picker .vc-degree-input[data-v-c4d6d6ea]{position:relative;z-index:2;font-size:12px;border-radius:4px;display:flex}.vc-gradient-picker .vc-degree-input:hover .vc-degree-input__panel[data-v-c4d6d6ea]{display:block}.vc-gradient-picker .vc-degree-input__control[data-v-c4d6d6ea]{width:100%;height:100%;display:flex;justify-content:center;align-items:center;border-radius:4px;background-color:#c8c8c840;color:#666;padding:0 6px 0 0}.vc-gradient-picker .vc-degree-input__control input[data-v-c4d6d6ea]{max-width:28px;text-align:center;border:none;outline:none;background-color:transparent;color:#666;font-size:inherit;overflow:visible}.vc-gradient-picker .vc-degree-input__panel[data-v-c4d6d6ea]{display:none;z-index:10;position:absolute;top:20px;left:0}.vc-gradient-picker .vc-degree-input__panel .vc-degree-input__disk[data-v-c4d6d6ea]{padding:4px;background-color:#f1f1f1;box-shadow:0 0 2px #00000029,0 1px 8px #0000000f,0 4px 12px #00000014;border-radius:4px;display:flex;justify-content:center;align-items:center;position:relative;transform:translate(0)}.vc-gradient-picker .vc-picker-degree-input[data-v-c4d6d6ea]{margin-left:8px}.vc-colorpicker[data-v-0492277d]{position:relative;box-sizing:border-box;border-radius:3px;box-shadow:0 0 10px #00000026;user-select:none;width:276px;z-index:10000}.vc-colorpicker *[data-v-0492277d]{outline:none;line-height:1}.vc-colorpicker--container[data-v-0492277d]{padding:16px}.vc-colorpicker--tabs[data-v-0492277d]{padding:2px;background:#f6f7f9;border-radius:6px;position:relative;margin-bottom:12px}.vc-colorpicker--tabs__inner[data-v-0492277d]{display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;padding:0;background:#f6f7f9;border-bottom:none;position:relative;box-sizing:border-box}.vc-colorpicker--tabs__btn[data-v-0492277d]{-ms-flex:1;flex:1;z-index:2;color:#636c78;font-size:14px;border-radius:4px;cursor:pointer}.vc-colorpicker--tabs__btn.vc-btn-active[data-v-0492277d]{color:#33383e;font-weight:600}.vc-colorpicker--tabs__btn button[data-v-0492277d]{width:100%;background-color:initial;padding:6px 0;font-size:14px;line-height:20px;color:#636c78;border:0;border-radius:0;outline:0;cursor:pointer;appearance:none;-webkit-appearance:none;font-weight:inherit}.vc-colorpicker--tabs__btn button .vc-btn__content[data-v-0492277d]{position:relative;white-space:nowrap}.vc-colorpicker--tabs__bg[data-v-0492277d]{position:absolute;top:0;bottom:0;background:#fff;box-shadow:0 1px 4px #0000001f;border-radius:4px;z-index:1;transition:left .2s ease-in-out}.vc-colorpicker.black[data-v-0492277d]{background-color:#000;color:#fff}.vc-colorpicker.white[data-v-0492277d]{background-color:#fff;color:#333}.vc-color-wrap[data-v-354ca836]{margin-right:10px;width:50px;height:24px;box-shadow:3px 0 5px #00000014;position:relative;cursor:pointer;overflow:hidden;display:inline-block;vertical-align:middle}.vc-color-wrap.transparent[data-v-354ca836]{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);background-repeat:repeat}.vc-color-wrap.round[data-v-354ca836]{width:22px;height:22px;border-radius:50%;border:1px solid #d8d8d8}.vc-color-wrap .current-color[data-v-354ca836]{width:100%;height:100%}.vc-color-extra[data-v-354ca836]{margin-top:10px}.tag-wrap[data-v-40c44f96]{display:inline-block;position:relative}.tag-wrap:hover .float-actions[data-v-40c44f96],.tag-wrap .float-actions:hover[data-v-40c44f96]{display:flex;flex-wrap:nowrap;opacity:1;max-height:100px}.tag-wrap .tag[data-v-40c44f96]{border:2px solid var(--zp-secondary);color:var(--zp-primary);border-radius:999px;padding:4px 16px;margin:4px;cursor:pointer;position:relative;display:flex;align-items:center;justify-content:space-between;flex-direction:row;gap:4px}.tag-wrap .tag.selected[data-v-40c44f96]{color:var(--primary-color);border:2px solid var(--primary-color)}.tag-wrap .tag-name[data-v-40c44f96]{max-width:192px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.tag-wrap .float-actions[data-v-40c44f96]{position:absolute;left:0;top:-32px;transition-delay:.5s;transition-duration:.3s;background:var(--zp-primary-background);box-sizing:border-box;border-radius:4px;user-select:none;display:none;opacity:0;max-height:0;overflow:hidden;z-index:9999;transition-property:opacity,max-height;transition-duration:.5s;transition-timing-function:ease-in-out;padding:4px;box-shadow:0 4px 16px var(--zp-luminous-deep);border-bottom:3px solid var(--zp-luminous)}.tag-wrap .float-actions div[data-v-40c44f96]{background:var(--zp-secondary-background);cursor:pointer;white-space:pre;font-size:12px;padding:1px 4px}.tag-wrap .float-actions div[data-v-40c44f96]:hover{background:var(--zp-secondary-variant-background)}.tag-wrap .float-actions[data-v-40c44f96]>:not(:last-child){margin-right:4px}.spin-container[data-v-2f2a3443]{text-align:center;background:rgba(0,0,0,.05);border-radius:4px;padding:256px}[data-v-2f2a3443] .ant-collapse>.ant-collapse-item>.ant-collapse-header{padding:0}.container[data-v-2f2a3443]{height:var(--pane-max-height);overflow:auto;display:flex;flex-direction:column;align-items:stretch}.container .generate-idx-hint[data-v-2f2a3443]{margin:64px;padding:64px;font-size:2em;text-align:center;background-color:var(--zp-secondary-background);white-space:pre-line;line-height:2.5em;border-radius:16px}.container .remove[data-v-2f2a3443]{padding:4px;position:cursor;border-radius:2px}.container .remove[data-v-2f2a3443]:hover{background-color:var(--zp-secondary-background)}.container .select[data-v-2f2a3443]{padding:8px}.container .search-bar[data-v-2f2a3443]{padding:8px;display:flex}.container .search-bar .form-name[data-v-2f2a3443]{flex-shrink:0;padding:4px 8px;width:128px}.container .list-container[data-v-2f2a3443]{background-color:var(--zp-secondary-background);overflow:scroll}.container .cat-name[data-v-2f2a3443]{user-select:none;position:sticky;top:0;padding:4px 16px;background:var(--zp-primary-background);margin:4px;transition:all .3s ease;border-left:4px solid var(--primary-color);cursor:pointer;z-index:1;display:flex;align-items:center;flex-direction:row}.container .cat-name .filter-input[data-v-2f2a3443]{margin-left:32px;width:256px}.container .cat-name .filter-input>span[data-v-2f2a3443]{border-radius:6px}.container .cat-name[data-v-2f2a3443]:hover{border-radius:4px;background-color:var(--zp-secondary-background)}.container .cat-name .arrow[data-v-2f2a3443]{color:var(--primary-color);transition:all .3s ease;margin-right:16px}.container .cat-name .arrow.down[data-v-2f2a3443]{transform:rotate(90deg)}.container .pinned-search[data-v-2f2a3443]{margin:16px;border-radius:16px;background:var(--zp-primary-background);padding:8px}.container .tag-list[data-v-2f2a3443]{list-style:none;margin:16px;border-radius:16px;background:var(--zp-primary-background);padding:8px}.container .tag-list .tag[data-v-2f2a3443]{border:2px solid var(--zp-secondary);color:var(--zp-primary);border-radius:999px;padding:4px 16px;margin:4px;display:inline-block;cursor:pointer;position:relative} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/TagSearch-cb7ad4a8.js b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/TagSearch-cb7ad4a8.js new file mode 100644 index 0000000000000000000000000000000000000000..9858c53a5a87289d4b246647e6bb991fac59e64f --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/assets/TagSearch-cb7ad4a8.js @@ -0,0 +1,15 @@ +import{P as Je,aw as Xi,d as se,bx as Lo,b4 as Zi,r as W,bA as Ji,m as Qe,u as Do,E as Z,al as yn,h as he,c as P,a as Gt,bB as Qi,b as el,f as tl,bC as nl,an as ha,bD as rl,aX as al,i as ol,bc as il,bE as ll,ar as en,as as mn,aq as sl,A as ul,a_ as cl,aY as dl,bF as pr,aZ as fl,bG as pl,bH as No,bs as vl,bI as Vo,bJ as hl,bK as gl,bL as yl,bM as ml,bN as bl,bq as Cl,bO as ga,bP as Fo,bQ as _l,bR as xl,bS as wl,ak as Te,bT as jt,ax as Ko,bU as fe,bV as Sl,I as $r,at as Wo,bW as kl,bX as We,o as zo,S as A,T as L,U as S,ae as le,a5 as ce,X as $e,a6 as lt,Y as K,bY as Al,V as ae,W as z,av as Ol,bZ as $l,b_ as El,b$ as ne,a0 as G,a1 as q,c0 as ya,c1 as ma,aE as vr,c2 as Rl,aN as dt,aO as ft,c3 as Uo,a3 as bn,a2 as xe,c4 as Tl,c5 as Ml,Z as Go,$ as Pl,c6 as Il,n as jl,x as Hl,O as Bl,c7 as ba,q as Ll,C as Ca,B as Dl,c8 as Nl,aa as Un,aK as Vl,c9 as Fl,y as _a,z as Gn,R as xa,ca as Kl,cb as Wl,ai as wa,cc as zl,ah as Ul,cd as Gl,ce as ql}from"./index-bd4c24ce.js";import{S as Yl}from"./index-0c3c532d.js";/* empty css */import{b as Xl,i as Zl}from"./index-7555095e.js";import{t as Sa,_ as Jl,a as Ql,H as es}from"./searchHistory-9695d8f0.js";import"./index-dbe83aae.js";import{i as ts}from"./_isIterateeCall-eeca32c3.js";var ns=function(){return{prefixCls:String,activeKey:{type:[Array,Number,String]},defaultActiveKey:{type:[Array,Number,String]},accordion:{type:Boolean,default:void 0},destroyInactivePanel:{type:Boolean,default:void 0},bordered:{type:Boolean,default:void 0},expandIcon:Function,openAnimation:Je.object,expandIconPosition:Je.oneOf(Xi("left","right")),collapsible:{type:String},ghost:{type:Boolean,default:void 0},onChange:Function,"onUpdate:activeKey":Function}},qo=function(){return{openAnimation:Je.object,prefixCls:String,header:Je.any,headerClass:String,showArrow:{type:Boolean,default:void 0},isActive:{type:Boolean,default:void 0},destroyInactivePanel:{type:Boolean,default:void 0},disabled:{type:Boolean,default:void 0},accordion:{type:Boolean,default:void 0},forceRender:{type:Boolean,default:void 0},expandIcon:Function,extra:Je.any,panelKey:Je.oneOfType([Je.string,Je.number]),collapsible:{type:String},role:String,onItemClick:{type:Function}}};function ka(e){var t=e;if(!Array.isArray(t)){var n=el(t);t=n==="number"||n==="string"?[t]:[]}return t.map(function(r){return String(r)})}const qt=se({compatConfig:{MODE:3},name:"ACollapse",inheritAttrs:!1,props:Lo(ns(),{accordion:!1,destroyInactivePanel:!1,bordered:!0,openAnimation:Zi("ant-motion-collapse",!1),expandIconPosition:"left"}),slots:["expandIcon"],setup:function(t,n){var r=n.attrs,a=n.slots,o=n.emit,s=W(ka(Ji([t.activeKey,t.defaultActiveKey])));Qe(function(){return t.activeKey},function(){s.value=ka(t.activeKey)},{deep:!0});var i=Do("collapse",t),l=i.prefixCls,c=i.direction,u=Z(function(){var g=t.expandIconPosition;return g!==void 0?g:c.value==="rtl"?"right":"left"}),d=function(p){var C=t.expandIcon,_=C===void 0?a.expandIcon:C,w=_?_(p):P(rl,{rotate:p.isActive?90:void 0},null);return P("div",null,[al(Array.isArray(_)?w[0]:w)?ha(w,{class:"".concat(l.value,"-arrow")},!1):w])},v=function(p){t.activeKey===void 0&&(s.value=p);var C=t.accordion?p[0]:p;o("update:activeKey",C),o("change",C)},f=function(p){var C=s.value;if(t.accordion)C=C[0]===p?[]:[p];else{C=ol(C);var _=C.indexOf(p),w=_>-1;w?C.splice(_,1):C.push(p)}v(C)},m=function(p,C){var _,w,$;if(!nl(p)){var O=s.value,M=t.accordion,D=t.destroyInactivePanel,j=t.collapsible,F=t.openAnimation,b=String((_=p.key)!==null&&_!==void 0?_:C),R=p.props||{},T=R.header,H=T===void 0?(w=p.children)===null||w===void 0||($=w.header)===null||$===void 0?void 0:$.call(w):T,N=R.headerClass,U=R.collapsible,h=R.disabled,x=!1;M?x=O[0]===b:x=O.indexOf(b)>-1;var E=U??j;(h||h==="")&&(E="disabled");var V={key:b,panelKey:b,header:H,headerClass:N,isActive:x,prefixCls:l.value,destroyInactivePanel:D,openAnimation:F,accordion:M,onItemClick:E==="disabled"?null:f,expandIcon:d,collapsible:E};return ha(p,V)}},y=function(){var p;return tl((p=a.default)===null||p===void 0?void 0:p.call(a)).map(m)};return function(){var g,p=t.accordion,C=t.bordered,_=t.ghost,w=yn((g={},he(g,l.value,!0),he(g,"".concat(l.value,"-borderless"),!C),he(g,"".concat(l.value,"-icon-position-").concat(u.value),!0),he(g,"".concat(l.value,"-rtl"),c.value==="rtl"),he(g,"".concat(l.value,"-ghost"),!!_),he(g,r.class,!!r.class),g));return P("div",Gt(Gt({class:w},Qi(r)),{},{style:r.style,role:p?"tablist":null}),[y()])}}}),rs=se({compatConfig:{MODE:3},name:"PanelContent",props:qo(),setup:function(t,n){var r=n.slots,a=W(!1);return il(function(){(t.isActive||t.forceRender)&&(a.value=!0)}),function(){var o,s;if(!a.value)return null;var i=t.prefixCls,l=t.isActive,c=t.role;return P("div",{ref:W,class:yn("".concat(i,"-content"),(o={},he(o,"".concat(i,"-content-active"),l),he(o,"".concat(i,"-content-inactive"),!l),o)),role:c},[P("div",{class:"".concat(i,"-content-box")},[(s=r.default)===null||s===void 0?void 0:s.call(r)])])}}}),Cn=se({compatConfig:{MODE:3},name:"ACollapsePanel",inheritAttrs:!1,props:Lo(qo(),{showArrow:!0,isActive:!1,onItemClick:function(){},headerClass:"",forceRender:!1}),slots:["expandIcon","extra","header"],setup:function(t,n){var r=n.slots,a=n.emit,o=n.attrs;ll(t.disabled===void 0,"Collapse.Panel",'`disabled` is deprecated. Please use `collapsible="disabled"` instead.');var s=Do("collapse",t),i=s.prefixCls,l=function(){a("itemClick",t.panelKey)},c=function(d){(d.key==="Enter"||d.keyCode===13||d.which===13)&&l()};return function(){var u,d,v,f,m=t.header,y=m===void 0?(u=r.header)===null||u===void 0?void 0:u.call(r):m,g=t.headerClass,p=t.isActive,C=t.showArrow,_=t.destroyInactivePanel,w=t.accordion,$=t.forceRender,O=t.openAnimation,M=t.expandIcon,D=M===void 0?r.expandIcon:M,j=t.extra,F=j===void 0?(d=r.extra)===null||d===void 0?void 0:d.call(r):j,b=t.collapsible,R=b==="disabled",T=i.value,H=yn("".concat(T,"-header"),(v={},he(v,g,g),he(v,"".concat(T,"-header-collapsible-only"),b==="header"),v)),N=yn((f={},he(f,"".concat(T,"-item"),!0),he(f,"".concat(T,"-item-active"),p),he(f,"".concat(T,"-item-disabled"),R),he(f,"".concat(T,"-no-arrow"),!C),he(f,"".concat(o.class),!!o.class),f)),U=P("i",{class:"arrow"},null);C&&typeof D=="function"&&(U=D(t));var h=en(P(rs,{prefixCls:T,isActive:p,forceRender:$,role:w?"tabpanel":null},{default:r.default}),[[mn,p]]),x=Gt({appear:!1,css:!1},O);return P("div",Gt(Gt({},o),{},{class:N}),[P("div",{class:H,onClick:function(){return b!=="header"&&l()},role:w?"tab":"button",tabindex:R?-1:0,"aria-expanded":p,onKeypress:c},[C&&U,b==="header"?P("span",{onClick:l,class:"".concat(T,"-header-text")},[y]):y,F&&P("div",{class:"".concat(T,"-extra")},[F])]),P(sl,x,{default:function(){return[!_||p?h:null]}})])}}});qt.Panel=Cn;qt.install=function(e){return e.component(qt.name,qt),e.component(Cn.name,Cn),e};var as={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M869 487.8L491.2 159.9c-2.9-2.5-6.6-3.9-10.5-3.9h-88.5c-7.4 0-10.8 9.2-5.2 14l350.2 304H152c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h585.1L386.9 854c-5.6 4.9-2.2 14 5.2 14h91.5c1.9 0 3.8-.7 5.2-2L869 536.2a32.07 32.07 0 000-48.4z"}}]},name:"arrow-right",theme:"outlined"};const os=as;function Aa(e){for(var t=1;t1?n[a-1]:void 0,s=a>2?n[2]:void 0;for(o=e.length>3&&typeof o=="function"?(a--,o):void 0,s&&ts(n[0],n[1],s)&&(o=a<3?void 0:o,a=1),t=Object(t);++r=0,o=!n&&a&&(t==="hex"||t==="hex6"||t==="hex3"||t==="hex4"||t==="hex8"||t==="name");return o?t==="name"&&this._a===0?this.toName():this.toRgbString():(t==="rgb"&&(r=this.toRgbString()),t==="prgb"&&(r=this.toPercentageRgbString()),(t==="hex"||t==="hex6")&&(r=this.toHexString()),t==="hex3"&&(r=this.toHexString(!0)),t==="hex4"&&(r=this.toHex8String(!0)),t==="hex8"&&(r=this.toHex8String()),t==="name"&&(r=this.toName()),t==="hsl"&&(r=this.toHslString()),t==="hsv"&&(r=this.toHsvString()),r||this.toHexString())},clone:function(){return k(this.toString())},_applyModification:function(t,n){var r=t.apply(null,[this].concat([].slice.call(n)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(js,arguments)},brighten:function(){return this._applyModification(Hs,arguments)},darken:function(){return this._applyModification(Bs,arguments)},desaturate:function(){return this._applyModification(Ms,arguments)},saturate:function(){return this._applyModification(Ps,arguments)},greyscale:function(){return this._applyModification(Is,arguments)},spin:function(){return this._applyModification(Ls,arguments)},_applyCombination:function(t,n){return t.apply(null,[this].concat([].slice.call(n)))},analogous:function(){return this._applyCombination(Vs,arguments)},complement:function(){return this._applyCombination(Ds,arguments)},monochromatic:function(){return this._applyCombination(Fs,arguments)},splitcomplement:function(){return this._applyCombination(Ns,arguments)},triad:function(){return this._applyCombination(Ta,[3])},tetrad:function(){return this._applyCombination(Ta,[4])}};k.fromRatio=function(e,t){if(_n(e)=="object"){var n={};for(var r in e)e.hasOwnProperty(r)&&(r==="a"?n[r]=e[r]:n[r]=zt(e[r]));e=n}return k(e,t)};function Os(e){var t={r:0,g:0,b:0},n=1,r=null,a=null,o=null,s=!1,i=!1;return typeof e=="string"&&(e=Gs(e)),_n(e)=="object"&&(Fe(e.r)&&Fe(e.g)&&Fe(e.b)?(t=$s(e.r,e.g,e.b),s=!0,i=String(e.r).substr(-1)==="%"?"prgb":"rgb"):Fe(e.h)&&Fe(e.s)&&Fe(e.v)?(r=zt(e.s),a=zt(e.v),t=Rs(e.h,r,a),s=!0,i="hsv"):Fe(e.h)&&Fe(e.s)&&Fe(e.l)&&(r=zt(e.s),o=zt(e.l),t=Es(e.h,r,o),s=!0,i="hsl"),e.hasOwnProperty("a")&&(n=e.a)),n=Zo(n),{ok:s,format:e.format||i,r:Math.min(255,Math.max(t.r,0)),g:Math.min(255,Math.max(t.g,0)),b:Math.min(255,Math.max(t.b,0)),a:n}}function $s(e,t,n){return{r:X(e,255)*255,g:X(t,255)*255,b:X(n,255)*255}}function Oa(e,t,n){e=X(e,255),t=X(t,255),n=X(n,255);var r=Math.max(e,t,n),a=Math.min(e,t,n),o,s,i=(r+a)/2;if(r==a)o=s=0;else{var l=r-a;switch(s=i>.5?l/(2-r-a):l/(r+a),r){case e:o=(t-n)/l+(t1&&(d-=1),d<1/6?c+(u-c)*6*d:d<1/2?u:d<2/3?c+(u-c)*(2/3-d)*6:c}if(t===0)r=a=o=n;else{var i=n<.5?n*(1+t):n+t-n*t,l=2*n-i;r=s(l,i,e+1/3),a=s(l,i,e),o=s(l,i,e-1/3)}return{r:r*255,g:a*255,b:o*255}}function $a(e,t,n){e=X(e,255),t=X(t,255),n=X(n,255);var r=Math.max(e,t,n),a=Math.min(e,t,n),o,s,i=r,l=r-a;if(s=r===0?0:l/r,r==a)o=0;else{switch(r){case e:o=(t-n)/l+(t>1)+720)%360;--t;)r.h=(r.h+a)%360,o.push(k(r));return o}function Fs(e,t){t=t||6;for(var n=k(e).toHsv(),r=n.h,a=n.s,o=n.v,s=[],i=1/t;t--;)s.push(k({h:r,s:a,v:o})),o=(o+i)%1;return s}k.mix=function(e,t,n){n=n===0?0:n||50;var r=k(e).toRgb(),a=k(t).toRgb(),o=n/100,s={r:(a.r-r.r)*o+r.r,g:(a.g-r.g)*o+r.g,b:(a.b-r.b)*o+r.b,a:(a.a-r.a)*o+r.a};return k(s)};k.readability=function(e,t){var n=k(e),r=k(t);return(Math.max(n.getLuminance(),r.getLuminance())+.05)/(Math.min(n.getLuminance(),r.getLuminance())+.05)};k.isReadable=function(e,t,n){var r=k.readability(e,t),a,o;switch(o=!1,a=qs(n),a.level+a.size){case"AAsmall":case"AAAlarge":o=r>=4.5;break;case"AAlarge":o=r>=3;break;case"AAAsmall":o=r>=7;break}return o};k.mostReadable=function(e,t,n){var r=null,a=0,o,s,i,l;n=n||{},s=n.includeFallbackColors,i=n.level,l=n.size;for(var c=0;ca&&(a=o,r=k(t[c]));return k.isReadable(e,r,{level:i,size:l})||!s?r:(n.includeFallbackColors=!1,k.mostReadable(e,["#fff","#000"],n))};var yr=k.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Ks=k.hexNames=Ws(yr);function Ws(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}function Zo(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function X(e,t){zs(e)&&(e="100%");var n=Us(e);return e=Math.min(t,Math.max(0,parseFloat(e))),n&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function jn(e){return Math.min(1,Math.max(0,e))}function _e(e){return parseInt(e,16)}function zs(e){return typeof e=="string"&&e.indexOf(".")!=-1&&parseFloat(e)===1}function Us(e){return typeof e=="string"&&e.indexOf("%")!=-1}function He(e){return e.length==1?"0"+e:""+e}function zt(e){return e<=1&&(e=e*100+"%"),e}function Jo(e){return Math.round(parseFloat(e)*255).toString(16)}function Ma(e){return _e(e)/255}var je=function(){var e="[-\\+]?\\d+%?",t="[-\\+]?\\d*\\.\\d+%?",n="(?:"+t+")|(?:"+e+")",r="[\\s|\\(]+("+n+")[,|\\s]+("+n+")[,|\\s]+("+n+")\\s*\\)?",a="[\\s|\\(]+("+n+")[,|\\s]+("+n+")[,|\\s]+("+n+")[,|\\s]+("+n+")\\s*\\)?";return{CSS_UNIT:new RegExp(n),rgb:new RegExp("rgb"+r),rgba:new RegExp("rgba"+a),hsl:new RegExp("hsl"+r),hsla:new RegExp("hsla"+a),hsv:new RegExp("hsv"+r),hsva:new RegExp("hsva"+a),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}}();function Fe(e){return!!je.CSS_UNIT.exec(e)}function Gs(e){e=e.replace(ks,"").replace(As,"").toLowerCase();var t=!1;if(yr[e])e=yr[e],t=!0;else if(e=="transparent")return{r:0,g:0,b:0,a:0,format:"name"};var n;return(n=je.rgb.exec(e))?{r:n[1],g:n[2],b:n[3]}:(n=je.rgba.exec(e))?{r:n[1],g:n[2],b:n[3],a:n[4]}:(n=je.hsl.exec(e))?{h:n[1],s:n[2],l:n[3]}:(n=je.hsla.exec(e))?{h:n[1],s:n[2],l:n[3],a:n[4]}:(n=je.hsv.exec(e))?{h:n[1],s:n[2],v:n[3]}:(n=je.hsva.exec(e))?{h:n[1],s:n[2],v:n[3],a:n[4]}:(n=je.hex8.exec(e))?{r:_e(n[1]),g:_e(n[2]),b:_e(n[3]),a:Ma(n[4]),format:t?"name":"hex8"}:(n=je.hex6.exec(e))?{r:_e(n[1]),g:_e(n[2]),b:_e(n[3]),format:t?"name":"hex"}:(n=je.hex4.exec(e))?{r:_e(n[1]+""+n[1]),g:_e(n[2]+""+n[2]),b:_e(n[3]+""+n[3]),a:Ma(n[4]+""+n[4]),format:t?"name":"hex8"}:(n=je.hex3.exec(e))?{r:_e(n[1]+""+n[1]),g:_e(n[2]+""+n[2]),b:_e(n[3]+""+n[3]),format:t?"name":"hex"}:!1}function qs(e){var t,n;return e=e||{level:"AA",size:"small"},t=(e.level||"AA").toUpperCase(),n=(e.size||"small").toLowerCase(),t!=="AA"&&t!=="AAA"&&(t="AA"),n!=="small"&&n!=="large"&&(n="small"),{level:t,size:n}}var pt=pt||{};pt.stringify=function(){var e={"visit_linear-gradient":function(t){return e.visit_gradient(t)},"visit_repeating-linear-gradient":function(t){return e.visit_gradient(t)},"visit_radial-gradient":function(t){return e.visit_gradient(t)},"visit_repeating-radial-gradient":function(t){return e.visit_gradient(t)},visit_gradient:function(t){var n=e.visit(t.orientation);return n&&(n+=", "),t.type+"("+n+e.visit(t.colorStops)+")"},visit_shape:function(t){var n=t.value,r=e.visit(t.at),a=e.visit(t.style);return a&&(n+=" "+a),r&&(n+=" at "+r),n},"visit_default-radial":function(t){var n="",r=e.visit(t.at);return r&&(n+=r),n},"visit_extent-keyword":function(t){var n=t.value,r=e.visit(t.at);return r&&(n+=" at "+r),n},"visit_position-keyword":function(t){return t.value},visit_position:function(t){return e.visit(t.value.x)+" "+e.visit(t.value.y)},"visit_%":function(t){return t.value+"%"},visit_em:function(t){return t.value+"em"},visit_px:function(t){return t.value+"px"},visit_literal:function(t){return e.visit_color(t.value,t)},visit_hex:function(t){return e.visit_color("#"+t.value,t)},visit_rgb:function(t){return e.visit_color("rgb("+t.value.join(", ")+")",t)},visit_rgba:function(t){return e.visit_color("rgba("+t.value.join(", ")+")",t)},visit_color:function(t,n){var r=t,a=e.visit(n.length);return a&&(r+=" "+a),r},visit_angular:function(t){return t.value+"deg"},visit_directional:function(t){return"to "+t.value},visit_array:function(t){var n="",r=t.length;return t.forEach(function(a,o){n+=e.visit(a),o0&&n("Invalid input not EOF"),h}function a(){return _(o)}function o(){return s("linear-gradient",e.linearGradient,l)||s("repeating-linear-gradient",e.repeatingLinearGradient,l)||s("radial-gradient",e.radialGradient,d)||s("repeating-radial-gradient",e.repeatingRadialGradient,d)}function s(h,x,E){return i(x,function(V){var ue=E();return ue&&(N(e.comma)||n("Missing comma before color stops")),{type:h,orientation:ue,colorStops:_(w)}})}function i(h,x){var E=N(h);if(E){N(e.startCall)||n("Missing (");var V=x(E);return N(e.endCall)||n("Missing )"),V}}function l(){return c()||u()}function c(){return H("directional",e.sideOrCorner,1)}function u(){return H("angular",e.angleValue,1)}function d(){var h,x=v(),E;return x&&(h=[],h.push(x),E=t,N(e.comma)&&(x=v(),x?h.push(x):t=E)),h}function v(){var h=f()||m();if(h)h.at=g();else{var x=y();if(x){h=x;var E=g();E&&(h.at=E)}else{var V=p();V&&(h={type:"default-radial",at:V})}}return h}function f(){var h=H("shape",/^(circle)/i,0);return h&&(h.style=T()||y()),h}function m(){var h=H("shape",/^(ellipse)/i,0);return h&&(h.style=b()||y()),h}function y(){return H("extent-keyword",e.extentKeywords,1)}function g(){if(H("position",/^at/,0)){var h=p();return h||n("Missing positioning value"),h}}function p(){var h=C();if(h.x||h.y)return{type:"position",value:h}}function C(){return{x:b(),y:b()}}function _(h){var x=h(),E=[];if(x)for(E.push(x);N(e.comma);)x=h(),x?E.push(x):n("One extra comma");return E}function w(){var h=$();return h||n("Expected color definition"),h.length=b(),h}function $(){return M()||j()||D()||O()}function O(){return H("literal",e.literalColor,0)}function M(){return H("hex",e.hexColor,1)}function D(){return i(e.rgbColor,function(){return{type:"rgb",value:_(F)}})}function j(){return i(e.rgbaColor,function(){return{type:"rgba",value:_(F)}})}function F(){return N(e.number)[1]}function b(){return H("%",e.percentageValue,1)||R()||T()}function R(){return H("position-keyword",e.positionKeywords,1)}function T(){return H("px",e.pixelValue,1)||H("em",e.emValue,1)}function H(h,x,E){var V=N(x);if(V)return{type:h,value:V[E]}}function N(h){var x,E;return E=/^[\n\r\t\s]+/.exec(t),E&&U(E[0].length),x=h.exec(t),x&&U(x[0].length),x}function U(h){t=t.substr(h)}return function(h){return t=h.toString(),r()}}();var Ys=pt.parse,Xs=pt.stringify,me="top",Me="bottom",Pe="right",be="left",Rr="auto",on=[me,Me,Pe,be],kt="start",tn="end",Zs="clippingParents",Qo="viewport",Vt="popper",Js="reference",Pa=on.reduce(function(e,t){return e.concat([t+"-"+kt,t+"-"+tn])},[]),ei=[].concat(on,[Rr]).reduce(function(e,t){return e.concat([t,t+"-"+kt,t+"-"+tn])},[]),Qs="beforeRead",eu="read",tu="afterRead",nu="beforeMain",ru="main",au="afterMain",ou="beforeWrite",iu="write",lu="afterWrite",su=[Qs,eu,tu,nu,ru,au,ou,iu,lu];function Ne(e){return e?(e.nodeName||"").toLowerCase():null}function Se(e){if(e==null)return window;if(e.toString()!=="[object Window]"){var t=e.ownerDocument;return t&&t.defaultView||window}return e}function st(e){var t=Se(e).Element;return e instanceof t||e instanceof Element}function Ee(e){var t=Se(e).HTMLElement;return e instanceof t||e instanceof HTMLElement}function Tr(e){if(typeof ShadowRoot>"u")return!1;var t=Se(e).ShadowRoot;return e instanceof t||e instanceof ShadowRoot}function uu(e){var t=e.state;Object.keys(t.elements).forEach(function(n){var r=t.styles[n]||{},a=t.attributes[n]||{},o=t.elements[n];!Ee(o)||!Ne(o)||(Object.assign(o.style,r),Object.keys(a).forEach(function(s){var i=a[s];i===!1?o.removeAttribute(s):o.setAttribute(s,i===!0?"":i)}))})}function cu(e){var t=e.state,n={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(t.elements.popper.style,n.popper),t.styles=n,t.elements.arrow&&Object.assign(t.elements.arrow.style,n.arrow),function(){Object.keys(t.elements).forEach(function(r){var a=t.elements[r],o=t.attributes[r]||{},s=Object.keys(t.styles.hasOwnProperty(r)?t.styles[r]:n[r]),i=s.reduce(function(l,c){return l[c]="",l},{});!Ee(a)||!Ne(a)||(Object.assign(a.style,i),Object.keys(o).forEach(function(l){a.removeAttribute(l)}))})}}const du={name:"applyStyles",enabled:!0,phase:"write",fn:uu,effect:cu,requires:["computeStyles"]};function Le(e){return e.split("-")[0]}var it=Math.max,xn=Math.min,At=Math.round;function mr(){var e=navigator.userAgentData;return e!=null&&e.brands&&Array.isArray(e.brands)?e.brands.map(function(t){return t.brand+"/"+t.version}).join(" "):navigator.userAgent}function ti(){return!/^((?!chrome|android).)*safari/i.test(mr())}function Ot(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!1);var r=e.getBoundingClientRect(),a=1,o=1;t&&Ee(e)&&(a=e.offsetWidth>0&&At(r.width)/e.offsetWidth||1,o=e.offsetHeight>0&&At(r.height)/e.offsetHeight||1);var s=st(e)?Se(e):window,i=s.visualViewport,l=!ti()&&n,c=(r.left+(l&&i?i.offsetLeft:0))/a,u=(r.top+(l&&i?i.offsetTop:0))/o,d=r.width/a,v=r.height/o;return{width:d,height:v,top:u,right:c+d,bottom:u+v,left:c,x:c,y:u}}function Mr(e){var t=Ot(e),n=e.offsetWidth,r=e.offsetHeight;return Math.abs(t.width-n)<=1&&(n=t.width),Math.abs(t.height-r)<=1&&(r=t.height),{x:e.offsetLeft,y:e.offsetTop,width:n,height:r}}function ni(e,t){var n=t.getRootNode&&t.getRootNode();if(e.contains(t))return!0;if(n&&Tr(n)){var r=t;do{if(r&&e.isSameNode(r))return!0;r=r.parentNode||r.host}while(r)}return!1}function Ue(e){return Se(e).getComputedStyle(e)}function fu(e){return["table","td","th"].indexOf(Ne(e))>=0}function rt(e){return((st(e)?e.ownerDocument:e.document)||window.document).documentElement}function Hn(e){return Ne(e)==="html"?e:e.assignedSlot||e.parentNode||(Tr(e)?e.host:null)||rt(e)}function Ia(e){return!Ee(e)||Ue(e).position==="fixed"?null:e.offsetParent}function pu(e){var t=/firefox/i.test(mr()),n=/Trident/i.test(mr());if(n&&Ee(e)){var r=Ue(e);if(r.position==="fixed")return null}var a=Hn(e);for(Tr(a)&&(a=a.host);Ee(a)&&["html","body"].indexOf(Ne(a))<0;){var o=Ue(a);if(o.transform!=="none"||o.perspective!=="none"||o.contain==="paint"||["transform","perspective"].indexOf(o.willChange)!==-1||t&&o.willChange==="filter"||t&&o.filter&&o.filter!=="none")return a;a=a.parentNode}return null}function ln(e){for(var t=Se(e),n=Ia(e);n&&fu(n)&&Ue(n).position==="static";)n=Ia(n);return n&&(Ne(n)==="html"||Ne(n)==="body"&&Ue(n).position==="static")?t:n||pu(e)||t}function Pr(e){return["top","bottom"].indexOf(e)>=0?"x":"y"}function Yt(e,t,n){return it(e,xn(t,n))}function vu(e,t,n){var r=Yt(e,t,n);return r>n?n:r}function ri(){return{top:0,right:0,bottom:0,left:0}}function ai(e){return Object.assign({},ri(),e)}function oi(e,t){return t.reduce(function(n,r){return n[r]=e,n},{})}var hu=function(t,n){return t=typeof t=="function"?t(Object.assign({},n.rects,{placement:n.placement})):t,ai(typeof t!="number"?t:oi(t,on))};function gu(e){var t,n=e.state,r=e.name,a=e.options,o=n.elements.arrow,s=n.modifiersData.popperOffsets,i=Le(n.placement),l=Pr(i),c=[be,Pe].indexOf(i)>=0,u=c?"height":"width";if(!(!o||!s)){var d=hu(a.padding,n),v=Mr(o),f=l==="y"?me:be,m=l==="y"?Me:Pe,y=n.rects.reference[u]+n.rects.reference[l]-s[l]-n.rects.popper[u],g=s[l]-n.rects.reference[l],p=ln(o),C=p?l==="y"?p.clientHeight||0:p.clientWidth||0:0,_=y/2-g/2,w=d[f],$=C-v[u]-d[m],O=C/2-v[u]/2+_,M=Yt(w,O,$),D=l;n.modifiersData[r]=(t={},t[D]=M,t.centerOffset=M-O,t)}}function yu(e){var t=e.state,n=e.options,r=n.element,a=r===void 0?"[data-popper-arrow]":r;a!=null&&(typeof a=="string"&&(a=t.elements.popper.querySelector(a),!a)||ni(t.elements.popper,a)&&(t.elements.arrow=a))}const mu={name:"arrow",enabled:!0,phase:"main",fn:gu,effect:yu,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function $t(e){return e.split("-")[1]}var bu={top:"auto",right:"auto",bottom:"auto",left:"auto"};function Cu(e,t){var n=e.x,r=e.y,a=t.devicePixelRatio||1;return{x:At(n*a)/a||0,y:At(r*a)/a||0}}function ja(e){var t,n=e.popper,r=e.popperRect,a=e.placement,o=e.variation,s=e.offsets,i=e.position,l=e.gpuAcceleration,c=e.adaptive,u=e.roundOffsets,d=e.isFixed,v=s.x,f=v===void 0?0:v,m=s.y,y=m===void 0?0:m,g=typeof u=="function"?u({x:f,y}):{x:f,y};f=g.x,y=g.y;var p=s.hasOwnProperty("x"),C=s.hasOwnProperty("y"),_=be,w=me,$=window;if(c){var O=ln(n),M="clientHeight",D="clientWidth";if(O===Se(n)&&(O=rt(n),Ue(O).position!=="static"&&i==="absolute"&&(M="scrollHeight",D="scrollWidth")),O=O,a===me||(a===be||a===Pe)&&o===tn){w=Me;var j=d&&O===$&&$.visualViewport?$.visualViewport.height:O[M];y-=j-r.height,y*=l?1:-1}if(a===be||(a===me||a===Me)&&o===tn){_=Pe;var F=d&&O===$&&$.visualViewport?$.visualViewport.width:O[D];f-=F-r.width,f*=l?1:-1}}var b=Object.assign({position:i},c&&bu),R=u===!0?Cu({x:f,y},Se(n)):{x:f,y};if(f=R.x,y=R.y,l){var T;return Object.assign({},b,(T={},T[w]=C?"0":"",T[_]=p?"0":"",T.transform=($.devicePixelRatio||1)<=1?"translate("+f+"px, "+y+"px)":"translate3d("+f+"px, "+y+"px, 0)",T))}return Object.assign({},b,(t={},t[w]=C?y+"px":"",t[_]=p?f+"px":"",t.transform="",t))}function _u(e){var t=e.state,n=e.options,r=n.gpuAcceleration,a=r===void 0?!0:r,o=n.adaptive,s=o===void 0?!0:o,i=n.roundOffsets,l=i===void 0?!0:i,c={placement:Le(t.placement),variation:$t(t.placement),popper:t.elements.popper,popperRect:t.rects.popper,gpuAcceleration:a,isFixed:t.options.strategy==="fixed"};t.modifiersData.popperOffsets!=null&&(t.styles.popper=Object.assign({},t.styles.popper,ja(Object.assign({},c,{offsets:t.modifiersData.popperOffsets,position:t.options.strategy,adaptive:s,roundOffsets:l})))),t.modifiersData.arrow!=null&&(t.styles.arrow=Object.assign({},t.styles.arrow,ja(Object.assign({},c,{offsets:t.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-placement":t.placement})}const xu={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:_u,data:{}};var dn={passive:!0};function wu(e){var t=e.state,n=e.instance,r=e.options,a=r.scroll,o=a===void 0?!0:a,s=r.resize,i=s===void 0?!0:s,l=Se(t.elements.popper),c=[].concat(t.scrollParents.reference,t.scrollParents.popper);return o&&c.forEach(function(u){u.addEventListener("scroll",n.update,dn)}),i&&l.addEventListener("resize",n.update,dn),function(){o&&c.forEach(function(u){u.removeEventListener("scroll",n.update,dn)}),i&&l.removeEventListener("resize",n.update,dn)}}const Su={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:wu,data:{}};var ku={left:"right",right:"left",bottom:"top",top:"bottom"};function hn(e){return e.replace(/left|right|bottom|top/g,function(t){return ku[t]})}var Au={start:"end",end:"start"};function Ha(e){return e.replace(/start|end/g,function(t){return Au[t]})}function Ir(e){var t=Se(e),n=t.pageXOffset,r=t.pageYOffset;return{scrollLeft:n,scrollTop:r}}function jr(e){return Ot(rt(e)).left+Ir(e).scrollLeft}function Ou(e,t){var n=Se(e),r=rt(e),a=n.visualViewport,o=r.clientWidth,s=r.clientHeight,i=0,l=0;if(a){o=a.width,s=a.height;var c=ti();(c||!c&&t==="fixed")&&(i=a.offsetLeft,l=a.offsetTop)}return{width:o,height:s,x:i+jr(e),y:l}}function $u(e){var t,n=rt(e),r=Ir(e),a=(t=e.ownerDocument)==null?void 0:t.body,o=it(n.scrollWidth,n.clientWidth,a?a.scrollWidth:0,a?a.clientWidth:0),s=it(n.scrollHeight,n.clientHeight,a?a.scrollHeight:0,a?a.clientHeight:0),i=-r.scrollLeft+jr(e),l=-r.scrollTop;return Ue(a||n).direction==="rtl"&&(i+=it(n.clientWidth,a?a.clientWidth:0)-o),{width:o,height:s,x:i,y:l}}function Hr(e){var t=Ue(e),n=t.overflow,r=t.overflowX,a=t.overflowY;return/auto|scroll|overlay|hidden/.test(n+a+r)}function ii(e){return["html","body","#document"].indexOf(Ne(e))>=0?e.ownerDocument.body:Ee(e)&&Hr(e)?e:ii(Hn(e))}function Xt(e,t){var n;t===void 0&&(t=[]);var r=ii(e),a=r===((n=e.ownerDocument)==null?void 0:n.body),o=Se(r),s=a?[o].concat(o.visualViewport||[],Hr(r)?r:[]):r,i=t.concat(s);return a?i:i.concat(Xt(Hn(s)))}function br(e){return Object.assign({},e,{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height})}function Eu(e,t){var n=Ot(e,!1,t==="fixed");return n.top=n.top+e.clientTop,n.left=n.left+e.clientLeft,n.bottom=n.top+e.clientHeight,n.right=n.left+e.clientWidth,n.width=e.clientWidth,n.height=e.clientHeight,n.x=n.left,n.y=n.top,n}function Ba(e,t,n){return t===Qo?br(Ou(e,n)):st(t)?Eu(t,n):br($u(rt(e)))}function Ru(e){var t=Xt(Hn(e)),n=["absolute","fixed"].indexOf(Ue(e).position)>=0,r=n&&Ee(e)?ln(e):e;return st(r)?t.filter(function(a){return st(a)&&ni(a,r)&&Ne(a)!=="body"}):[]}function Tu(e,t,n,r){var a=t==="clippingParents"?Ru(e):[].concat(t),o=[].concat(a,[n]),s=o[0],i=o.reduce(function(l,c){var u=Ba(e,c,r);return l.top=it(u.top,l.top),l.right=xn(u.right,l.right),l.bottom=xn(u.bottom,l.bottom),l.left=it(u.left,l.left),l},Ba(e,s,r));return i.width=i.right-i.left,i.height=i.bottom-i.top,i.x=i.left,i.y=i.top,i}function li(e){var t=e.reference,n=e.element,r=e.placement,a=r?Le(r):null,o=r?$t(r):null,s=t.x+t.width/2-n.width/2,i=t.y+t.height/2-n.height/2,l;switch(a){case me:l={x:s,y:t.y-n.height};break;case Me:l={x:s,y:t.y+t.height};break;case Pe:l={x:t.x+t.width,y:i};break;case be:l={x:t.x-n.width,y:i};break;default:l={x:t.x,y:t.y}}var c=a?Pr(a):null;if(c!=null){var u=c==="y"?"height":"width";switch(o){case kt:l[c]=l[c]-(t[u]/2-n[u]/2);break;case tn:l[c]=l[c]+(t[u]/2-n[u]/2);break}}return l}function nn(e,t){t===void 0&&(t={});var n=t,r=n.placement,a=r===void 0?e.placement:r,o=n.strategy,s=o===void 0?e.strategy:o,i=n.boundary,l=i===void 0?Zs:i,c=n.rootBoundary,u=c===void 0?Qo:c,d=n.elementContext,v=d===void 0?Vt:d,f=n.altBoundary,m=f===void 0?!1:f,y=n.padding,g=y===void 0?0:y,p=ai(typeof g!="number"?g:oi(g,on)),C=v===Vt?Js:Vt,_=e.rects.popper,w=e.elements[m?C:v],$=Tu(st(w)?w:w.contextElement||rt(e.elements.popper),l,u,s),O=Ot(e.elements.reference),M=li({reference:O,element:_,strategy:"absolute",placement:a}),D=br(Object.assign({},_,M)),j=v===Vt?D:O,F={top:$.top-j.top+p.top,bottom:j.bottom-$.bottom+p.bottom,left:$.left-j.left+p.left,right:j.right-$.right+p.right},b=e.modifiersData.offset;if(v===Vt&&b){var R=b[a];Object.keys(F).forEach(function(T){var H=[Pe,Me].indexOf(T)>=0?1:-1,N=[me,Me].indexOf(T)>=0?"y":"x";F[T]+=R[N]*H})}return F}function Mu(e,t){t===void 0&&(t={});var n=t,r=n.placement,a=n.boundary,o=n.rootBoundary,s=n.padding,i=n.flipVariations,l=n.allowedAutoPlacements,c=l===void 0?ei:l,u=$t(r),d=u?i?Pa:Pa.filter(function(m){return $t(m)===u}):on,v=d.filter(function(m){return c.indexOf(m)>=0});v.length===0&&(v=d);var f=v.reduce(function(m,y){return m[y]=nn(e,{placement:y,boundary:a,rootBoundary:o,padding:s})[Le(y)],m},{});return Object.keys(f).sort(function(m,y){return f[m]-f[y]})}function Pu(e){if(Le(e)===Rr)return[];var t=hn(e);return[Ha(e),t,Ha(t)]}function Iu(e){var t=e.state,n=e.options,r=e.name;if(!t.modifiersData[r]._skip){for(var a=n.mainAxis,o=a===void 0?!0:a,s=n.altAxis,i=s===void 0?!0:s,l=n.fallbackPlacements,c=n.padding,u=n.boundary,d=n.rootBoundary,v=n.altBoundary,f=n.flipVariations,m=f===void 0?!0:f,y=n.allowedAutoPlacements,g=t.options.placement,p=Le(g),C=p===g,_=l||(C||!m?[hn(g)]:Pu(g)),w=[g].concat(_).reduce(function(Be,Ce){return Be.concat(Le(Ce)===Rr?Mu(t,{placement:Ce,boundary:u,rootBoundary:d,padding:c,flipVariations:m,allowedAutoPlacements:y}):Ce)},[]),$=t.rects.reference,O=t.rects.popper,M=new Map,D=!0,j=w[0],F=0;F=0,N=H?"width":"height",U=nn(t,{placement:b,boundary:u,rootBoundary:d,altBoundary:v,padding:c}),h=H?T?Pe:be:T?Me:me;$[N]>O[N]&&(h=hn(h));var x=hn(h),E=[];if(o&&E.push(U[R]<=0),i&&E.push(U[h]<=0,U[x]<=0),E.every(function(Be){return Be})){j=b,D=!1;break}M.set(b,E)}if(D)for(var V=m?3:1,ue=function(Ce){var Ye=w.find(function(yt){var Ve=M.get(yt);if(Ve)return Ve.slice(0,Ce).every(function(Dt){return Dt})});if(Ye)return j=Ye,"break"},Ae=V;Ae>0;Ae--){var ye=ue(Ae);if(ye==="break")break}t.placement!==j&&(t.modifiersData[r]._skip=!0,t.placement=j,t.reset=!0)}}const ju={name:"flip",enabled:!0,phase:"main",fn:Iu,requiresIfExists:["offset"],data:{_skip:!1}};function La(e,t,n){return n===void 0&&(n={x:0,y:0}),{top:e.top-t.height-n.y,right:e.right-t.width+n.x,bottom:e.bottom-t.height+n.y,left:e.left-t.width-n.x}}function Da(e){return[me,Pe,Me,be].some(function(t){return e[t]>=0})}function Hu(e){var t=e.state,n=e.name,r=t.rects.reference,a=t.rects.popper,o=t.modifiersData.preventOverflow,s=nn(t,{elementContext:"reference"}),i=nn(t,{altBoundary:!0}),l=La(s,r),c=La(i,a,o),u=Da(l),d=Da(c);t.modifiersData[n]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:u,hasPopperEscaped:d},t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-reference-hidden":u,"data-popper-escaped":d})}const Bu={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:Hu};function Lu(e,t,n){var r=Le(e),a=[be,me].indexOf(r)>=0?-1:1,o=typeof n=="function"?n(Object.assign({},t,{placement:e})):n,s=o[0],i=o[1];return s=s||0,i=(i||0)*a,[be,Pe].indexOf(r)>=0?{x:i,y:s}:{x:s,y:i}}function Du(e){var t=e.state,n=e.options,r=e.name,a=n.offset,o=a===void 0?[0,0]:a,s=ei.reduce(function(u,d){return u[d]=Lu(d,t.rects,o),u},{}),i=s[t.placement],l=i.x,c=i.y;t.modifiersData.popperOffsets!=null&&(t.modifiersData.popperOffsets.x+=l,t.modifiersData.popperOffsets.y+=c),t.modifiersData[r]=s}const Nu={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:Du};function Vu(e){var t=e.state,n=e.name;t.modifiersData[n]=li({reference:t.rects.reference,element:t.rects.popper,strategy:"absolute",placement:t.placement})}const Fu={name:"popperOffsets",enabled:!0,phase:"read",fn:Vu,data:{}};function Ku(e){return e==="x"?"y":"x"}function Wu(e){var t=e.state,n=e.options,r=e.name,a=n.mainAxis,o=a===void 0?!0:a,s=n.altAxis,i=s===void 0?!1:s,l=n.boundary,c=n.rootBoundary,u=n.altBoundary,d=n.padding,v=n.tether,f=v===void 0?!0:v,m=n.tetherOffset,y=m===void 0?0:m,g=nn(t,{boundary:l,rootBoundary:c,padding:d,altBoundary:u}),p=Le(t.placement),C=$t(t.placement),_=!C,w=Pr(p),$=Ku(w),O=t.modifiersData.popperOffsets,M=t.rects.reference,D=t.rects.popper,j=typeof y=="function"?y(Object.assign({},t.rects,{placement:t.placement})):y,F=typeof j=="number"?{mainAxis:j,altAxis:j}:Object.assign({mainAxis:0,altAxis:0},j),b=t.modifiersData.offset?t.modifiersData.offset[t.placement]:null,R={x:0,y:0};if(O){if(o){var T,H=w==="y"?me:be,N=w==="y"?Me:Pe,U=w==="y"?"height":"width",h=O[w],x=h+g[H],E=h-g[N],V=f?-D[U]/2:0,ue=C===kt?M[U]:D[U],Ae=C===kt?-D[U]:-M[U],ye=t.elements.arrow,Be=f&&ye?Mr(ye):{width:0,height:0},Ce=t.modifiersData["arrow#persistent"]?t.modifiersData["arrow#persistent"].padding:ri(),Ye=Ce[H],yt=Ce[N],Ve=Yt(0,M[U],Be[U]),Dt=_?M[U]/2-V-Ve-Ye-F.mainAxis:ue-Ve-Ye-F.mainAxis,Kn=_?-M[U]/2+V+Ve+yt+F.mainAxis:Ae+Ve+yt+F.mainAxis,B=t.elements.arrow&&ln(t.elements.arrow),Nt=B?w==="y"?B.clientTop||0:B.clientLeft||0:0,ee=(T=b==null?void 0:b[w])!=null?T:0,Wn=h+Dt-ee-Nt,Xe=h+Kn-ee,la=Yt(f?xn(x,Wn):x,h,f?it(E,Xe):E);O[w]=la,R[w]=la-h}if(i){var sa,qi=w==="x"?me:be,Yi=w==="x"?Me:Pe,at=O[$],cn=$==="y"?"height":"width",ua=at+g[qi],ca=at-g[Yi],zn=[me,be].indexOf(p)!==-1,da=(sa=b==null?void 0:b[$])!=null?sa:0,fa=zn?ua:at-M[cn]-D[cn]-da+F.altAxis,pa=zn?at+M[cn]+D[cn]-da-F.altAxis:ca,va=f&&zn?vu(fa,at,pa):Yt(f?fa:ua,at,f?pa:ca);O[$]=va,R[$]=va-at}t.modifiersData[r]=R}}const zu={name:"preventOverflow",enabled:!0,phase:"main",fn:Wu,requiresIfExists:["offset"]};function Uu(e){return{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}}function Gu(e){return e===Se(e)||!Ee(e)?Ir(e):Uu(e)}function qu(e){var t=e.getBoundingClientRect(),n=At(t.width)/e.offsetWidth||1,r=At(t.height)/e.offsetHeight||1;return n!==1||r!==1}function Yu(e,t,n){n===void 0&&(n=!1);var r=Ee(t),a=Ee(t)&&qu(t),o=rt(t),s=Ot(e,a,n),i={scrollLeft:0,scrollTop:0},l={x:0,y:0};return(r||!r&&!n)&&((Ne(t)!=="body"||Hr(o))&&(i=Gu(t)),Ee(t)?(l=Ot(t,!0),l.x+=t.clientLeft,l.y+=t.clientTop):o&&(l.x=jr(o))),{x:s.left+i.scrollLeft-l.x,y:s.top+i.scrollTop-l.y,width:s.width,height:s.height}}function Xu(e){var t=new Map,n=new Set,r=[];e.forEach(function(o){t.set(o.name,o)});function a(o){n.add(o.name);var s=[].concat(o.requires||[],o.requiresIfExists||[]);s.forEach(function(i){if(!n.has(i)){var l=t.get(i);l&&a(l)}}),r.push(o)}return e.forEach(function(o){n.has(o.name)||a(o)}),r}function Zu(e){var t=Xu(e);return su.reduce(function(n,r){return n.concat(t.filter(function(a){return a.phase===r}))},[])}function Ju(e){var t;return function(){return t||(t=new Promise(function(n){Promise.resolve().then(function(){t=void 0,n(e())})})),t}}function Qu(e){var t=e.reduce(function(n,r){var a=n[r.name];return n[r.name]=a?Object.assign({},a,r,{options:Object.assign({},a.options,r.options),data:Object.assign({},a.data,r.data)}):r,n},{});return Object.keys(t).map(function(n){return t[n]})}var Na={placement:"bottom",modifiers:[],strategy:"absolute"};function Va(){for(var e=arguments.length,t=new Array(e),n=0;n + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */function Fa(e){return Object.prototype.toString.call(e)==="[object Object]"}function rc(e){var t,n;return Fa(e)===!1?!1:(t=e.constructor,t===void 0?!0:(n=t.prototype,!(Fa(n)===!1||n.hasOwnProperty("isPrototypeOf")===!1)))}function Zt(){return Zt=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0||(a[n]=e[n]);return a}const ac={silent:!1,logLevel:"warn"},oc=["validator"],ui=Object.prototype,ci=ui.toString,ic=ui.hasOwnProperty,di=/^\s*function (\w+)/;function Ka(e){var t;const n=(t=e==null?void 0:e.type)!==null&&t!==void 0?t:e;if(n){const r=n.toString().match(di);return r?r[1]:""}return""}const ut=rc,lc=e=>e;let pe=lc;const Et=(e,t)=>ic.call(e,t),sc=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},Rt=Array.isArray||function(e){return ci.call(e)==="[object Array]"},Tt=e=>ci.call(e)==="[object Function]",wn=e=>ut(e)&&Et(e,"_vueTypes_name"),fi=e=>ut(e)&&(Et(e,"type")||["_vueTypes_name","validator","default","required"].some(t=>Et(e,t)));function Br(e,t){return Object.defineProperty(e.bind(t),"__original",{value:e})}function vt(e,t,n=!1){let r,a=!0,o="";r=ut(e)?e:{type:e};const s=wn(r)?r._vueTypes_name+" - ":"";if(fi(r)&&r.type!==null){if(r.type===void 0||r.type===!0||!r.required&&t===void 0)return a;Rt(r.type)?(a=r.type.some(i=>vt(i,t,!0)===!0),o=r.type.map(i=>Ka(i)).join(" or ")):(o=Ka(r),a=o==="Array"?Rt(t):o==="Object"?ut(t):o==="String"||o==="Number"||o==="Boolean"||o==="Function"?function(i){if(i==null)return"";const l=i.constructor.toString().match(di);return l?l[1]:""}(t)===o:t instanceof r.type)}if(!a){const i=`${s}value "${t}" should be of type "${o}"`;return n===!1?(pe(i),!1):i}if(Et(r,"validator")&&Tt(r.validator)){const i=pe,l=[];if(pe=c=>{l.push(c)},a=r.validator(t),pe=i,!a){const c=(l.length>1?"* ":"")+l.join(` +* `);return l.length=0,n===!1?(pe(c),a):c}}return a}function we(e,t){const n=Object.defineProperties(t,{_vueTypes_name:{value:e,writable:!0},isRequired:{get(){return this.required=!0,this}},def:{value(a){return a===void 0?(Et(this,"default")&&delete this.default,this):Tt(a)||vt(this,a,!0)===!0?(this.default=Rt(a)?()=>[...a]:ut(a)?()=>Object.assign({},a):a,this):(pe(`${this._vueTypes_name} - invalid default value: "${a}"`),this)}}}),{validator:r}=n;return Tt(r)&&(n.validator=Br(r,n)),n}function De(e,t){const n=we(e,t);return Object.defineProperty(n,"validate",{value(r){return Tt(this.validator)&&pe(`${this._vueTypes_name} - calling .validate() will overwrite the current custom validator function. Validator info: +${JSON.stringify(this)}`),this.validator=Br(r,this),this}})}function Wa(e,t,n){const r=function(l){const c={};return Object.getOwnPropertyNames(l).forEach(u=>{c[u]=Object.getOwnPropertyDescriptor(l,u)}),Object.defineProperties({},c)}(t);if(r._vueTypes_name=e,!ut(n))return r;const{validator:a}=n,o=si(n,oc);if(Tt(a)){let{validator:l}=r;l&&(l=(i=(s=l).__original)!==null&&i!==void 0?i:s),r.validator=Br(l?function(c){return l.call(this,c)&&a.call(this,c)}:a,r)}var s,i;return Object.assign(r,o)}function Bn(e){return e.replace(/^(?!\s*$)/gm," ")}const uc=()=>De("any",{}),cc=()=>De("function",{type:Function}),dc=()=>De("boolean",{type:Boolean}),fc=()=>De("string",{type:String}),pc=()=>De("number",{type:Number}),vc=()=>De("array",{type:Array}),hc=()=>De("object",{type:Object}),gc=()=>we("integer",{type:Number,validator:e=>sc(e)}),yc=()=>we("symbol",{validator:e=>typeof e=="symbol"});function mc(e,t="custom validation failed"){if(typeof e!="function")throw new TypeError("[VueTypes error]: You must provide a function as argument");return we(e.name||"<>",{type:null,validator(n){const r=e(n);return r||pe(`${this._vueTypes_name} - ${t}`),r}})}function bc(e){if(!Rt(e))throw new TypeError("[VueTypes error]: You must provide an array as argument.");const t=`oneOf - value should be one of "${e.join('", "')}".`,n=e.reduce((r,a)=>{if(a!=null){const o=a.constructor;r.indexOf(o)===-1&&r.push(o)}return r},[]);return we("oneOf",{type:n.length>0?n:void 0,validator(r){const a=e.indexOf(r)!==-1;return a||pe(t),a}})}function Cc(e){if(!Rt(e))throw new TypeError("[VueTypes error]: You must provide an array as argument");let t=!1,n=[];for(let a=0;an.indexOf(a)===o);const r=n.length>0?n:null;return we("oneOfType",t?{type:r,validator(a){const o=[],s=e.some(i=>{const l=vt(wn(i)&&i._vueTypes_name==="oneOf"?i.type||null:i,a,!0);return typeof l=="string"&&o.push(l),l===!0});return s||pe(`oneOfType - provided value does not match any of the ${o.length} passed-in validators: +${Bn(o.join(` +`))}`),s}}:{type:r})}function _c(e){return we("arrayOf",{type:Array,validator(t){let n="";const r=t.every(a=>(n=vt(e,a,!0),n===!0));return r||pe(`arrayOf - value validation error: +${Bn(n)}`),r}})}function xc(e){return we("instanceOf",{type:e})}function wc(e){return we("objectOf",{type:Object,validator(t){let n="";const r=Object.keys(t).every(a=>(n=vt(e,t[a],!0),n===!0));return r||pe(`objectOf - value validation error: +${Bn(n)}`),r}})}function Sc(e){const t=Object.keys(e),n=t.filter(a=>{var o;return!((o=e[a])===null||o===void 0||!o.required)}),r=we("shape",{type:Object,validator(a){if(!ut(a))return!1;const o=Object.keys(a);if(n.length>0&&n.some(s=>o.indexOf(s)===-1)){const s=n.filter(i=>o.indexOf(i)===-1);return pe(s.length===1?`shape - required property "${s[0]}" is not defined.`:`shape - required properties "${s.join('", "')}" are not defined.`),!1}return o.every(s=>{if(t.indexOf(s)===-1)return this._vueTypes_isLoose===!0||(pe(`shape - shape definition does not include a "${s}" property. Allowed keys: "${t.join('", "')}".`),!1);const i=vt(e[s],a[s],!0);return typeof i=="string"&&pe(`shape - "${s}" property validation error: + ${Bn(i)}`),i===!0})}});return Object.defineProperty(r,"_vueTypes_isLoose",{writable:!0,value:!1}),Object.defineProperty(r,"loose",{get(){return this._vueTypes_isLoose=!0,this}}),r}const kc=["name","validate","getter"],Ac=(()=>{var e;return(e=class{static get any(){return uc()}static get func(){return cc().def(this.defaults.func)}static get bool(){return dc().def(this.defaults.bool)}static get string(){return fc().def(this.defaults.string)}static get number(){return pc().def(this.defaults.number)}static get array(){return vc().def(this.defaults.array)}static get object(){return hc().def(this.defaults.object)}static get integer(){return gc().def(this.defaults.integer)}static get symbol(){return yc()}static get nullable(){return{type:null}}static extend(t){if(Rt(t))return t.forEach(l=>this.extend(l)),this;const{name:n,validate:r=!1,getter:a=!1}=t,o=si(t,kc);if(Et(this,n))throw new TypeError(`[VueTypes error]: Type "${n}" already defined`);const{type:s}=o;if(wn(s))return delete o.type,Object.defineProperty(this,n,a?{get:()=>Wa(n,s,o)}:{value(...l){const c=Wa(n,s,o);return c.validator&&(c.validator=c.validator.bind(c,...l)),c}});let i;return i=a?{get(){const l=Object.assign({},o);return r?De(n,l):we(n,l)},enumerable:!0}:{value(...l){const c=Object.assign({},o);let u;return u=r?De(n,c):we(n,c),c.validator&&(u.validator=c.validator.bind(u,...l)),u},enumerable:!0},Object.defineProperty(this,n,i)}}).defaults={},e.sensibleDefaults=void 0,e.config=ac,e.custom=mc,e.oneOf=bc,e.instanceOf=xc,e.oneOfType=Cc,e.arrayOf=_c,e.objectOf=wc,e.shape=Sc,e.utils={validate:(t,n)=>vt(n,t,!0)===!0,toType:(t,n,r=!1)=>r?De(t,n):we(t,n)},e})();function Oc(e={func:()=>{},bool:!0,string:"",number:0,array:()=>[],object:()=>({}),integer:0}){var t;return(t=class extends Ac{static get sensibleDefaults(){return Zt({},this.defaults)}static set sensibleDefaults(n){this.defaults=n!==!1?Zt({},n!==!0?n:e):{}}}).defaults=Zt({},e),t}let I=class extends Oc(){};var za=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Lr(e){var t={exports:{}};return e(t,t.exports),t.exports}var fn=function(e){return e&&e.Math==Math&&e},oe=fn(typeof globalThis=="object"&&globalThis)||fn(typeof window=="object"&&window)||fn(typeof self=="object"&&self)||fn(typeof za=="object"&&za)||function(){return this}()||Function("return this")(),Y=function(e){try{return!!e()}catch{return!0}},Oe=!Y(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Ua={}.propertyIsEnumerable,Ga=Object.getOwnPropertyDescriptor,$c={f:Ga&&!Ua.call({1:2},1)?function(e){var t=Ga(this,e);return!!t&&t.enumerable}:Ua},Ln=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Ec={}.toString,ze=function(e){return Ec.call(e).slice(8,-1)},Rc="".split,Dn=Y(function(){return!Object("z").propertyIsEnumerable(0)})?function(e){return ze(e)=="String"?Rc.call(e,""):Object(e)}:Object,et=function(e){if(e==null)throw TypeError("Can't call method on "+e);return e},Ht=function(e){return Dn(et(e))},ie=function(e){return typeof e=="object"?e!==null:typeof e=="function"},Dr=function(e,t){if(!ie(e))return e;var n,r;if(t&&typeof(n=e.toString)=="function"&&!ie(r=n.call(e))||typeof(n=e.valueOf)=="function"&&!ie(r=n.call(e))||!t&&typeof(n=e.toString)=="function"&&!ie(r=n.call(e)))return r;throw TypeError("Can't convert object to primitive value")},Tc={}.hasOwnProperty,re=function(e,t){return Tc.call(e,t)},Cr=oe.document,Mc=ie(Cr)&&ie(Cr.createElement),pi=function(e){return Mc?Cr.createElement(e):{}},vi=!Oe&&!Y(function(){return Object.defineProperty(pi("div"),"a",{get:function(){return 7}}).a!=7}),qa=Object.getOwnPropertyDescriptor,Nr={f:Oe?qa:function(e,t){if(e=Ht(e),t=Dr(t,!0),vi)try{return qa(e,t)}catch{}if(re(e,t))return Ln(!$c.f.call(e,t),e[t])}},ge=function(e){if(!ie(e))throw TypeError(String(e)+" is not an object");return e},Ya=Object.defineProperty,Ge={f:Oe?Ya:function(e,t,n){if(ge(e),t=Dr(t,!0),ge(n),vi)try{return Ya(e,t,n)}catch{}if("get"in n||"set"in n)throw TypeError("Accessors not supported");return"value"in n&&(e[t]=n.value),e}},Re=Oe?function(e,t,n){return Ge.f(e,t,Ln(1,n))}:function(e,t,n){return e[t]=n,e},Vr=function(e,t){try{Re(oe,e,t)}catch{oe[e]=t}return t},ct=oe["__core-js_shared__"]||Vr("__core-js_shared__",{}),Pc=Function.toString;typeof ct.inspectSource!="function"&&(ct.inspectSource=function(e){return Pc.call(e)});var Sn,Jt,kn,hi=ct.inspectSource,Xa=oe.WeakMap,Ic=typeof Xa=="function"&&/native code/.test(hi(Xa)),gi=Lr(function(e){(e.exports=function(t,n){return ct[t]||(ct[t]=n!==void 0?n:{})})("versions",[]).push({version:"3.8.3",mode:"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"})}),jc=0,Hc=Math.random(),Fr=function(e){return"Symbol("+String(e===void 0?"":e)+")_"+(++jc+Hc).toString(36)},Za=gi("keys"),Kr=function(e){return Za[e]||(Za[e]=Fr(e))},Nn={},Bc=oe.WeakMap;if(Ic){var mt=ct.state||(ct.state=new Bc),Lc=mt.get,Dc=mt.has,Nc=mt.set;Sn=function(e,t){return t.facade=e,Nc.call(mt,e,t),t},Jt=function(e){return Lc.call(mt,e)||{}},kn=function(e){return Dc.call(mt,e)}}else{var Ft=Kr("state");Nn[Ft]=!0,Sn=function(e,t){return t.facade=e,Re(e,Ft,t),t},Jt=function(e){return re(e,Ft)?e[Ft]:{}},kn=function(e){return re(e,Ft)}}var tt={set:Sn,get:Jt,has:kn,enforce:function(e){return kn(e)?Jt(e):Sn(e,{})},getterFor:function(e){return function(t){var n;if(!ie(t)||(n=Jt(t)).type!==e)throw TypeError("Incompatible receiver, "+e+" required");return n}}},nt=Lr(function(e){var t=tt.get,n=tt.enforce,r=String(String).split("String");(e.exports=function(a,o,s,i){var l,c=!!i&&!!i.unsafe,u=!!i&&!!i.enumerable,d=!!i&&!!i.noTargetGet;typeof s=="function"&&(typeof o!="string"||re(s,"name")||Re(s,"name",o),(l=n(s)).source||(l.source=r.join(typeof o=="string"?o:""))),a!==oe?(c?!d&&a[o]&&(u=!0):delete a[o],u?a[o]=s:Re(a,o,s)):u?a[o]=s:Vr(o,s)})(Function.prototype,"toString",function(){return typeof this=="function"&&t(this).source||hi(this)})}),qn=oe,Ja=function(e){return typeof e=="function"?e:void 0},Vn=function(e,t){return arguments.length<2?Ja(qn[e])||Ja(oe[e]):qn[e]&&qn[e][t]||oe[e]&&oe[e][t]},Vc=Math.ceil,Fc=Math.floor,Bt=function(e){return isNaN(e=+e)?0:(e>0?Fc:Vc)(e)},Kc=Math.min,ke=function(e){return e>0?Kc(Bt(e),9007199254740991):0},Wc=Math.max,zc=Math.min,An=function(e,t){var n=Bt(e);return n<0?Wc(n+t,0):zc(n,t)},Qa=function(e){return function(t,n,r){var a,o=Ht(t),s=ke(o.length),i=An(r,s);if(e&&n!=n){for(;s>i;)if((a=o[i++])!=a)return!0}else for(;s>i;i++)if((e||i in o)&&o[i]===n)return e||i||0;return!e&&-1}},yi={includes:Qa(!0),indexOf:Qa(!1)},Uc=yi.indexOf,mi=function(e,t){var n,r=Ht(e),a=0,o=[];for(n in r)!re(Nn,n)&&re(r,n)&&o.push(n);for(;t.length>a;)re(r,n=t[a++])&&(~Uc(o,n)||o.push(n));return o},On=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Gc=On.concat("length","prototype"),qc={f:Object.getOwnPropertyNames||function(e){return mi(e,Gc)}},Yc={f:Object.getOwnPropertySymbols},Xc=Vn("Reflect","ownKeys")||function(e){var t=qc.f(ge(e)),n=Yc.f;return n?t.concat(n(e)):t},Zc=function(e,t){for(var n=Xc(t),r=Ge.f,a=Nr.f,o=0;o1?arguments[1]:void 0)}});(function(){function e(){ht(this,e)}return gt(e,null,[{key:"isInBrowser",value:function(){return typeof window<"u"}},{key:"isServer",value:function(){return typeof window>"u"}},{key:"getUA",value:function(){return e.isInBrowser()?window.navigator.userAgent.toLowerCase():""}},{key:"isMobile",value:function(){return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion)}},{key:"isOpera",value:function(){return navigator.userAgent.indexOf("Opera")!==-1}},{key:"isIE",value:function(){var t=e.getUA();return t!==""&&t.indexOf("msie")>0}},{key:"isIE9",value:function(){var t=e.getUA();return t!==""&&t.indexOf("msie 9.0")>0}},{key:"isEdge",value:function(){var t=e.getUA();return t!==""&&t.indexOf("edge/")>0}},{key:"isChrome",value:function(){var t=e.getUA();return t!==""&&/chrome\/\d+/.test(t)&&!e.isEdge()}},{key:"isPhantomJS",value:function(){var t=e.getUA();return t!==""&&/phantomjs/.test(t)}},{key:"isFirefox",value:function(){var t=e.getUA();return t!==""&&/firefox/.test(t)}}]),e})();var sd=[].join,ud=Dn!=Object,cd=Wr("join",",");ve({target:"Array",proto:!0,forced:ud||!cd},{join:function(e){return sd.call(Ht(this),e===void 0?",":e)}});var bt,$n,qe=function(e){return Object(et(e))},Mt=Array.isArray||function(e){return ze(e)=="Array"},Ci=!!Object.getOwnPropertySymbols&&!Y(function(){return!String(Symbol())}),dd=Ci&&!Symbol.sham&&typeof Symbol.iterator=="symbol",pn=gi("wks"),Qt=oe.Symbol,fd=dd?Qt:Qt&&Qt.withoutSetter||Fr,Q=function(e){return re(pn,e)||(Ci&&re(Qt,e)?pn[e]=Qt[e]:pn[e]=fd("Symbol."+e)),pn[e]},pd=Q("species"),Fn=function(e,t){var n;return Mt(e)&&(typeof(n=e.constructor)!="function"||n!==Array&&!Mt(n.prototype)?ie(n)&&(n=n[pd])===null&&(n=void 0):n=void 0),new(n===void 0?Array:n)(t===0?0:t)},Pt=function(e,t,n){var r=Dr(t);r in e?Ge.f(e,r,Ln(0,n)):e[r]=n},Xn=Vn("navigator","userAgent")||"",ro=oe.process,ao=ro&&ro.versions,oo=ao&&ao.v8;oo?$n=(bt=oo.split("."))[0]+bt[1]:Xn&&(!(bt=Xn.match(/Edge\/(\d+)/))||bt[1]>=74)&&(bt=Xn.match(/Chrome\/(\d+)/))&&($n=bt[1]);var En=$n&&+$n,vd=Q("species"),zr=function(e){return En>=51||!Y(function(){var t=[];return(t.constructor={})[vd]=function(){return{foo:1}},t[e](Boolean).foo!==1})},hd=zr("splice"),gd=Lt("splice",{ACCESSORS:!0,0:0,1:2}),yd=Math.max,md=Math.min;ve({target:"Array",proto:!0,forced:!hd||!gd},{splice:function(e,t){var n,r,a,o,s,i,l=qe(this),c=ke(l.length),u=An(e,c),d=arguments.length;if(d===0?n=r=0:d===1?(n=0,r=c-u):(n=d-2,r=md(yd(Bt(t),0),c-u)),c+n-r>9007199254740991)throw TypeError("Maximum allowed length exceeded");for(a=Fn(l,r),o=0;oc-r+n;o--)delete l[o-1]}else if(n>r)for(o=c-r;o>u;o--)i=o+n-1,(s=o+r-1)in l?l[i]=l[s]:delete l[i];for(o=0;o0&&(!o.multiline||o.multiline&&e[o.lastIndex-1]!==` +`)&&(l="(?: "+l+")",u=" "+u,c++),n=new RegExp("^(?:"+l+")",i)),er&&(n=new RegExp("^"+l+"$(?!\\s)",i)),Qn&&(t=o.lastIndex),r=Rn.call(s?n:o,u),s?r?(r.input=r.input.slice(c),r[0]=r[0].slice(c),r.index=o.lastIndex,o.lastIndex+=r[0].length):o.lastIndex=0:Qn&&r&&(o.lastIndex=o.global?r.index+r[0].length:t),er&&r&&r.length>1&&xd.call(r[0],n,function(){for(a=1;a")!=="7"}),uo="a".replace(/./,"$0")==="$0",co=Q("replace"),fo=!!/./[co]&&/./[co]("a","$0")==="",Od=!Y(function(){var e=/(?:)/,t=e.exec;e.exec=function(){return t.apply(this,arguments)};var n="ab".split(e);return n.length!==2||n[0]!=="a"||n[1]!=="b"}),Oi=function(e,t,n,r){var a=Q(e),o=!Y(function(){var d={};return d[a]=function(){return 7},""[e](d)!=7}),s=o&&!Y(function(){var d=!1,v=/a/;return e==="split"&&((v={}).constructor={},v.constructor[kd]=function(){return v},v.flags="",v[a]=/./[a]),v.exec=function(){return d=!0,null},v[a](""),!d});if(!o||!s||e==="replace"&&(!Ad||!uo||fo)||e==="split"&&!Od){var i=/./[a],l=n(a,""[e],function(d,v,f,m,y){return v.exec===rn?o&&!y?{done:!0,value:i.call(v,f,m)}:{done:!0,value:d.call(f,v,m)}:{done:!1}},{REPLACE_KEEPS_$0:uo,REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE:fo}),c=l[0],u=l[1];nt(String.prototype,e,c),nt(RegExp.prototype,a,t==2?function(d,v){return u.call(d,this,v)}:function(d){return u.call(d,this)})}r&&Re(RegExp.prototype[a],"sham",!0)},$d=Q("match"),$i=function(e){var t;return ie(e)&&((t=e[$d])!==void 0?!!t:ze(e)=="RegExp")},Gr=function(e){if(typeof e!="function")throw TypeError(String(e)+" is not a function");return e},Ed=Q("species"),po=function(e){return function(t,n){var r,a,o=String(et(t)),s=Bt(n),i=o.length;return s<0||s>=i?e?"":void 0:(r=o.charCodeAt(s))<55296||r>56319||s+1===i||(a=o.charCodeAt(s+1))<56320||a>57343?e?o.charAt(s):r:e?o.slice(s,s+2):a-56320+(r-55296<<10)+65536}},Ei={codeAt:po(!1),charAt:po(!0)},Rd=Ei.charAt,Ri=function(e,t,n){return t+(n?Rd(e,t).length:1)},xr=function(e,t){var n=e.exec;if(typeof n=="function"){var r=n.call(e,t);if(typeof r!="object")throw TypeError("RegExp exec method returned something other than an Object or null");return r}if(ze(e)!=="RegExp")throw TypeError("RegExp#exec called on incompatible receiver");return rn.call(e,t)},Td=[].push,Md=Math.min,Ct=!Y(function(){return!RegExp(4294967295,"y")});Oi("split",2,function(e,t,n){var r;return r="abbc".split(/(b)*/)[1]=="c"||"test".split(/(?:)/,-1).length!=4||"ab".split(/(?:ab)*/).length!=2||".".split(/(.?)(.?)/).length!=4||".".split(/()()/).length>1||"".split(/.?/).length?function(a,o){var s=String(et(this)),i=o===void 0?4294967295:o>>>0;if(i===0)return[];if(a===void 0)return[s];if(!$i(a))return t.call(s,a,i);for(var l,c,u,d=[],v=(a.ignoreCase?"i":"")+(a.multiline?"m":"")+(a.unicode?"u":"")+(a.sticky?"y":""),f=0,m=new RegExp(a.source,v+"g");(l=rn.call(m,s))&&!((c=m.lastIndex)>f&&(d.push(s.slice(f,l.index)),l.length>1&&l.index=i));)m.lastIndex===l.index&&m.lastIndex++;return f===s.length?!u&&m.test("")||d.push(""):d.push(s.slice(f)),d.length>i?d.slice(0,i):d}:"0".split(void 0,0).length?function(a,o){return a===void 0&&o===0?[]:t.call(this,a,o)}:t,[function(a,o){var s=et(this),i=a==null?void 0:a[e];return i!==void 0?i.call(a,s,o):r.call(String(s),a,o)},function(a,o){var s=n(r,a,this,o,r!==t);if(s.done)return s.value;var i=ge(a),l=String(this),c=function(w,$){var O,M=ge(w).constructor;return M===void 0||(O=ge(M)[Ed])==null?$:Gr(O)}(i,RegExp),u=i.unicode,d=(i.ignoreCase?"i":"")+(i.multiline?"m":"")+(i.unicode?"u":"")+(Ct?"y":"g"),v=new c(Ct?i:"^(?:"+i.source+")",d),f=o===void 0?4294967295:o>>>0;if(f===0)return[];if(l.length===0)return xr(v,l)===null?[l]:[];for(var m=0,y=0,g=[];y1?arguments[1]:void 0,t.length)),r=String(e);return vo?vo.call(t,r,n):t.slice(n,n+r.length)===r}});var _t=function(e){return typeof e=="string"},xt=function(e){return e!==null&&Mi(e)==="object"},an=function(){function e(){ht(this,e)}return gt(e,null,[{key:"isWindow",value:function(t){return t===window}},{key:"addEventListener",value:function(t,n,r){var a=arguments.length>3&&arguments[3]!==void 0&&arguments[3];t&&n&&r&&t.addEventListener(n,r,a)}},{key:"removeEventListener",value:function(t,n,r){var a=arguments.length>3&&arguments[3]!==void 0&&arguments[3];t&&n&&r&&t.removeEventListener(n,r,a)}},{key:"triggerDragEvent",value:function(t,n){var r=!1,a=function(s){var i;(i=n.drag)===null||i===void 0||i.call(n,s)},o=function s(i){var l;e.removeEventListener(document,"mousemove",a),e.removeEventListener(document,"mouseup",s),document.onselectstart=null,document.ondragstart=null,r=!1,(l=n.end)===null||l===void 0||l.call(n,i)};e.addEventListener(t,"mousedown",function(s){var i;r||(document.onselectstart=function(){return!1},document.ondragstart=function(){return!1},e.addEventListener(document,"mousemove",a),e.addEventListener(document,"mouseup",o),r=!0,(i=n.start)===null||i===void 0||i.call(n,s))})}},{key:"getBoundingClientRect",value:function(t){return t&&xt(t)&&t.nodeType===1?t.getBoundingClientRect():null}},{key:"hasClass",value:function(t,n){return!!(t&&xt(t)&&_t(n)&&t.nodeType===1)&&t.classList.contains(n.trim())}},{key:"addClass",value:function(t,n){if(t&&xt(t)&&_t(n)&&t.nodeType===1&&(n=n.trim(),!e.hasClass(t,n))){var r=t.className;t.className=r?r+" "+n:n}}},{key:"removeClass",value:function(t,n){if(t&&xt(t)&&_t(n)&&t.nodeType===1&&typeof t.className=="string"){n=n.trim();for(var r=t.className.trim().split(" "),a=r.length-1;a>=0;a--)r[a]=r[a].trim(),r[a]&&r[a]!==n||r.splice(a,1);t.className=r.join(" ")}}},{key:"toggleClass",value:function(t,n,r){t&&xt(t)&&_t(n)&&t.nodeType===1&&t.classList.toggle(n,r)}},{key:"replaceClass",value:function(t,n,r){t&&xt(t)&&_t(n)&&_t(r)&&t.nodeType===1&&(n=n.trim(),r=r.trim(),e.removeClass(t,n),e.addClass(t,r))}},{key:"getScrollTop",value:function(t){var n="scrollTop"in t?t.scrollTop:t.pageYOffset;return Math.max(n,0)}},{key:"setScrollTop",value:function(t,n){"scrollTop"in t?t.scrollTop=n:t.scrollTo(t.scrollX,n)}},{key:"getRootScrollTop",value:function(){return window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0}},{key:"setRootScrollTop",value:function(t){e.setScrollTop(window,t),e.setScrollTop(document.body,t)}},{key:"getElementTop",value:function(t,n){if(e.isWindow(t))return 0;var r=n?e.getScrollTop(n):e.getRootScrollTop();return t.getBoundingClientRect().top+r}},{key:"getVisibleHeight",value:function(t){return e.isWindow(t)?t.innerHeight:t.getBoundingClientRect().height}},{key:"isHidden",value:function(t){if(!t)return!1;var n=window.getComputedStyle(t),r=n.display==="none",a=t.offsetParent===null&&n.position!=="fixed";return r||a}},{key:"triggerEvent",value:function(t,n){if("createEvent"in document){var r=document.createEvent("HTMLEvents");r.initEvent(n,!1,!0),t.dispatchEvent(r)}}},{key:"calcAngle",value:function(t,n){var r=t.getBoundingClientRect(),a=r.left+r.width/2,o=r.top+r.height/2,s=Math.abs(a-n.clientX),i=Math.abs(o-n.clientY),l=i/Math.sqrt(Math.pow(s,2)+Math.pow(i,2)),c=Math.acos(l),u=Math.floor(180/(Math.PI/c));return n.clientX>a&&n.clientY>o&&(u=180-u),n.clientX==a&&n.clientY>o&&(u=180),n.clientX>a&&n.clientY==o&&(u=90),n.clientXo&&(u=180+u),n.clientX1?r-1:0),o=1;o]*>)/g,Zd=/\$([$&'`]|\d\d?)/g,Jd=function(e,t,n,r,a,o){var s=n+e.length,i=r.length,l=Zd;return a!==void 0&&(a=qe(a),l=Xd),Yd.call(o,l,function(c,u){var d;switch(u.charAt(0)){case"$":return"$";case"&":return e;case"`":return t.slice(0,n);case"'":return t.slice(s);case"<":d=a[u.slice(1,-1)];break;default:var v=+u;if(v===0)return c;if(v>i){var f=qd(v/10);return f===0?c:f<=i?r[f-1]===void 0?u.charAt(1):r[f-1]+u.charAt(1):c}d=r[v-1]}return d===void 0?"":d})},Qd=Math.max,ef=Math.min;Oi("replace",2,function(e,t,n,r){var a=r.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE,o=r.REPLACE_KEEPS_$0,s=a?"$":"$0";return[function(i,l){var c=et(this),u=i==null?void 0:i[e];return u!==void 0?u.call(i,c,l):t.call(String(c),i,l)},function(i,l){if(!a&&o||typeof l=="string"&&l.indexOf(s)===-1){var c=n(t,i,this,l);if(c.done)return c.value}var u=ge(i),d=String(this),v=typeof l=="function";v||(l=String(l));var f=u.global;if(f){var m=u.unicode;u.lastIndex=0}for(var y=[];;){var g=xr(u,d);if(g===null||(y.push(g),!f))break;String(g[0])===""&&(u.lastIndex=Ri(d,ke(u.lastIndex),m))}for(var p,C="",_=0,w=0;w=_&&(C+=d.slice(_,O)+b,_=O+$.length)}return C+d.slice(_)}]});(function(){function e(){ht(this,e)}return gt(e,null,[{key:"camelize",value:function(t){return t.replace(/-(\w)/g,function(n,r){return r?r.toUpperCase():""})}},{key:"capitalize",value:function(t){return t.charAt(0).toUpperCase()+t.slice(1)}}]),e})();(function(){function e(){ht(this,e)}return gt(e,null,[{key:"_clone",value:function(){}}]),e})();var Pi=Q("isConcatSpreadable"),tf=En>=51||!Y(function(){var e=[];return e[Pi]=!1,e.concat()[0]!==e}),nf=zr("concat"),rf=function(e){if(!ie(e))return!1;var t=e[Pi];return t!==void 0?!!t:Mt(e)};ve({target:"Array",proto:!0,forced:!tf||!nf},{concat:function(e){var t,n,r,a,o,s=qe(this),i=Fn(s,0),l=0;for(t=-1,r=arguments.length;t9007199254740991)throw TypeError("Maximum allowed index exceeded");for(n=0;n=9007199254740991)throw TypeError("Maximum allowed index exceeded");Pt(i,l++,o)}return i.length=l,i}});var rr,un=function(e,t,n){if(Gr(e),t===void 0)return e;switch(n){case 0:return function(){return e.call(t)};case 1:return function(r){return e.call(t,r)};case 2:return function(r,a){return e.call(t,r,a)};case 3:return function(r,a,o){return e.call(t,r,a,o)}}return function(){return e.apply(t,arguments)}},ho=[].push,Ze=function(e){var t=e==1,n=e==2,r=e==3,a=e==4,o=e==6,s=e==7,i=e==5||o;return function(l,c,u,d){for(var v,f,m=qe(l),y=Dn(m),g=un(c,u,3),p=ke(y.length),C=0,_=d||Fn,w=t?_(l,p):n||s?_(l,0):void 0;p>C;C++)if((i||C in y)&&(f=g(v=y[C],C,m),e))if(t)w[C]=f;else if(f)switch(e){case 3:return!0;case 5:return v;case 6:return C;case 2:ho.call(w,v)}else switch(e){case 4:return!1;case 7:ho.call(w,v)}return o?-1:r||a?a:w}},Ii={forEach:Ze(0),map:Ze(1),filter:Ze(2),some:Ze(3),every:Ze(4),find:Ze(5),findIndex:Ze(6),filterOut:Ze(7)},af=Oe?Object.defineProperties:function(e,t){ge(e);for(var n,r=qr(t),a=r.length,o=0;a>o;)Ge.f(e,n=r[o++],t[n]);return e},of=Vn("document","documentElement"),ji=Kr("IE_PROTO"),ar=function(){},go=function(e){return" + + + + +

+ + + + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/vite.svg b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/vite.svg new file mode 100644 index 0000000000000000000000000000000000000000..e7b8dfb1b2a60bd50538bec9f876511b9cac21e3 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/dist/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/env.d.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/env.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2964e97b5847c9602be9a3d21835337aa9bddcff --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/env.d.ts @@ -0,0 +1,8 @@ + +/// +/// + + +interface Window { + IIB_container_id?: string +} \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/index.html b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/index.html new file mode 100644 index 0000000000000000000000000000000000000000..01720af8827770e8218d141d3ac4dcda819146e7 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/index.html @@ -0,0 +1,18 @@ + + + + + + + + + Infinite Image Browsing + + + +
+ It seems to have failed to load. You can try refreshing the page.
If that doesn't work, click on FAQ for help
+ + + + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/index.tpl.js b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/index.tpl.js new file mode 100644 index 0000000000000000000000000000000000000000..ae548d75d94791fc0955f7465d304390a61896ba --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/index.tpl.js @@ -0,0 +1,166 @@ +/* eslint-disable no-undef */ +Promise.resolve().then(async () => { + /** + * This is a file generated using `yarn build`. + * If you want to make changes, please modify `index.tpl.js` and run the command to generate it again. + */ + const html = `__built_html__`.replace(/\/infinite_image_browsing/g, (window.location.pathname + '/infinite_image_browsing').replace(/\/\//g, '/')) + let containerSelector = '#infinite_image_browsing_container_wrapper' + let shouldMaximize = localStorage.getItem('iib://disable_maximize') !== 'true' + + try { + containerSelector = __iib_root_container__ + shouldMaximize = __iib_should_maximize__ + } catch (e) { /* empty */ } + + const delay = (timeout = 0) => new Promise((resolve) => setTimeout(resolve, timeout)) + const asyncCheck = async (getter, checkSize = 100, timeout = 1000) => { + let target = getter() + let num = 0 + while (checkSize * num < timeout && (target === undefined || target === null)) { + await delay(checkSize) + target = getter() + num++ + } + return target + } + + const getTabIdxById = (id) => { + const tabList = gradioApp().querySelectorAll('#tabs > .tabitem[id^=tab_]') + return Array.from(tabList).findIndex((v) => v.id.includes(id)) + } + + const switch2targetTab = (idx) => { + try { + gradioApp().querySelector('#tabs').querySelectorAll('button')[idx].click() + } catch (error) { + console.error(error) + } + } + + const isLobe = () => { + try { + return !!gradioApp().querySelector('[alt*="lobehub"]') + } catch (error) { + return false + } + } + + /** + * @type {HTMLDivElement} + */ + const wrap = await asyncCheck(() => gradioApp().querySelector(containerSelector), 500, Infinity) + wrap.childNodes.forEach((v) => wrap.removeChild(v)) + const iframe = document.createElement('iframe') + iframe.srcdoc = html + iframe.style = 'width: 100%;height:100vh' + wrap.appendChild(iframe) + + if (shouldMaximize) { + onUiTabChange(() => { + const el = get_uiCurrentTabContent() + if (el?.id.includes('infinite-image-browsing')) { + try { + const iibTop = gradioApp().querySelector('#iib_top') + if (!iibTop) { + throw new Error('element \'#iib_top\' is not found') + } + const topRect = iibTop.getBoundingClientRect() + wrap.style = ` + top:${Math.max(isLobe() ? 32 : 128, topRect.top) - 10}px; + position: fixed; + left: 10px; + right: 10px; + z-index: 100; + width: unset; + bottom: 10px;` + iframe.style = 'width: 100%;height:100%' + } catch (error) { + console.error('Error mounting IIB. Running fallback.', error) + wrap.style = '' + iframe.style = 'width: 100%;height:100vh' + } + } + }) + } + + const IIB_container_id = [Date.now(), Math.random()].join() + window.IIB_container_id = IIB_container_id + const imgTransferBus = new BroadcastChannel('iib-image-transfer-bus') + imgTransferBus.addEventListener('message', async (ev) => { + const data = ev.data + if ( + typeof data !== 'object' || + (typeof data.IIB_container_id === 'string' && data.IIB_container_id !== IIB_container_id) + ) { + return + } + console.log('iib-message:', data) + const appDoc = gradioApp() + switch (data.event) { + case 'click_hidden_button': { + const btn = gradioApp().querySelector(`#${data.btnEleId}`) + btn.click() + break + } + case 'send_to_control_net': { + data.type === 'img2img' ? window.switch_to_img2img() : window.switch_to_txt2img() + await delay(100) + const cn = appDoc.querySelector(`#${data.type}_controlnet`) + const wrap = cn.querySelector('.label-wrap') + if (!wrap.className.includes('open')) { + wrap.click() + await delay(100) + } + wrap.scrollIntoView() + wrap.dispatchEvent(await createPasteEvent(data.url)) + break + } + case 'send_to_outpaint': { + switch2targetTab(getTabIdxById('openOutpaint')) + await delay(100) + const iframe = appDoc.querySelector('#openoutpaint-iframe') + openoutpaint_send_image(await imgUrl2DataUrl(data.url)) + iframe.contentWindow.postMessage({ + key: appDoc.querySelector('#openoutpaint-key').value, + type: 'openoutpaint/set-prompt', + prompt: data.prompt, + negPrompt: data.negPrompt + }) + break + } + } + + function imgUrl2DataUrl(imgUrl) { + return new Promise((resolve, reject) => { + fetch(imgUrl) + .then((response) => response.blob()) + .then((blob) => { + const reader = new FileReader() + reader.readAsDataURL(blob) + reader.onloadend = function () { + const dataURL = reader.result + resolve(dataURL) + } + }) + .catch((error) => reject(error)) + }) + } + + async function createPasteEvent(imgUrl) { + const response = await fetch(imgUrl) + const imageBlob = await response.blob() + const imageFile = new File([imageBlob], 'image.jpg', { + type: imageBlob.type, + lastModified: Date.now() + }) + const dataTransfer = new DataTransfer() + dataTransfer.items.add(imageFile) + const pasteEvent = new ClipboardEvent('paste', { + clipboardData: dataTransfer, + bubbles: true + }) + return pasteEvent + } + }) +}) diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/package.json b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/package.json new file mode 100644 index 0000000000000000000000000000000000000000..07a6e4dbd7edc26ffa935c673a1737e464ee642a --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/package.json @@ -0,0 +1,57 @@ +{ + "name": "vue", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "preview": "vite preview", + "type-check": "vue-tsc --noEmit", + "build": "tsx build", + "tauri": "tauri dev", + "tauri-build": "tauri build", + "tauri-build-debug": "tauri build --debug" + }, + "dependencies": { + "@octokit/rest": "^20.1.1", + "@tauri-apps/api": "^1.4.0", + "@vueuse/core": "^10.1.2", + "@zanllp/vue-virtual-scroller": "^2.0.0-beta.7", + "ant-design-vue": "^3.2.20", + "axios": "^1.4.0", + "jian-pinyin": "^0.2.3", + "js-cookie": "^3.0.5", + "multi-nprogress": "^0.3.5", + "pinia": "^2.1.3", + "pinia-plugin-persistedstate": "^3.1.0", + "sjcl": "^1.0.8", + "splitpanes": "^3.1.5", + "vue": "^3.3.4", + "vue-diff": "^1.2.4", + "vue-i18n": "^9.3.0-beta.19", + "vue3-colorpicker": "^2.3.0", + "vue3-ts-util": "^1.0.4" + }, + "devDependencies": { + "@tauri-apps/cli": "^1.4.0", + "@types/js-cookie": "^3.0.3", + "@types/node": "^20.2.5", + "@types/nprogress": "^0.2.0", + "@types/sjcl": "^1.0.30", + "@vitejs/plugin-vue": "^4.2.3", + "@vitejs/plugin-vue-jsx": "^3.0.1", + "@vue/eslint-config-typescript": "^11.0.3", + "@vue/tsconfig": "^0.4.0", + "antd-vue-volar": "^1.0.1", + "eslint": "^8.41.0", + "eslint-plugin-vue": "^9.14.1", + "less": "^4.1.3", + "sass": "^1.62.1", + "tsx": "^3.12.7", + "typescript": "^5.0.2", + "unplugin-vue-components": "^0.25.0", + "vite": "^4.3.9", + "vue-router": "^4.2.2", + "vue-tsc": "^1.4.2" + } +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/public/vite.svg b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/public/vite.svg new file mode 100644 index 0000000000000000000000000000000000000000..e7b8dfb1b2a60bd50538bec9f876511b9cac21e3 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/public/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/.gitignore b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..af3522111c2a4220dab07d6c308f6125e074c73a --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/.gitignore @@ -0,0 +1,6 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ +app.conf.json +iib_api_server-x86_64-pc-windows-msvc.exe +iib_api_server-x86_64-unknown-linux-gnu \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/.taurignore b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/.taurignore new file mode 100644 index 0000000000000000000000000000000000000000..b0bf3470f676c804a4d1fd1e8b23337cddfd363d --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/.taurignore @@ -0,0 +1 @@ +app.conf.json \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/Cargo.lock b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/Cargo.lock new file mode 100644 index 0000000000000000000000000000000000000000..66a481eaa5c0093f006096efe72ccc268ddc38de --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/Cargo.lock @@ -0,0 +1,4593 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "addr2line" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4fa78e18c64fce05e902adecd7a5eed15a5e0a3439f7b0e169f0252214865e3" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "aho-corasick" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac" +dependencies = [ + "memchr", +] + +[[package]] +name = "aho-corasick" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43f6cb1bf222025340178f382c426f13757b2960e89779dfcb319c32542a5a41" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.71" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8" + +[[package]] +name = "async-broadcast" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c48ccdbf6ca6b121e0f586cbc0e73ae440e56c67c30fa0873b4e110d9c26d2b" +dependencies = [ + "event-listener", + "futures-core", +] + +[[package]] +name = "async-channel" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf46fee83e5ccffc220104713af3292ff9bc7c64c7de289f66dae8e38d826833" +dependencies = [ + "concurrent-queue", + "event-listener", + "futures-core", +] + +[[package]] +name = "async-executor" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fa3dc5f2a8564f07759c008b9109dc0d39de92a88d5588b8a5036d286383afb" +dependencies = [ + "async-lock", + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "slab", +] + +[[package]] +name = "async-fs" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "279cf904654eeebfa37ac9bb1598880884924aab82e290aa65c9e77a0e142e06" +dependencies = [ + "async-lock", + "autocfg", + "blocking", + "futures-lite", +] + +[[package]] +name = "async-io" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af" +dependencies = [ + "async-lock", + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-lite", + "log", + "parking", + "polling", + "rustix", + "slab", + "socket2", + "waker-fn", +] + +[[package]] +name = "async-lock" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa24f727524730b077666307f2734b4a1a1c57acb79193127dcc8914d5242dd7" +dependencies = [ + "event-listener", +] + +[[package]] +name = "async-process" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9d28b1d97e08915212e2e45310d47854eafa69600756fc735fb788f75199c9" +dependencies = [ + "async-io", + "async-lock", + "autocfg", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", + "signal-hook", + "windows-sys 0.48.0", +] + +[[package]] +name = "async-recursion" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e97ce7de6cf12de5d7226c73f5ba9811622f4db3a5b91b55c53e987e5f91cba" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.22", +] + +[[package]] +name = "async-task" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc7ab41815b3c653ccd2978ec3255c81349336702dfdf62ee6f7069b12a3aae" + +[[package]] +name = "async-trait" +version = "0.1.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b2d0f03b3640e3a630367e40c468cb7f309529c708ed1d88597047b0e7c6ef7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.22", +] + +[[package]] +name = "atk" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3d816ce6f0e2909a96830d6911c2aff044370b1ef92d7f267b43bae5addedd" +dependencies = [ + "atk-sys", + "bitflags", + "glib", + "libc", +] + +[[package]] +name = "atk-sys" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58aeb089fb698e06db8089971c7ee317ab9644bade33383f63631437b03aafb6" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps 6.1.1", +] + +[[package]] +name = "atomic-waker" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1181e1e0d1fce796a03db1ae795d67167da795f9cf4a39c37589e85ef57f26d3" + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "backtrace" +version = "0.3.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4319208da049c43661739c5fade2ba182f09d1dc2299b32298d3a31692b17e12" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", +] + +[[package]] +name = "base64" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" + +[[package]] +name = "base64" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "blocking" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77231a1c8f801696fc0123ec6150ce92cffb8e164a02afb9c8ddee0e9b65ad65" +dependencies = [ + "async-channel", + "async-lock", + "async-task", + "atomic-waker", + "fastrand", + "futures-lite", + "log", +] + +[[package]] +name = "brotli" +version = "3.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a0b1dbcc8ae29329621f8d4f0d835787c1c38bb1401979b49d13b0b305ff68" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "2.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b6561fd3f895a11e8f72af2cb7d22e08366bebc2b6b57f7744c4bda27034744" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bstr" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a246e68bb43f6cd9db24bea052a53e40405417c5fb372e3d1a8a7f770a564ef5" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "bumpalo" +version = "3.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1" + +[[package]] +name = "bytemuck" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea" + +[[package]] +name = "byteorder" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" + +[[package]] +name = "bytes" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" +dependencies = [ + "serde", +] + +[[package]] +name = "cairo-rs" +version = "0.15.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c76ee391b03d35510d9fa917357c7f1855bd9a6659c95a1b392e33f49b3369bc" +dependencies = [ + "bitflags", + "cairo-sys-rs", + "glib", + "libc", + "thiserror", +] + +[[package]] +name = "cairo-sys-rs" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c55d429bef56ac9172d25fecb85dc8068307d17acd74b377866b7a1ef25d3c8" +dependencies = [ + "glib-sys", + "libc", + "system-deps 6.1.1", +] + +[[package]] +name = "cargo_toml" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "599aa35200ffff8f04c1925aa1acc92fa2e08874379ef42e210a80e527e60838" +dependencies = [ + "serde", + "toml 0.7.5", +] + +[[package]] +name = "cc" +version = "1.0.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfb" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f" +dependencies = [ + "byteorder", + "fnv", + "uuid", +] + +[[package]] +name = "cfg-expr" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3431df59f28accaf4cb4eed4a9acc66bea3f3c3753aa6cdc2f024174ef232af7" +dependencies = [ + "smallvec", +] + +[[package]] +name = "cfg-expr" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "215c0072ecc28f92eeb0eea38ba63ddfcb65c2828c46311d646f1a3ff5f9841c" +dependencies = [ + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chrono" +version = "0.4.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec837a71355b28f6556dbd569b37b3f363091c0bd4b2e735674521b4c5fd9bc5" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "time 0.1.45", + "wasm-bindgen", + "winapi", +] + +[[package]] +name = "cocoa" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f425db7937052c684daec3bd6375c8abe2d146dca4b8b143d6db777c39138f3a" +dependencies = [ + "bitflags", + "block", + "cocoa-foundation", + "core-foundation", + "core-graphics", + "foreign-types", + "libc", + "objc", +] + +[[package]] +name = "cocoa-foundation" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "931d3837c286f56e3c58423ce4eba12d08db2374461a785c86f672b08b5650d6" +dependencies = [ + "bitflags", + "block", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", + "objc", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "combine" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35ed6e9d84f0b51a7f52daf1c7d71dd136fd7a3f41a8462b8cdb8c78d920fad4" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62ec6771ecfa0762d24683ee5a32ad78487a3d3afdc0fb8cae19d2c5deb50b7c" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "core-foundation" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" + +[[package]] +name = "core-graphics" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2581bbab3b8ffc6fcbd550bf46c355135d16e9ff2a6ea032ad6b9bf1d7efe4fb" +dependencies = [ + "bitflags", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bb142d41022986c1d8ff29103a1411c8a3dfad3552f87a4f8dc50d61d4f4e33" +dependencies = [ + "bitflags", + "core-foundation", + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e69e28e9f7f77debdedbaafa2866e1de9ba56df55a8bd7cfc724c25a09987c" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cssparser" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "754b69d351cdc2d8ee09ae203db831e005560fc6030da058f86ad60c92a9cb0a" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa 0.4.8", + "matches", + "phf 0.8.0", + "proc-macro2", + "quote", + "smallvec", + "syn 1.0.109", +] + +[[package]] +name = "cssparser-macros" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" +dependencies = [ + "quote", + "syn 2.0.22", +] + +[[package]] +name = "ctor" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d2301688392eb071b0bf1a37be05c469d3cc4dbbd95df672fe28ab021e6a096" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "darling" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0558d22a7b463ed0241e993f76f09f30b126687447751a8638587b864e4b3944" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8bfa2e259f8ee1ce5e97824a3c55ec4404a0d772ca7fa96bf19f0752a046eb" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.22", +] + +[[package]] +name = "darling_macro" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29a358ff9f12ec09c3e61fef9b5a9902623a695a46a917b07f269bff1445611a" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.22", +] + +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_more" +version = "0.99.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 1.0.109", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dirs-next" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1" +dependencies = [ + "cfg-if", + "dirs-sys-next", +] + +[[package]] +name = "dirs-sys-next" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" +dependencies = [ + "libc", + "redox_users", + "winapi", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dtoa" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65d09067bfacaa79114679b279d7f5885b53295b1e2cfb4e79c8e4bd3d633169" + +[[package]] +name = "dtoa-short" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbaceec3c6e4211c79e7b1800fb9680527106beb2f9c51904a3210c03a448c74" +dependencies = [ + "dtoa", +] + +[[package]] +name = "dunce" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56ce8c6da7551ec6c462cbaf3bfbc75131ebbfa1c944aeaa9dab51ca1c5f0c3b" + +[[package]] +name = "embed-resource" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7f1e82a60222fc67bfd50d752a9c89da5cce4c39ed39decc84a443b07bbd69a" +dependencies = [ + "cc", + "rustc_version", + "toml 0.7.5", + "vswhom", + "winreg 0.11.0", +] + +[[package]] +name = "embed_plist" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" + +[[package]] +name = "encoding_rs" +version = "0.8.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071a31f4ee85403370b58aca746f01041ede6f0da2730960ad001edc2b71b394" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "enumflags2" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c041f5090df68b32bcd905365fd51769c8b9d553fe87fde0b683534f10c01bd2" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e9a1f9f7d83e59740248a6e14ecf93929ade55027844dfcea78beafccc15745" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.22", +] + +[[package]] +name = "equivalent" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88bffebc5d80432c9b140ee17875ff173a8ab62faad5b257da912bd2f6c1c0a1" + +[[package]] +name = "errno" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" +dependencies = [ + "errno-dragonfly", + "libc", + "windows-sys 0.48.0", +] + +[[package]] +name = "errno-dragonfly" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + +[[package]] +name = "fastrand" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" +dependencies = [ + "instant", +] + +[[package]] +name = "fdeflate" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d329bdeac514ee06249dabc27877490f17f5d371ec693360768b838e19f3ae10" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset 0.9.0", + "rustc_version", +] + +[[package]] +name = "filetime" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cbc844cecaee9d4443931972e1289c8ff485cb4cc2767cb03ca139ed6885153" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.2.16", + "windows-sys 0.48.0", +] + +[[package]] +name = "flate2" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843" +dependencies = [ + "mac", + "new_debug_unreachable", +] + +[[package]] +name = "futures-channel" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" + +[[package]] +name = "futures-executor" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccecee823288125bd88b4d7f565c9e58e41858e47ab72e8ea2d64e93624386e0" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" + +[[package]] +name = "futures-lite" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "memchr", + "parking", + "pin-project-lite", + "waker-fn", +] + +[[package]] +name = "futures-macro" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.22", +] + +[[package]] +name = "futures-sink" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" + +[[package]] +name = "futures-task" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" + +[[package]] +name = "futures-util" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "fxhash" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" +dependencies = [ + "byteorder", +] + +[[package]] +name = "gdk" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6e05c1f572ab0e1f15be94217f0dc29088c248b14f792a5ff0af0d84bcda9e8" +dependencies = [ + "bitflags", + "cairo-rs", + "gdk-pixbuf", + "gdk-sys", + "gio", + "glib", + "libc", + "pango", +] + +[[package]] +name = "gdk-pixbuf" +version = "0.15.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad38dd9cc8b099cceecdf41375bb6d481b1b5a7cd5cd603e10a69a9383f8619a" +dependencies = [ + "bitflags", + "gdk-pixbuf-sys", + "gio", + "glib", + "libc", +] + +[[package]] +name = "gdk-pixbuf-sys" +version = "0.15.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "140b2f5378256527150350a8346dbdb08fadc13453a7a2d73aecd5fab3c402a7" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps 6.1.1", +] + +[[package]] +name = "gdk-sys" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e7a08c1e8f06f4177fb7e51a777b8c1689f743a7bc11ea91d44d2226073a88" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "pkg-config", + "system-deps 6.1.1", +] + +[[package]] +name = "gdkwayland-sys" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cca49a59ad8cfdf36ef7330fe7bdfbe1d34323220cc16a0de2679ee773aee2c2" +dependencies = [ + "gdk-sys", + "glib-sys", + "gobject-sys", + "libc", + "pkg-config", + "system-deps 6.1.1", +] + +[[package]] +name = "gdkx11-sys" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4b7f8c7a84b407aa9b143877e267e848ff34106578b64d1e0a24bf550716178" +dependencies = [ + "gdk-sys", + "glib-sys", + "libc", + "system-deps 6.1.1", + "x11", +] + +[[package]] +name = "generator" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc16584ff22b460a382b7feec54b23d2908d858152e5739a120b949293bd74e" +dependencies = [ + "cc", + "libc", + "log", + "rustversion", + "windows 0.48.0", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.9.0+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.11.0+wasi-snapshot-preview1", +] + +[[package]] +name = "gimli" +version = "0.27.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e" + +[[package]] +name = "gio" +version = "0.15.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68fdbc90312d462781a395f7a16d96a2b379bb6ef8cd6310a2df272771c4283b" +dependencies = [ + "bitflags", + "futures-channel", + "futures-core", + "futures-io", + "gio-sys", + "glib", + "libc", + "once_cell", + "thiserror", +] + +[[package]] +name = "gio-sys" +version = "0.15.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32157a475271e2c4a023382e9cab31c4584ee30a97da41d3c4e9fdd605abcf8d" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps 6.1.1", + "winapi", +] + +[[package]] +name = "glib" +version = "0.15.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edb0306fbad0ab5428b0ca674a23893db909a98582969c9b537be4ced78c505d" +dependencies = [ + "bitflags", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "once_cell", + "smallvec", + "thiserror", +] + +[[package]] +name = "glib-macros" +version = "0.15.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10c6ae9f6fa26f4fb2ac16b528d138d971ead56141de489f8111e259b9df3c4a" +dependencies = [ + "anyhow", + "heck 0.4.1", + "proc-macro-crate", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "glib-sys" +version = "0.15.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef4b192f8e65e9cf76cbf4ea71fa8e3be4a0e18ffe3d68b8da6836974cc5bad4" +dependencies = [ + "libc", + "system-deps 6.1.1", +] + +[[package]] +name = "glob" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" + +[[package]] +name = "globset" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "029d74589adefde59de1a0c4f4732695c32805624aec7b68d91503d4dba79afc" +dependencies = [ + "aho-corasick 0.7.20", + "bstr", + "fnv", + "log", + "regex", +] + +[[package]] +name = "gobject-sys" +version = "0.15.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d57ce44246becd17153bd035ab4d32cfee096a657fc01f2231c9278378d1e0a" +dependencies = [ + "glib-sys", + "libc", + "system-deps 6.1.1", +] + +[[package]] +name = "gtk" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e3004a2d5d6d8b5057d2b57b3712c9529b62e82c77f25c1fecde1fd5c23bd0" +dependencies = [ + "atk", + "bitflags", + "cairo-rs", + "field-offset", + "futures-channel", + "gdk", + "gdk-pixbuf", + "gio", + "glib", + "gtk-sys", + "gtk3-macros", + "libc", + "once_cell", + "pango", + "pkg-config", +] + +[[package]] +name = "gtk-sys" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5bc2f0587cba247f60246a0ca11fe25fb733eabc3de12d1965fc07efab87c84" +dependencies = [ + "atk-sys", + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "system-deps 6.1.1", +] + +[[package]] +name = "gtk3-macros" +version = "0.15.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "684c0456c086e8e7e9af73ec5b84e35938df394712054550e81558d21c44ab0d" +dependencies = [ + "anyhow", + "proc-macro-crate", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "h2" +version = "0.3.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97ec8491ebaf99c8eaa73058b045fe58073cd6be7f596ac993ced0b0a0c01049" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http", + "indexmap 1.9.3", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" + +[[package]] +name = "heck" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "hermit-abi" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "html5ever" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5c13fb08e5d4dfc151ee5e88bae63f7773d61852f3bdc73c9f4b9e1bde03148" +dependencies = [ + "log", + "mac", + "markup5ever", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "http" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482" +dependencies = [ + "bytes", + "fnv", + "itoa 1.0.6", +] + +[[package]] +name = "http-body" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" +dependencies = [ + "bytes", + "http", + "pin-project-lite", +] + +[[package]] +name = "http-range" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21dec9db110f5f872ed9699c3ecf50cf16f423502706ba5c72462e28d3157573" + +[[package]] +name = "httparse" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" + +[[package]] +name = "httpdate" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" + +[[package]] +name = "hyper" +version = "0.14.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa 1.0.6", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", + "want", +] + +[[package]] +name = "hyper-tls" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" +dependencies = [ + "bytes", + "hyper", + "native-tls", + "tokio", + "tokio-native-tls", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fad5b825842d2b38bd206f3e81d6957625fd7f0a361e345c30e01a0ae2dd613" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows 0.48.0", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ico" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3804960be0bb5e4edb1e1ad67afd321a9ecfd875c3e65c099468fd2717d7cae" +dependencies = [ + "byteorder", + "png", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "ignore" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbe7873dab538a9a44ad79ede1faf5f30d49f9a5c883ddbab48bce81b64b7492" +dependencies = [ + "globset", + "lazy_static", + "log", + "memchr", + "regex", + "same-file", + "thread_local", + "walkdir", + "winapi-util", +] + +[[package]] +name = "image" +version = "0.24.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527909aa81e20ac3a44803521443a765550f09b5130c2c2fa1ea59c2f8f50a3a" +dependencies = [ + "bytemuck", + "byteorder", + "color_quant", + "num-rational", + "num-traits", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" +dependencies = [ + "equivalent", + "hashbrown 0.14.0", +] + +[[package]] +name = "infer" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a898e4b7951673fce96614ce5751d13c40fc5674bc2d759288e46c3ab62598b3" +dependencies = [ + "cfb", +] + +[[package]] +name = "infinite_image_browsing" +version = "0.0.1" +dependencies = [ + "chrono", + "reqwest", + "serde", + "serde_json", + "tauri", + "tauri-build", +] + +[[package]] +name = "instant" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "io-lifetimes" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" +dependencies = [ + "hermit-abi", + "libc", + "windows-sys 0.48.0", +] + +[[package]] +name = "ipnet" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" + +[[package]] +name = "itoa" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" + +[[package]] +name = "itoa" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" + +[[package]] +name = "javascriptcore-rs" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf053e7843f2812ff03ef5afe34bb9c06ffee120385caad4f6b9967fcd37d41c" +dependencies = [ + "bitflags", + "glib", + "javascriptcore-rs-sys", +] + +[[package]] +name = "javascriptcore-rs-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "905fbb87419c5cde6e3269537e4ea7d46431f3008c5d057e915ef3f115e7793c" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps 5.0.0", +] + +[[package]] +name = "jni" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "039022cdf4d7b1cf548d31f60ae783138e5fd42013f6271049d7df7afadef96c" +dependencies = [ + "cesu8", + "combine", + "jni-sys", + "log", + "thiserror", + "walkdir", +] + +[[package]] +name = "jni-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" + +[[package]] +name = "js-sys" +version = "0.3.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "json-patch" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f54898088ccb91df1b492cc80029a6fdf1c48ca0db7c6822a8babad69c94658" +dependencies = [ + "serde", + "serde_json", + "thiserror", + "treediff", +] + +[[package]] +name = "kuchiki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ea8e9c6e031377cff82ee3001dc8026cdf431ed4e2e6b51f98ab8c73484a358" +dependencies = [ + "cssparser", + "html5ever", + "matches", + "selectors", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.147" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" + +[[package]] +name = "line-wrap" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f30344350a2a51da54c1d53be93fade8a237e545dbcc4bdbe635413f2117cab9" +dependencies = [ + "safemem", +] + +[[package]] +name = "linux-raw-sys" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" + +[[package]] +name = "lock_api" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4" + +[[package]] +name = "loom" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff50ecb28bb86013e935fb6683ab1f6d3a20016f123c76fd4c27470076ac30f5" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "serde", + "serde_json", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "mac" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" + +[[package]] +name = "mac-notification-sys" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e72d50edb17756489e79d52eb146927bec8eba9dd48faadf9ef08bca3791ad5" +dependencies = [ + "cc", + "dirs-next", + "objc-foundation", + "objc_id", + "time 0.3.22", +] + +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +dependencies = [ + "libc", +] + +[[package]] +name = "markup5ever" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a24f40fb03852d1cdd84330cddcaf98e9ec08a7b7768e952fad3b4cf048ec8fd" +dependencies = [ + "log", + "phf 0.8.0", + "phf_codegen", + "string_cache", + "string_cache_codegen", + "tendril", +] + +[[package]] +name = "matchers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matches" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "memoffset" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5de893c32cde5f383baa4c04c5d6dbdd735cfd4a794b0debdb2bb1b421da5ff4" +dependencies = [ + "autocfg", +] + +[[package]] +name = "memoffset" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "miniz_oxide" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" +dependencies = [ + "adler", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2" +dependencies = [ + "libc", + "wasi 0.11.0+wasi-snapshot-preview1", + "windows-sys 0.48.0", +] + +[[package]] +name = "native-tls" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" +dependencies = [ + "lazy_static", + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "ndk" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2032c77e030ddee34a6787a64166008da93f6a352b629261d0fee232b8742dd4" +dependencies = [ + "bitflags", + "jni-sys", + "ndk-sys", + "num_enum", + "thiserror", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e5a6ae77c8ee183dcbbba6150e2e6b9f3f4196a7666c02a715a95692ec1fa97" +dependencies = [ + "jni-sys", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54" + +[[package]] +name = "nix" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfdda3d196821d6af13126e40375cdf7da646a96114af134d5f417a9a1dc8e1a" +dependencies = [ + "bitflags", + "cfg-if", + "libc", + "memoffset 0.7.1", + "static_assertions", +] + +[[package]] +name = "nodrop" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" + +[[package]] +name = "notify-rust" +version = "4.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfa211d18e360f08e36c364308f394b5eb23a6629150690e109a916dc6f610e" +dependencies = [ + "log", + "mac-notification-sys", + "serde", + "tauri-winrt-notification", + "zbus", +] + +[[package]] +name = "nu-ansi-term" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" +dependencies = [ + "overload", + "winapi", +] + +[[package]] +name = "num-integer" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +dependencies = [ + "autocfg", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "num_enum" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f646caf906c20226733ed5b1374287eb97e3c2a5c227ce668c1f2ce20ae57c9" +dependencies = [ + "num_enum_derive", +] + +[[package]] +name = "num_enum_derive" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcbff9bc912032c62bf65ef1d5aea88983b420f4f839db1e9b0c281a25c9c799" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "objc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" +dependencies = [ + "malloc_buf", + "objc_exception", +] + +[[package]] +name = "objc-foundation" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9" +dependencies = [ + "block", + "objc", + "objc_id", +] + +[[package]] +name = "objc_exception" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad970fb455818ad6cba4c122ad012fae53ae8b4795f86378bce65e4f6bab2ca4" +dependencies = [ + "cc", +] + +[[package]] +name = "objc_id" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b" +dependencies = [ + "objc", +] + +[[package]] +name = "object" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bda667d9f2b5051b8833f59f3bf748b28ef54f850f4fcb389a252aa383866d1" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" + +[[package]] +name = "open" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2078c0039e6a54a0c42c28faa984e115fb4c2d5bf2208f77d1961002df8576f8" +dependencies = [ + "pathdiff", + "windows-sys 0.42.0", +] + +[[package]] +name = "openssl" +version = "0.10.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "345df152bc43501c5eb9e4654ff05f794effb78d4efe3d53abc158baddc0703d" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.22", +] + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" + +[[package]] +name = "openssl-sys" +version = "0.9.90" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "374533b0e45f3a7ced10fcaeccca020e66656bc03dac384f852e4e5a7a8104a6" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "os_info" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "006e42d5b888366f1880eda20371fedde764ed2213dc8496f49622fa0c99cd5e" +dependencies = [ + "log", + "serde", + "winapi", +] + +[[package]] +name = "os_pipe" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae859aa07428ca9a929b936690f8b12dc5f11dd8c6992a18ca93919f28bc177" +dependencies = [ + "libc", + "windows-sys 0.48.0", +] + +[[package]] +name = "overload" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" + +[[package]] +name = "pango" +version = "0.15.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e4045548659aee5313bde6c582b0d83a627b7904dd20dc2d9ef0895d414e4f" +dependencies = [ + "bitflags", + "glib", + "libc", + "once_cell", + "pango-sys", +] + +[[package]] +name = "pango-sys" +version = "0.15.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2a00081cde4661982ed91d80ef437c20eacaf6aa1a5962c0279ae194662c3aa" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps 6.1.1", +] + +[[package]] +name = "parking" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14f2252c834a40ed9bb5422029649578e63aa341ac401f74e719dd1afda8394e" + +[[package]] +name = "parking_lot" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.3.5", + "smallvec", + "windows-targets 0.48.1", +] + +[[package]] +name = "pathdiff" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" + +[[package]] +name = "percent-encoding" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" + +[[package]] +name = "phf" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dfb61232e34fcb633f43d12c58f83c1df82962dcdfa565a4e866ffc17dafe12" +dependencies = [ + "phf_macros 0.8.0", + "phf_shared 0.8.0", + "proc-macro-hack", +] + +[[package]] +name = "phf" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" +dependencies = [ + "phf_macros 0.10.0", + "phf_shared 0.10.0", + "proc-macro-hack", +] + +[[package]] +name = "phf_codegen" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbffee61585b0411840d3ece935cce9cb6321f01c45477d30066498cd5e1a815" +dependencies = [ + "phf_generator 0.8.0", + "phf_shared 0.8.0", +] + +[[package]] +name = "phf_generator" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17367f0cc86f2d25802b2c26ee58a7b23faeccf78a396094c13dced0d0182526" +dependencies = [ + "phf_shared 0.8.0", + "rand 0.7.3", +] + +[[package]] +name = "phf_generator" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" +dependencies = [ + "phf_shared 0.10.0", + "rand 0.8.5", +] + +[[package]] +name = "phf_macros" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6fde18ff429ffc8fe78e2bf7f8b7a5a5a6e2a8b58bc5a9ac69198bbda9189c" +dependencies = [ + "phf_generator 0.8.0", + "phf_shared 0.8.0", + "proc-macro-hack", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "phf_macros" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58fdf3184dd560f160dd73922bea2d5cd6e8f064bf4b13110abd81b03697b4e0" +dependencies = [ + "phf_generator 0.10.0", + "phf_shared 0.10.0", + "proc-macro-hack", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "phf_shared" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c00cf8b9eafe68dde5e9eaa2cef8ee84a9336a47d566ec55ca16589633b65af7" +dependencies = [ + "siphasher", +] + +[[package]] +name = "phf_shared" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" + +[[package]] +name = "plist" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bd9647b268a3d3e14ff09c23201133a62589c658db02bb7388c7246aafe0590" +dependencies = [ + "base64 0.21.2", + "indexmap 1.9.3", + "line-wrap", + "quick-xml 0.28.2", + "serde", + "time 0.3.22", +] + +[[package]] +name = "png" +version = "0.17.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59871cc5b6cce7eaccca5a802b4173377a1c2ba90654246789a8fa2334426d11" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "polling" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b2d323e8ca7996b3e23126511a523f7e62924d93ecd5ae73b333815b0eb3dce" +dependencies = [ + "autocfg", + "bitflags", + "cfg-if", + "concurrent-queue", + "libc", + "log", + "pin-project-lite", + "windows-sys 0.48.0", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro-hack" +version = "0.5.20+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" + +[[package]] +name = "proc-macro2" +version = "1.0.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b368fba921b0dce7e60f5e04ec15e565b3303972b42bcfde1d0713b881959eb" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quick-xml" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11bafc859c6815fbaffbbbf4229ecb767ac913fecb27f9ad4343662e9ef099ea" +dependencies = [ + "memchr", +] + +[[package]] +name = "quick-xml" +version = "0.28.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce5e73202a820a31f8a0ee32ada5e21029c81fd9e3ebf668a40832e4219d9d1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "573015e8ab27661678357f27dc26460738fd2b6c86e46f386fde94cb5d913105" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" +dependencies = [ + "getrandom 0.1.16", + "libc", + "rand_chacha 0.2.2", + "rand_core 0.5.1", + "rand_hc", + "rand_pcg", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" +dependencies = [ + "ppv-lite86", + "rand_core 0.5.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom 0.1.16", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.10", +] + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +dependencies = [ + "rand_core 0.5.1", +] + +[[package]] +name = "rand_pcg" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16abd0c1b639e9eb4d7c50c0b8100b0d0f849be2349829c740fe8e6eb4816429" +dependencies = [ + "rand_core 0.5.1", +] + +[[package]] +name = "raw-window-handle" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ff9a1f06a88b01621b7ae906ef0211290d1c8a168a15542486a8f61c0833b9" + +[[package]] +name = "redox_syscall" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_syscall" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_users" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" +dependencies = [ + "getrandom 0.2.10", + "redox_syscall 0.2.16", + "thiserror", +] + +[[package]] +name = "regex" +version = "1.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0ab3ca65655bb1e41f2a8c8cd662eb4fb035e67c3f78da1d61dffe89d07300f" +dependencies = [ + "aho-corasick 1.0.2", + "memchr", + "regex-syntax 0.7.2", +] + +[[package]] +name = "regex-automata" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" +dependencies = [ + "regex-syntax 0.6.29", +] + +[[package]] +name = "regex-syntax" +version = "0.6.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" + +[[package]] +name = "regex-syntax" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436b050e76ed2903236f032a59761c1eb99e1b0aead2c257922771dab1fc8c78" + +[[package]] +name = "reqwest" +version = "0.11.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cde824a14b7c14f85caff81225f411faacc04a2013f41670f41443742b1c1c55" +dependencies = [ + "base64 0.21.2", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "hyper", + "hyper-tls", + "ipnet", + "js-sys", + "log", + "mime", + "native-tls", + "once_cell", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "serde_urlencoded", + "tokio", + "tokio-native-tls", + "tokio-util", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "winreg 0.10.1", +] + +[[package]] +name = "rfd" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0149778bd99b6959285b0933288206090c50e2327f47a9c463bfdbf45c8823ea" +dependencies = [ + "block", + "dispatch", + "glib-sys", + "gobject-sys", + "gtk-sys", + "js-sys", + "lazy_static", + "log", + "objc", + "objc-foundation", + "objc_id", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows 0.37.0", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.37.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62f25693a73057a1b4cb56179dd3c7ea21a7c6c5ee7d85781f5749b46f34b79c" +dependencies = [ + "bitflags", + "errno", + "io-lifetimes", + "libc", + "linux-raw-sys", + "windows-sys 0.48.0", +] + +[[package]] +name = "rustversion" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f3208ce4d8448b3f3e7d168a73f5e0c43a61e32930de3bceeccedb388b6bf06" + +[[package]] +name = "ryu" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041" + +[[package]] +name = "safemem" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef703b7cb59335eae2eb93ceb664c0eb7ea6bf567079d843e09420219668e072" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" +dependencies = [ + "windows-sys 0.48.0", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "security-framework" +version = "2.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc758eb7bffce5b308734e9b0c1468893cae9ff70ebf13e7090be8dcbcc83a8" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f51d0c0d83bec45f16480d0ce0058397a69e48fcdc52d1dc8855fb68acbd31a7" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "selectors" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df320f1889ac4ba6bc0cdc9c9af7af4bd64bb927bccdf32d81140dc1f9be12fe" +dependencies = [ + "bitflags", + "cssparser", + "derive_more", + "fxhash", + "log", + "matches", + "phf 0.8.0", + "phf_codegen", + "precomputed-hash", + "servo_arc", + "smallvec", + "thin-slice", +] + +[[package]] +name = "semver" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" +dependencies = [ + "serde", +] + +[[package]] +name = "serde" +version = "1.0.164" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.164" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.22", +] + +[[package]] +name = "serde_json" +version = "1.0.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46266871c240a00b8f503b877622fe33430b3c7d963bdc0f2adc511e54a1eae3" +dependencies = [ + "itoa 1.0.6", + "ryu", + "serde", +] + +[[package]] +name = "serde_repr" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.22", +] + +[[package]] +name = "serde_spanned" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96426c9936fd7a0124915f9185ea1d20aa9445cc9821142f0a73bc9207a2e186" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa 1.0.6", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f02d8aa6e3c385bf084924f660ce2a3a6bd333ba55b35e8590b321f35d88513" +dependencies = [ + "base64 0.21.2", + "chrono", + "hex", + "indexmap 1.9.3", + "serde", + "serde_json", + "serde_with_macros", + "time 0.3.22", +] + +[[package]] +name = "serde_with_macros" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edc7d5d3932fb12ce722ee5e64dd38c504efba37567f0c402f6ca728c3b8b070" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.22", +] + +[[package]] +name = "serialize-to-javascript" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9823f2d3b6a81d98228151fdeaf848206a7855a7a042bbf9bf870449a66cafb" +dependencies = [ + "serde", + "serde_json", + "serialize-to-javascript-impl", +] + +[[package]] +name = "serialize-to-javascript-impl" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74064874e9f6a15f04c1f3cb627902d0e6b410abbf36668afa873c61889f1763" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "servo_arc" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98238b800e0d1576d8b6e3de32827c2d74bee68bb97748dcf5071fb53965432" +dependencies = [ + "nodrop", + "stable_deref_trait", +] + +[[package]] +name = "sha1" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shared_child" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0d94659ad3c2137fef23ae75b03d5241d633f8acded53d672decfa0e6e0caef" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "signal-hook" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "732768f1176d21d09e076c23a93123d40bba92d50c4058da34d45c8de8e682b9" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" +dependencies = [ + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "238abfbb77c1915110ad968465608b68e869e0772622c9656714e73e5a1a522f" + +[[package]] +name = "siphasher" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de" + +[[package]] +name = "slab" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6528351c9bc8ab22353f9d776db39a20288e8d6c37ef8cfe3317cf875eecfc2d" +dependencies = [ + "autocfg", +] + +[[package]] +name = "smallvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" + +[[package]] +name = "socket2" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "soup2" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b4d76501d8ba387cf0fefbe055c3e0a59891d09f0f995ae4e4b16f6b60f3c0" +dependencies = [ + "bitflags", + "gio", + "glib", + "libc", + "once_cell", + "soup2-sys", +] + +[[package]] +name = "soup2-sys" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009ef427103fcb17f802871647a7fa6c60cbb654b4c4e4c0ac60a31c5f6dc9cf" +dependencies = [ + "bitflags", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps 5.0.0", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + +[[package]] +name = "state" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbe866e1e51e8260c9eed836a042a5e7f6726bb2b411dffeaa712e19c388f23b" +dependencies = [ + "loom", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "string_cache" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f91138e76242f575eb1d3b38b4f1362f10d3a43f47d182a5b359af488a02293b" +dependencies = [ + "new_debug_unreachable", + "once_cell", + "parking_lot", + "phf_shared 0.10.0", + "precomputed-hash", + "serde", +] + +[[package]] +name = "string_cache_codegen" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988" +dependencies = [ + "phf_generator 0.10.0", + "phf_shared 0.10.0", + "proc-macro2", + "quote", +] + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2efbeae7acf4eabd6bcdcbd11c92f45231ddda7539edc7806bd1a04a03b24616" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sys-locale" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8a11bd9c338fdba09f7881ab41551932ad42e405f61d01e8406baea71c07aee" +dependencies = [ + "js-sys", + "libc", + "wasm-bindgen", + "web-sys", + "windows-sys 0.45.0", +] + +[[package]] +name = "system-deps" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18db855554db7bd0e73e06cf7ba3df39f97812cb11d3f75e71c39bf45171797e" +dependencies = [ + "cfg-expr 0.9.1", + "heck 0.3.3", + "pkg-config", + "toml 0.5.11", + "version-compare 0.0.11", +] + +[[package]] +name = "system-deps" +version = "6.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30c2de8a4d8f4b823d634affc9cd2a74ec98c53a756f317e529a48046cbf71f3" +dependencies = [ + "cfg-expr 0.15.3", + "heck 0.4.1", + "pkg-config", + "toml 0.7.5", + "version-compare 0.1.1", +] + +[[package]] +name = "tao" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6d198e01085564cea63e976ad1566c1ba2c2e4cc79578e35d9f05521505e31" +dependencies = [ + "bitflags", + "cairo-rs", + "cc", + "cocoa", + "core-foundation", + "core-graphics", + "crossbeam-channel", + "dispatch", + "gdk", + "gdk-pixbuf", + "gdk-sys", + "gdkwayland-sys", + "gdkx11-sys", + "gio", + "glib", + "glib-sys", + "gtk", + "image", + "instant", + "jni", + "lazy_static", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "objc", + "once_cell", + "parking_lot", + "png", + "raw-window-handle", + "scopeguard", + "serde", + "tao-macros", + "unicode-segmentation", + "uuid", + "windows 0.39.0", + "windows-implement", + "x11-dl", +] + +[[package]] +name = "tao-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b27a4bcc5eb524658234589bdffc7e7bfb996dbae6ce9393bfd39cb4159b445" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "tar" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b55807c0344e1e6c04d7c965f5289c39a8d94ae23ed5c0b57aabac549f871c6" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "target-lexicon" +version = "0.12.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b1c7f239eb94671427157bd93b3694320f3668d4e1eff08c7285366fd777fac" + +[[package]] +name = "tauri" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fbe522898e35407a8e60dc3870f7579fea2fc262a6a6072eccdd37ae1e1d91e" +dependencies = [ + "anyhow", + "bytes", + "cocoa", + "dirs-next", + "embed_plist", + "encoding_rs", + "flate2", + "futures-util", + "glib", + "glob", + "gtk", + "heck 0.4.1", + "http", + "ignore", + "notify-rust", + "objc", + "once_cell", + "open", + "os_info", + "os_pipe", + "percent-encoding", + "rand 0.8.5", + "raw-window-handle", + "regex", + "reqwest", + "rfd", + "semver", + "serde", + "serde_json", + "serde_repr", + "serialize-to-javascript", + "shared_child", + "state", + "sys-locale", + "tar", + "tauri-macros", + "tauri-runtime", + "tauri-runtime-wry", + "tauri-utils", + "tempfile", + "thiserror", + "tokio", + "url", + "uuid", + "webkit2gtk", + "webview2-com", + "windows 0.39.0", +] + +[[package]] +name = "tauri-build" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d2edd6a259b5591c8efdeb9d5702cb53515b82a6affebd55c7fd6d3a27b7d1b" +dependencies = [ + "anyhow", + "cargo_toml", + "heck 0.4.1", + "json-patch", + "semver", + "serde", + "serde_json", + "tauri-utils", + "tauri-winres", +] + +[[package]] +name = "tauri-codegen" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54ad2d49fdeab4a08717f5b49a163bdc72efc3b1950b6758245fcde79b645e1a" +dependencies = [ + "base64 0.21.2", + "brotli", + "ico", + "json-patch", + "plist", + "png", + "proc-macro2", + "quote", + "regex", + "semver", + "serde", + "serde_json", + "sha2", + "tauri-utils", + "thiserror", + "time 0.3.22", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-macros" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eb12a2454e747896929338d93b0642144bb51e0dddbb36e579035731f0d76b7" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "quote", + "syn 1.0.109", + "tauri-codegen", + "tauri-utils", +] + +[[package]] +name = "tauri-runtime" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "108683199cb18f96d2d4134187bb789964143c845d2d154848dda209191fd769" +dependencies = [ + "gtk", + "http", + "http-range", + "rand 0.8.5", + "raw-window-handle", + "serde", + "serde_json", + "tauri-utils", + "thiserror", + "url", + "uuid", + "webview2-com", + "windows 0.39.0", +] + +[[package]] +name = "tauri-runtime-wry" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7aa256a1407a3a091b5d843eccc1a5042289baf0a43d1179d9f0fcfea37c1b" +dependencies = [ + "cocoa", + "gtk", + "percent-encoding", + "rand 0.8.5", + "raw-window-handle", + "tauri-runtime", + "tauri-utils", + "uuid", + "webkit2gtk", + "webview2-com", + "windows 0.39.0", + "wry", +] + +[[package]] +name = "tauri-utils" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03fc02bb6072bb397e1d473c6f76c953cda48b4a2d0cce605df284aa74a12e84" +dependencies = [ + "brotli", + "ctor", + "dunce", + "glob", + "heck 0.4.1", + "html5ever", + "infer", + "json-patch", + "kuchiki", + "memchr", + "phf 0.10.1", + "proc-macro2", + "quote", + "semver", + "serde", + "serde_json", + "serde_with", + "thiserror", + "url", + "walkdir", + "windows 0.39.0", +] + +[[package]] +name = "tauri-winres" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5993dc129e544393574288923d1ec447c857f3f644187f4fbf7d9a875fbfc4fb" +dependencies = [ + "embed-resource", + "toml 0.7.5", +] + +[[package]] +name = "tauri-winrt-notification" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f5bff1d532fead7c43324a0fa33643b8621a47ce2944a633be4cb6c0240898f" +dependencies = [ + "quick-xml 0.23.1", + "windows 0.39.0", +] + +[[package]] +name = "tempfile" +version = "3.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31c0432476357e58790aaa47a8efb0c5138f137343f3b5f23bd36a27e3b0a6d6" +dependencies = [ + "autocfg", + "cfg-if", + "fastrand", + "redox_syscall 0.3.5", + "rustix", + "windows-sys 0.48.0", +] + +[[package]] +name = "tendril" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0" +dependencies = [ + "futf", + "mac", + "utf-8", +] + +[[package]] +name = "thin-slice" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eaa81235c7058867fa8c0e7314f33dcce9c215f535d1913822a2b3f5e289f3c" + +[[package]] +name = "thiserror" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.22", +] + +[[package]] +name = "thread_local" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152" +dependencies = [ + "cfg-if", + "once_cell", +] + +[[package]] +name = "time" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" +dependencies = [ + "libc", + "wasi 0.10.0+wasi-snapshot-preview1", + "winapi", +] + +[[package]] +name = "time" +version = "0.3.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea9e1b3cf1243ae005d9e74085d4d542f3125458f3a81af210d901dcd7411efd" +dependencies = [ + "itoa 1.0.6", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb" + +[[package]] +name = "time-macros" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "372950940a5f07bf38dbe211d7283c9e6d7327df53794992d293e534c733d09b" +dependencies = [ + "time-core", +] + +[[package]] +name = "tinyvec" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "532826ff75199d5833b9d2c5fe410f29235e25704ee5f0ef599fb51c21f4a4da" +dependencies = [ + "autocfg", + "backtrace", + "bytes", + "libc", + "mio", + "num_cpus", + "pin-project-lite", + "socket2", + "windows-sys 0.48.0", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "806fe8c2c87eccc8b3267cbae29ed3ab2d0bd37fca70ab622e46aaa9375ddb7d" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", + "tracing", +] + +[[package]] +name = "toml" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" +dependencies = [ + "serde", +] + +[[package]] +name = "toml" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebafdf5ad1220cb59e7d17cf4d2c72015297b75b19a10472f99b89225089240" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.19.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "266f016b7f039eec8a1a80dfe6156b633d208b9fccca5e4db1d6775b0c4e34a7" +dependencies = [ + "indexmap 2.0.0", + "serde", + "serde_spanned", + "toml_datetime", + "winnow", +] + +[[package]] +name = "tower-service" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" + +[[package]] +name = "tracing" +version = "0.1.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +dependencies = [ + "cfg-if", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.22", +] + +[[package]] +name = "tracing-core" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" +dependencies = [ + "lazy_static", + "log", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a651bc37f915e81f087d86e62a18eec5f79550c7faff886f7090b4ea757c77" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "treediff" +version = "4.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52984d277bdf2a751072b5df30ec0377febdb02f7696d64c2d7d54630bac4303" +dependencies = [ + "serde_json", +] + +[[package]] +name = "try-lock" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed" + +[[package]] +name = "typenum" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" + +[[package]] +name = "uds_windows" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce65604324d3cce9b966701489fbd0cf318cb1f7bd9dd07ac9a4ee6fb791930d" +dependencies = [ + "tempfile", + "winapi", +] + +[[package]] +name = "unicode-bidi" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" + +[[package]] +name = "unicode-ident" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0" + +[[package]] +name = "unicode-normalization" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-segmentation" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" + +[[package]] +name = "url" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "uuid" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d023da39d1fde5a8a3fe1f3e01ca9632ada0a63e9797de55a879d6e2236277be" +dependencies = [ + "getrandom 0.2.10", +] + +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version-compare" +version = "0.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c18c859eead79d8b95d09e4678566e8d70105c4e7b251f707a03df32442661b" + +[[package]] +name = "version-compare" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "579a42fc0b8e0c63b76519a339be31bed574929511fa53c1a3acae26eb258f29" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "vswhom" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" +dependencies = [ + "libc", + "vswhom-sys", +] + +[[package]] +name = "vswhom-sys" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3b17ae1f6c8a2b28506cd96d412eebf83b4a0ff2cbefeeb952f2f9dfa44ba18" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "waker-fn" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca" + +[[package]] +name = "walkdir" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36df944cda56c7d8d8b7496af378e6b16de9284591917d307c9b4d313c44e698" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + +[[package]] +name = "wasi" +version = "0.10.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.22", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.22", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" + +[[package]] +name = "wasm-streams" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bbae3363c08332cadccd13b67db371814cd214c2524020932f0804b8cf7c078" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webkit2gtk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8f859735e4a452aeb28c6c56a852967a8a76c8eb1cc32dbf931ad28a13d6370" +dependencies = [ + "bitflags", + "cairo-rs", + "gdk", + "gdk-sys", + "gio", + "gio-sys", + "glib", + "glib-sys", + "gobject-sys", + "gtk", + "gtk-sys", + "javascriptcore-rs", + "libc", + "once_cell", + "soup2", + "webkit2gtk-sys", +] + +[[package]] +name = "webkit2gtk-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d76ca6ecc47aeba01ec61e480139dda143796abcae6f83bcddf50d6b5b1dcf3" +dependencies = [ + "atk-sys", + "bitflags", + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "gtk-sys", + "javascriptcore-rs-sys", + "libc", + "pango-sys", + "pkg-config", + "soup2-sys", + "system-deps 6.1.1", +] + +[[package]] +name = "webview2-com" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a769c9f1a64a8734bde70caafac2b96cada12cd4aefa49196b3a386b8b4178" +dependencies = [ + "webview2-com-macros", + "webview2-com-sys", + "windows 0.39.0", + "windows-implement", +] + +[[package]] +name = "webview2-com-macros" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaebe196c01691db62e9e4ca52c5ef1e4fd837dcae27dae3ada599b5a8fd05ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "webview2-com-sys" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aac48ef20ddf657755fdcda8dfed2a7b4fc7e4581acce6fe9b88c3d64f29dee7" +dependencies = [ + "regex", + "serde", + "serde_json", + "thiserror", + "windows 0.39.0", + "windows-bindgen", + "windows-metadata", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57b543186b344cc61c85b5aab0d2e3adf4e0f99bc076eff9aa5927bcc0b8a647" +dependencies = [ + "windows_aarch64_msvc 0.37.0", + "windows_i686_gnu 0.37.0", + "windows_i686_msvc 0.37.0", + "windows_x86_64_gnu 0.37.0", + "windows_x86_64_msvc 0.37.0", +] + +[[package]] +name = "windows" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1c4bd0a50ac6020f65184721f758dba47bb9fbc2133df715ec74a237b26794a" +dependencies = [ + "windows-implement", + "windows_aarch64_msvc 0.39.0", + "windows_i686_gnu 0.39.0", + "windows_i686_msvc 0.39.0", + "windows_x86_64_gnu 0.39.0", + "windows_x86_64_msvc 0.39.0", +] + +[[package]] +name = "windows" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +dependencies = [ + "windows-targets 0.48.1", +] + +[[package]] +name = "windows-bindgen" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68003dbd0e38abc0fb85b939240f4bce37c43a5981d3df37ccbaaa981b47cb41" +dependencies = [ + "windows-metadata", + "windows-tokens", +] + +[[package]] +name = "windows-implement" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba01f98f509cb5dc05f4e5fc95e535f78260f15fea8fe1a8abdd08f774f1cee7" +dependencies = [ + "syn 1.0.109", + "windows-tokens", +] + +[[package]] +name = "windows-metadata" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ee5e275231f07c6e240d14f34e1b635bf1faa1c76c57cfd59a5cdb9848e4278" + +[[package]] +name = "windows-sys" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.1", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05d4b17490f70499f20b9e791dcf6a299785ce8af4d709018206dc5b4953e95f" +dependencies = [ + "windows_aarch64_gnullvm 0.48.0", + "windows_aarch64_msvc 0.48.0", + "windows_i686_gnu 0.48.0", + "windows_i686_msvc 0.48.0", + "windows_x86_64_gnu 0.48.0", + "windows_x86_64_gnullvm 0.48.0", + "windows_x86_64_msvc 0.48.0", +] + +[[package]] +name = "windows-tokens" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f838de2fe15fe6bac988e74b798f26499a8b21a9d97edec321e79b28d1d7f597" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2623277cb2d1c216ba3b578c0f3cf9cdebeddb6e66b1b218bb33596ea7769c3a" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7711666096bd4096ffa835238905bb33fb87267910e154b18b44eaabb340f2" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" + +[[package]] +name = "windows_i686_gnu" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3925fd0b0b804730d44d4b6278c50f9699703ec49bcd628020f46f4ba07d9e1" + +[[package]] +name = "windows_i686_gnu" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "763fc57100a5f7042e3057e7e8d9bdd7860d330070251a73d003563a3bb49e1b" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" + +[[package]] +name = "windows_i686_msvc" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce907ac74fe331b524c1298683efbf598bb031bc84d5e274db2083696d07c57c" + +[[package]] +name = "windows_i686_msvc" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bc7cbfe58828921e10a9f446fcaaf649204dcfe6c1ddd712c5eebae6bda1106" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2babfba0828f2e6b32457d5341427dcbb577ceef556273229959ac23a10af33d" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6868c165637d653ae1e8dc4d82c25d4f97dd6605eaa8d784b5c6e0ab2a252b65" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4dd6dc7df2d84cf7b33822ed5b86318fb1781948e9663bacd047fc9dd52259d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e4d40883ae9cae962787ca76ba76390ffa29214667a111db9e0a1ad8377e809" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" + +[[package]] +name = "winnow" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca0ace3845f0d96209f0375e6d367e3eb87eb65d27d445bdc9f1843a26f39448" +dependencies = [ + "memchr", +] + +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + +[[package]] +name = "winreg" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a1a57ff50e9b408431e8f97d5456f2807f8eb2a2cd79b06068fc87f8ecf189" +dependencies = [ + "cfg-if", + "winapi", +] + +[[package]] +name = "wry" +version = "0.24.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33748f35413c8a98d45f7a08832d848c0c5915501803d1faade5a4ebcd258cea" +dependencies = [ + "base64 0.13.1", + "block", + "cocoa", + "core-graphics", + "crossbeam-channel", + "dunce", + "gdk", + "gio", + "glib", + "gtk", + "html5ever", + "http", + "kuchiki", + "libc", + "log", + "objc", + "objc_id", + "once_cell", + "serde", + "serde_json", + "sha2", + "soup2", + "tao", + "thiserror", + "url", + "webkit2gtk", + "webkit2gtk-sys", + "webview2-com", + "windows 0.39.0", + "windows-implement", +] + +[[package]] +name = "x11" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "xattr" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d1526bbe5aaeb5eb06885f4d987bcdfa5e23187055de9b83fe00156a821fabc" +dependencies = [ + "libc", +] + +[[package]] +name = "xdg-home" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2769203cd13a0c6015d515be729c526d041e9cf2c0cc478d57faee85f40c6dcd" +dependencies = [ + "nix", + "winapi", +] + +[[package]] +name = "zbus" +version = "3.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31de390a2d872e4cd04edd71b425e29853f786dc99317ed72d73d6fcf5ebb948" +dependencies = [ + "async-broadcast", + "async-executor", + "async-fs", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "byteorder", + "derivative", + "enumflags2", + "event-listener", + "futures-core", + "futures-sink", + "futures-util", + "hex", + "nix", + "once_cell", + "ordered-stream", + "rand 0.8.5", + "serde", + "serde_repr", + "sha1", + "static_assertions", + "tracing", + "uds_windows", + "winapi", + "xdg-home", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "3.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d1794a946878c0e807f55a397187c11fc7a038ba5d868e7db4f3bd7760bc9d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "regex", + "syn 1.0.109", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb80bb776dbda6e23d705cf0123c3b95df99c4ebeaec6c2599d4a5419902b4a9" +dependencies = [ + "serde", + "static_assertions", + "zvariant", +] + +[[package]] +name = "zvariant" +version = "3.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44b291bee0d960c53170780af148dca5fa260a63cdd24f1962fa82e03e53338c" +dependencies = [ + "byteorder", + "enumflags2", + "libc", + "serde", + "static_assertions", + "zvariant_derive", +] + +[[package]] +name = "zvariant_derive" +version = "3.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "934d7a7dfc310d6ee06c87ffe88ef4eca7d3e37bb251dece2ef93da8f17d8ecd" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 1.0.109", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7234f0d811589db492d16893e3f21e8e2fd282e6d01b0cddee310322062cc200" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/Cargo.toml b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..df7f5a45f01202acf8d6e1780adc6d0be9309ca9 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "infinite_image_browsing" +version = "0.0.1" +description = "Infinite Image Browsing" +authors = ["zanllp"] +license = "mit" +repository = "" +edition = "2021" + + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[build-dependencies] +tauri-build = { version = "1.4", features = [] } + +[dependencies] +tauri = { version = "1.4", features = [ "api-all", "devtools", "process-command-api"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +reqwest = { version = "0.11", features = ["blocking", "json"] } +chrono = "0.4" + +[features] +# this feature is used for production builds or when `devPath` points to the filesystem +# DO NOT REMOVE!! +custom-protocol = ["tauri/custom-protocol"] diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/build.rs b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/build.rs new file mode 100644 index 0000000000000000000000000000000000000000..795b9b7c83dbfc6bf454958eef78f93e211703d2 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/build.rs @@ -0,0 +1,3 @@ +fn main() { + tauri_build::build() +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/128x128.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/128x128.png new file mode 100644 index 0000000000000000000000000000000000000000..4398e925dacc3de445d58f32b998b0975c41196d Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/128x128.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/128x128@2x.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/128x128@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..dfe8ac4deb698e20adc85fac8998aaf623edd90b Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/128x128@2x.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/32x32.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/32x32.png new file mode 100644 index 0000000000000000000000000000000000000000..0111967051321edbe23ebfd34578b9188e59998c Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/32x32.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square107x107Logo.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square107x107Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..77999ba944050316ecf5a1f13fc9aa0a4c7a8c9e Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square107x107Logo.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square142x142Logo.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square142x142Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..2ca2ea7ef24e853f32018c9b02dd026861734f5a Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square142x142Logo.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square150x150Logo.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square150x150Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..c5dd45eac6bcf7dfe42127c8757ee325f071da30 Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square150x150Logo.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square284x284Logo.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square284x284Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..8052711ca8845696ea3668760a63991aade5390a Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square284x284Logo.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square30x30Logo.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square30x30Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..b2ea9712be0a92ad10997b8f6fd535e8e0535445 Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square30x30Logo.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square310x310Logo.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square310x310Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..8d9025588da30e7ecea896a0a48511688c31709f Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square310x310Logo.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square44x44Logo.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square44x44Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..d76ef105578f9879d5e84dc987c6bbbc57b28949 Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square44x44Logo.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square71x71Logo.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square71x71Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..84feca193d41983b04794f33b61d34b27c59bd23 Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square71x71Logo.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square89x89Logo.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square89x89Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..5684cb88afa0b9ae803d51f902307de3a2233756 Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/Square89x89Logo.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/StoreLogo.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/StoreLogo.png new file mode 100644 index 0000000000000000000000000000000000000000..477ec1ab15392b6c5f852a869d1c35b4e085e7e9 Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/StoreLogo.png differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/icon.icns b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/icon.icns new file mode 100644 index 0000000000000000000000000000000000000000..e17e355a7cd5e7d0d5c881e9d430e1836e079b51 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/icon.icns @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b80c39897bb3251efb89e1e624805673624a49ea26773d549ae8dbc48ce3e1ea +size 795743 diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/icon.ico b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..eaefe0037ea42a1228b094c72110751222aef1f0 Binary files /dev/null and b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/icon.ico differ diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/icon.png b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..3f42f9c7656b638e44d862f1fc26056a1e0e8623 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/icons/icon.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e9f241295a0b34b3aec695c5cd0402fe9c28caf445a79502f9d016382dd5344 +size 131752 diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/src/main.rs b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..35b66d983a478be016b7ef875dd66b7ad2f91c7c --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/src/main.rs @@ -0,0 +1,116 @@ +// Prevents additional console window on Windows in release, DO NOT REMOVE!! +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + +use serde::Deserialize; +use std::fs::File; +use std::fs::OpenOptions; +use std::io::prelude::*; +use std::io::Error; +use std::io::Write; +use tauri::api::process::Command; +use tauri::api::process::CommandEvent; +use tauri::WindowEvent; +use chrono::Local; +use chrono::format::{DelayedFormat, StrftimeItems}; + +// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command +#[tauri::command] +fn greet(name: &str) -> String { + format!("Hello, {}! You've been greeted from Rust!", name) +} +struct AppState { + port: u16, +} +#[derive(serde::Serialize)] +struct AppConf { + port: u16, +} +#[tauri::command] +fn get_tauri_conf(state: tauri::State<'_, AppState>) -> AppConf { + AppConf { port: state.port } +} + +#[derive(Deserialize, Default, Debug)] +struct Config { + sdwebui_dir: String, +} + +fn read_config_file(path: &str) -> Result { + let mut file = File::open(path)?; + let mut contents = String::new(); + file.read_to_string(&mut contents)?; + Ok(contents) +} + +fn shutdown_api_server(port: u16) { + let url = format!("http://127.0.0.1:{}/infinite_image_browsing/shutdown", port); + let res = reqwest::blocking::Client::new().post(url).send(); + if let Err(e) = res { + eprintln!("{}", e); + } +} + +#[tauri::command] +fn shutdown_api_server_command(state: tauri::State<'_, AppState>) { + shutdown_api_server(state.port); +} + +fn main() { + let listener = std::net::TcpListener::bind("localhost:0").expect("无法绑定到任何可用端口"); + let port = listener.local_addr().unwrap().port(); + drop(listener); + let port_str = port.to_string(); + let mut args = vec!["--port", &port_str, "--allow_cors", "--enable_shutdown"]; + let contents = read_config_file("app.conf.json").unwrap_or_default(); + let conf = serde_json::from_str::(&contents).unwrap_or_default(); + if !conf.sdwebui_dir.is_empty() { + args.push("--sd_webui_dir"); + args.push(&conf.sdwebui_dir); + } + let (mut rx, _child) = Command::new_sidecar("iib_api_server") + .expect("failed to create `iib_api_server` binary command") + .args(args) + .spawn() + .expect("Failed to spawn sidecar"); + let log_file = OpenOptions::new() + .create(true) + .write(true) + .append(true) + .open("iib_api_server.log") + .expect("Failed to open log file"); + tauri::async_runtime::spawn(async move { + // read events such as stdout + while let Some(event) = rx.recv().await { + match event { + CommandEvent::Stdout(line) => { + let timestamp: DelayedFormat> = + Local::now().format("[%Y-%m-%d %H:%M:%S]"); + let log_line = format!("INFO {} {}", timestamp, line); + println!("{}", log_line); + writeln!(&log_file, "{}", log_line).expect("Failed to write to log file"); + }, + CommandEvent::Stderr(line) => { + let timestamp: DelayedFormat> = + Local::now().format("[%Y-%m-%d %H:%M:%S]"); + let log_line = format!("ERR {} {}", timestamp, line); + println!("{}", log_line); + writeln!(&log_file, "{}", log_line).expect("Failed to write to log file"); + } + _ => (), + }; + } + }); + tauri::Builder::default() + .manage(AppState { port }) + .invoke_handler(tauri::generate_handler![ + greet, + get_tauri_conf, + shutdown_api_server_command + ]) + .on_window_event(move |event| match event.event() { + WindowEvent::CloseRequested { .. } => shutdown_api_server(port), + _ => (), + }) + .run(tauri::generate_context!()) + .expect("error while running tauri application"); +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/tauri.conf.json b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/tauri.conf.json new file mode 100644 index 0000000000000000000000000000000000000000..75ef15594a09151e1a35fdcb6a095fcfe3fdacbf --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src-tauri/tauri.conf.json @@ -0,0 +1,64 @@ +{ + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn build", + "devPath": "http://localhost:5173", + "distDir": "../dist", + "withGlobalTauri": false + }, + "package": { + "productName": "Infinite Image Browsing", + "version": "1.2.0" + }, + "tauri": { + "allowlist": { + "all": true, + "fs": { + "all": true, + "scope": [ + "**" + ] + }, + "shell": { + "all": true, + "open": true, + "sidecar": true, + "scope": [ + { + "name": "iib_api_server", + "sidecar": true + } + ] + } + }, + "bundle": { + "active": true, + "targets": "all", + "identifier": "com.zanllp.iib", + "icon": [ + "icons/32x32.png", + "icons/128x128.png", + "icons/128x128@2x.png", + "icons/icon.icns", + "icons/icon.ico" + ], + "externalBin": [ + "iib_api_server" + ] + }, + "security": { + "csp": null + }, + "windows": [ + { + "fullscreen": false, + "resizable": true, + "fileDropEnabled": false, + "title": "Infinite Image Browsing", + "width": 800, + "height": 600, + "maximized": true + } + ] + } +} \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/App.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/App.vue new file mode 100644 index 0000000000000000000000000000000000000000..d177e1babf837bd696e4e7be55b3babb80f03e13 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/App.vue @@ -0,0 +1,157 @@ + + + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/api/db.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/api/db.ts new file mode 100644 index 0000000000000000000000000000000000000000..48daa42daa549fdc0b530ec4d626e02e68237771 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/api/db.ts @@ -0,0 +1,156 @@ +import { Dict } from '@/util' +import type { FileNodeInfo } from './files' +import { axiosInst } from './index' +import { PageCursor } from 'vue3-ts-util' + +export interface Tag { + name: string + id: number | string + display_name: string | null + type: string + color: string + count: number +} + +export type DataBaseBasicInfo = { + img_count: number + tags: Tag[] + expired: boolean + expired_dirs: string[] +} + +export const getDbBasicInfo = async () => { + const resp = await axiosInst.value.get('/db/basic_info') + return resp.data as DataBaseBasicInfo +} + +export const getExpiredDirs = async () => { + const resp = await axiosInst.value.get('/db/expired_dirs') + return resp.data as Pick +} + +export const updateImageData = async () => { + await axiosInst.value.post('/db/update_image_data', {}, { timeout: Infinity }) +} + +export const updateTag = async (tag: Tag) => { + await axiosInst.value.post('/db/update_tag', tag) +} + +export type TagId = number | string +export interface MatchImageByTagsReq { + folder_paths_str?: string + and_tags: TagId[] + or_tags: TagId[] + not_tags: TagId[] +} + +export const getImagesByTags = async (req: MatchImageByTagsReq, cursor: string) => { + const resp = await axiosInst.value.post('/db/match_images_by_tags', { + ...req, + folder_paths: (req.folder_paths_str ?? '').split(/,|\n/).map(v => v.trim()).filter(v => v), + cursor + }) + return resp.data as { + files: FileNodeInfo[], + cursor: PageCursor + } +} + +export const addCustomTag = async (req: { tag_name: string }) => { + const resp = await axiosInst.value.post('/db/add_custom_tag', req) + return resp.data as Tag +} + +export const toggleCustomTagToImg = async (req: { tag_id: TagId; img_path: string }) => { + const resp = await axiosInst.value.post('/db/toggle_custom_tag_to_img', req) + return resp.data as { is_remove: boolean } +} + +export const removeCustomTag = async (req: { tag_id: TagId }) => { + await axiosInst.value.post('/db/remove_custom_tag', req) +} + +export const removeCustomTagToImg = async (req: { tag_id: TagId; img_id: TagId }) => { + await axiosInst.value.post('/db/add_custom_tag_from_img', req) +} + +export const getImageSelectedCustomTag = async (path: string) => { + const resp = await axiosInst.value.get('/db/img_selected_custom_tag', { params: { path } }) + return resp.data as Tag[] +} + +export interface SearchBySubstrReq { + surstr: string; + cursor: string; + regexp: string; + path_only?: boolean; + folder_paths?: string[]; + size?: number; +} + + +export const getImagesBySubstr = async (req: SearchBySubstrReq) => { + const resp = await axiosInst.value.post('/db/search_by_substr', req) + return resp.data as { + files: FileNodeInfo[], + cursor: PageCursor + } +} + +const extraPaths = '/db/extra_paths' +export type ExtraPathType = 'scanned' | 'walk' | 'cli_access_only' | '' | 'scanned-fixed' + +export interface ExtraPathModel { + path: string + alias?: string + types: ExtraPathType[] +} + +export const getExtraPath = async () => { + const resp = await axiosInst.value.get(extraPaths) + return resp.data as ExtraPathModel[] +} + +export const addExtraPath = async (model: ExtraPathModel) => { + await axiosInst.value.post(extraPaths, model) +} +export const removeExtraPath = async (req: ExtraPathModel) => { + await axiosInst.value.delete(extraPaths, { data: req }) +} + +export interface ExtraPathAliasModel { + path: string + alias: string +} + +export const aliasExtraPath = async (model: ExtraPathAliasModel) => { + await axiosInst.value.post('/db/alias_extra_path', model) +} + +export const batchGetTagsByPath = async (paths: string[]) => { + const resp = await axiosInst.value.post('/db/get_image_tags', { paths }) + return resp.data as Dict +} + +export const rebuildImageIndex = () => axiosInst.value.post('/db/rebuild_index') + +export interface BatchUpdateTagParams { + img_paths: string[] + action: 'add' | 'remove' + tag_id: number +} + +export const batchUpdateImageTag = (data: BatchUpdateTagParams) => { + return axiosInst.value.post('/db/batch_update_image_tag', data) +} + +export interface RenameFileParams { + path: string + name: string +} + +export const renameFile = async (data: RenameFileParams) => { + const resp = await axiosInst.value.post('/db/rename', data) + return resp.data as Promise<{ new_path:string }> +} \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/api/files.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/api/files.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4c6db26d9b5e67bbcd7acfc3d6db5b8ce1c9815 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/api/files.ts @@ -0,0 +1,61 @@ +import { Dict } from '@/util' +import { axiosInst } from '.' + +export interface FileNodeInfo { + size: string + type: 'file' | 'dir' + created_time: string + name: string + date: string + bytes: number + fullpath: string + is_under_scanned_path: boolean + gen_info_raw?: string + gen_info_obj?: object + cover_url?: string +} + +export interface GenDiffInfo { + empty: boolean + ownFile: string + otherFile: string + diff: any +} + +export const getTargetFolderFiles = async (folder_path: string) => { + const resp = await axiosInst.value.get('/files', { params: { folder_path } }) + return resp.data as { files: FileNodeInfo[] } +} + +export const deleteFiles = async (file_paths: string[]) => { + const resp = await axiosInst.value.post('/delete_files', { file_paths }) + return resp.data as { files: FileNodeInfo[] } +} + +export const moveFiles = async ( + file_paths: string[], + dest: string, + create_dest_folder?: boolean +) => { + const resp = await axiosInst.value.post('/move_files', { file_paths, dest, create_dest_folder }) + return resp.data as { files: FileNodeInfo[] } +} + +export const copyFiles = async ( + file_paths: string[], + dest: string, + create_dest_folder?: boolean +) => { + const resp = await axiosInst.value.post('/copy_files', { file_paths, dest, create_dest_folder }) + return resp.data as { files: FileNodeInfo[] } +} + +export const mkdirs = async (dest_folder: string) => { + await axiosInst.value.post('/mkdirs', { dest_folder }) +} + + +export const batchGetFilesInfo = async (paths: string[]) => { + const resp = await axiosInst.value.post('/batch_get_files_info', { paths }) + return resp.data as Dict +} \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/api/index.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/api/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..8ad2c736d876ee52dbd2461e520372d90b4fd8b1 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/api/index.ts @@ -0,0 +1,181 @@ +import { Input, Modal, message } from 'ant-design-vue' +import axios, { AxiosInstance, isAxiosError } from 'axios' +import type { GlobalSettingPart } from './type' +import { t } from '@/i18n' +import type { ExtraPathModel, Tag } from './db' +import cookie from 'js-cookie' +import { delay } from 'vue3-ts-util' +import { computed, h, ref } from 'vue' +import 'ant-design-vue/es/input/style/index.css' +import sjcl from 'sjcl' +import { tauriConf } from '@/util/tauriAppConf' +import { Dict, isSync } from '@/util' +import { FileNodeInfo } from './files' + +export const apiBase = computed(() => + tauriConf.value + ? `http://127.0.0.1:${tauriConf.value.port}/infinite_image_browsing` + : '/infinite_image_browsing' +) + +const sha256 = (data: string) => { + const hash = sjcl.hash.sha256.hash(data) + return sjcl.codec.hex.fromBits(hash) +} + +const addInterceptor = (axiosInst: AxiosInstance) => { + axiosInst.interceptors.response.use( + (resp) => resp, + async (err) => { + if (isAxiosError(err)) { + if (err.response?.status === 401) { + const key = await new Promise((resolve) => { + const key = ref('') + Modal.confirm({ + title: t('serverKeyRequired'), + content: () => { + return h(Input, { + value: key.value, + 'onUpdate:value': (v: string) => (key.value = v) + }) + }, + onOk() { + resolve(key.value) + } + }) + }) + if (!key) { + return + } + cookie.set('IIB_S', sha256(key + '_ciallo')) + await delay(100) + location.reload() + } + + switch (err.response?.data?.detail?.type) { + case 'secret_key_required': + Modal.error({ + width: '60vw', + title: t('secretKeyMustBeConfigured'), + content: () => h('p', { style: 'white-space: pre-line;' } , t('secretKeyRequiredWarnMsg')) + }) + throw new Error(t('secretKeyRequiredWarnMsg')) + } + let errmsg = err.response?.data?.detail + try { + if (!errmsg) { + errmsg = JSON.parse(await err.response?.data.text()).detail + } + } catch (e) { + console.error(err.response ,e) + } + errmsg ??= t('errorOccurred') + message.error(errmsg) + throw new Error(errmsg) + } + return err + } + ) +} + +export const axiosInst = computed(() => { + const axiosInst = axios.create({ + baseURL: apiBase.value + }) + addInterceptor(axiosInst) + return axiosInst +}) +export const greeting = async () => { + const resp = await axiosInst.value.get('hello') + return resp.data as string +} + +export interface GlobalConf { + all_custom_tags: Tag[] + global_setting: GlobalSettingPart + is_win: boolean + cwd: string + home: string + sd_cwd: string + extra_paths: ExtraPathModel[] + enable_access_control: boolean + launch_mode: 'server' | 'sd' + export_fe_fn: boolean + app_fe_setting: Record<'global'|'fullscreen_layout'| `workspace_snapshot_${string}`, any> + is_readonly: boolean +} + +export const getGlobalSetting = async () => { + const resp = await axiosInst.value.get('/global_setting') + const data = resp.data as GlobalConf + try { + if (!isSync()) { + data.app_fe_setting = {} as any + } + } catch (error) { + console.error(error) + } + return data +} + +export const getVersion = async () => { + const resp = await axiosInst.value.get('/version') + return resp.data as { hash?: string, tag?: string } +} + +export const checkPathExists = async (paths: string[]) => { + const resp = await axiosInst.value.post('/check_path_exists', { paths }) + return resp.data as Record +} + +export const setImgPath = async (path: string) => { + return axiosInst.value.post(`/send_img_path?path=${encodeURIComponent(path)}`) +} + +export const genInfoCompleted = async () => { + return (await axiosInst.value.get('/gen_info_completed', { timeout: 60_000 })).data as boolean +} + +export const getImageGenerationInfo = async (path: string) => { + return (await axiosInst.value.get(`/image_geninfo?path=${encodeURIComponent(path)}`)) + .data as string +} + +export const getImageGenerationInfoBatch = async (paths: string[]) => { + if (!paths.length) { + return {} + } + const resp = await axiosInst.value.post('/image_geninfo_batch', { paths }) + return resp.data +} + +export const openFolder = async (path: string) => { + await axiosInst.value.post('/open_folder', { path }) +} + +export const openWithDefaultApp = async (path: string) => { + await axiosInst.value.post('/open_with_default_app', { path }) +} + +export interface Top4MediaInfo extends FileNodeInfo { + media_type: 'video' | 'image' +} + +export const batchGetDirTop4MediaInfo = async (paths: string[]) => { + const resp = await axiosInst.value.post('/batch_top_4_media_info', { paths }) + return resp.data as Dict +} + +export const setAppFeSetting = async (name: keyof GlobalConf['app_fe_setting'], setting: Record) => { + if (!isSync()) return + await axiosInst.value.post('/app_fe_setting', { name, value: JSON.stringify(setting) }) +} + +export const removeAppFeSetting = async (name: keyof GlobalConf['app_fe_setting']) => { + if (!isSync()) return + await axiosInst.value.delete('/app_fe_setting', { data: { name } }) +} + +export const setTargetFrameAsCover = async (body: {path: string, base64_img: string, updated_time: string}) => { + await axiosInst.value.post('/set_target_frame_as_video_cover', body) +} \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/api/type.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/api/type.ts new file mode 100644 index 0000000000000000000000000000000000000000..296dda8ec40b08de05948f0d6bd09cadda80359f --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/api/type.ts @@ -0,0 +1,31 @@ +export interface GlobalSettingPart { + outdir_samples: string + outdir_txt2img_samples: string + outdir_img2img_samples: string + outdir_extras_samples: string + outdir_grids: string + outdir_txt2img_grids: string + outdir_img2img_grids: string + outdir_save: string + dataset_filename_word_regex: string + dataset_filename_join_string: string + sd_model_checkpoint: string + sd_vae: string + img2img_background_color: string + deepbooru_filter_tags: string + sd_hypernetwork: string + font: string + quicksettings: string + ui_reorder: string + ui_extra_networks_tab_reorder: string + localization: string + show_progress_type: string + live_preview_content: string + ddim_discretize: string + sd_checkpoint_hash: string + sd_lora: string + control_net_model_config: string + control_net_model_adapter_config: string + control_net_models_path: string + additional_networks_extra_lora_path: string +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/BaseFileListInfo.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/BaseFileListInfo.vue new file mode 100644 index 0000000000000000000000000000000000000000..8613e0468e85405bb53c7cfbd99aeb0de15b838e --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/BaseFileListInfo.vue @@ -0,0 +1,23 @@ + + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/ChangeIndicator.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/ChangeIndicator.vue new file mode 100644 index 0000000000000000000000000000000000000000..82a3f345fc7f6c00017c6e220d3e39a7444d3675 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/ChangeIndicator.vue @@ -0,0 +1,313 @@ + + + + + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/ContextMenu.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/ContextMenu.vue new file mode 100644 index 0000000000000000000000000000000000000000..358698b9ac27773272861266ce408793130b1575 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/ContextMenu.vue @@ -0,0 +1,97 @@ + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/FileItem.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/FileItem.vue new file mode 100644 index 0000000000000000000000000000000000000000..28f1f5be8bdf04aeefebd52c8d5f15e26979a075 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/FileItem.vue @@ -0,0 +1,394 @@ + + + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/HistoryRecord.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/HistoryRecord.vue new file mode 100644 index 0000000000000000000000000000000000000000..fa6612cd2725ee24014af8dc629443a9a56c860e --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/HistoryRecord.vue @@ -0,0 +1,79 @@ + + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/MultiSelectKeep.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/MultiSelectKeep.vue new file mode 100644 index 0000000000000000000000000000000000000000..8e3913b8105fb1f411e9af469d34b6fd8e0252d3 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/MultiSelectKeep.vue @@ -0,0 +1,51 @@ + + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/functionalCallableComp.tsx b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/functionalCallableComp.tsx new file mode 100644 index 0000000000000000000000000000000000000000..8072a2f8dcbe2a7836ddebb3fddd48bf80575ca4 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/functionalCallableComp.tsx @@ -0,0 +1,185 @@ +import { Button, Input, Modal, message } from 'ant-design-vue' +import { StyleValue, ref } from 'vue' +import * as Path from '@/util/path' +import { FileNodeInfo, mkdirs } from '@/api/files' +import { setTargetFrameAsCover } from '@/api' +import { t } from '@/i18n' +import { downloadFiles, globalEvents, toRawFileUrl, toStreamVideoUrl } from '@/util' +import { DownloadOutlined } from '@/icon' +import { isStandalone } from '@/util/env' +import { addCustomTag, getDbBasicInfo, rebuildImageIndex, renameFile } from '@/api/db' +import { useTagStore } from '@/store/useTagStore' +import { useGlobalStore } from '@/store/useGlobalStore' +import { base64ToFile, video2base64 } from '@/util/video' + +export const openCreateFlodersModal = (base: string) => { + const floderName = ref('') + return new Promise((resolve) => { + Modal.confirm({ + title: t('inputFolderName'), + content: () => , + async onOk() { + if (!floderName.value) { + return + } + const dest = Path.join(base, floderName.value) + await mkdirs(dest) + resolve() + } + }) + }) +} + +export const MultiSelectTips = () => ( +

+ Tips: {t('multiSelectTips')} +

+) + +export const openVideoModal = (file: FileNodeInfo, onTagClick?: (id: string| number) => void) => { + const tagStore = useTagStore() + const global = useGlobalStore() + const isSelected = (id: string | number) => { + return !!tagStore.tagMap.get(file.fullpath)?.some(v => v.id === id) + } + const videoRef = ref(null) + const onSetCurrFrameAsVideoPoster = async () => { + if (!videoRef.value) { + return + } + const video = videoRef.value + video.pause() + const base64 = video2base64(video) + await setTargetFrameAsCover({ path: file.fullpath, base64_img: base64, updated_time: file.date } ) + file.cover_url = URL.createObjectURL(await base64ToFile(base64, 'cover')) + message.success(t('success') + '! ' + t('clearCacheIfNotTakeEffect')) + } + const tagBaseStyle: StyleValue = { + margin: '2px', + padding: '2px 16px', + 'border-radius': '4px', + display: 'inline-block', + cursor: 'pointer', + 'font-weight': 'bold', + transition: '.5s all ease', + 'user-select': 'none', + } + Modal.confirm({ + width: '80vw', + title: file.name, + icon: null, + content: () => ( +
+ +
+
+ { t('addNewCustomTag') } +
+ {global.conf!.all_custom_tags.map((tag) => +
onTagClick?.(tag.id)} style={{ + background: isSelected(tag.id) ? tagStore.getColor(tag) : 'var(--zp-primary-background)', + color: !isSelected(tag.id) ? tagStore.getColor(tag) : 'white', + border: `2px solid ${tagStore.getColor(tag)}`, + ...tagBaseStyle + }}> + { tag.name } +
)} +
+
+ + +
+
+ ), + maskClosable: true, + wrapClassName: 'hidden-antd-btns-modal' + }) +} + +export const openRebuildImageIndexModal = () => { + Modal.confirm({ + title: t('confirmRebuildImageIndex'), + onOk: async () => { + await rebuildImageIndex() + globalEvents.emit('searchIndexExpired') + message.success(t('rebuildComplete')) + } + }) +} + + +export const openRenameFileModal = (path: string) => { + const name = ref(path.split(/[\\/]/).pop() ?? '') + return new Promise((resolve) => { + Modal.confirm({ + title: t('rename'), + content: () => , + async onOk() { + if (!name.value) { + return + } + const resp = await renameFile({ path, name: name.value }) + resolve(resp.new_path) + } + }) + }) +} + + +export const openAddNewTagModal = () => { + const name = ref('') + const global = useGlobalStore() + return new Promise((resolve) => { + Modal.confirm({ + title: t('addNewCustomTag'), + content: () => , + async onOk() { + if (!name.value) { + return + } + const info = await getDbBasicInfo() + const tag = await addCustomTag({ tag_name: name.value }) + if (tag.type !== 'custom') { + message.error(t('existInOtherType')) + throw new Error(t('existInOtherType')) + } + if (info.tags.find((v) => v.id === tag.id)) { + message.error(t('alreadyExists')) + throw new Error(t('alreadyExists')) + } else { + global.conf?.all_custom_tags.push(tag) + message.success(t('success')) + } + resolve(name.value) + } + }) + }) +} + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/numInput.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/numInput.vue new file mode 100644 index 0000000000000000000000000000000000000000..8a95da86b00bce0b6f4e95130c63ef0007759207 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/components/numInput.vue @@ -0,0 +1,23 @@ + + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/defineExportFunc.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/defineExportFunc.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a100c698e3dee1eaea92c6941aec777f54780df --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/defineExportFunc.ts @@ -0,0 +1,86 @@ +import { GridViewFile, TabPane, useGlobalStore } from './store/useGlobalStore' +import { useTagStore } from './store/useTagStore' +import { Dict, globalEvents, switch2IIB } from './util' +import { uniqueId } from 'lodash-es' + +export const exportFn = async (g: ReturnType) => { + if (!g.conf?.export_fe_fn) { + return + } + const tag = useTagStore() + const insertTabPane = ({ + tabIdx = 0, + paneIdx = 0, + pane + }: { + tabIdx?: number + paneIdx?: number + pane: TabPane + }) => { + const tab = g.tabList[tabIdx] + if (!pane.key) { + (pane as any).key = uniqueId() + } + tab.panes.splice(paneIdx, 0, pane) + tab.key = pane.key + return { + key: pane.key, + ref: getPageRef(pane.key) + } + } + + define({ + insertTabPane, + getTabList: () => g.tabList, + getPageRef, + switch2IIB, + openIIBInNewTab: () => window.parent.open('/infinite_image_browsing'), + setTagColor(name: string, color: string) { + tag.colorCache.set(name, color) + }, + setTags(path: string, tags: string[]) { + tag.set(path, tags) + }, + getTags(path: string) { + return tag.tagMap.get(path) + }, + createGridViewFile(path: string, tags?: string[]): GridViewFile { + return { + name: path.split(/[/\\]/).pop() ?? '', + size: '-', + bytes: 0, + type: 'file', + created_time: '', + date: '', + fullpath: path, + tags: tags?.map((v) => ({ name: v })), + is_under_scanned_path: true + } + } + }) + + function getPageRef(key: string) { + return new Proxy( + {}, + { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + get(_target, p, _receiver) { + if (p === 'close') { + const tabIdx = g.tabList.findIndex((v) => v.panes.some((v) => v.key === key)) + return () => globalEvents.emit('closeTabPane', tabIdx, key) + } + return g.pageFuncExportMap.get(key)?.[p as string] + } + } + ) + } + + function define(funcs: Dict<(...args: any[]) => any>) { + const w = window as any + for (const key in funcs) { + w[key] = (...args: any) => { + return funcs[key](...args) + } + } + } +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/de.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/de.ts new file mode 100644 index 0000000000000000000000000000000000000000..87dd2226b737ed3481fb4c2c0f0b4a8130aefa40 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/de.ts @@ -0,0 +1,129 @@ +import type { IIBI18nMap } from '.' + +export const de: Partial = { + serverKeyRequired: + 'Für die weitere Nutzung ist die Eingabe eines Schlüssels erforderlich, der vom Server konfiguriert wurde.', + removeFromSearchScanPathAndQuickMove: 'Schnellzugriff entfernen', + addToSearchScanPathAndQuickMove: 'Schnellzugriff hinzufügen', + openWithLocalFileBrowser: 'Im lokalen Dateimanager öffnen', + 'fuzzy-search-noResults': 'Es wurde nichts gefunden', + 'fuzzy-search-placeholder': + 'Geben Sie einen Teil der Bildinformationen oder des Dateinamens ein, um passende Ergebnisse zu finden', + 'fuzzy-search': 'Schnellsuche', + autoUpdate: 'Erkannte Änderungen, automatische Aktualisierung wird ausgeführt', + faq: 'FAQ', + selectExactMatchTag: 'Wähle Tags für exakte Übereinstimmung aus', + selectAnyMatchTag: '(Optional) Wähle Tags für beliebige Übereinstimmung aus', + selectExcludeTag: '(Optional) Wähle Tags zum Ausschliessen aus', + exactMatch: 'Exakte Übereinstimmung', + anyMatch: 'Beliebige Übereinstimmung', + exclude: 'Ausschliessen', + 'auto.refreshed': 'Automatische Aktualisierung erfolgreich durchgeführt!', + copied: 'In die Zwischenablage kopiert!', + 'index.expired': 'Index abgelaufen, automatische Aktualisierung wird durchgeführt', + manualExitFullScreen: + 'Du hast das letzte Bild gelöscht und musst möglicherweise manuell den Vollbild-Vorschaumodus beenden', + 'walk-mode-move-message': + 'Im Walk-Modus ist das Verschieben des Verzeichnisses nur über \'Schnellzugriff\' gestattet', + refreshCompleted: 'Aktualisierung erfolgreich abgeschlossen', + addedTagToImage: 'Schlagwort wurde erfolgreich diesem Bild hinzugefügt', + removedTagFromImage: 'Schlagwort wurde von diesem Bild entfernt', + openContextMenu: 'Öffne das Kontextmenü', + copyPrompt: 'Kopiere Prompt-Konfiguration', + toggleTag: '(Favorite) Schlagwort hinzufügen/entfernen', + addCompleted: 'Hinzufügen abgeschlossen', + removeCompleted: 'Entfernen abgeschlossen', + existInOtherType: 'Bereits in anderem Typ vorhanden', + alreadyExists: 'Bereits vorhanden', + cancel: 'Abbrechen', + submit: 'Bestätigen', + add: 'Hinzufügen', + custom: 'Benutzerdefiniert', + needGenerateIdx: + 'Klicken Sie auf die Schaltfläche, um einen Index zur Bildersuche zu generieren. \n Dieser Vorgang kann einige Minuten in Anspruch nehmen.', + search: 'Suchen', + UpdateIndex: 'Index aktualisieren', + generateIndexHint: 'Index für die Bildersuche generieren', + Model: 'Modell', + Sampler: 'Sampler', + lora: 'LoRA', + size: 'Grösse', + pos: 'Positiver Prompt', + unknownSavedDir: + 'Das Speicherverzeichnis konnte nicht gefunden werden (Einstellung für das Speicherverzeichnis in der Konfiguration)', + errorOccurred: 'Ein Fehler ist aufgetreten', + useThumbnailPreview: 'Verwende Miniaturansichtsvorschau', + gridThumbnailWidth: 'Breite der Miniatur-Rasteransicht', + start: 'Start', + tip: 'Hinweis', + sortByDateAscending: 'Datum aufsteigend', + sortByDateDescending: 'Datum absteigend', + sortByCreatedDateAscending: 'Erstellungsdatum aufsteigend', + sortByCreatedDateDescending: 'Erstellungsdatum absteigend', + sortByNameAscending: 'Name aufsteigend', + sortByNameDescending: 'Name absteigend', + sortBySizeAscending: 'Grösse aufsteigend', + sortBySizeDescending: 'Grösse absteigend', + inputAddressAndPressEnter: 'Geben Sie die Adresse ein und drücken Sie Enter', + go: 'Los', + unknownError: 'Unbekannter Fehler aufgetreten', + loadingNextFolder: 'Lade Dateien aus dem nächsten Verzeichnis', + moveFailedCheckPath: 'Fehler beim Verschieben. Überprüfen Sie den eingegebenen Pfad.\n', + detailList: 'Detailübersicht', + previewGrid: 'Vorschau-Rasteransicht', + moveSelectedFilesTo: 'Ausgewählte Dateien verschieben nach', + confirm: 'Bestätigen', + download: 'Herunterladen', + local: 'Lokal', + sendImageFailed: + 'Fehler beim Senden des Bildes. Bitte kontaktieren Sie den Entwickler mit der Fehlermeldung aus der Konsole.', + confirmDelete: 'Sind Sie sicher, dass Sie dies löschen möchten?', + deleteSuccess: 'Erfolgreich gelöscht', + doubleClickToCopy: 'Doppelklick zum Kopieren', + root: 'Root', + drive: ' Laufwerk', + refresh: 'Aktualisieren', + quickMove: 'Schnellzugriff', + more: 'Mehr', + viewMode: 'Ansichtsmodus', + sortingMethod: 'Sortiermethode', + copyPath: 'Pfad kopieren', + deleteSelected: 'Löschen', + previewInNewWindow: 'In neuem Fenster öffnen', + copySourceFilePreviewLink: 'Kopiere Dateilink aus dem Verzeichnis', + viewGenerationInfo: 'Anzeige von Generierungsinformationen (Prompt, etc.)', + sendToTxt2img: 'Senden an Text-zu-Bild', + sendToImg2img: 'Senden an Bild-zu-Bild', + sendToInpaint: 'Senden an Inpaint', + sendToExtraFeatures: 'Senden an Extras', + sendToControlNet: 'Senden an ControlNet', + loadNextPage: 'Nächste Seite laden', + localFile: 'Lokale Datei', + globalSettings: 'Globale Einstellungen', + welcome: 'Willkommen', + openInNewWindow: 'In neuem Fenster öffnen', + restoreLastRecord: 'Letztes Verzeichnis wiederherstellen', + launch: 'Ausführen', + walkMode: 'Verwende den Walk-Modus, um Bilder zu durchsuchen', + recent: 'Kürzlich', + emptyStartPage: 'Leere Startseite', + t2i: 'Text-zu-Bild', + i2i: 'Bild-zu-Bild', + saveButtonSavesTo: 'Speichern', + extra: 'Extras', + gridImage: 'Rasterbild', + 'i2i-grid': 'Bild-zu-Bild Raster', + image: 'Bild', + 't2i-grid': 'Text-zu-Bild Raster', + workingFolder: 'Arbeitsordner', + lang: 'Sprache', + langChangeReload: 'Neuladen: Einige Änderungen erfordern ein Neuladen, um wirksam zu werden', + openOnTheRight: 'Rechts öffnen', + openInNewTab: 'In neuem Tab öffnen', + openWithWalkMode: 'Im Walk-Modus öffnen', + longPressOpenContextMenu: 'Langes Rechtsklicken zur Öffnung des Kontextmenüs unterstützen', + searchResults: 'Suchergebnisse', + imgSearch: 'Bildsuche', + send2savedDir: 'In den gespeicherten Ordner senden', + promptcompare: 'Prompts vergleichen', +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/en.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/en.ts new file mode 100644 index 0000000000000000000000000000000000000000..6436e6e103111e7a8da1e8d676be16e74fffe622 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/en.ts @@ -0,0 +1,319 @@ +import type { IIBI18nMap } from '.' + +export const en: IIBI18nMap = { + pathOnly: 'Path Only', + disableMaximize: 'Disable Maximize', + takeEffectAfterReloadPage: 'Take effect after reloading the page', + compressFile: 'Compress File', + packOnlyNotDownload: 'Pack Only, Not Download', + notAllowSingleCtrlOrShiftAsShortcut: '不允許使用單獨的 Ctrl 或者 Shift 作為快速鍵', + conflictWithOtherShortcuts: 'Conflict with other shortcuts', + pinnedSearchHistoryDesc: 'You can quickly restore to the previous search state by clicking the pinned search history.', + addNewCustomTag: 'Add New Custom Tag', + clearCacheIfNotTakeEffect: 'If the changes do not take effect, try clearing the page cache', + success: 'Success', + setCurrFrameAsVideoPoster: 'Set Current Frame as Video Cover', + sync: 'Sync', + syncDesc: 'When you need to achieve simple setting isolation between multiple devices or users, you can turn off this option. Most of the settings of IIB will only be saved to the current browser (isolation in the case of cross-domain), and will not be synchronized to the server.', + readonlyModeSettingPageDesc: 'You are currently in read-only mode. You can adjust the settings, but these changes will not be saved.', + syncHistoryToLocal: 'Sync History to Local', + showCommaInGenInfoPanel: 'Show Comma in Generation Info Panel', + walkModeAutoRefreshDisabled: 'Auto Refresh in Walk Mode Disabled', + disable: 'Disable', + autoRefresh: 'Auto Refresh', + autoRefreshNormalFixedMode: 'Enable Auto Refresh (Normal/Fixed Mode)', + autoRefreshWalkMode: 'Enable Auto Refresh (Walk Mode)', + autoRefreshWalkModePosLimit: 'Position Limit for Auto Refresh in Walk Mode', + pollInterval: 'Poll Interval', + pollRefresh: 'Polling refresh', + pollRefreshTip: 'By default, IIB will automatically refresh when you return to IIB from other tabs or when the visibility of IIB changes. This feature is designed to keep IIB refreshed even when you stay in IIB all the time, please use it with caution', + + stopPollRefresh: 'Stop Polling refresh', + restoreLastWorkspaceStateSuccess: 'Restore Last Workspace State Success', + restoreWorkspaceSnapshotSuccess: 'Restore Workspace Snapshot Success', + openOnAppStart: 'Open on app start', + confirmThisAction: 'Confirm this action?', + WorkspaceSnapshotDesc: `Using the Workspace Snapshot feature, you can save the current state of the workspace so that you can quickly restore to the current state the next time you open IIB. +You can specify which snapshot to restore to when starting IIB in the global settings page, or restore to the last workspace state before closing.`, + saveWorkspaceSnapshot: 'Save Workspace Snapshot', + WorkspaceSnapshot: 'Workspace Snapshot', + restoreLastWorkspaceState: 'Restore Last Workspace State', + restoreWorkspaceSnapshot: 'Restore Workspace Snapshot: {0}', + nameRequired: 'Name is required', + save: 'Save', + name: 'Name', + saveCompleted: 'Save completed', + openThisAppInNewWindow: 'Open IIB in a new window', + readonly: 'Read-only', + accessLimited: 'Access Limited', + selectFolder: 'Select Folder', + openFileLocationInNewTab: 'Open File Location in New Tab', + copyTo: 'Copy to', + moveTo: 'Move to', + moveSuccess: 'Move success', + copySuccess: 'Copy success', + copyFilePath: 'Copy file path', + + previewMaskBackgroundOpacity: 'Preview Mask Background Opacity', + experimentalLRLayout: 'Experimental Side-by-Side Layout', + width: 'Width', + alwaysOnTooltipInfo: 'If this is turned off, the info panel will be hidden until you move the mouse to the right side of the screen', + alwaysOn: 'Always On', + time: 'Time', + pin: 'Pin', + unpin: 'Unpin', + restore: 'Restore', + restoreFromHistory: 'Restore from History', + history: 'History', + historyRecordsSubstr: 'Input Value', + historyRecordsisRegex: 'Is Regex', + walkModeDoc: 'Browse all files in a specified folder without paging, using infinite scrolling to display them. DFS will be used to traverse all files. Note: Sorting is only performed within the same layer in this mode.', + normalModelDoc: 'Similar to the Windows file browser, with high flexibility. But exceptions may occur when accessing cloud storage or similar SMB.', + fixedModeDoc: 'Similar to Normal mode, but with faster initial page speed, better compatibility, and slightly less flexibility. If you encounter an exception in Normal mode, you can try this mode instead.', + type: 'Type', + filterByKeyword: 'Filter tags by keyword', + loadmore: 'Load more', + rename: 'Rename', + inputAlias: 'Input Alias', + addAliasCompleted: 'Add Alias Completed', + alias: 'Alias', + exit: 'Exit', + 'select-all': 'Select All', + 'rerverse-select': 'Reverse Select', + 'clear-all-selected': 'Clear All Selected', + 'keep-multi-selected': 'Keep Multi-selected', + 'Source Identifier': 'Source', + openWithDefaultApp: 'Open with default app', + saveSelectedAsJson: 'Save selected image info', + saveAllAsJson: 'Save all image info', + saveLoadedImageAsJson: 'Save loaded image info', + selectedItems: ' {0} selected', + items: '{0} items', + scrollDownToComparePrompt: 'Scroll down to compare prompts', + sourceText: 'Source Text', + structuredData: 'Structured Data', + searchScope: 'Search Scope', + specifiedSearchFolder: 'Specify the folders to search, separate multiple folders with commas or line breaks', + batchAddTag: 'Batch Add Tag', + batchRemoveTag: 'Batch Remove Tag', + imageCompareTips: + 'When dragging files, this panel will also appear, so you don\'t need to open the "Image Comparison" feature separately.', + dragToResizePanel: 'Drag to resize the panel', + clickToToggleMaximizeMinimize: 'Click to toggle maximize/minimize', + dragToMovePanel: 'Drag to move the panel', + privacyAndSecurity: 'Security & Privacy', + deleteOneOnlySkipConfirm: 'Do not confirm when deleting a single file', + resetOnGlobalSettingsPage: 'You can reset on the global settings page', + secretKeyMustBeConfigured: 'Secret Key must be configured', + secretKeyRequiredWarnMsg: `For security reasons, you must separately configure Secret Key for this extension, refer to the IIB_SECRET_KEY in the .env.example file under the root directory of this extension. + This error only appears when gradio-auth is configured.`, + remove: 'Remove', + batchDownload: 'Batch Download', + archive: 'Archive', + zipDownload: 'Download as ZIP', + batchDownloaDDragAndDropHint: + 'Use drag and drop or the \'Send to Batch Download\' option in the right-click menu to add images from other pages here. Multiple selections are supported.', + lyco: 'LyCORIS', + sendToThirdPartyExtension: 'Send to third-party extension', + createFolder: 'Create Folder', + inputFolderName: 'Input Folder Name', + desktop: 'Desktop', + move: 'Move', + majorUpdateCustomCellSizeTips: 'Major Update: You can now customize the size of the grid image. Adjust it in the global settings page or in the "More" menu in the upper right corner.', + ImageBrowsingSettings: 'Image Browsing Settings', + other: 'Other', + livePreview: 'Live Preview', + gridCellWidth: 'Grid Cell Width (px)', + showChangeIndicators: 'Show Change Indicators', + seedAsChange: 'Seed as Change', + defaultShowChangeIndicators: 'Default Show Change Indicators', + defaultSeedAsChange: 'Default Compare Seed as Change', + defaultGridCellWidth: 'Default Grid Cell Width (px)', + thumbnailResolution: 'Thumbnail Resolution (px)', + inputTargetFolderPath: 'Enter the absolute path of the target folder', + pathDoesNotExist: 'Path does not exist', + confirmToAddToExtraPath: + 'Are you sure you want to add? This may take a lot of time to index if the folder is large. ', + clientSpecificSettings: 'Client-specific settings', + initiateSoftwareStartupConfig: 'Initiate software startup configuration', + 'tauriLaunchConf.readSdWebuiConfigTitle': 'Read Stable Diffusion Webui Config', + 'tauriLaunchConf.readSdWebuiConfigDescription': + 'If you have installed sd-webui and this extension, it is recommended to use this option to directly read the configuration and share data.', + 'tauriLaunchConf.selectSdWebuiFolder': 'Click to select the SD-webui folder', + 'tauriLaunchConf.skipThisConfigTitle': 'Skip This Configuration', + 'tauriLaunchConf.skipThisConfigDescription': + 'All features will still be available and you can reset them in the settings page.', + 'tauriLaunchConf.skipButton': 'Skip', + 'tauriLaunchConfMessages.configNotFound': + 'Cannot find the corresponding configuration. Please check if the selected folder is correct.', + 'tauriLaunchConfMessages.folderNotFound': + 'Cannot find the corresponding folder. Please check if the selected folder is correct.', + 'tauriLaunchConfMessages.configCompletedMessage': + 'Configuration completed. The application will restart shortly.', + 'tauriLaunchConfMessages.firstTimeUserTitle': + 'It looks like this is your first time using the application. Some configuration is required.', + selectAll: 'Select All', + close: 'Close', + fileName: 'File Name', + resolution: 'Resolution', + fileSize: 'File Size', + fullscreenview: 'Fullscreen View', + promptcompare: 'Compare Prompts', + imgCompare: 'Image Comparison', + share: 'Share', + dragImageHere: 'Drag image here', + copyLocationUrlSuccessMsg: + 'Copy completed, you can directly open the current folder through the copied link', + multiSelectTips: + 'You can hold down the Shift, Ctrl, or Cmd key and then click on files to perform batch delete/move operations', + document: 'Document', + copy: 'Copy', + edit: 'Edit', + defaultSortingMethod: 'Default Sorting Method', + defaultViewMode: 'Default View Mode', + showPreviewImage: 'Show Preview Image', + dontShowAgain: 'Don\'t show again', + accessControlModeTips: + 'To ensure data security, you are currently running in access control mode, which only allows access to authorized folders. You can adjust the access permissions settings (IIB_ACCESS_CONTROL) by editing the .env file in the root directory of this extension. If the .env file does not exist, you can copy the .env.example file and rename it to .env.', + changlog: 'Change log', + clear: 'Clear', + toggleTagSelection: 'Toggle Selection of Tag "{tag}"', + fullscreenRestriction: + 'Due to technical limitations, the first image cannot be deleted when opening the Full-screen view.', + shortcutKey: 'Keyboard Shortcuts (Only Available in Full-screen view mode)', + shortcutKeyDescription: + 'Click on the input box and press the shortcut key you want to use, supporting combinations with Shift and Ctrl.', + serverKeyRequired: + 'The server has configured a key. You must provide the same key to continue using it.', + removeFromSearchScanPathAndQuickMove: 'Remove from Search Scan Path and Quick Move', + addToSearchScanPathAndQuickMove: 'Add to Search Scan Path', + openWithLocalFileBrowser: 'Open with Local File Browser', + 'fuzzy-search-noResults': 'Nothing was found', + 'fuzzy-search-placeholder': 'Enter a part of the image information or filename to search', + 'fuzzy-search': 'Fuzzy search', + autoUpdate: 'Detected changes, automatically updating', + faq: 'FAQ', + selectExactMatchTag: 'Select Exact Match Tags. You can search by entering partial characters', + selectAnyMatchTag: 'Optional, Select Any Match Tags. You can search by entering partial characters', + selectExcludeTag: 'Optional, Select Exclude Tags. You can search by entering partial characters', + exactMatch: 'Exact Match', + anyMatch: 'Match Any', + exclude: 'Exclude', + 'auto.refreshed': 'Auto refresh completed!', + copied: 'Copied!', + 'index.expired': 'Index expired, updating automatically', + manualExitFullScreen: + 'You have deleted the last image and may need to manually exit Full-screen view', + 'walk-mode-move-message': 'Moving position is only allowed using \'Quick Move\' in walk mode', + refreshCompleted: 'Refresh completed', + //! MissingTranslations + addedTagToImage: 'Tag "{tag}" has been added to this image', + removedTagFromImage: 'Tag "{tag}" has been removed from this image', + openContextMenu: 'Open context menu', + copyPrompt: 'Copy prompt', + copyPositivePrompt: 'Copy positive prompt', + toggleTag: 'Toggle Tag Selection (Favorite)', + addCompleted: 'Add completed', + removeCompleted: 'Remove Completed', + existInOtherType: 'Already exists in other type', + alreadyExists: 'Already exists', + cancel: 'Cancel', + submit: 'Submit', + add: 'Add', + custom: 'Custom', + needGenerateIdx: + 'You need to click the button to generate an index for searching images. \n This process may take a few minutes to complete.', + search: 'Search', + UpdateIndex: 'Update index', + generateIndexHint: 'Generate index for search image', + Model: 'Model', + Sampler: 'Sampler', + lora: 'LoRA', + size: 'Size', + pos: 'Positive Prompt', + unknownSavedDir: 'Cannot find the saved folder (outdir_save field in the config)', + errorOccurred: 'An error occurred', + useThumbnailPreview: 'Use thumbnail preview', + gridThumbnailWidth: 'Grid thumbnail width', + start: 'Start', + tip: 'Tip', + sortByDateAscending: 'Updated date ascending', + sortByDateDescending: 'UPdated date descending', + sortByCreatedDateAscending: 'Created date ascending', + sortByCreatedDateDescending: 'Created date descending', + sortByNameAscending: 'Name ascending', + sortByNameDescending: 'Name descending', + sortBySizeAscending: 'Size ascending', + sortBySizeDescending: 'Size descending', + inputAddressAndPressEnter: 'Input address and press Enter', + go: 'Go', + unknownError: 'Unknown error', + loadingNextFolder: 'Loading files from the next folder', + moveFailedCheckPath: 'Move failed. Check your path input.', + detailList: 'Detail list', + previewGrid: 'Preview grid', + moveSelectedFilesTo: 'Move / Copy selected files to', + confirm: 'Confirm', + download: 'Download', + local: 'Local', + sendImageFailed: + 'Failed to send image. Please contact the developer with the error message from the console.', + confirmDelete: 'Are you sure you want to delete?', + deleteSuccess: 'Deleted successfully', + doubleClickToCopy: 'Double-click to copy', + root: 'Root', + drive: ' drive', + refresh: 'Refresh', + quickMove: 'Quick move', + more: 'More', + viewMode: 'View mode', + sortingMethod: 'Sorting method', + copyPath: 'Copy path', + deleteSelected: 'Delete', + previewInNewWindow: 'Open in new window', + copySourceFilePreviewLink: 'Copy source file preview link', + viewGenerationInfo: 'View generation information (prompt, etc.)', + sendToTxt2img: 'Send to txt2img', + sendToImg2img: 'Send to img2img', + sendToInpaint: 'Send to Inpaint', + sendToBatchDownload: 'Send to BatchDownload', + sendToExtraFeatures: 'Send to Extra', + sendToControlNet: 'Send to ControlNet', + loadNextPage: 'Load next page', + localFile: 'Local file', + globalSettings: 'Global settings', + welcome: 'Welcome', + openInNewWindow: 'Open in new tab', + restoreLastRecord: 'Restore last record', + launch: 'Launch', + walkMode: 'Use Walk mode to browse images', + launchFromNormalAndFixed: 'Use Normal / Fixed mode to browse images', + recent: 'Recent', + emptyStartPage: 'Empty start page', + t2i: 'txt2img', + i2i: 'img2img', + saveButtonSavesTo: 'save', + extra: 'extras', + gridImage: 'Grid image', + 'i2i-grid': 'img2img grid', + image: 'Image', + 't2i-grid': 'txt2img grid', + workingFolder: 'working folder', + lang: 'Language', + langChangeReload: 'Reload: Some changes may require a reload to take effect', + openOnTheRight: 'Open to the Side', + openInNewTab: 'Open in a new tab', + openWithWalkMode: 'Open with Walk Mode', + longPressOpenContextMenu: 'Support long press to open right-click menu', + searchResults: 'Search Results', + imgSearch: 'Image Search', + onlyFoldersAndImages: 'Only show folders/images/videos', + send2savedDir: 'Send to saved folder', + regexSearchEnabledHint: + '(You can also enable regex search by clicking the regex icon on the right)', + rebuildImageIndex: 'Rebuild image index', + confirmRebuildImageIndex: 'Confirm rebuilding image index?', + rebuildComplete: 'Rebuild complete', + tagSearchNoResultsMessage: + 'It seems like no results were found. Try rebuilding the index to remove unused tags?' +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/index.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e8f3f9b94573ba2a40ba43891f058fe009ea50b --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/index.ts @@ -0,0 +1,42 @@ +import { createI18n } from 'vue-i18n' +import { zhHans } from './zh-hans' +import { en } from './en' +import { de } from './de' +import { zhHant } from './zh-hant' + +declare module 'vue' { + export interface ComponentCustomProperties { + $t(key: keyof IIBI18nMap, ...args: []): string + } +} + +export const getPreferredLang = () => { + const lang = navigator.language.toLowerCase() + if (lang.startsWith('zh')) { + return /hk|tw|mo/.test(lang) ? 'zhHant' : 'zhHans' + } + switch (lang) { + case 'de': + case 'de-de': + return 'de' + default: + return 'en' + } +} + +export const i18n = createI18n({ + locale: getPreferredLang(), + fallbackLocale: 'en', + messages: { + zhHans, + zhHant, + zh: zhHans, + en, + de + }, + legacy: false +}) + +export const { t, locale } = i18n.global + +export type IIBI18nMap = typeof zhHans diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/zh-hans.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/zh-hans.ts new file mode 100644 index 0000000000000000000000000000000000000000..7bc1e966294e119248f9a0b803d643978c277711 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/zh-hans.ts @@ -0,0 +1,298 @@ + +export const zhHans = { + pathOnly: '仅路径', + takeEffectAfterReloadPage: '更改将在重新加载页面后生效', + disableMaximize: '禁用最大化', + compressFile: '对文件压缩', + packOnlyNotDownload: '仅打包不下载', + notAllowSingleCtrlOrShiftAsShortcut: '不允许使用单独的 Ctrl 或者 Shift 作为快捷键', + conflictWithOtherShortcuts: '与其他快捷键冲突', + pinnedSearchHistoryDesc: '你可以通过点击置顶的搜索历史来快速还原到之前的搜索状态', + addNewCustomTag: '添加新的自定义标签', + clearCacheIfNotTakeEffect: '如果更改没有生效,请尝试清理页面缓存', + success: '成功', + setCurrFrameAsVideoPoster: '设置当前帧为视频封面', + sync: '同步', + syncDesc: '当你需要实现多设备或者多用户之间的简单设置隔离时你可以关闭这个选项, IIB的大部分设置将只会保存到当前浏览器上(跨域的情况下也是隔离),不会同步到服务器', + readonlyModeSettingPageDesc: '当前为只读模式,你可以调整调整设置,但这些更改不会被保存', + syncHistoryToLocal: '同步历史到本地', + showCommaInGenInfoPanel: '在生成信息面板中显示逗号', + walkModeAutoRefreshDisabled: 'Walk模式下自动刷新已停用', + disable: '停用', + autoRefresh: '自动刷新', + autoRefreshNormalFixedMode: '启用自动刷新 (Normal/Fixed模式)', + autoRefreshWalkMode: '启用自动刷新 (Walk模式)', + autoRefreshWalkModePosLimit: 'Walk模式下触发自动刷新的位置极限', + pollRefresh: '轮询刷新', + pollInterval: '轮询间隔', + stopPollRefresh: '停止轮询刷新', + pollRefreshTip: '默认情况下你从其他TAB返回IIB时或者IIB的可见性发生改变时IIB都会自动刷新。这个功能是为了让你一直呆在IIB内时他也能自动刷新,请慎重使用', + restoreLastWorkspaceStateSuccess: '成功恢复上次工作区状态', + restoreWorkspaceSnapshotSuccess: '成功恢复工作区快照', + openOnAppStart: '启动时打开', + confirmThisAction: '确认这个操作?', + saveWorkspaceSnapshot: '保存工作区快照', + WorkspaceSnapshot: '工作区快照', + restoreLastWorkspaceState: '恢复上次工作区状态', + restoreWorkspaceSnapshot: '恢复工作区快照: {0}', + WorkspaceSnapshotDesc: `使用工作区快照功能你可以保存当前工作区的状态,以便下次打开IIB时快速恢复到当前状态。 +你可以在全局设置页面中指定启动IIB时恢复到哪一个快照,或者恢复到最后关闭前的工作区状态。`, + nameRequired: '名称不能为空', + save: '保存', + name: '名称', + saveCompleted: '保存完成', + openThisAppInNewWindow: '在新窗口打开本应用', + readonly: '只读', + accessLimited: '访问受限', + selectFolder: '选择文件夹', + openFileLocationInNewTab: '在新标签页打开文件位置', + copyTo: '复制到', + moveTo: '移动到', + moveSuccess: '移动成功', + copySuccess: '复制成功', + copyFilePath: '复制文件路径', + previewMaskBackgroundOpacity: '预览遮罩背景透明度', + experimentalLRLayout: '实验性并列布局', + width: '宽度', + alwaysOnTooltipInfo: '若关闭此项,信息面板将收起,直至鼠标移动至屏幕右侧时才打开', + alwaysOn: '常驻', + time: '时间', + pin: '置顶', + unpin: '取消置顶', + restore: '还原', + restoreFromHistory: '从历史记录中恢复', + history: '历史记录', + historyRecordsSubstr: '输入值', + historyRecordsisRegex: '是否正则', + walkModeDoc: '无需翻页即可浏览指定文件夹下的所有文件,使用无限滚动的方式呈现。将会使用DFS的方式遍历所有文件. 注意:该模式下排序仅在同层之间进行', + normalModelDoc: '类似于windows的文件浏览器,拥有较高的灵活性. 但在访问云存储或者类似SMB这样的地方时可能会出现异常', + fixedModeDoc: '类似Normal模式,但页面初始速度更快,兼容性更好,灵活性稍差。在Normal模式下出现了异常的话都可以改用这个试试', + type: '类型', + filterByKeyword: '输入标签关键词过滤', + loadmore: '加载更多', + rename: '重命名', + inputAlias: '输入别名', + addAliasCompleted: '添加别名完成', + alias: '别名', + exit: '退出', + 'select-all': '全选', + 'rerverse-select': '反选', + 'clear-all-selected': '清除所有选择', + 'keep-multi-selected': '保留多选', + 'Source Identifier': '来源', + openWithDefaultApp: '使用默认应用打开', + saveSelectedAsJson: '保存选中图像信息', + saveAllAsJson: '保存所有图像信息', + saveLoadedImageAsJson: '保存已加载的图像信息', + items: '{0}个项目', + selectedItems: '已选择{0}个项目', + scrollDownToComparePrompt: '向下滚查看Prompt比较', + sourceText: '源文本', + structuredData: '结构化数据', + searchScope: '搜索范围', + specifiedSearchFolder: '指定搜索的文件夹,使用逗号或者换行分割多个', + batchAddTag: '批量添加Tag', + batchRemoveTag: '批量移除Tag', + errorOccurred: '发生了个错误', + useThumbnailPreview: '使用缩略图预览', + gridThumbnailWidth: '网格缩略图宽度', + start: '开始', + tip: '提示', + sortByDateAscending: '修改日期升序', + sortByDateDescending: '修改日期降序', + sortByCreatedDateAscending: '创建日期升序', + sortByCreatedDateDescending: '创建日期降序', + sortByNameAscending: '名称升序', + sortByNameDescending: '名称降序', + sortBySizeAscending: '大小升序', + sortBySizeDescending: '大小降序', + inputAddressAndPressEnter: '输入地址回车', + go: '前往', + unknownError: '未知错误', + loadingNextFolder: '即将加载下一个文件夹的文件', + moveFailedCheckPath: '移动失败,检查你的路径输入', + detailList: '详情列表', + previewGrid: '预览网格', + moveSelectedFilesTo: '下列文件 移动 / 复制 至', + confirm: '确定', + download: '下载', + local: '本地', + sendImageFailed: '发送图像失败,请携带console的错误消息找开发者', + confirmDelete: '确认删除?', + deleteSuccess: '删除成功', + doubleClickToCopy: '双击复制', + root: '根', + drive: '盘', + promptcompare: 'Compare Prompts', + refresh: '刷新', + quickMove: '快速移动', + more: '更多', + viewMode: '查看模式', + sortingMethod: '排序方法', + copyPath: '复制路径', + deleteSelected: '删除', + previewInNewWindow: '在新窗口预览', + copySourceFilePreviewLink: '复制源文件预览链接', + viewGenerationInfo: '查看生成信息(prompt等)', + sendToTxt2img: '发送到文生图', + sendToImg2img: '发送到图生图', + sendToInpaint: '发送到局部重绘', + sendToControlNet: '发送到ControlNet', + sendToBatchDownload: '发送到批量下载', + sendToExtraFeatures: '发送到附加功能', + loadNextPage: '加载下一页', + localFile: '本地文件', + globalSettings: '全局设置', + welcome: '欢迎', + openInNewWindow: '在新页面打开', + restoreLastRecord: '还原上次记录', + launch: '启动', + walkMode: '使用 Walk 模式浏览图片', + launchFromNormalAndFixed: '使用 Normal / Fixed 模式浏览图片', + recent: '最近', + emptyStartPage: '空启动页', + t2i: '文生图', + i2i: '图生图', + saveButtonSavesTo: '保存', + extra: '附加', + gridImage: '宫格图', + 'i2i-grid': '图生图宫格', + image: '图像', + 't2i-grid': '文生图宫格', + workingFolder: '工作文件夹', + lang: '语言', + langChangeReload: '重新加载: 一些变化可能需要在重新加载后生效', + openOnTheRight: '在右边打开', + openInNewTab: '在新标签打开', + openWithWalkMode: '使用 Walk 模式打开', + longPressOpenContextMenu: '支持使用长按打开右键菜单', + searchResults: '搜索结果', + imgSearch: '图像搜索', + onlyFoldersAndImages: '只显示文件夹/图像/视频', + send2savedDir: '发送到保存的文件夹', + unknownSavedDir: '找不到保存的文件夹(配置文件中的outdir_save字段)', + Model: '模型', + Sampler: '采样器', + lora: 'LoRA', + size: '尺寸', + pos: '正面提示', + generateIndexHint: '生成索引用于搜索图像', + UpdateIndex: '更新索引', + needGenerateIdx: '你需要先点击按钮生成索引用于搜索图像\n这个过程可能需要消耗几分钟', + search: '搜索', + custom: '自定义', + add: '新增', + cancel: '取消', + submit: '提交', + existInOtherType: '已存在于其他类型', + alreadyExists: '已存在', + toggleTag: '切换标签选中 (收藏)', + addCompleted: '添加完成', + removeCompleted: '删除完成', + addedTagToImage: '已添加标签 "{tag}" 到本图片', + removedTagFromImage: '已从本图片上移除 "{tag}" 标签', + openContextMenu: '打开上下文菜单', + copyPrompt: '复制提示', + copyPositivePrompt: '复制正向提示', + refreshCompleted: '刷新完成', + 'walk-mode-move-message': '在walk模式下仅允许使用“快速移动”移动位置', + manualExitFullScreen: '你删除了最后一张图片,也许需要你手动退出全屏查看', + copied: '已复制!', + 'index.expired': '索引过期,正在自动更新', + 'auto.refreshed': '自动刷新完成!', + exactMatch: '完全匹配', + anyMatch: '匹配任意', + exclude: '排除掉', + selectExactMatchTag: '选择完全匹配的 Tag。 您可以输入部分字符进行搜索', + selectAnyMatchTag: '可选,选择匹配其中一个或多个的 Tag。 您可以输入部分字符进行搜索', + selectExcludeTag: '可选,选择需要排除掉的 Tag。 您可以输入部分字符进行搜索', + faq: '常见问题', + autoUpdate: '检测到发生改变自动更新', + 'fuzzy-search': '模糊搜索', + 'fuzzy-search-placeholder': '输入图像信息或者文件名的一部分来进行搜索', + 'fuzzy-search-noResults': '什么都没找到', + openWithLocalFileBrowser: '使用本地文件浏览器打开', + addToSearchScanPathAndQuickMove: '添加到搜索扫描路径', + removeFromSearchScanPathAndQuickMove: '从搜索扫描路径和快速移动中移除', + serverKeyRequired: '服务器配置了密匙,你必须提供相同的密匙才能继续使用', + shortcutKey: '快捷键(仅允许在全屏查看下使用)', + shortcutKeyDescription: '点击输入框按下你想使用的按键,支持与Shift和Ctrl进行组合', + fullscreenRestriction: '受技术限制,当前拓展不允许删除打开全屏查看时的首张图片。', + clear: '清除', + toggleTagSelection: '切换 "{tag}" 标签选中', + changlog: '更新日志', + accessControlModeTips: + '为确保数据安全,您当前正以访问控制模式运行,仅能访问授权文件夹。您可以通过编辑本拓展根目录的下.env文件来调整访问权限设置 (IIB_ACCESS_CONTROL) .如果不存在.env文件, 你可以将.env.example文件复制并重命名为.env', + dontShowAgain: '不再显示', + defaultSortingMethod: '默认排序方法', + defaultViewMode: '默认查看模式', + showPreviewImage: '显示预览图', + copy: '复制', + edit: '编辑', + document: '文档', + multiSelectTips: '您可以按住 Shift、Ctrl 或 Cmd 键,然后单击文件来进行多选删除/移动操作', + copyLocationUrlSuccessMsg: '复制完成,你可以通过复制的链接直接打开当前文件夹', + share: '分享', + dragImageHere: '拖拽图像到这里', + imgCompare: '图像对比', + close: '关闭', + fullscreenview: '全屏查看', + fileName: '文件名', + resolution: '分辨率', + fileSize: '文件大小', + selectAll: '全选', + 'tauriLaunchConf.readSdWebuiConfigTitle': '读取Stable Diffusion Webui的配置', + 'tauriLaunchConf.readSdWebuiConfigDescription': + '如果你已经安装sd-webui,且在sd-webui内安装了本拓展,推荐直接使用这个,将直接读取配置并且数据共享', + 'tauriLaunchConf.selectSdWebuiFolder': '点击选择SD-webui的文件夹', + 'tauriLaunchConf.skipThisConfigTitle': '跳过本次配置', + 'tauriLaunchConf.skipThisConfigDescription': '所有功能仍将可用,你可以在设置页重置', + 'tauriLaunchConf.skipButton': '跳过', + 'tauriLaunchConfMessages.configNotFound': '找不到对应配置,检查选择的文件夹是否正确', + 'tauriLaunchConfMessages.folderNotFound': '找不到对应文件夹,检查选择的文件夹是否正确', + 'tauriLaunchConfMessages.configCompletedMessage': '配置完成,即将重启', + 'tauriLaunchConfMessages.firstTimeUserTitle': '看起来你好像是第一次使用, 需要进行一些配置', + inputTargetFolderPath: '输入目标文件夹的绝对路径', + pathDoesNotExist: '路径不存在', + confirmToAddToExtraPath: '确定添加?如果文件夹过大将会消耗过多时间建立索引。', + clientSpecificSettings: '客户端特有的设置', + initiateSoftwareStartupConfig: '初始化软件启动配置', + gridCellWidth: '网格单元宽度 (px)', + showChangeIndicators: '显示变更指示器', + seedAsChange: '将Seed也进行比较', + defaultShowChangeIndicators: '默认显示变更指示器', + defaultSeedAsChange: '默认将Seed也进行比较', + defaultGridCellWidth: '默认网格单元宽度 (px)', + thumbnailResolution: '缩略图分辨率 (px)', + livePreview: '实时预览', + other: '其他', + ImageBrowsingSettings: '图像浏览设置', + majorUpdateCustomCellSizeTips: '重大更新:你可以自定义网格图像的大小了,在全局设置页或者右上角的“更多”里面进行调整', + desktop: '桌面', + move: '移动', + inputFolderName: '输入文件夹名', + createFolder: '创建文件夹', + sendToThirdPartyExtension: '发送到第三方拓展', + lyco: 'LyCORIS', + batchDownloaDDragAndDropHint: + '使用拖拽或者右键菜单中的“发送到批量下载”将其他页面的图片添加到这里,支持多选', + zipDownload: '打包成zip下载', + archive: '归档', + batchDownload: '批量下载', + remove: '移除', + secretKeyRequiredWarnMsg: `为了安全考虑,你必须为本拓展单独配置Secret Key,具体参考本拓展根目录下的.env.example文件内的IIB_SECRET_KEY。 + 这项警告只会在配置了gradio-auth时出现`, + secretKeyMustBeConfigured: '必须配置Secret Key', + deleteOneOnlySkipConfirm: '删除单个文件时不进行确认', + resetOnGlobalSettingsPage: '你可以在全局设置页重置', + privacyAndSecurity: '安全与隐私', + dragToResizePanel: '按住并拖动来调整面板的大小', + clickToToggleMaximizeMinimize: '单击切换最大化/最小化', + dragToMovePanel: '按住并拖动来移动面板', + imageCompareTips: '拖拽文件时也会出现这个面板,可以不需要打开 “图像对比” 功能', + regexSearchEnabledHint: '(你也可以通过点击右侧的正则式图标来启用正则式搜索)', + confirmRebuildImageIndex: '确认重建图像索引?', + rebuildComplete: '重新构建完成', + rebuildImageIndex: '重新构建图像索引', + tagSearchNoResultsMessage: '看起来没匹配到任何结果,尝试通过重新构建索引来去掉无用的tag?' +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/zh-hant.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/zh-hant.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b5ad6af9325f3e0c8c138b2f7ee386fb5de8e03 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/i18n/zh-hant.ts @@ -0,0 +1,301 @@ +import type { IIBI18nMap } from '.' + +export const zhHant: Partial = { + pathOnly: '僅路徑', + disableMaximize: '禁用最大化', + takeEffectAfterReloadPage: '需要重新載入頁面才能生效', + compressFile: '對文件壓縮', + packOnlyNotDownload: '僅打包不下載', + notAllowSingleCtrlOrShiftAsShortcut: '不允許使用單獨的 Ctrl 或者 Shift 作為快速鍵', + conflictWithOtherShortcuts: '與其他快速鍵衝突', + pinnedSearchHistoryDesc: '你可以通過點擊置頂的搜索歷史來快速還原到之前的搜索狀態。', + addNewCustomTag: '添加新的自定義標籤', + clearCacheIfNotTakeEffect: '如果更改沒有生效,請嘗試清理頁面緩存', + success: '成功', + setCurrFrameAsVideoPoster: '設置當前幀為視頻封面', + sync: '同步', + syncDesc: '當你需要實現多設備或者多用戶之間的簡單設置隔離時你可以關閉這個選項, IIB的大部分設置將只會保存到當前瀏覽器上(跨域的情況下也是隔離),不會同步到服務器', + readonlyModeSettingPageDesc: '當前為只讀模式,你可以調整調整設置,但這些更改不會被保存', + syncHistoryToLocal: '同步歷史到本地', + showCommaInGenInfoPanel: '在生成信息面板中顯示逗號', + walkModeAutoRefreshDisabled: 'Walk模式下自動刷新已停用', + disable: '停用', + autoRefresh: '自動刷新', + autoRefreshNormalFixedMode: '啟用自動刷新 (Normal/Fixed模式)', + autoRefreshWalkMode: '啟用自動刷新 (Walk模式)', + autoRefreshWalkModePosLimit: 'Walk模式下觸發自動刷新的位置極限', + pollInterval: '輪詢間隔', + pollRefresh: '輪詢刷新', + stopPollRefresh: '停止輪詢刷新', + pollRefreshTip: '默認情況下你從其他TAB返回IIB時或者IIB的可見性發生改變時IIB都會自動刷新。這個功能是為了讓你一直呆在IIB內時他也能自動刷新,請慎重使用', + restoreLastWorkspaceStateSuccess: '成功恢復上次工作區狀態', + restoreWorkspaceSnapshotSuccess: '成功恢復工作區快照', + openOnAppStart: '啟動時打開', + confirmThisAction: '確認這個操作?', + WorkspaceSnapshotDesc: `使用工作區快照功能你可以保存當前工作區的狀態,以便下次打開IIB時快速恢復到當前狀態。 +你可以在全局設置頁面中指定啟動IIB時恢復到哪一個快照,或者恢復到最後關閉前的工作區狀態。`, + WorkspaceSnapshot: '工作區快照', + restoreLastWorkspaceState: '恢復上次工作區狀態', + restoreWorkspaceSnapshot: '恢復工作區快照: {0}', + saveWorkspaceSnapshot: '保存工作區快照', + save: '保存', + name: '名稱', + nameRequired: '名稱不能為空', + saveCompleted: '保存完成', + openThisAppInNewWindow: '在新窗口打開本應用', + readonly: '只讀', + accessLimited: '訪問受限', + selectFolder: '選擇文件夾', + openFileLocationInNewTab: '在新標籤頁打開文件位置', + copyTo: '複製到', + moveTo: '移動到', + moveSuccess: '移動成功', + copySuccess: '複製成功', + copyFilePath: '複製文件路徑', + + previewMaskBackgroundOpacity: '預覽遮罩背景透明度', + experimentalLRLayout: '實驗性並列布局', + width: '寬度', + alwaysOnTooltipInfo: '若關閉此項,信息面板將收起,直至滑鼠移動至屏幕右側時才打開', + alwaysOn: '常駐', + time: '時間', + pin: '置頂', + unpin: '取消置頂', + restore: '還原', + restoreFromHistory: '從歷史記錄中恢復', + history: '歷史記錄', + historyRecordsSubstr: '輸入值', + historyRecordsisRegex: '是否正則', + walkModeDoc: '無需翻頁即可瀏覽指定資料夾下的所有檔案,使用無限捲動的方式呈現。將會使用 DFS 的方式遍歷所有檔案. 注意:該模式下排序僅在同層之間進行', + normalModelDoc: '類似於 Windows 的檔案瀏覽器,擁有較高的靈活性. 但在訪問雲端儲存或者類似 SMB 這樣的地方時可能會出現異常', + fixedModeDoc: '類似 Normal 模式,但頁面初始速度更快,相容性更好,靈活性稍差。在 Normal 模式下出現了異常的話都可以改用這個試試', + type: '類型', + filterByKeyword: '輸入標籤關鍵詞過濾', + loadmore: '載入更多', + rename: '重命名', + inputAlias: '輸入別名', + addAliasCompleted: '添加別名完成', + alias: '別名', + showChangeIndicators: '顯示變更指示器', + seedAsChange: '將Seed也進行比較', + defaultShowChangeIndicators: '預設顯示變更指示器', + defaultSeedAsChange: '預設將Seed也進行比較', + exit: '退出', + 'select-all': '全選', + 'rerverse-select': '反選', + 'clear-all-selected': '清除所有選擇', + 'keep-multi-selected': '保留多選', + 'Source Identifier': '來源', + openWithDefaultApp: '使用預設應用程式開啟', + saveSelectedAsJson: '儲存選取的圖像資訊', + saveAllAsJson: '儲存所有圖像資訊', + saveLoadedImageAsJson: '儲存已載入的圖像資訊', + scrollDownToComparePrompt: '向下滾查看Prompt比較', + sourceText: '源文本', + structuredData: '結構化數據', + searchScope: '搜尋範圍', + specifiedSearchFolder: '指定搜尋的資料夾,使用逗號或換行分割多個', + batchAddTag: '批量添加Tag', + batchRemoveTag: '批量移除Tag', + errorOccurred: '發生了個錯誤', + useThumbnailPreview: '使用縮圖預覽', + gridThumbnailWidth: '網格縮圖寬度', + start: '開始', + tip: '提示', + sortByDateAscending: '修改日期昇序', + sortByDateDescending: '修改日期降序', + sortByCreatedDateAscending: '創建日期昇序', + sortByCreatedDateDescending: '創建日期降序', + sortByNameAscending: '名稱昇序', + sortByNameDescending: '名稱降序', + sortBySizeAscending: '大小昇序', + sortBySizeDescending: '大小降序', + inputAddressAndPressEnter: '輸入地址回車', + go: '前往', + unknownError: '未知錯誤', + loadingNextFolder: '即將載入下一個文件夾的文件', + moveFailedCheckPath: '移動失敗,檢查你的路徑輸入', + detailList: '詳情列表', + previewGrid: '預覽網格', + moveSelectedFilesTo: '下列文件 移動 / 複製 至', + confirm: '確定', + download: '下載', + local: '本地', + sendImageFailed: '發送圖像失敗,請攜帶console的錯誤訊息找開發者', + confirmDelete: '確認刪除?', + deleteSuccess: '刪除成功', + doubleClickToCopy: '雙擊複製', + promptcompare: 'Compare Prompts', + root: '根', + drive: '磁碟', + refresh: '重新整理', + quickMove: '快速移動', + more: '更多', + viewMode: '檢視模式', + sortingMethod: '排序方法', + copyPath: '複製路徑', + deleteSelected: '刪除', + previewInNewWindow: '在新窗口預覽', + copySourceFilePreviewLink: '複製源文件預覽連結', + viewGenerationInfo: '檢視生成信息(提示等)', + sendToTxt2img: '發送到文生圖', + sendToImg2img: '發送到圖生圖', + sendToInpaint: '發送到局部重繪', + sendToControlNet: '發送到ControlNet', + sendToBatchDownload: '發送到批量下載', + sendToExtraFeatures: '發送到附加功能', + loadNextPage: '載入下一頁', + localFile: '本地檔案', + globalSettings: '全域設定', + welcome: '歡迎', + openInNewWindow: '在新頁面打開', + restoreLastRecord: '還原上次記錄', + launch: '啟動', + walkMode: '使用 Walk 模式瀏覽圖片', + + launchFromNormalAndFixed: '使用 Normal / Fixed 模式瀏覽圖片', + recent: '最近', + emptyStartPage: '空啟動頁', + t2i: '文生圖', + i2i: '圖生圖', + saveButtonSavesTo: '儲存', + extra: '附加', + gridImage: '網格式圖', + 'i2i-grid': '圖生圖網格', + image: '圖片', + 't2i-grid': '文生圖網格', + workingFolder: '工作文件夾', + lang: '語言', + langChangeReload: '重新載入: 一些變化可能需要在重新載入後生效', + openOnTheRight: '在右邊打開', + openInNewTab: '在新分頁打開', + openWithWalkMode: '使用 Walk 模式打開', + longPressOpenContextMenu: '支持使用長按打開右鍵功能表', + searchResults: '搜尋結果', + imgSearch: '圖片搜尋', + onlyFoldersAndImages: '只顯示文件夾/圖片/視頻', + send2savedDir: '發送到儲存的文件夾', + unknownSavedDir: '找不到儲存的文件夾(配置文件中的outdir_save欄位)', + Model: '模型', + Sampler: '採樣器', + lora: 'LoRA', + size: '尺寸', + pos: '正面提示', + generateIndexHint: '生成索引用於搜尋圖片', + UpdateIndex: '更新索引', + needGenerateIdx: '你需要先點擊按鈕生成索引用於搜尋圖片\n這個過程可能需要消耗幾分鐘', + search: '搜尋', + custom: '自定義', + add: '新增', + cancel: '取消', + submit: '提交', + existInOtherType: '已存在於其他類型', + alreadyExists: '已存在', + toggleTag: '切換標籤選中 (收藏)', + addCompleted: '新增完成', + removeCompleted: '移除完成', + addedTagToImage: '已添加標籤 "{tag}" 到本圖片', + removedTagFromImage: '已從本圖片上移除 "{tag}" 標籤', + openContextMenu: '打開上下文功能表', + copyPrompt: '複製提示', + copyPositivePrompt: '複製正向提示', + refreshCompleted: '重新整理完成', + 'walk-mode-move-message': '在walk模式下僅允許使用“快速移動”移動位置', + manualExitFullScreen: '你刪除了最後一張圖片,也許需要你手動退出全螢幕檢視', + copied: '已複製!', + 'index.expired': '索引過期,正在自動更新', + 'auto.refreshed': '自動重新整理完成!', + exactMatch: '完全匹配', + anyMatch: '匹配任意', + exclude: '排除掉', + selectExactMatchTag: '選擇完全匹配的 Tag。 您可以輸入部分字符進行搜索', + selectAnyMatchTag: '可選,選擇匹配其中一個或多個的 Tag。 您可以輸入部分字符進行搜索', + selectExcludeTag: '可選,選擇需要排除掉的 Tag。 您可以輸入部分字符進行搜索', + faq: '常見問題', + autoUpdate: '檢測到發生改變自動更新', + 'fuzzy-search': '模糊搜尋', + 'fuzzy-search-placeholder': '輸入圖片信息或者文件名的一部分來進行搜尋', + 'fuzzy-search-noResults': '什麼都沒找到', + openWithLocalFileBrowser: '使用本地檔案瀏覽器打開', + addToSearchScanPathAndQuickMove: '加入搜尋掃描路徑', + removeFromSearchScanPathAndQuickMove: '從搜尋掃描路徑和快速移動中移除', + serverKeyRequired: '伺服器配置了密鑰,你必须提供相同的密鑰才能繼續使用', + shortcutKey: '快速鍵(僅允許在全螢幕檢視下使用)', + shortcutKeyDescription: '點擊輸入框按下你想使用的按鍵,支持與Shift和Ctrl進行組合', + fullscreenRestriction: '受技術限制,目前拓展不允許刪除打開全螢幕檢視時的首張圖片。', + clear: '清除', + toggleTagSelection: '切換 "{tag}" 標籤選中', + changlog: '更新紀錄', + accessControlModeTips: + '為確保數據安全,您目前正以訪問控制模式運行,僅能訪問授權文件夾。您可以通過編輯本拓展根目錄的下.env文件來調整訪問權限設置 (IIB_ACCESS_CONTROL) .如果不存在.env文件, 你可以將.env.example文件複製並重命名為.env', + dontShowAgain: '不再顯示', + defaultSortingMethod: '默認排序方法', + defaultViewMode: '默認檢視模式', + showPreviewImage: '顯示預覽圖', + copy: '複製', + edit: '編輯', + document: '文件', + multiSelectTips: '您可以按住Shift、Ctrl或 Cmd鍵,然後單擊文件來進行多選刪除/移動操作', + copyLocationUrlSuccessMsg: '複製完成,你可以通過複製的url直接打開目前文件夾', + share: '分享', + dragImageHere: '拖拽圖片到這裡', + imgCompare: '圖片對比', + close: '關閉', + fullscreenview: '全屏查看', + fileName: '文件名稱', + resolution: '解析度', + fileSize: '文件大小', + selectAll: '全選', + 'tauriLaunchConf.readSdWebuiConfigTitle': '讀取Stable Diffusion Webui的配置', + 'tauriLaunchConf.readSdWebuiConfigDescription': + '如果你已經安裝sd-webui,且在sd-webui內安裝了本拓展,推薦直接使用這個,將直接讀取配置並且數據共享', + 'tauriLaunchConf.selectSdWebuiFolder': '點擊選擇SD-webui的文件夾', + 'tauriLaunchConf.skipThisConfigTitle': '跳過本次配置', + 'tauriLaunchConf.skipThisConfigDescription': '所有功能仍將可用,你可以在設置頁重置', + 'tauriLaunchConf.skipButton': '跳過', + 'tauriLaunchConfMessages.configNotFound': '找不到對應配置,檢查選擇的文件夾是否正確', + 'tauriLaunchConfMessages.folderNotFound': '找不到對應文件夾,檢查選擇的文件夾是否正確', + 'tauriLaunchConfMessages.configCompletedMessage': '配置完成,即將重啟', + 'tauriLaunchConfMessages.firstTimeUserTitle': '看起來你好像是第一次使用,需要進行一些配置', + inputTargetFolderPath: '輸入目標文件夾的絕對路徑', + pathDoesNotExist: '路徑不存在', + confirmToAddToExtraPath: '確定添加?如果文件夾過大將會消耗過多時間建立索引。', + clientSpecificSettings: '客戶端特有的設置', + initiateSoftwareStartupConfig: '初始化軟件啟動配置', + gridCellWidth: '網格單元寬度 (px)', + defaultGridCellWidth: '默認網格單元寬度 (px)', + thumbnailResolution: '縮圖解析度 (px)', + livePreview: '實時預覽', + other: '其他', + + ImageBrowsingSettings: '圖片瀏覽設置', + majorUpdateCustomCellSizeTips: + '重大更新:你可以自定義網格圖像的大小了,在全域設置頁或者右上角的“更多”裡面進行調整', + desktop: '桌面', + move: '移動', + inputFolderName: '輸入文件夾名稱', + createFolder: '新增文件夾', + sendToThirdPartyExtension: '發送到第三方拓展', + lyco: 'LyCORIS', + batchDownloaDDragAndDropHint: + '使用拖拽或者右鍵功能表中的“發送到批量下載”將其他頁面的圖片添加到這裡,支持多選', + zipDownload: '打包成zip下載', + archive: '歸檔', + batchDownload: '批量下載', + remove: '移除', + secretKeyRequiredWarnMsg: + '為了安全考慮,你必須為本拓展單獨配置Secret Key,具體參考本拓展根目錄下的.env.example文件內的IIB_SECRET_KEY。 這項警告只會在配置了gradio-auth時出現', + secretKeyMustBeConfigured: '必須配置Secret Key', + deleteOneOnlySkipConfirm: '刪除單個文件時不進行確認', + resetOnGlobalSettingsPage: '你可以在全域設置頁重置', + privacyAndSecurity: '安全與隱私', + dragToResizePanel: '按住並拖動來調整面板的大小', + clickToToggleMaximizeMinimize: '單擊切換最大化/最小化', + dragToMovePanel: '按住並拖動來移動面板', + imageCompareTips: '拖拽文件時也會出現這個面板,可以不需要打開 “圖片對比” 功能', + regexSearchEnabledHint: '(你也可以通過點擊右側的正則式圖標來啟用正則式搜索)', + confirmRebuildImageIndex: '確認重建圖像索引?', + rebuildImageIndex: '重新構建圖像索引', + rebuildComplete: '重新構建完成', + tagSearchNoResultsMessage: '看起來沒有匹配到任何結果,嘗試通過重新構建索引來去除無用的標籤?' +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/icon/fullscreen.svg b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/icon/fullscreen.svg new file mode 100644 index 0000000000000000000000000000000000000000..c8120a42ebc166048f6f57812ebd40e882dc5ae0 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/icon/fullscreen.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/icon/index.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/icon/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fc2a9c37a5b588515fe87d538e4c04f6275360e --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/icon/index.ts @@ -0,0 +1,10 @@ +export * from '@ant-design/icons-vue' +import regex from './regex.svg' +import play from './play.svg' +import fullscreen from './fullscreen.svg' + +export { + regex, + play, + fullscreen +} \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/icon/play.svg b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/icon/play.svg new file mode 100644 index 0000000000000000000000000000000000000000..fc435ac4fd852f46f5bca73e6748cebdafcbb0a1 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/icon/play.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/icon/regex.svg b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/icon/regex.svg new file mode 100644 index 0000000000000000000000000000000000000000..bbc569e3f3a19e78c7c6f60a90867cd755bcf4ba --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/icon/regex.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/index.scss b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/index.scss new file mode 100644 index 0000000000000000000000000000000000000000..8cf80d72df27acc3b07830ce42af5c0e6086b5aa --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/index.scss @@ -0,0 +1,253 @@ +$primary-color: #d03f0a; +$danger-color: #fa114f; +$info-color: #17a2b8; +$success-color: #28a745; +:root { + // ganymede的 + --grey-13: #000000; + --grey-12: #141414; + --grey-11: #1f1f1f; + --grey-10: #262626; + --grey-9: #434343; + --grey-8: #595959; + --grey-7: #8c8c8c; + --grey-6: #bfbfbf; + --grey-5: #d9d9d9; + --grey-4: #f0f0f0; + --grey-3: #f5f5f5; + --grey-2: #fafafa; + --grey-1: #fff; + --primary-color: #{$primary-color}; + --danger-color: #{$danger-color}; + --info-color: #{$info-color}; + --success-color: #{$success-color}; + // css变量尝试了没办法直接for + --primary-color-1: #{$primary-color}11; + --primary-color-2: #{$primary-color}22; + --primary-color-3: #{$primary-color}33; + --primary-color-4: #{$primary-color}44; + --primary-color-5: #{$primary-color}55; + --primary-color-6: #{$primary-color}66; + --primary-color-7: #{$primary-color}77; + --primary-color-8: #{$primary-color}88; + --primary-color-9: #{$primary-color}99; + --primary-color-a: #{$primary-color}aa; + --primary-color-b: #{$primary-color}bb; + --primary-color-c: #{$primary-color}cc; + --primary-color-d: #{$primary-color}dd; + --primary-color-e: #{$primary-color}ee; + --primary-color-f: #{$primary-color}ff; + --light-border-color: var(--grey-5); + --main-text-color: var(--grey-11); + --main-bg-color: var(--grey-3); + --zp-black: #222222; + --zp-grey96: #2b2b2b; + --zp-grey90: #383838; + --zp-grey80: #4e4e4e; + --zp-grey70: #646464; + --zp-grey60: #7a7a7a; + --zp-grey50: #909090; + --zp-grey40: #a7a7a7; + --zp-grey30: #bdbdbd; + --zp-grey20: #d3d3d3; + --zp-grey10: #e9e9e9; + --zp-grey7: #f0f0f0; + --zp-grey4: #f6f6f6; + --zp-white: #ffffff; + --zp-primary: var(--zp-black); + --zp-secondary: var(--zp-grey50); + --zp-tertiary: var(--zp-grey30); + --zp-primary-background: var(--zp-white); + --zp-secondary-background: var(--zp-grey4); + --zp-tertiary-background: var(--zp-white); + --zp-secondary-variant-background: var(--zp-grey7); + --zp-luminous-blue:#0069ff; + --zp-luminous-blue-deep:#0069ff3d; + --zp-luminous-green:#29f56d; + --zp-luminous-green-deep:#28f5213d; + --zp-luminous: var(--zp-luminous-blue); + --zp-luminous-deep: var(--zp-luminous-blue-deep); + --zp-brand-primary: var(--primary-color); + // 边框颜色 + --zp-border: var(--zp-grey20); + --zp-icon-bg: #0004; + @media (prefers-color-scheme: dark) { + .body:not(.dark) { + --zp-primary: var(--zp-grey20); + --zp-secondary: var(--zp-grey60); + --zp-tertiary: var(--zp-grey70); + --zp-primary-background: var(--zp-black); + --zp-secondary-background: var(--zp-grey96); + --zp-secondary-variant-background: var(--zp-grey90); + --zp-tertiary-background: var(--zp-grey4); + --zp-border: var(--zp-grey96); + --zp-icon-bg: #fff4; + --zp-luminous: var(--zp-luminous-green); + --zp-luminous-deep: var(--zp-luminous-green-deep); + --zp-brand-primary: #1890ff; + } + } + body.dark { + --zp-primary: var(--zp-grey20); + --zp-secondary: var(--zp-grey60); + --zp-tertiary: var(--zp-grey70); + --zp-primary-background: var(--zp-black); + --zp-secondary-background: var(--zp-grey96); + --zp-secondary-variant-background: var(--zp-grey90); + --zp-tertiary-background: var(--zp-grey4); + --zp-border: var(--zp-grey96); + --zp-icon-bg: #fff4; + + --zp-luminous: var(--zp-luminous-green); + --zp-luminous-deep: var(--zp-luminous-green-deep); + + --zp-brand-primary: #1890ff; + } +} + +.flex-placeholder, +[flex-placeholder] { + flex: 1; +} + +html { + position: relative; + display: inline-block; + width: 100%; + --scroll-container-max-height: 100vh; +} + +body { + position: absolute; + width: 100%; + ::-webkit-scrollbar { + width: 10px; // 滚动条宽度 + background-color: var(--zp-secondary-variant-background); // 滚动条背景颜色 + } + + ::-webkit-scrollbar-thumb { + background-color: var(--zp-secondary); // 滚动条拖动块颜色 + border-radius: 5px; // 滚动条拖动块圆角 + } + + ::-webkit-scrollbar-thumb:hover { + background-color: #1453ad; // 滚动条拖动块悬停颜色 + } + + ::-webkit-scrollbar-track { + background-color: var(--zp-secondary-variant-background); // 滚动条轨道颜色 + } + + ::-webkit-scrollbar-track:hover { + background-color: var(--zp-secondary-background); // 滚动条轨道悬停颜色 + } + background: var(--zp-primary-background); + color: var(--zp-primary); + .ant-tabs > div.ant-tabs-nav { + margin: 0; + } + .ant-modal-wrap,.ant-message, .ant-tooltip { + z-index: 10000; + } + + .hidden-antd-btns-modal .ant-modal-confirm-btns { + display: none; + } +} + +@mixin line-clamp($n: 1) { + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: $n; + overflow: hidden; +} +.line-clamp-1 { + @include line-clamp(1); +} +.line-clamp-2 { + @include line-clamp(2); +} +.line-clamp-3 { + @include line-clamp(3); +} + +.actions { + & > * { + margin-right: 8px; + } +} + +.tips { + background: var(--zp-secondary-background); + padding: 8px; + border-left: 4px solid var(--primary-color); +} + +ul.ant-dropdown-menu { + max-height:80vh; + overflow: auto; +} + +.ant-tabs-tab-active { + &::after { + content: ''; + position: absolute; + left: 0; + right: 0; + bottom: 0; + height: 2px; + background: var(--zp-brand-primary); + } +} + +.fullscreen-lr-layout +.ant-image-preview-root { + .ant-image-preview-mask, .ant-image-preview-wrap { + right: var(--iib-lr-layout-container-offset); + } +} + + +.ant-image-preview-root { + .ant-image-preview-mask { + background-color: var(--iib-preview-mask-bg, rgba(0, 0, 0, 0.6)); + } +} + +.preview-switch { + position: fixed; + top: 0; + bottom: 0; + left: 0; + right: var(--iib-lr-layout-container-offset, 0); + display: flex; + align-items: center; + justify-content: space-between; + z-index: 11111; + pointer-events: none; + + &>* { + color: white; + margin: 16px; + font-size: 4em; + pointer-events: all; + cursor: pointer; + + &.disable { + opacity: 0; + pointer-events: none; + cursor: none; + } + } +} + +.uni-desc { + border-left: 2px solid var(--primary-color); + background: var(--zp-primary-background); + padding: 8px; + white-space: pre-wrap; + color: var(--zp-secondary); + &.primary-bg { + background: var(--primary-color-1); + } +} diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/main.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/main.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa1833a33b453dfc17adb6a6b782b9f9d0ed85f8 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/main.ts @@ -0,0 +1,25 @@ +import { createApp } from 'vue' +import type {} from 'antd-vue-volar' +// @ts-ignore +import App from './App.vue' +import 'ant-design-vue/es/message/style' +import 'ant-design-vue/es/notification/style' +import 'ant-design-vue/es/modal/style' +import './index.scss' +import { createPinia } from 'pinia' +import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' +import { i18n } from './i18n' +import VueDiff from 'vue-diff' + +import 'vue-diff/dist/index.css'; + +const pinia = createPinia() +pinia.use(piniaPluginPersistedstate) +createApp(App) + .use(pinia) + .use(i18n) + .use(VueDiff, { + componentName: 'VueDiff', + }) + .mount('#zanllp_dev_gradio_fe') + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/DraggingPort.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/DraggingPort.vue new file mode 100644 index 0000000000000000000000000000000000000000..2357f2794cbee743f3e4200b3fd6a4ab604d4d22 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/DraggingPort.vue @@ -0,0 +1,149 @@ + + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/ImgSliComparePane.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/ImgSliComparePane.vue new file mode 100644 index 0000000000000000000000000000000000000000..3d5879f8ff50ef47ec89a1fd5799575a61339de4 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/ImgSliComparePane.vue @@ -0,0 +1,102 @@ + + + + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/ImgSliDrawer.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/ImgSliDrawer.vue new file mode 100644 index 0000000000000000000000000000000000000000..8f2cd7f54657cfd608f1370897b91f63f9af4627 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/ImgSliDrawer.vue @@ -0,0 +1,54 @@ + + + + + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/ImgSliPagePane.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/ImgSliPagePane.vue new file mode 100644 index 0000000000000000000000000000000000000000..2d8915f5a230b300f392747aa667ab23ca0017aa --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/ImgSliPagePane.vue @@ -0,0 +1,24 @@ + + + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/ImgSliSide.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/ImgSliSide.vue new file mode 100644 index 0000000000000000000000000000000000000000..e6a6d6a09facea23ca4e9cf2b901b56c3642c73e --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/ImgSliSide.vue @@ -0,0 +1,58 @@ + + + + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/PromptCompare.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/PromptCompare.vue new file mode 100644 index 0000000000000000000000000000000000000000..d2c73b77f45d5e4fe09f51c266079d7b721fede6 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/ImgSli/PromptCompare.vue @@ -0,0 +1,93 @@ + + + + + \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/SplitViewTab.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/SplitViewTab.vue new file mode 100644 index 0000000000000000000000000000000000000000..98eddeb2d39d1cad25326904bf8dab00069a81db --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/SplitViewTab.vue @@ -0,0 +1,135 @@ + + + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/actionContextMenu.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/actionContextMenu.vue new file mode 100644 index 0000000000000000000000000000000000000000..9d7aea99b900a4ddddf983c3b76cc5785c98f928 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/actionContextMenu.vue @@ -0,0 +1,29 @@ + + + + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/edgeTrigger.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/edgeTrigger.vue new file mode 100644 index 0000000000000000000000000000000000000000..c6e60d91ed3a39032997c16878dfdb33ea4a79f2 --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/edgeTrigger.vue @@ -0,0 +1,95 @@ + + + + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/emptyStartup.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/emptyStartup.vue new file mode 100644 index 0000000000000000000000000000000000000000..2ceb76aa4459f0064b63e5184c76a9021a4223db --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/emptyStartup.vue @@ -0,0 +1,466 @@ + + + + diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/extraPathControlFunc.ts b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/extraPathControlFunc.ts new file mode 100644 index 0000000000000000000000000000000000000000..5dd0cc0cbf413732b5c41da8a15255eadb361f1c --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/SplitViewTab/extraPathControlFunc.ts @@ -0,0 +1,127 @@ + +import { ExtraPathType, addExtraPath, aliasExtraPath, removeExtraPath } from '@/api/db' +import { globalEvents } from '@/util' +import { Input, Modal, RadioButton, RadioGroup, message, Button } from 'ant-design-vue' +import { open } from '@tauri-apps/api/dialog' +import { checkPathExists } from '@/api' +import { h, ref } from 'vue' +import { t } from '@/i18n' +import { useGlobalStore } from '@/store/useGlobalStore' +import { isTauri } from '@/util/env' + + + +export const addToExtraPath = async (initType: ExtraPathType, initPath?: string) => { + const g = useGlobalStore() + const path = ref(initPath ?? '') + + const type = ref(initType) + const openToSelectPath = async () => { + const ret = await open({ directory: true, defaultPath: initPath }) + if (typeof ret === 'string') { + path.value = ret + } else { + return + } + } + path.value = await new Promise((resolve) => { + Modal.confirm({ + title: t('inputTargetFolderPath'), + width: '800px', + content: () => { + return h('div', [ + g.conf?.enable_access_control ? h('a', { + style: { + 'word-break': 'break-all', + 'margin-bottom': '4px', + display: 'block' + }, + target: '_blank', + href: 'https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/518' + }, 'Please open this link first (Access Control mode only)') : '', + isTauri ? h(Button, { onClick: openToSelectPath, style: { margin: '4px 0' } } , t('selectFolder') ): '', + h(Input, { + value: path.value, + 'onUpdate:value': (v: string) => (path.value = v) + }), + h('div', [ + h('span', t('type')+': '), + h(RadioGroup, { + value: type.value, + 'onUpdate:value': (v: ExtraPathType) => (type.value = v), + buttonStyle: 'solid', + style: { margin: '16px 0 32px' } + }, [ + h(RadioButton, { value: 'walk' }, 'Walk'), + h(RadioButton, { value: 'scanned' }, 'Normal'), + h(RadioButton, { value: 'scanned-fixed' }, 'Fixed') + ]) + ]), + h('p', 'Walk: '+ t('walkModeDoc')), + h('p', 'Normal: '+ t('normalModelDoc')), + h('p', 'Fixed: '+ t('fixedModeDoc')) + ]) + }, + async onOk () { + if (!path.value) { + message.error(t('pathIsEmpty')) + throw new Error('pathIsEmpty') + } + const res = await checkPathExists([path.value]) + if (res[path.value]) { + resolve(path.value) + } else { + message.error(t('pathDoesNotExist')) + } + } + }) + }) + Modal.confirm({ + content: t('confirmToAddToExtraPath'), + async onOk () { + await addExtraPath({ types: [type.value], path: path.value }) + message.success(t('addCompleted')) + globalEvents.emit('searchIndexExpired') + globalEvents.emit('updateGlobalSetting') + } + }) +} + +export const onRemoveExtraPathClick = (path: string, type: ExtraPathType) => { + Modal.confirm({ + content: t('confirmDelete'), + closable: true, + async onOk () { + await removeExtraPath({ types: [type], path }) + message.success(t('removeCompleted')) + globalEvents.emit('searchIndexExpired') + globalEvents.emit('updateGlobalSetting') + } + }) +} + +export const onAliasExtraPathClick = (path: string) => { + const alias = ref('') + Modal.confirm({ + title: t('inputAlias'), + content: () => { + return h('div', [ + h('div', { + style: { + 'word-break': 'break-all', + 'margin-bottom': '4px' + } + }, 'Path: ' + path), + h(Input, { + value: alias.value, + 'onUpdate:value': (v: string) => (alias.value = v) + })] + ) + }, + async onOk () { + await aliasExtraPath({ alias: alias.value, path }) + message.success(t('addAliasCompleted')) + globalEvents.emit('updateGlobalSetting') + } + }) +} \ No newline at end of file diff --git a/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/TagSearch/MatchedImageGrid.vue b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/TagSearch/MatchedImageGrid.vue new file mode 100644 index 0000000000000000000000000000000000000000..1b4b8895d4d27854847b8079823629a77dd9a0ce --- /dev/null +++ b/extensions-builtin/sd-webui-infinite-image-browsing-main/vue/src/page/TagSearch/MatchedImageGrid.vue @@ -0,0 +1,208 @@ + +