Compare commits

..

1 Commits
main ... cf

Author SHA1 Message Date
7417c1af48 changelog 2023-06-03 10:02:34 +05:30
81 changed files with 2496 additions and 11564 deletions

2
.github/FUNDING.yml vendored
View File

@ -1,3 +1,3 @@
# These are supported funding model platforms
ko_fi: easydiffusion
ko_fi: cmdr2_stablediffusion_ui

4
.gitignore vendored
View File

@ -3,6 +3,4 @@ installer
installer.tar
dist
.idea/*
node_modules/*
.tmp1
.tmp2
node_modules/*

View File

@ -712,411 +712,3 @@ FileSaver.js is licensed under the MIT license:
SOFTWARE.
[1]: http://eligrey.com
croppr.js
=========
https://github.com/jamesssooi/Croppr.js
croppr.js is licensed under the MIT license:
MIT License
Copyright (c) 2017 James Ooi
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.
ExifReader
==========
https://github.com/mattiasw/ExifReader
ExifReader is licensed under the Mozilla Public License:
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View File

@ -1,61 +1,5 @@
# What's new?
## v3.0
### Major Changes
- **ControlNet** - Full support for ControlNet, with native integration of the common ControlNet models. Just select a control image, then choose the ControlNet filter/model and run. No additional configuration or download necessary. Supports custom ControlNets as well.
- **SDXL** - Full support for SDXL. No configuration necessary, just put the SDXL model in the `models/stable-diffusion` folder.
- **Multiple LoRAs** - Use multiple LoRAs, including SDXL and SD2-compatible LoRAs. Put them in the `models/lora` folder.
- **Embeddings** - Use textual inversion embeddings easily, by putting them in the `models/embeddings` folder and using their names in the prompt (or by clicking the `+ Embeddings` button to select embeddings visually). Thanks @JeLuf.
- **Seamless Tiling** - Generate repeating textures that can be useful for games and other art projects. Works best in 512x512 resolution. Thanks @JeLuf.
- **Inpainting Models** - Full support for inpainting models, including custom inpainting models. No configuration (or yaml files) necessary.
- **Faster than v2.5** - Nearly 40% faster than Easy Diffusion v2.5, and can be even faster if you enable xFormers.
- **Even less VRAM usage** - Less than 2 GB for 512x512 images on 'low' VRAM usage setting (SD 1.5). Can generate large images with SDXL.
- **WebP images** - Supports saving images in the lossless webp format.
- **Undo/Redo in the UI** - Remove tasks or images from the queue easily, and undo the action if you removed anything accidentally. Thanks @JeLuf.
- **Three new samplers, and latent upscaler** - Added `DEIS`, `DDPM` and `DPM++ 2m SDE` as additional samplers. Thanks @ogmaresca and @rbertus2000.
- **Significantly faster 'Upscale' and 'Fix Faces' buttons on the images**
- **Major rewrite of the code** - We've switched to using diffusers under-the-hood, which allows us to release new features faster, and focus on making the UI and installer even easier to use.
### Detailed changelog
* 3.0.9c - 6 Feb 2025 - (Internal code change) Remove hardcoded references to `torch.cuda`, and replace with torchruntime's device utilities.
* 3.0.9b - 28 Jan 2025 - Fix a bug affecting older versions of Easy Diffusion, which tried to upgrade to an incompatible version of PyTorch.
* 3.0.9b - 4 Jan 2025 - Replace the use of WMIC (deprecated) with a powershell call.
* 3.0.9 - 28 May 2024 - Slider for controlling the strength of controlnets.
* 3.0.8 - 27 May 2024 - SDXL ControlNets for Img2Img and Inpainting.
* 3.0.7 - 11 Dec 2023 - Setting to enable/disable VAE tiling (in the Image Settings panel). Sometimes VAE tiling reduces the quality of the image, so this setting will help control that.
* 3.0.6 - 18 Sep 2023 - Add thumbnails to embeddings from the UI, using the new `Upload Thumbnail` button in the Embeddings popup. Thanks @JeLuf.
* 3.0.6 - 15 Sep 2023 - Fix broken embeddings dialog when LoRA information couldn't be fetched.
* 3.0.6 - 14 Sep 2023 - UI for adding notes to LoRA files (to help you remember which prompts to use). Also added a button to automatically fetch prompts from Civitai for a LoRA file, using the `Import from Civitai` button. Thanks @JeLuf.
* 3.0.5 - 2 Sep 2023 - Support SDXL ControlNets.
* 3.0.4 - 1 Sep 2023 - Fix incorrect metadata generated for embeddings, when the exact word doesn't match the case, or is part of a larger word.
* 3.0.4 - 1 Sep 2023 - Simplify the installation for AMD users on Linux. Thanks @JeLuf.
* 3.0.4 - 1 Sep 2023 - Allow using a different folder for models. This is useful if you want to share a models folder across different software, or on a different drive. You can change this path in the Settings tab.
* 3.0.3 - 31 Aug 2023 - Auto-save images to disk (if enabled by the user) when upscaling/fixing using the buttons on the image.
* 3.0.3 - 30 Aug 2023 - Allow loading NovelAI-based custom models.
* 3.0.3 - 30 Aug 2023 - Fix broken VAE tiling. This allows you to create larger images with lesser VRAM usage.
* 3.0.3 - 30 Aug 2023 - Allow blocking NSFW images using a server-side config. This prevents the browser from generating NSFW images or changing the config. Open `config.yaml` in a text editor (e.g. Notepad), and add `block_nsfw: true` at the end, and save the file.
* 3.0.2 - 29 Aug 2023 - Fixed incorrect matching of embeddings from prompts.
* 3.0.2 - 24 Aug 2023 - Fix broken seamless tiling.
* 3.0.2 - 23 Aug 2023 - Fix styling on mobile devices.
* 3.0.2 - 22 Aug 2023 - Full support for inpainting models, including custom models. Support SD 1.x and SD 2.x inpainting models. Does not require you to specify a yaml config file.
* 3.0.2 - 22 Aug 2023 - Reduce VRAM consumption of controlnet in 'low' VRAM mode, and allow accelerating controlnets using xformers.
* 3.0.2 - 22 Aug 2023 - Improve auto-detection of SD 2.0 and 2.1 models, removing the need for custom yaml files for SD 2.x models. Improve the model load time by speeding-up the black image test.
* 3.0.1 - 18 Aug 2023 - Rotate an image if EXIF rotation is present. For e.g. this is common in images taken with a smartphone.
* 3.0.1 - 18 Aug 2023 - Resize control images to the task dimensions, to avoid memory errors with high-res control images.
* 3.0.1 - 18 Aug 2023 - Show controlnet filter preview in the task entry.
* 3.0.1 - 18 Aug 2023 - Fix drag-and-drop and 'Use these Settings' for LoRA and ControlNet.
* 3.0.1 - 18 Aug 2023 - Auto-save LoRA models and strengths.
* 3.0.1 - 17 Aug 2023 - Automatically use the correct yaml config file for custom SDXL models, even if a yaml file isn't present in the folder.
* 3.0.1 - 17 Aug 2023 - Fix broken embeddings with SDXL.
* 3.0.1 - 16 Aug 2023 - Fix broken LoRA with SDXL.
* 3.0.1 - 15 Aug 2023 - Fix broken seamless tiling.
* 3.0.1 - 15 Aug 2023 - Fix textual inversion embeddings not working in `low` VRAM usage mode.
* 3.0.1 - 15 Aug 2023 - Fix for custom VAEs not working in `low` VRAM usage mode.
* 3.0.1 - 14 Aug 2023 - Slider to change the image dimensions proportionally (in Image Settings). Thanks @JeLuf.
* 3.0.1 - 14 Aug 2023 - Show an error to the user if an embedding isn't compatible with the model, instead of failing silently without informing the user. Thanks @JeLuf.
* 3.0.1 - 14 Aug 2023 - Disable watermarking for SDXL img2img. Thanks @AvidGameFan.
* 3.0.0 - 3 Aug 2023 - Enabled diffusers for everyone by default. The old v2 engine can be used by disabling the "Use v3 engine" option in the Settings tab.
## v2.5
### Major Changes
- **Nearly twice as fast** - significantly faster speed of image generation. Code contributions are welcome to make our project even faster: https://github.com/easydiffusion/sdkit/#is-it-fast
@ -64,13 +8,13 @@
- **Full support for Stable Diffusion 2.1 (including CPU)** - supports loading v1.4 or v2.0 or v2.1 models seamlessly. No need to enable "Test SD2", and no need to add `sd2_` to your SD 2.0 model file names. Works on CPU as well.
- **Memory optimized Stable Diffusion 2.1** - you can now use Stable Diffusion 2.1 models, with the same low VRAM optimizations that we've always had for SD 1.4. Please note, the SD 2.0 and 2.1 models require more GPU and System RAM, as compared to the SD 1.4 and 1.5 models.
- **11 new samplers!** - explore the new samplers, some of which can generate great images in less than 10 inference steps! We've added the Karras and UniPC samplers. Thanks @Schorny for the UniPC samplers.
- **Model Merging** - You can now merge two models (`.ckpt` or `.safetensors`) and output `.ckpt` or `.safetensors` models, optionally in `fp16` precision. Details: https://github.com/easydiffusion/easydiffusion/wiki/Model-Merging . Thanks @JeLuf.
- **Model Merging** - You can now merge two models (`.ckpt` or `.safetensors`) and output `.ckpt` or `.safetensors` models, optionally in `fp16` precision. Details: https://github.com/cmdr2/stable-diffusion-ui/wiki/Model-Merging . Thanks @JeLuf.
- **Fast loading/unloading of VAEs** - No longer needs to reload the entire Stable Diffusion model, each time you change the VAE
- **Database of known models** - automatically picks the right configuration for known models. E.g. we automatically detect and apply "v" parameterization (required for some SD 2.0 models), and "fp32" attention precision (required for some SD 2.1 models).
- **Color correction for img2img** - an option to preserve the color profile (histogram) of the initial image. This is especially useful if you're getting red-tinted images after inpainting/masking.
- **Three GPU Memory Usage Settings** - `High` (fastest, maximum VRAM usage), `Balanced` (default - almost as fast, significantly lower VRAM usage), `Low` (slowest, very low VRAM usage). The `Low` setting is applied automatically for GPUs with less than 4 GB of VRAM.
- **Find models in sub-folders** - This allows you to organize your models into sub-folders inside `models/stable-diffusion`, instead of keeping them all in a single folder. Thanks @patriceac and @ogmaresca.
- **Custom Modifier Categories** - Ability to create custom modifiers with thumbnails, and custom categories (and hierarchy of categories). Details: https://github.com/easydiffusion/easydiffusion/wiki/Custom-Modifiers . Thanks @ogmaresca.
- **Custom Modifier Categories** - Ability to create custom modifiers with thumbnails, and custom categories (and hierarchy of categories). Details: https://github.com/cmdr2/stable-diffusion-ui/wiki/Custom-Modifiers . Thanks @ogmaresca.
- **Embed metadata, or save as TXT/JSON** - You can now embed the metadata directly into the images, or save them as text or json files (choose in the Settings tab). Thanks @patriceac.
- **Major rewrite of the code** - Most of the codebase has been reorganized and rewritten, to make it more manageable and easier for new developers to contribute features. We've separated our core engine into a new project called `sdkit`, which allows anyone to easily integrate Stable Diffusion (and related modules like GFPGAN etc) into their programming projects (via a simple `pip install sdkit`): https://github.com/easydiffusion/sdkit/
- **Name change** - Last, and probably the least, the UI is now called "Easy Diffusion". It indicates the focus of this project - an easy way for people to play with Stable Diffusion.
@ -78,37 +22,6 @@
Our focus continues to remain on an easy installation experience, and an easy user-interface. While still remaining pretty powerful, in terms of features and speed.
### Detailed changelog
* 2.5.48 - 1 Aug 2023 - (beta-only) Full support for ControlNets. You can select a control image to guide the AI. You can pick a filter to pre-process the image, and one of the known (or custom) controlnet models. Supports `OpenPose`, `Canny`, `Straight Lines`, `Depth`, `Line Art`, `Scribble`, `Soft Edge`, `Shuffle` and `Segment`.
* 2.5.47 - 30 Jul 2023 - An option to use `Strict Mask Border` while inpainting, to avoid touching areas outside the mask. But this might show a slight outline of the mask, which you will have to touch up separately.
* 2.5.47 - 29 Jul 2023 - (beta-only) Fix long prompts with SDXL.
* 2.5.47 - 29 Jul 2023 - (beta-only) Fix red dots in some SDXL images.
* 2.5.47 - 29 Jul 2023 - Significantly faster `Fix Faces` and `Upscale` buttons (on the image). They no longer need to generate the image from scratch, instead they just upscale/fix the generated image in-place.
* 2.5.47 - 28 Jul 2023 - Lots of internal code reorganization, in preparation for supporting Controlnets. No user-facing changes.
* 2.5.46 - 27 Jul 2023 - (beta-only) Full support for SD-XL models (base and refiner)!
* 2.5.45 - 24 Jul 2023 - (beta-only) Hide the samplers that won't be supported in the new diffusers version.
* 2.5.45 - 22 Jul 2023 - (beta-only) Fix the recently-broken inpainting models.
* 2.5.45 - 16 Jul 2023 - (beta-only) Fix the image quality of LoRAs, which had degraded in v2.5.44.
* 2.5.44 - 15 Jul 2023 - (beta-only) Support for multiple LoRA files.
* 2.5.43 - 9 Jul 2023 - (beta-only) Support for loading Textual Inversion embeddings. You can find the option in the Image Settings panel. Thanks @JeLuf.
* 2.5.43 - 9 Jul 2023 - Improve the startup time of the UI.
* 2.5.42 - 4 Jul 2023 - Keyboard shortcuts for the Image Editor. Thanks @JeLuf.
* 2.5.42 - 28 Jun 2023 - Allow dropping images from folders to use as an Initial Image.
* 2.5.42 - 26 Jun 2023 - Show a popup for Image Modifiers, allowing a larger screen space, better UX on mobile screens, and more room for us to develop and improve the Image Modifiers panel. Thanks @Hakorr.
* 2.5.42 - 26 Jun 2023 - (beta-only) Show a welcome screen for users of the diffusers beta, with instructions on how to use the new prompt syntax, and known bugs. Thanks @JeLuf.
* 2.5.42 - 26 Jun 2023 - Use YAML files for config. You can now edit the `config.yaml` file (using a text editor, like Notepad). This file is present inside the Easy Diffusion folder, and is easier to read and edit (for humans) than JSON. Thanks @JeLuf.
* 2.5.41 - 24 Jun 2023 - (beta-only) Fix broken inpainting in low VRAM usage mode.
* 2.5.41 - 24 Jun 2023 - (beta-only) Fix a recent regression where the LoRA would not get applied when changing SD models.
* 2.5.41 - 23 Jun 2023 - Fix a regression where latent upscaler stopped working on PCs without a graphics card.
* 2.5.41 - 20 Jun 2023 - Automatically fix black images if fp32 attention precision is required in diffusers.
* 2.5.41 - 19 Jun 2023 - Another fix for multi-gpu rendering (in all VRAM usage modes).
* 2.5.41 - 13 Jun 2023 - Fix multi-gpu bug with "low" VRAM usage mode while generating images.
* 2.5.41 - 12 Jun 2023 - Fix multi-gpu bug with CodeFormer.
* 2.5.41 - 6 Jun 2023 - Allow changing the strength of CodeFormer, and slightly improved styling of the CodeFormer options.
* 2.5.41 - 5 Jun 2023 - Allow sharing an Easy Diffusion instance via https://try.cloudflare.com/ . You can find this option at the bottom of the Settings tab. Thanks @JeLuf.
* 2.5.41 - 5 Jun 2023 - Show an option to download for tiled images. Shows a button on the generated image. Creates larger images by tiling them with the image generated by Easy Diffusion. Thanks @JeLuf.
* 2.5.41 - 5 Jun 2023 - (beta-only) Allow LoRA strengths between -2 and 2. Thanks @ogmaresca.
* 2.5.40 - 5 Jun 2023 - Reduce the VRAM usage of Latent Upscaling when using "balanced" VRAM usage mode.
* 2.5.40 - 5 Jun 2023 - Fix the "realesrgan" key error when using CodeFormer with more than 1 image in a batch.
* 2.5.40 - 3 Jun 2023 - Added CodeFormer as another option for fixing faces and eyes. CodeFormer tends to perform better than GFPGAN for many images. Thanks @patriceac for the implementation, and for contacting the CodeFormer team (who were supportive of it being integrated into Easy Diffusion).
* 2.5.39 - 25 May 2023 - (beta-only) Seamless Tiling - make seamlessly tiled images, e.g. rock and grass textures. Thanks @JeLuf.
* 2.5.38 - 24 May 2023 - Better reporting of errors, and show an explanation if the user cannot disable the "Use CPU" setting.
@ -146,7 +59,7 @@ Our focus continues to remain on an easy installation experience, and an easy us
* 2.5.24 - 11 Mar 2023 - Button to load an image mask from a file.
* 2.5.24 - 10 Mar 2023 - Logo change. Image credit: @lazlo_vii.
* 2.5.23 - 8 Mar 2023 - Experimental support for Mac M1/M2. Thanks @michaelgallacher, @JeLuf and vishae!
* 2.5.23 - 8 Mar 2023 - Ability to create custom modifiers with thumbnails, and custom categories (and hierarchy of categories). More details - https://github.com/easydiffusion/easydiffusion/wiki/Custom-Modifiers . Thanks @ogmaresca.
* 2.5.23 - 8 Mar 2023 - Ability to create custom modifiers with thumbnails, and custom categories (and hierarchy of categories). More details - https://github.com/cmdr2/stable-diffusion-ui/wiki/Custom-Modifiers . Thanks @ogmaresca.
* 2.5.22 - 28 Feb 2023 - Minor styling changes to UI buttons, and the models dropdown.
* 2.5.22 - 28 Feb 2023 - Lots of UI-related bug fixes. Thanks @patriceac.
* 2.5.21 - 22 Feb 2023 - An option to control the size of the image thumbnails. You can use the `Display options` in the top-right corner to change this. Thanks @JeLuf.
@ -171,7 +84,7 @@ Our focus continues to remain on an easy installation experience, and an easy us
* 2.5.14 - 3 Feb 2023 - Fix the 'Make Similar Images' button, which was producing incorrect images (weren't very similar).
* 2.5.13 - 1 Feb 2023 - Fix the remaining GPU memory leaks, including a better fix (more comprehensive) for the change in 2.5.12 (27 Jan).
* 2.5.12 - 27 Jan 2023 - Fix a memory leak, which made the UI unresponsive after an out-of-memory error. The allocated memory is now freed-up after an error.
* 2.5.11 - 25 Jan 2023 - UI for Merging Models. Thanks @JeLuf. More info: https://github.com/easydiffusion/easydiffusion/wiki/Model-Merging
* 2.5.11 - 25 Jan 2023 - UI for Merging Models. Thanks @JeLuf. More info: https://github.com/cmdr2/stable-diffusion-ui/wiki/Model-Merging
* 2.5.10 - 24 Jan 2023 - Reduce the VRAM usage for img2img in 'balanced' mode (without reducing the rendering speed), to make it similar to v2.4 of this UI.
* 2.5.9 - 23 Jan 2023 - Fix a bug where img2img would produce poorer-quality images for the same settings, as compared to version 2.4 of this UI.
* 2.5.9 - 23 Jan 2023 - Reduce the VRAM usage for 'balanced' mode (without reducing the rendering speed), to make it similar to v2.4 of the UI.
@ -200,8 +113,8 @@ Our focus continues to remain on an easy installation experience, and an easy us
- **Automatic scanning for malicious model files** - using `picklescan`, and support for `safetensor` model format. Thanks @JeLuf
- **Image Editor** - for drawing simple images for guiding the AI. Thanks @mdiller
- **Use pre-trained hypernetworks** - for improving the quality of images. Thanks @C0bra5
- **Support for custom VAE models**. You can place your VAE files in the `models/vae` folder, and refresh the browser page to use them. More info: https://github.com/easydiffusion/easydiffusion/wiki/VAE-Variational-Auto-Encoder
- **Experimental support for multiple GPUs!** It should work automatically. Just open one browser tab per GPU, and spread your tasks across your GPUs. For e.g. open our UI in two browser tabs if you have two GPUs. You can customize which GPUs it should use in the "Settings" tab, otherwise let it automatically pick the best GPUs. Thanks @madrang . More info: https://github.com/easydiffusion/easydiffusion/wiki/Run-on-Multiple-GPUs
- **Support for custom VAE models**. You can place your VAE files in the `models/vae` folder, and refresh the browser page to use them. More info: https://github.com/cmdr2/stable-diffusion-ui/wiki/VAE-Variational-Auto-Encoder
- **Experimental support for multiple GPUs!** It should work automatically. Just open one browser tab per GPU, and spread your tasks across your GPUs. For e.g. open our UI in two browser tabs if you have two GPUs. You can customize which GPUs it should use in the "Settings" tab, otherwise let it automatically pick the best GPUs. Thanks @madrang . More info: https://github.com/cmdr2/stable-diffusion-ui/wiki/Run-on-Multiple-GPUs
- **Cleaner UI design** - Show settings and help in new tabs, instead of dropdown popups (which were buggy). Thanks @mdiller
- **Progress bar.** Thanks @mdiller
- **Custom Image Modifiers** - You can now save your custom image modifiers! Your saved modifiers can include special characters like `{}, (), [], |`

View File

@ -1,6 +1,6 @@
Hi there, these instructions are meant for the developers of this project.
If you only want to use the Stable Diffusion UI, you've downloaded the wrong file. In that case, please download and follow the instructions at https://github.com/easydiffusion/easydiffusion#installation
If you only want to use the Stable Diffusion UI, you've downloaded the wrong file. In that case, please download and follow the instructions at https://github.com/cmdr2/stable-diffusion-ui#installation
Thanks
@ -13,7 +13,7 @@ If you would like to contribute to this project, there is a discord for discussi
This is in-flux, but one way to get a development environment running for editing the UI of this project is:
(swap `.sh` or `.bat` in instructions depending on your environment, and be sure to adjust any paths to match where you're working)
1) Install the project to a new location using the [usual installation process](https://github.com/easydiffusion/easydiffusion#installation), e.g. to `/projects/stable-diffusion-ui-archive`
1) Install the project to a new location using the [usual installation process](https://github.com/cmdr2/stable-diffusion-ui#installation), e.g. to `/projects/stable-diffusion-ui-archive`
2) Start the newly installed project, and check that you can view and generate images on `localhost:9000`
3) Next, please clone the project repository using `git clone` (e.g. to `/projects/stable-diffusion-ui-repo`)
4) Close the server (started in step 2), and edit `/projects/stable-diffusion-ui-archive/scripts/on_env_start.sh` (or `on_env_start.bat`)
@ -47,5 +47,3 @@ Build the Windows installer using Windows, and the Linux installer using Linux.
1. Run `build.bat` or `./build.sh` depending on whether you're in Windows or Linux.
2. Make a new GitHub release and upload the Windows and Linux installer builds created inside the `dist` folder.
For NSIS (on Windows), you need to have these plugins in the `nsis/Plugins` folder: `amd64-unicode`, `x86-ansi`, `x86-unicode`

View File

@ -1,24 +1,24 @@
Congrats on downloading Easy Diffusion, version 3!
Congrats on downloading Stable Diffusion UI, version 2!
If you haven't downloaded Easy Diffusion yet, please download from https://github.com/easydiffusion/easydiffusion#installation
If you haven't downloaded Stable Diffusion UI yet, please download from https://github.com/cmdr2/stable-diffusion-ui#installation
After downloading, to install please follow these instructions:
For Windows:
- Please double-click the "Easy-Diffusion-Windows.exe" file and follow the instructions.
- Please double-click the "Start Stable Diffusion UI.cmd" file inside the "stable-diffusion-ui" folder.
For Linux and Mac:
- Please open a terminal, and go to the "easy-diffusion" directory. Then run ./start.sh
For Linux:
- Please open a terminal, and go to the "stable-diffusion-ui" directory. Then run ./start.sh
That file will automatically install everything. After that it will start the Easy Diffusion interface in a web browser.
That file will automatically install everything. After that it will start the Stable Diffusion interface in a web browser.
To start Easy Diffusion in the future, please run the same command mentioned above.
To start the UI in the future, please run the same command mentioned above.
If you have any problems, please:
1. Try the troubleshooting steps at https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting
1. Try the troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting
2. Or, seek help from the community at https://discord.com/invite/u9yhsFmEkB
3. Or, file an issue at https://github.com/easydiffusion/easydiffusion/issues
3. Or, file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues
Thanks
cmdr2 (and contributors to the project)
cmdr2 (and contributors to the project)

BIN
NSIS/astro.bmp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 288 KiB

1
NSIS/nsisconf.nsh Normal file
View File

@ -0,0 +1 @@
!define EXISTING_INSTALLATION_DIR "D:\path\to\installed\easy-diffusion"

BIN
NSIS/sd.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 KiB

View File

@ -7,9 +7,9 @@ RequestExecutionLevel user
!AddPluginDir /amd64-unicode "."
; HM NIS Edit Wizard helper defines
!define PRODUCT_NAME "Easy Diffusion"
!define PRODUCT_VERSION "3.0"
!define PRODUCT_VERSION "2.5"
!define PRODUCT_PUBLISHER "cmdr2 and contributors"
!define PRODUCT_WEB_SITE "https://easydiffusion.github.io"
!define PRODUCT_WEB_SITE "https://stable-diffusion-ui.github.io"
!define PRODUCT_DIR_REGKEY "Software\Microsoft\Easy Diffusion\App Paths\installer.exe"
; MUI 1.67 compatible ------
@ -165,9 +165,9 @@ FunctionEnd
; MUI Settings
;---------------------------------------------------------------------------------------------------------
!define MUI_ABORTWARNING
!define MUI_ICON "${EXISTING_INSTALLATION_DIR}\installer_files\cyborg_flower_girl.ico"
!define MUI_ICON "cyborg_flower_girl.ico"
!define MUI_WELCOMEFINISHPAGE_BITMAP "${EXISTING_INSTALLATION_DIR}\installer_files\cyborg_flower_girl.bmp"
!define MUI_WELCOMEFINISHPAGE_BITMAP "cyborg_flower_girl.bmp"
; Welcome page
!define MUI_WELCOMEPAGE_TEXT "This installer will guide you through the installation of Easy Diffusion.$\n$\n\
@ -176,8 +176,8 @@ Click Next to continue."
Page custom MediaPackDialog
; License page
!insertmacro MUI_PAGE_LICENSE "${EXISTING_INSTALLATION_DIR}\LICENSE"
!insertmacro MUI_PAGE_LICENSE "${EXISTING_INSTALLATION_DIR}\CreativeML Open RAIL-M License"
!insertmacro MUI_PAGE_LICENSE "..\LICENSE"
!insertmacro MUI_PAGE_LICENSE "..\CreativeML Open RAIL-M License"
; Directory page
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE "DirectoryLeave"
!insertmacro MUI_PAGE_DIRECTORY
@ -210,33 +210,29 @@ ShowInstDetails show
; List of files to be installed
Section "MainSection" SEC01
SetOutPath "$INSTDIR"
File "${EXISTING_INSTALLATION_DIR}\CreativeML Open RAIL-M License"
File "${EXISTING_INSTALLATION_DIR}\How to install and run.txt"
File "${EXISTING_INSTALLATION_DIR}\LICENSE"
File "${EXISTING_INSTALLATION_DIR}\Start Stable Diffusion UI.cmd"
File "..\CreativeML Open RAIL-M License"
File "..\How to install and run.txt"
File "..\LICENSE"
File "..\scripts\Start Stable Diffusion UI.cmd"
File /r "${EXISTING_INSTALLATION_DIR}\installer_files"
File /r "${EXISTING_INSTALLATION_DIR}\profile"
File /r "${EXISTING_INSTALLATION_DIR}\sd-ui-files"
SetOutPath "$INSTDIR\installer_files"
File "cyborg_flower_girl.ico"
SetOutPath "$INSTDIR\scripts"
File "${EXISTING_INSTALLATION_DIR}\scripts\install_status.txt"
File "${EXISTING_INSTALLATION_DIR}\scripts\on_env_start.bat"
File "..\scripts\on_env_start.bat"
File "C:\windows\system32\curl.exe"
File "${EXISTING_INSTALLATION_DIR}\scripts\config.yaml.sample"
CreateDirectory "$INSTDIR\models"
CreateDirectory "$INSTDIR\models\stable-diffusion"
CreateDirectory "$INSTDIR\models\gfpgan"
CreateDirectory "$INSTDIR\models\realesrgan"
CreateDirectory "$INSTDIR\models\vae"
CreateDirectory "$INSTDIR\profile\.cache\huggingface\hub"
SetOutPath "$INSTDIR\profile\.cache\huggingface\hub"
File /r /x pytorch_model.bin "${EXISTING_INSTALLATION_DIR}\profile\.cache\huggingface\hub\models--openai--clip-vit-large-patch14"
CreateDirectory "$SMPROGRAMS\Easy Diffusion"
CreateShortCut "$SMPROGRAMS\Easy Diffusion\Easy Diffusion.lnk" "$INSTDIR\Start Stable Diffusion UI.cmd" "" "$INSTDIR\installer_files\cyborg_flower_girl.ico"
DetailPrint 'Downloading the Stable Diffusion 1.5 model...'
NScurl::http get "https://github.com/easydiffusion/sdkit-test-data/releases/download/assets/sd-v1-5.safetensors" "$INSTDIR\models\stable-diffusion\sd-v1-5.safetensors" /CANCEL /INSIST /END
DetailPrint 'Downloading the Stable Diffusion 1.4 model...'
NScurl::http get "https://huggingface.co/CompVis/stable-diffusion-v-1-4-original/resolve/main/sd-v1-4.ckpt" "$INSTDIR\models\stable-diffusion\sd-v1-4.ckpt" /CANCEL /INSIST /END
DetailPrint 'Downloading the GFPGAN model...'
NScurl::http get "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth" "$INSTDIR\models\gfpgan\GFPGANv1.4.pth" /CANCEL /INSIST /END

View File

@ -3,7 +3,7 @@
This is a summary of whether Easy Diffusion uses your data or tracks you:
* The short answer is - Easy Diffusion does *not* use your data, and does *not* track you.
* Easy Diffusion does not send your prompts or usage or analytics to anyone. There is no tracking. We don't even know how many people use Easy Diffusion, let alone their prompts.
* Easy Diffusion fetches updates to the code whenever it starts up. It does this by contacting GitHub directly, via SSL (secure connection). Only your computer and GitHub and [this repository](https://github.com/easydiffusion/easydiffusion) are involved, and no third party is involved. Some countries intercepts SSL connections, that's not something we can do much about. GitHub does *not* share statistics (even with me) about how many people fetched code updates.
* Easy Diffusion fetches updates to the code whenever it starts up. It does this by contacting GitHub directly, via SSL (secure connection). Only your computer and GitHub and [this repository](https://github.com/cmdr2/stable-diffusion-ui) are involved, and no third party is involved. Some countries intercepts SSL connections, that's not something we can do much about. GitHub does *not* share statistics (even with me) about how many people fetched code updates.
* Easy Diffusion fetches the models from huggingface.co and github.com, if they don't exist on your PC. For e.g. if the safety checker (NSFW) model doesn't exist, it'll try to download it.
* Easy Diffusion fetches code packages from pypi.org, which is the standard hosting service for all Python projects. That's where packages installed via `pip install` are stored.
* Occasionally, antivirus software are known to *incorrectly* flag and delete some model files, which will result in Easy Diffusion re-downloading `pytorch_model.bin`. This *incorrect deletion* affects other Stable Diffusion UIs as well, like Invoke AI - https://itch.io/post/7509488

View File

@ -3,6 +3,6 @@ Hi there,
What you have downloaded is meant for the developers of this project, not for users.
If you only want to use the Stable Diffusion UI, you've downloaded the wrong file.
Please download and follow the instructions at https://github.com/easydiffusion/easydiffusion#installation
Please download and follow the instructions at https://github.com/cmdr2/stable-diffusion-ui#installation
Thanks

View File

@ -1,36 +1,28 @@
# Easy Diffusion 3.0
### An easy way to install and use [Stable Diffusion](https://github.com/CompVis/stable-diffusion) on your computer.
# Easy Diffusion 2.5
### The easiest way to install and use [Stable Diffusion](https://github.com/CompVis/stable-diffusion) on your computer.
Does not require technical knowledge, does not require pre-installed software. 1-click install, powerful features, friendly community.
️‍🔥🎉 **New!** Support for Flux has been added in the beta branch (v3.5 engine)!
[Installation guide](#installation) | [Troubleshooting guide](https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting) | [User guide](https://github.com/easydiffusion/easydiffusion/wiki) | <sub>[![Discord Server](https://img.shields.io/discord/1014774730907209781?label=Discord)](https://discord.com/invite/u9yhsFmEkB)</sub> <sup>(for support queries, and development discussions)</sup>
---
![262597678-11089485-2514-4a11-88fb-c3acc81fc9ec](https://github.com/easydiffusion/easydiffusion/assets/844287/050b5e15-e909-45bf-8162-a38234830e38)
[Installation guide](#installation) | [Troubleshooting guide](https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting) | <sub>[![Discord Server](https://img.shields.io/discord/1014774730907209781?label=Discord)](https://discord.com/invite/u9yhsFmEkB)</sub> <sup>(for support queries, and development discussions)</sup>
![t2i](https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/assets/stable-samples/txt2img/768/merged-0006.png)
# Installation
Click the download button for your operating system:
<p float="left">
<a href="https://github.com/cmdr2/stable-diffusion-ui/releases/latest/download/Easy-Diffusion-Linux.zip"><img src="https://github.com/cmdr2/stable-diffusion-ui/raw/main/media/download-linux.png" width="200" /></a>
<a href="https://github.com/cmdr2/stable-diffusion-ui/releases/latest/download/Easy-Diffusion-Mac.zip"><img src="https://github.com/cmdr2/stable-diffusion-ui/raw/main/media/download-mac.png" width="200" /></a>
<a href="https://github.com/cmdr2/stable-diffusion-ui/releases/latest/download/Easy-Diffusion-Windows.exe"><img src="https://github.com/cmdr2/stable-diffusion-ui/raw/main/media/download-win.png" width="200" /></a>
<a href="https://github.com/cmdr2/stable-diffusion-ui/releases/download/v2.5.24/Easy-Diffusion-Windows.exe"><img src="https://github.com/cmdr2/stable-diffusion-ui/raw/main/media/download-win.png" width="200" /></a>
<a href="https://github.com/cmdr2/stable-diffusion-ui/releases/download/v2.5.24/Easy-Diffusion-Linux.zip"><img src="https://github.com/cmdr2/stable-diffusion-ui/raw/main/media/download-linux.png" width="200" /></a>
<a href="https://github.com/cmdr2/stable-diffusion-ui/releases/download/v2.5.24/Easy-Diffusion-Mac.zip"><img src="https://github.com/cmdr2/stable-diffusion-ui/raw/main/media/download-mac.png" width="200" /></a>
</p>
**Hardware requirements:**
- **Windows:** NVIDIA¹ or AMD graphics card (minimum 2 GB RAM), or run on your CPU.
- **Linux:** NVIDIA¹ or AMD² graphics card (minimum 2 GB RAM), or run on your CPU.
- **Mac:** M1/M2/M3/M4 or AMD graphics card (Intel Mac), or run on your CPU.
- **Windows:** NVIDIA graphics card (minimum 2 GB RAM), or run on your CPU.
- **Linux:** NVIDIA or AMD graphics card (minimum 2 GB RAM), or run on your CPU.
- **Mac:** M1 or M2, or run on your CPU.
- Minimum 8 GB of system RAM.
- Atleast 25 GB of space on the hard disk.
¹) [CUDA Compute capability](https://en.wikipedia.org/wiki/CUDA#GPUs_supported) level of 3.7 or higher required.
²) ROCm 5.2 (or newer) support required.
The installer will take care of whatever is needed. If you face any problems, you can join the friendly [Discord community](https://discord.com/invite/u9yhsFmEkB) and ask for assistance.
## On Windows:
@ -66,21 +58,18 @@ Just delete the `EasyDiffusion` folder to uninstall all the downloaded packages.
- **UI Themes**: Customize the program to your liking.
- **Searchable models dropdown**: organize your models into sub-folders, and search through them in the UI.
### Powerful image generation
- **Supports**: "*Text to Image*", "*Image to Image*" and "*InPainting*"
- **ControlNet**: For advanced control over the image, e.g. by setting the pose or drawing the outline for the AI to fill in.
- **16 Samplers**: `PLMS`, `DDIM`, `DEIS`, `Heun`, `Euler`, `Euler Ancestral`, `DPM2`, `DPM2 Ancestral`, `LMS`, `DPM Solver`, `DPM++ 2s Ancestral`, `DPM++ 2m`, `DPM++ 2m SDE`, `DPM++ SDE`, `DDPM`, `UniPC`.
- **Stable Diffusion XL and 2.1**: Generate higher-quality images using the latest Stable Diffusion XL models.
- **Textual Inversion Embeddings**: For guiding the AI strongly towards a particular concept.
### Image generation
- **Supports**: "*Text to Image*" and "*Image to Image*".
- **21 Samplers**: `ddim`, `plms`, `heun`, `euler`, `euler_a`, `dpm2`, `dpm2_a`, `lms`, `dpm_solver_stability`, `dpmpp_2s_a`, `dpmpp_2m`, `dpmpp_sde`, `dpm_fast`, `dpm_adaptive`, `ddpm`, `deis`, `unipc_snr`, `unipc_tu`, `unipc_tq`, `unipc_snr_2`, `unipc_tu_2`.
- **In-Painting**: Specify areas of your image to paint into.
- **Simple Drawing Tool**: Draw basic images to guide the AI, without needing an external drawing program.
- **Face Correction (GFPGAN)**
- **Upscaling (RealESRGAN)**
- **Loopback**: Use the output image as the input image for the next image task.
- **Loopback**: Use the output image as the input image for the next img2img task.
- **Negative Prompt**: Specify aspects of the image to *remove*.
- **Attention/Emphasis**: `+` in the prompt increases the model's attention to enclosed words, and `-` decreases it. E.g. `apple++ falling from a tree`.
- **Weighted Prompts**: Use weights for specific words in your prompt to change their importance, e.g. `(red)2.4 (dragon)1.2`.
- **Attention/Emphasis**: () in the prompt increases the model's attention to enclosed words, and [] decreases it.
- **Weighted Prompts**: Use weights for specific words in your prompt to change their importance, e.g. `red:2.4 dragon:1.2`.
- **Prompt Matrix**: Quickly create multiple variations of your prompt, e.g. `a photograph of an astronaut riding a horse | illustration | cinematic lighting`.
- **Prompt Set**: Quickly create multiple variations of your prompt, e.g. `a photograph of an astronaut on the {moon,earth}`
- **1-click Upscale/Face Correction**: Upscale or correct an image after it has been generated.
- **Make Similar Images**: Click to generate multiple variations of a generated image.
- **NSFW Setting**: A setting in the UI to control *NSFW content*.
@ -88,13 +77,12 @@ Just delete the `EasyDiffusion` folder to uninstall all the downloaded packages.
### Advanced features
- **Custom Models**: Use your own `.ckpt` or `.safetensors` file, by placing it inside the `models/stable-diffusion` folder!
- **Stable Diffusion XL and 2.1 support**
- **Stable Diffusion 2.1 support**
- **Merge Models**
- **Use custom VAE models**
- **Textual Inversion Embeddings**
- **ControlNet**
- **Use pre-trained Hypernetworks**
- **Use custom GFPGAN models**
- **UI Plugins**: Choose from a growing list of [community-generated UI plugins](https://github.com/easydiffusion/easydiffusion/wiki/UI-Plugins), or write your own plugin to add features to the project!
- **UI Plugins**: Choose from a growing list of [community-generated UI plugins](https://github.com/cmdr2/stable-diffusion-ui/wiki/UI-Plugins), or write your own plugin to add features to the project!
### Performance and security
- **Fast**: Creates a 512x512 image with euler_a in 5 seconds, on an NVIDIA 3060 12GB.
@ -104,14 +92,24 @@ Just delete the `EasyDiffusion` folder to uninstall all the downloaded packages.
- **Auto scan for malicious models**: Uses picklescan to prevent malicious models.
- **Safetensors support**: Support loading models in the safetensor format, for improved safety.
- **Auto-updater**: Gets you the latest improvements and bug-fixes to a rapidly evolving project.
- **Developer Console**: A developer-mode for those who want to modify their Stable Diffusion code, modify packages, and edit the conda environment.
- **Developer Console**: A developer-mode for those who want to modify their Stable Diffusion code, and edit the conda environment.
**(and a lot more)**
----
## Easy for new users, powerful features for advanced users:
![image](https://github.com/easydiffusion/easydiffusion/assets/844287/efbbac9f-42ce-4aef-8625-fd23c74a8241)
## Easy for new users:
![Screenshot of the initial UI](https://user-images.githubusercontent.com/844287/217043152-29454d15-0387-4228-b70d-9a4b84aeb8ba.png)
## Powerful features for advanced users:
![Screenshot of advanced settings](https://user-images.githubusercontent.com/844287/217042588-fc53c975-bacd-4a9c-af88-37408734ade3.png)
## Live Preview
Useful for judging (and stopping) an image quickly, without waiting for it to finish rendering.
![live-512](https://user-images.githubusercontent.com/844287/192097249-729a0a1e-a677-485e-9ccc-16a9e848fabe.gif)
## Task Queue
![Screenshot of task queue](https://user-images.githubusercontent.com/844287/217043984-0b35f73b-1318-47cb-9eed-a2a91b430490.png)
@ -120,22 +118,19 @@ Just delete the `EasyDiffusion` folder to uninstall all the downloaded packages.
----
# How to use?
Please refer to our [guide](https://github.com/easydiffusion/easydiffusion/wiki/How-to-Use) to understand how to use the features in this UI.
Please refer to our [guide](https://github.com/cmdr2/stable-diffusion-ui/wiki/How-to-Use) to understand how to use the features in this UI.
# Bugs reports and code contributions welcome
If there are any problems or suggestions, please feel free to ask on the [discord server](https://discord.com/invite/u9yhsFmEkB) or [file an issue](https://github.com/easydiffusion/easydiffusion/issues).
If there are any problems or suggestions, please feel free to ask on the [discord server](https://discord.com/invite/u9yhsFmEkB) or [file an issue](https://github.com/cmdr2/stable-diffusion-ui/issues).
We could really use help on these aspects (click to view tasks that need your help):
* [User Interface](https://github.com/users/cmdr2/projects/1/views/1)
* [Engine](https://github.com/users/cmdr2/projects/3/views/1)
* [Installer](https://github.com/users/cmdr2/projects/4/views/1)
* [Documentation](https://github.com/users/cmdr2/projects/5/views/1)
If you have any code contributions in mind, please feel free to say Hi to us on the [discord server](https://discord.com/invite/u9yhsFmEkB). We use the Discord server for development-related discussions, and for helping users.
# Credits
* Stable Diffusion: https://github.com/Stability-AI/stablediffusion
* CodeFormer: https://github.com/sczhou/CodeFormer (license: https://github.com/sczhou/CodeFormer/blob/master/LICENSE)
* GFPGAN: https://github.com/TencentARC/GFPGAN
* RealESRGAN: https://github.com/xinntao/Real-ESRGAN
* k-diffusion: https://github.com/crowsonkb/k-diffusion
* Code contributors and artists on the cmdr2 UI: https://github.com/cmdr2/stable-diffusion-ui and Discord (https://discord.com/invite/u9yhsFmEkB)
* Lots of contributors on the internet
# Disclaimer
The authors of this project are not responsible for any content generated using this interface.

View File

@ -1,78 +1,47 @@
@echo off
setlocal enabledelayedexpansion
@echo "Hi there, what you are running is meant for the developers of this project, not for users." & echo.
@echo "If you only want to use Easy Diffusion, you've downloaded the wrong file."
@echo "Please download and follow the instructions at https://github.com/easydiffusion/easydiffusion#installation" & echo.
@echo "If you only want to use the Stable Diffusion UI, you've downloaded the wrong file."
@echo "Please download and follow the instructions at https://github.com/cmdr2/stable-diffusion-ui#installation" & echo.
@echo "If you are actually a developer of this project, please type Y and press enter" & echo.
set /p answer=Are you a developer of this project (Y/N)?
if /i "%answer:~,1%" NEQ "Y" exit /b
@rem verify dependencies
call makensis /VERSION >.tmp1 2>.tmp2
if "!ERRORLEVEL!" NEQ "0" (
echo makensis.exe not found! Download it from https://sourceforge.net/projects/nsisbi/files/ and set it on the PATH variable.
pause
exit
)
mkdir dist\win\stable-diffusion-ui\scripts
@REM mkdir dist\linux-mac\stable-diffusion-ui\scripts
set /p OUT_DIR=Output folder path (will create the installer files inside this, e.g. F:\EasyDiffusion):
@rem copy the installer files for Windows
mkdir "%OUT_DIR%\scripts"
mkdir "%OUT_DIR%\installer_files"
copy scripts\on_env_start.bat dist\win\stable-diffusion-ui\scripts\
copy scripts\bootstrap.bat dist\win\stable-diffusion-ui\scripts\
copy "scripts\Start Stable Diffusion UI.cmd" dist\win\stable-diffusion-ui\
copy LICENSE dist\win\stable-diffusion-ui\
copy "CreativeML Open RAIL-M License" dist\win\stable-diffusion-ui\
copy "How to install and run.txt" dist\win\stable-diffusion-ui\
echo. > dist\win\stable-diffusion-ui\scripts\install_status.txt
set BASE_DIR=%cd%
@rem copy the installer files for Linux and Mac
@rem STEP 1: copy the installer files for Windows
@REM copy scripts\on_env_start.sh dist\linux-mac\stable-diffusion-ui\scripts\
@REM copy scripts\bootstrap.sh dist\linux-mac\stable-diffusion-ui\scripts\
@REM copy scripts\start.sh dist\linux-mac\stable-diffusion-ui\
@REM copy LICENSE dist\linux-mac\stable-diffusion-ui\
@REM copy "CreativeML Open RAIL-M License" dist\linux-mac\stable-diffusion-ui\
@REM copy "How to install and run.txt" dist\linux-mac\stable-diffusion-ui\
@REM echo. > dist\linux-mac\stable-diffusion-ui\scripts\install_status.txt
copy "%BASE_DIR%\scripts\on_env_start.bat" "%OUT_DIR%\scripts\"
copy "%BASE_DIR%\scripts\config.yaml.sample" "%OUT_DIR%\scripts\config.yaml.sample"
copy "%BASE_DIR%\scripts\Start Stable Diffusion UI.cmd" "%OUT_DIR%\"
copy "%BASE_DIR%\LICENSE" "%OUT_DIR%\"
copy "%BASE_DIR%\CreativeML Open RAIL-M License" "%OUT_DIR%\"
copy "%BASE_DIR%\How to install and run.txt" "%OUT_DIR%\"
copy "%BASE_DIR%\NSIS\cyborg_flower_girl.ico" "%OUT_DIR%\installer_files\"
copy "%BASE_DIR%\NSIS\cyborg_flower_girl.bmp" "%OUT_DIR%\installer_files\"
echo. > "%OUT_DIR%\scripts\install_status.txt"
@rem make the zip
cd dist\win
call powershell Compress-Archive -Path stable-diffusion-ui -DestinationPath ..\stable-diffusion-ui-windows.zip
cd ..\..
@REM cd dist\linux-mac
@REM call powershell Compress-Archive -Path stable-diffusion-ui -DestinationPath ..\stable-diffusion-ui-linux.zip
@REM call powershell Compress-Archive -Path stable-diffusion-ui -DestinationPath ..\stable-diffusion-ui-mac.zip
@REM cd ..\..
echo "Build ready. Upload the zip files inside the 'dist' folder."
echo ----
echo Basic files ready. Verify the files in %OUT_DIR%, then press Enter to initialize the environment, or close to quit.
echo ----
pause
@rem STEP 2: Initialize the environment with git, python and conda
cd /d "%OUT_DIR%\"
call "%BASE_DIR%\scripts\bootstrap.bat"
echo ----
echo Environment ready. Verify the environment, then press Enter to download the necessary packages, or close to quit.
echo ----
pause
@rem STEP 3: Download the packages and create a working installation
cd /d "%OUT_DIR%\"
start "Install Easy Diffusion" /D "%OUT_DIR%" "Start Stable Diffusion UI.cmd"
echo ----
echo Installation in progress (in a new window). Once complete, verify the installation, then press Enter to create an installer from these files, or close to quit.
echo ----
pause
@rem STEP 4: Build the installer from a working installation
cd /d "%OUT_DIR%\"
echo ^^!define EXISTING_INSTALLATION_DIR "%OUT_DIR%" > nsisconf.nsh
call makensis /NOCD /V4 "%BASE_DIR%\NSIS\sdui.nsi"
echo ----
if "!ERRORLEVEL!" EQU "0" (
echo Installer built successfully at %OUT_DIR%
) else (
echo Installer failed to build at %OUT_DIR%
)
echo ----
pause

View File

@ -1,8 +1,8 @@
#!/bin/bash
printf "Hi there, what you are running is meant for the developers of this project, not for users.\n\n"
printf "If you only want to use Easy Diffusion, you've downloaded the wrong file.\n"
printf "Please download and follow the instructions at https://github.com/easydiffusion/easydiffusion#installation \n\n"
printf "If you only want to use the Stable Diffusion UI, you've downloaded the wrong file.\n"
printf "Please download and follow the instructions at https://github.com/cmdr2/stable-diffusion-ui#installation\n\n"
printf "If you are actually a developer of this project, please type Y and press enter\n\n"
read -p "Are you a developer of this project (Y/N) " yn
@ -11,30 +11,39 @@ case $yn in
* ) exit;;
esac
mkdir -p dist/linux-mac/easy-diffusion/scripts
# mkdir -p dist/win/stable-diffusion-ui/scripts
mkdir -p dist/linux-mac/stable-diffusion-ui/scripts
# copy the installer files for Windows
# cp scripts/on_env_start.bat dist/win/stable-diffusion-ui/scripts/
# cp scripts/bootstrap.bat dist/win/stable-diffusion-ui/scripts/
# cp "scripts/Start Stable Diffusion UI.cmd" dist/win/stable-diffusion-ui/
# cp LICENSE dist/win/stable-diffusion-ui/
# cp "CreativeML Open RAIL-M License" dist/win/stable-diffusion-ui/
# cp "How to install and run.txt" dist/win/stable-diffusion-ui/
# echo "" > dist/win/stable-diffusion-ui/scripts/install_status.txt
# copy the installer files for Linux and Mac
cp scripts/on_env_start.sh dist/linux-mac/easy-diffusion/scripts/
cp scripts/bootstrap.sh dist/linux-mac/easy-diffusion/scripts/
cp scripts/functions.sh dist/linux-mac/easy-diffusion/scripts/
cp scripts/config.yaml.sample dist/linux-mac/easy-diffusion/scripts/config.yaml.sample
cp scripts/start.sh dist/linux-mac/easy-diffusion/
cp LICENSE dist/linux-mac/easy-diffusion/
cp "CreativeML Open RAIL-M License" dist/linux-mac/easy-diffusion/
cp "How to install and run.txt" dist/linux-mac/easy-diffusion/
echo "" > dist/linux-mac/easy-diffusion/scripts/install_status.txt
# set the permissions
chmod u+x dist/linux-mac/easy-diffusion/scripts/on_env_start.sh
chmod u+x dist/linux-mac/easy-diffusion/scripts/bootstrap.sh
chmod u+x dist/linux-mac/easy-diffusion/start.sh
cp scripts/on_env_start.sh dist/linux-mac/stable-diffusion-ui/scripts/
cp scripts/bootstrap.sh dist/linux-mac/stable-diffusion-ui/scripts/
cp scripts/functions.sh dist/linux-mac/stable-diffusion-ui/scripts/
cp scripts/start.sh dist/linux-mac/stable-diffusion-ui/
cp LICENSE dist/linux-mac/stable-diffusion-ui/
cp "CreativeML Open RAIL-M License" dist/linux-mac/stable-diffusion-ui/
cp "How to install and run.txt" dist/linux-mac/stable-diffusion-ui/
echo "" > dist/linux-mac/stable-diffusion-ui/scripts/install_status.txt
# make the zip
# cd dist/win
# zip -r ../stable-diffusion-ui-windows.zip stable-diffusion-ui
# cd ../..
cd dist/linux-mac
zip -r ../Easy-Diffusion-Linux.zip easy-diffusion
zip -r ../Easy-Diffusion-Mac.zip easy-diffusion
zip -r ../stable-diffusion-ui-linux.zip stable-diffusion-ui
zip -r ../stable-diffusion-ui-mac.zip stable-diffusion-ui
cd ../..
echo "Build ready. Upload the zip files inside the 'dist' folder."

View File

@ -2,9 +2,7 @@
echo "Opening Stable Diffusion UI - Developer Console.." & echo.
cd /d %~dp0
set PATH=C:\Windows\System32;C:\Windows\System32\WindowsPowerShell\v1.0;%PATH%
set PATH=C:\Windows\System32;%PATH%
@rem set legacy and new installer's PATH, if they exist
if exist "installer" set PATH=%cd%\installer;%cd%\installer\Library\bin;%cd%\installer\Scripts;%cd%\installer\Library\usr\bin;%PATH%
@ -24,32 +22,21 @@ call where conda
call conda --version
echo.
echo COMSPEC=%COMSPEC%
echo.
powershell -Command "(Get-WmiObject Win32_VideoController | Select-Object Name, AdapterRAM, DriverDate, DriverVersion)"
@rem activate the legacy environment (if present) and set PYTHONPATH
if exist "installer_files\env" (
set PYTHONPATH=%cd%\installer_files\env\lib\site-packages
set PYTHON=%cd%\installer_files\env\python.exe
echo PYTHON=%PYTHON%
)
if exist "stable-diffusion\env" (
call conda activate .\stable-diffusion\env
set PYTHONPATH=%cd%\stable-diffusion\env\lib\site-packages
set PYTHON=%cd%\stable-diffusion\env\python.exe
echo PYTHON=%PYTHON%
)
@REM call where python
call "%PYTHON%" --version
call where python
call python --version
echo PYTHONPATH=%PYTHONPATH%
if exist "%cd%\profile" (
set HF_HOME=%cd%\profile\.cache\huggingface
)
@rem done
echo.

View File

@ -3,8 +3,7 @@
cd /d %~dp0
echo Install dir: %~dp0
set PATH=C:\Windows\System32;C:\Windows\System32\WindowsPowerShell\v1.0;%PATH%
set PYTHONHOME=
set PATH=C:\Windows\System32;%PATH%
if exist "on_sd_start.bat" (
echo ================================================================================
@ -15,7 +14,7 @@ if exist "on_sd_start.bat" (
echo download. This will not work.
echo.
echo Recommended: Please close this window and download the installer from
echo https://easydiffusion.github.io/docs/installation/
echo https://stable-diffusion-ui.github.io/docs/installation/
echo.
echo ================================================================================
echo.
@ -37,10 +36,8 @@ call git --version
call where conda
call conda --version
echo .
echo COMSPEC=%COMSPEC%
powershell -Command "(Get-WmiObject Win32_VideoController | Select-Object Name, AdapterRAM, DriverDate, DriverVersion)"
@rem Download the rest of the installer and UI
call scripts\on_env_start.bat
@pause

View File

@ -11,11 +11,9 @@ setlocal enabledelayedexpansion
set MAMBA_ROOT_PREFIX=%cd%\installer_files\mamba
set INSTALL_ENV_DIR=%cd%\installer_files\env
set LEGACY_INSTALL_ENV_DIR=%cd%\installer
set MICROMAMBA_DOWNLOAD_URL=https://github.com/easydiffusion/easydiffusion/releases/download/v1.1/micromamba.exe
set MICROMAMBA_DOWNLOAD_URL=https://github.com/cmdr2/stable-diffusion-ui/releases/download/v1.1/micromamba.exe
set umamba_exists=F
set PYTHONHOME=
set OLD_APPDATA=%APPDATA%
set OLD_USERPROFILE=%USERPROFILE%
set APPDATA=%cd%\installer_files\appdata
@ -24,12 +22,15 @@ set USERPROFILE=%cd%\profile
@rem figure out whether git and conda needs to be installed
if exist "%INSTALL_ENV_DIR%" set PATH=%INSTALL_ENV_DIR%;%INSTALL_ENV_DIR%\Library\bin;%INSTALL_ENV_DIR%\Scripts;%INSTALL_ENV_DIR%\Library\usr\bin;%PATH%
set PACKAGES_TO_INSTALL=git python=3.9
set PACKAGES_TO_INSTALL=
if not exist "%LEGACY_INSTALL_ENV_DIR%\etc\profile.d\conda.sh" (
if not exist "%INSTALL_ENV_DIR%\etc\profile.d\conda.sh" set PACKAGES_TO_INSTALL=%PACKAGES_TO_INSTALL% conda
if not exist "%INSTALL_ENV_DIR%\etc\profile.d\conda.sh" set PACKAGES_TO_INSTALL=%PACKAGES_TO_INSTALL% conda python=3.8.5
)
call git --version >.tmp1 2>.tmp2
if "!ERRORLEVEL!" NEQ "0" set PACKAGES_TO_INSTALL=%PACKAGES_TO_INSTALL% git
call "%MAMBA_ROOT_PREFIX%\micromamba.exe" --version >.tmp1 2>.tmp2
if "!ERRORLEVEL!" EQU "0" set umamba_exists=T

View File

@ -46,7 +46,7 @@ if [ -e "$INSTALL_ENV_DIR" ]; then export PATH="$INSTALL_ENV_DIR/bin:$PATH"; fi
PACKAGES_TO_INSTALL=""
if [ ! -e "$LEGACY_INSTALL_ENV_DIR/etc/profile.d/conda.sh" ] && [ ! -e "$INSTALL_ENV_DIR/etc/profile.d/conda.sh" ]; then PACKAGES_TO_INSTALL="$PACKAGES_TO_INSTALL conda python=3.9"; fi
if [ ! -e "$LEGACY_INSTALL_ENV_DIR/etc/profile.d/conda.sh" ] && [ ! -e "$INSTALL_ENV_DIR/etc/profile.d/conda.sh" ]; then PACKAGES_TO_INSTALL="$PACKAGES_TO_INSTALL conda python=3.8.5"; fi
if ! hash "git" &>/dev/null; then PACKAGES_TO_INSTALL="$PACKAGES_TO_INSTALL git"; fi
if "$MAMBA_ROOT_PREFIX/micromamba" --version &>/dev/null; then umamba_exists="T"; fi

View File

@ -8,42 +8,23 @@ a custom index URL depending on the platform.
"""
import os, sys
import os
from importlib.metadata import version as pkg_version
import platform
import traceback
import shutil
from pathlib import Path
from pprint import pprint
import re
import torchruntime
from torchruntime.device_db import get_gpus
os_name = platform.system()
modules_to_check = {
"setuptools": "69.5.1",
# "sdkit": "2.0.15.6", # checked later
# "diffusers": "0.21.4", # checked later
"stable-diffusion-sdkit": "2.1.5",
"torch": ("1.11.0", "1.13.1", "2.0.0"),
"torchvision": ("0.12.0", "0.14.1", "0.15.1"),
"sdkit": "1.0.101",
"stable-diffusion-sdkit": "2.1.4",
"rich": "12.6.0",
"uvicorn": "0.19.0",
"fastapi": "0.115.6",
"pycloudflared": "0.2.0",
"ruamel.yaml": "0.17.21",
"sqlalchemy": "2.0.19",
"python-multipart": "0.0.6",
"fastapi": "0.85.1",
# "xformers": "0.0.16",
"huggingface-hub": "0.21.4",
"wandb": "0.17.2",
# "torchruntime": "1.16.2",
"torchsde": "0.2.6",
"basicsr": "1.4.2",
"gfpgan": "1.3.8",
}
modules_to_log = ["torchruntime", "torch", "torchvision", "sdkit", "stable-diffusion-sdkit", "diffusers"]
BLACKWELL_DEVICES = re.compile(r"\b(?:5060|5070|5080|5090)\b")
def version(module_name: str) -> str:
@ -53,60 +34,53 @@ def version(module_name: str) -> str:
return None
def install(module_name: str, module_version: str, index_url=None):
install_cmd = f'"{sys.executable}" -m pip install --upgrade {module_name}=={module_version}'
def install(module_name: str, module_version: str):
if module_name == "xformers" and (os_name == "Darwin" or is_amd_on_linux()):
return
index_url = None
if module_name in ("torch", "torchvision"):
module_version, index_url = apply_torch_install_overrides(module_version)
if is_amd_on_linux(): # hack until AMD works properly on torch 2.0 (avoids black images on some cards)
if module_name == "torch":
module_version = "1.13.1+rocm5.2"
elif module_name == "torchvision":
module_version = "0.14.1+rocm5.2"
elif os_name == "Darwin":
if module_name == "torch":
module_version = "1.13.1"
elif module_name == "torchvision":
module_version = "0.14.1"
install_cmd = f"python -m pip install --upgrade {module_name}=={module_version}"
if index_url:
install_cmd += f" --index-url {index_url}"
if module_name == "sdkit" and version("sdkit") is not None:
install_cmd += " -q"
if module_name in ("basicsr", "gfpgan"):
install_cmd += " --use-pep517" # potential fix for https://github.com/easydiffusion/easydiffusion/issues/1942
print(">", install_cmd)
os.system(install_cmd)
def update_modules():
if version("torch") is None:
torchruntime.install(["torch", "torchvision"])
else:
torch_version_str = version("torch")
torch_version = version_str_to_tuple(torch_version_str)
is_cpu_torch = "+" not in torch_version_str
print(f"Current torch version: {torch_version} ({torch_version_str})")
if torch_version < (2, 7) or is_cpu_torch:
gpu_infos = get_gpus()
device_names = set(gpu.device_name for gpu in gpu_infos)
if any(BLACKWELL_DEVICES.search(device_name) for device_name in device_names):
if sys.version_info < (3, 9):
print(
"\n###################################\n"
"NVIDIA 50xx series of graphics cards detected!\n\n"
"To use this graphics card, please install the latest version of Easy Diffusion from: https://github.com/easydiffusion/easydiffusion#installation"
"\n###################################\n"
)
sys.exit()
else:
print("Upgrading torch to support NVIDIA 50xx series of graphics cards")
torchruntime.install(["--force", "--upgrade", "torch", "torchvision"])
def init():
for module_name, allowed_versions in modules_to_check.items():
if os.path.exists(f"src/{module_name}"):
if os.path.exists(f"../src/{module_name}"):
print(f"Skipping {module_name} update, since it's in developer/editable mode")
continue
allowed_versions, latest_version = get_allowed_versions(module_name, allowed_versions)
if module_name == "setuptools":
if os_name == "Windows":
allowed_versions = ("59.8.0",)
latest_version = "59.8.0"
else:
allowed_versions = ("69.5.1",)
latest_version = "69.5.1"
requires_install = version(module_name) not in allowed_versions
requires_install = False
if module_name in ("torch", "torchvision"):
if version(module_name) is None: # allow any torch version
requires_install = True
elif os_name == "Darwin" and ( # force mac to downgrade from torch 2.0
version("torch").startswith("2.") or version("torchvision").startswith("0.15.")
):
requires_install = True
elif version(module_name) not in allowed_versions:
requires_install = True
if requires_install:
try:
@ -114,235 +88,71 @@ def update_modules():
except:
traceback.print_exc()
fail(module_name)
else:
if version(module_name) != latest_version:
print(
f"WARNING! Tried to install {module_name}=={latest_version}, but the version is still {version(module_name)}!"
)
# different sdkit versions, with the corresponding diffusers
# if sdkit is 2.0.15.x (or lower), then diffusers should be restricted to 0.21.4 (see below for the reason)
# otherwise use the current sdkit version (with the corresponding diffusers version)
expected_sdkit_version_str = "2.0.22.8"
expected_diffusers_version_str = "0.28.2"
legacy_sdkit_version_str = "2.0.15.17"
legacy_diffusers_version_str = "0.21.4"
sdkit_version_str = version("sdkit")
if sdkit_version_str is None: # first install
_install("sdkit", expected_sdkit_version_str)
_install("diffusers", expected_diffusers_version_str)
else:
sdkit_version = version_str_to_tuple(sdkit_version_str)
legacy_sdkit_version = version_str_to_tuple(legacy_sdkit_version_str)
if sdkit_version[:3] <= legacy_sdkit_version[:3]:
# stick to diffusers 0.21.4, since it preserves torch 0.11+ compatibility.
# upgrading beyond this will result in a 2+ GB download of torch on older installations
# and a time-consuming chain of small package updates due to huggingface_hub upgrade.
# for now, the user will need to explicitly upgrade to a newer sdkit, to break this ceiling.
install_pkg_if_necessary("sdkit", legacy_sdkit_version_str)
install_pkg_if_necessary("diffusers", legacy_diffusers_version_str)
else:
torch_version = version_str_to_tuple(version("torch"))
if torch_version < (1, 13):
# install the gpu-compatible torch (if necessary), instead of the default CPU-only one
# from the diffusers dependency chain
torchruntime.install(["--upgrade", "torch", "torchvision"])
install_pkg_if_necessary("sdkit", expected_sdkit_version_str)
install_pkg_if_necessary("diffusers", expected_diffusers_version_str)
# hotfix accelerate
accelerate_version = version("accelerate")
if accelerate_version is None:
install("accelerate", "0.23.0")
else:
accelerate_version = accelerate_version.split(".")
accelerate_version = tuple(map(int, accelerate_version))
if accelerate_version < (0, 23):
install("accelerate", "0.23.0")
# hotfix - 29 May 2024. sdkit has stopped pulling its dependencies for some reason
# temporarily dumping sdkit's requirements here:
if os_name != "Windows":
sdkit_deps = [
"gfpgan",
"piexif",
"realesrgan",
"requests",
"picklescan",
"safetensors==0.3.3",
"k-diffusion==0.0.12",
"compel==2.0.1",
"controlnet-aux==0.0.6",
"invisible-watermark==0.2.0", # required for SD XL
]
for mod in sdkit_deps:
mod_name = mod
mod_force_version_str = None
if "==" in mod:
mod_name, mod_force_version_str = mod.split("==")
curr_mod_version_str = version(mod_name)
if curr_mod_version_str is None:
_install(mod_name, mod_force_version_str)
elif mod_force_version_str is not None:
curr_mod_version = version_str_to_tuple(curr_mod_version_str)
mod_force_version = version_str_to_tuple(mod_force_version_str)
if curr_mod_version != mod_force_version:
_install(mod_name, mod_force_version_str)
for module_name in modules_to_log:
print(f"{module_name}: {version(module_name)}")
def _install(module_name, module_version=None):
if module_version is None:
install_cmd = f'"{sys.executable}" -m pip install {module_name}'
else:
install_cmd = f'"{sys.executable}" -m pip install --upgrade {module_name}=={module_version}'
print(">", install_cmd)
os.system(install_cmd)
def install_pkg_if_necessary(pkg_name, required_version):
if os.path.exists(f"src/{pkg_name}"):
print(f"Skipping {pkg_name} update, since it's in developer/editable mode")
return
pkg_version = version(pkg_name)
if pkg_version != required_version:
_install(pkg_name, required_version)
def version_str_to_tuple(ver_str):
ver_str = ver_str.split("+")[0]
ver_str = re.sub("[^0-9.]", "", ver_str)
ver = ver_str.split(".")
return tuple(map(int, ver))
### utilities
def get_allowed_versions(module_name: str, allowed_versions: tuple):
allowed_versions = (allowed_versions,) if isinstance(allowed_versions, str) else allowed_versions
latest_version = allowed_versions[-1]
if module_name in ("torch", "torchvision"):
allowed_versions = include_cuda_versions(allowed_versions)
return allowed_versions, latest_version
def apply_torch_install_overrides(module_version: str):
index_url = None
if os_name == "Windows":
module_version += "+cu117"
index_url = "https://download.pytorch.org/whl/cu117"
elif is_amd_on_linux():
index_url = "https://download.pytorch.org/whl/rocm5.2"
return module_version, index_url
def include_cuda_versions(module_versions: tuple) -> tuple:
"Adds CUDA-specific versions to the list of allowed version numbers"
allowed_versions = tuple(module_versions)
allowed_versions += tuple(f"{v}+cu116" for v in module_versions)
allowed_versions += tuple(f"{v}+cu117" for v in module_versions)
allowed_versions += tuple(f"{v}+rocm5.2" for v in module_versions)
allowed_versions += tuple(f"{v}+rocm5.4.2" for v in module_versions)
return allowed_versions
def is_amd_on_linux():
if os_name == "Linux":
try:
with open("/proc/bus/pci/devices", "r") as f:
device_info = f.read()
if "amdgpu" in device_info and "nvidia" not in device_info:
return True
except:
return False
return False
def fail(module_name):
print(
f"""Error installing {module_name}. Sorry about that, please try to:
1. Run this installer again.
2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting
2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting
3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB
4. If that doesn't solve the problem, please file an issue at https://github.com/easydiffusion/easydiffusion/issues
4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues
Thanks!"""
)
exit(1)
### Launcher
### start
def get_config():
config_directory = os.path.dirname(__file__) # this will be "scripts"
config_yaml = os.path.join(config_directory, "..", "config.yaml")
config_json = os.path.join(config_directory, "config.json")
config = None
# migrate the old config yaml location
config_legacy_yaml = os.path.join(config_directory, "config.yaml")
if os.path.isfile(config_legacy_yaml):
shutil.move(config_legacy_yaml, config_yaml)
if os.path.isfile(config_yaml):
from ruamel.yaml import YAML
yaml = YAML(typ="safe")
with open(config_yaml, "r") as configfile:
try:
config = yaml.load(configfile)
except Exception as e:
print(e, file=sys.stderr)
elif os.path.isfile(config_json):
import json
with open(config_json, "r") as configfile:
try:
config = json.load(configfile)
except Exception as e:
print(e, file=sys.stderr)
if config is None:
config = {}
return config
def launch_uvicorn():
config = get_config()
pprint(config)
with open("scripts/install_status.txt", "a") as f:
f.write("sd_weights_downloaded\n")
f.write("sd_install_complete\n")
print("\n\nEasy Diffusion installation complete, starting the server!\n\n")
torchruntime.configure()
if hasattr(torchruntime, "info"):
torchruntime.info()
if os_name == "Windows":
os.environ["PYTHONPATH"] = str(Path(os.environ["INSTALL_ENV_DIR"], "lib", "site-packages"))
else:
os.environ["PYTHONPATH"] = str(Path(os.environ["INSTALL_ENV_DIR"], "lib", "python3.8", "site-packages"))
os.environ["SD_UI_PATH"] = str(Path(Path.cwd(), "ui"))
print(f"PYTHONPATH={os.environ['PYTHONPATH']}")
print(f"Python: {shutil.which('python')}")
print(f"Version: {platform. python_version()}")
bind_ip = "127.0.0.1"
listen_port = 9000
if "net" in config:
print("Checking network settings")
if "listen_port" in config["net"]:
listen_port = config["net"]["listen_port"]
print("Set listen port to ", listen_port)
if "listen_to_network" in config["net"] and config["net"]["listen_to_network"] == True:
if "bind_ip" in config["net"]:
bind_ip = config["net"]["bind_ip"]
else:
bind_ip = "0.0.0.0"
print("Set bind_ip to ", bind_ip)
os.chdir("stable-diffusion")
print("\nLaunching uvicorn\n")
import uvicorn
uvicorn.run(
"main:server_api",
port=listen_port,
log_level="error",
app_dir=os.environ["SD_UI_PATH"],
host=bind_ip,
access_log=False,
)
update_modules()
if len(sys.argv) > 1 and sys.argv[1] == "--launch-uvicorn":
launch_uvicorn()
init()

View File

@ -1,24 +0,0 @@
# Change listen_port if port 9000 is already in use on your system
# Set listen_to_network to true to make Easy Diffusion accessibble on your local network
net:
listen_port: 9000
listen_to_network: false
# Multi GPU setup
render_devices: auto
# Set open_browser_on_start to false to disable opening a new browser tab on each restart
ui:
open_browser_on_start: true
# set update_branch to main to use the stable version, or to beta to use the experimental
# beta version.
update_branch: main
# Set force_save_path to enforce an auto save path. Clients will not be able to change or
# disable auto save when this option is set. Please adapt the path in the examples to your
# needs.
# Windows:
# force_save_path: C:\\Easy Diffusion Images\\
# Linux:
# force_save_path: /data/easy-diffusion-images/

View File

@ -39,8 +39,6 @@ if [ "$0" == "bash" ]; then
export PYTHONPATH="$(pwd)/stable-diffusion/env/lib/python3.8/site-packages"
fi
export PYTHONNOUSERSITE=y
which python
python --version

View File

@ -15,9 +15,9 @@ fail() {
Error downloading Stable Diffusion UI. Sorry about that, please try to:
1. Run this installer again.
2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting
2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting
3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB
4. If that doesn't solve the problem, please file an issue at https://github.com/easydiffusion/easydiffusion/issues
4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues
Thanks!

View File

@ -1,11 +1,10 @@
import os
import argparse
import sys
import shutil
# The config file is in the same directory as this script
config_directory = os.path.dirname(__file__)
config_yaml = os.path.join(config_directory, "..", "config.yaml")
config_yaml = os.path.join(config_directory, "config.yaml")
config_json = os.path.join(config_directory, "config.json")
parser = argparse.ArgumentParser(description='Get values from config file')
@ -16,21 +15,15 @@ parser.add_argument('key', metavar='key', nargs='+',
args = parser.parse_args()
config = None
# migrate the old config yaml location
config_legacy_yaml = os.path.join(config_directory, "config.yaml")
if os.path.isfile(config_legacy_yaml):
shutil.move(config_legacy_yaml, config_yaml)
if os.path.isfile(config_yaml):
from ruamel.yaml import YAML
yaml = YAML(typ='safe')
import yaml
with open(config_yaml, 'r') as configfile:
try:
config = yaml.load(configfile)
config = yaml.safe_load(configfile)
except Exception as e:
print(e, file=sys.stderr)
config = {}
elif os.path.isfile(config_json):
import json
with open(config_json, 'r') as configfile:
@ -38,8 +31,8 @@ elif os.path.isfile(config_json):
config = json.load(configfile)
except Exception as e:
print(e, file=sys.stderr)
if config is None:
config = {}
else:
config = {}
for k in args.key:

View File

@ -1,6 +1,6 @@
@echo off
@echo. & echo "Easy Diffusion - v3" & echo.
@echo. & echo "Easy Diffusion - v2" & echo.
set PATH=C:\Windows\System32;%PATH%
@ -26,19 +26,19 @@ if "%update_branch%"=="" (
set update_branch=main
)
@REM @>nul findstr /m "sd_install_complete" scripts\install_status.txt
@REM @if "%ERRORLEVEL%" NEQ "0" (
@REM for /f "tokens=*" %%a in ('python -c "import os; parts = os.getcwd().split(os.path.sep); print(len(parts))"') do if "%%a" NEQ "2" (
@REM echo. & echo "!!!! WARNING !!!!" & echo.
@REM echo "Your 'stable-diffusion-ui' folder is at %cd%" & echo.
@REM echo "The 'stable-diffusion-ui' folder needs to be at the top of your drive, for e.g. 'C:\stable-diffusion-ui' or 'D:\stable-diffusion-ui' etc."
@REM echo "Not placing this folder at the top of a drive can cause errors on some computers."
@REM echo. & echo "Recommended: Please close this window and move the 'stable-diffusion-ui' folder to the top of a drive. For e.g. 'C:\stable-diffusion-ui'. Then run the installer again." & echo.
@REM echo "Not Recommended: If you're sure that you want to install at the current location, please press any key to continue." & echo.
@>nul findstr /m "conda_sd_ui_deps_installed" scripts\install_status.txt
@if "%ERRORLEVEL%" NEQ "0" (
for /f "tokens=*" %%a in ('python -c "import os; parts = os.getcwd().split(os.path.sep); print(len(parts))"') do if "%%a" NEQ "2" (
echo. & echo "!!!! WARNING !!!!" & echo.
echo "Your 'stable-diffusion-ui' folder is at %cd%" & echo.
echo "The 'stable-diffusion-ui' folder needs to be at the top of your drive, for e.g. 'C:\stable-diffusion-ui' or 'D:\stable-diffusion-ui' etc."
echo "Not placing this folder at the top of a drive can cause errors on some computers."
echo. & echo "Recommended: Please close this window and move the 'stable-diffusion-ui' folder to the top of a drive. For e.g. 'C:\stable-diffusion-ui'. Then run the installer again." & echo.
echo "Not Recommended: If you're sure that you want to install at the current location, please press any key to continue." & echo.
@REM pause
@REM )
@REM )
pause
)
)
@>nul findstr /m "sd_ui_git_cloned" scripts\install_status.txt
@if "%ERRORLEVEL%" EQU "0" (
@ -46,8 +46,6 @@ if "%update_branch%"=="" (
@cd sd-ui-files
@call git add -A .
@call git stash
@call git reset --hard
@call git -c advice.detachedHead=false checkout "%update_branch%"
@call git pull
@ -57,10 +55,10 @@ if "%update_branch%"=="" (
@echo. & echo "Downloading Easy Diffusion..." & echo.
@echo "Using the %update_branch% channel" & echo.
@call git clone -b "%update_branch%" https://github.com/easydiffusion/easydiffusion.git sd-ui-files && (
@call git clone -b "%update_branch%" https://github.com/cmdr2/stable-diffusion-ui.git sd-ui-files && (
@echo sd_ui_git_cloned >> scripts\install_status.txt
) || (
@echo "Error downloading Easy Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/easydiffusion/easydiffusion/issues" & echo "Thanks!"
@echo "Error downloading Easy Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!"
pause
@exit /b
)
@ -69,8 +67,8 @@ if "%update_branch%"=="" (
@xcopy sd-ui-files\ui ui /s /i /Y /q
@copy sd-ui-files\scripts\on_sd_start.bat scripts\ /Y
@copy sd-ui-files\scripts\check_modules.py scripts\ /Y
@copy sd-ui-files\scripts\check_models.py scripts\ /Y
@copy sd-ui-files\scripts\get_config.py scripts\ /Y
@copy sd-ui-files\scripts\config.yaml.sample scripts\ /Y
@copy "sd-ui-files\scripts\Start Stable Diffusion UI.cmd" . /Y
@copy "sd-ui-files\scripts\Developer Console.cmd" . /Y

View File

@ -2,7 +2,7 @@
source ./scripts/functions.sh
printf "\n\nEasy Diffusion - v3\n\n"
printf "\n\nEasy Diffusion\n\n"
export PYTHONNOUSERSITE=y
@ -29,8 +29,6 @@ if [ -f "scripts/install_status.txt" ] && [ `grep -c sd_ui_git_cloned scripts/in
cd sd-ui-files
git add -A .
git stash
git reset --hard
git -c advice.detachedHead=false checkout "$update_branch"
git pull
@ -40,7 +38,7 @@ else
printf "\n\nDownloading Easy Diffusion..\n\n"
printf "Using the $update_branch channel\n\n"
if git clone -b "$update_branch" https://github.com/easydiffusion/easydiffusion.git sd-ui-files ; then
if git clone -b "$update_branch" https://github.com/cmdr2/stable-diffusion-ui.git sd-ui-files ; then
echo sd_ui_git_cloned >> scripts/install_status.txt
else
fail "git clone failed"
@ -52,8 +50,8 @@ cp -Rf sd-ui-files/ui .
cp sd-ui-files/scripts/on_sd_start.sh scripts/
cp sd-ui-files/scripts/bootstrap.sh scripts/
cp sd-ui-files/scripts/check_modules.py scripts/
cp sd-ui-files/scripts/check_models.py scripts/
cp sd-ui-files/scripts/get_config.py scripts/
cp sd-ui-files/scripts/config.yaml.sample scripts/
cp sd-ui-files/scripts/start.sh .
cp sd-ui-files/scripts/developer_console.sh .
cp sd-ui-files/scripts/functions.sh scripts/

View File

@ -5,8 +5,8 @@
@copy sd-ui-files\scripts\on_env_start.bat scripts\ /Y
@copy sd-ui-files\scripts\check_modules.py scripts\ /Y
@copy sd-ui-files\scripts\check_models.py scripts\ /Y
@copy sd-ui-files\scripts\get_config.py scripts\ /Y
@copy sd-ui-files\scripts\config.yaml.sample scripts\ /Y
if exist "%cd%\profile" (
set HF_HOME=%cd%\profile\.cache\huggingface
@ -27,14 +27,13 @@ if exist "%cd%\stable-diffusion\env" (
@rem activate the installer env
call conda activate
@if "%ERRORLEVEL%" NEQ "0" (
@echo. & echo "Error activating conda for Easy Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/easydiffusion/easydiffusion/issues" & echo "Thanks!" & echo.
@echo. & echo "Error activating conda for Easy Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
pause
exit /b
)
@REM remove the old version of the dev console script, if it's still present
if exist "Open Developer Console.cmd" del "Open Developer Console.cmd"
if exist "ui\plugins\ui\merge.plugin.js" del "ui\plugins\ui\merge.plugin.js"
@rem create the stable-diffusion folder, to work with legacy installations
if not exist "stable-diffusion" mkdir stable-diffusion
@ -53,30 +52,70 @@ if exist ldm rename ldm ldm-old
if not exist "%INSTALL_ENV_DIR%\DLLs\libssl-1_1-x64.dll" copy "%INSTALL_ENV_DIR%\Library\bin\libssl-1_1-x64.dll" "%INSTALL_ENV_DIR%\DLLs\"
if not exist "%INSTALL_ENV_DIR%\DLLs\libcrypto-1_1-x64.dll" copy "%INSTALL_ENV_DIR%\Library\bin\libcrypto-1_1-x64.dll" "%INSTALL_ENV_DIR%\DLLs\"
cd ..
@rem set any overrides
set HF_HUB_DISABLE_SYMLINKS_WARNING=true
@rem install or upgrade the required modules
set PATH=C:\Windows\System32;%PATH%
@REM prevent from using packages from the user's home directory, to avoid conflicts
set PYTHONNOUSERSITE=1
set PYTHONPATH=%INSTALL_ENV_DIR%\lib\site-packages
echo PYTHONPATH=%PYTHONPATH%
set PYTHON=%INSTALL_ENV_DIR%\python.exe
echo PYTHON=%PYTHON%
@rem Download the required packages
@REM call where python
call "%PYTHON%" --version
call python ..\scripts\check_modules.py
if "%ERRORLEVEL%" NEQ "0" (
pause
exit /b
)
@rem this is outside check_modules.py to ensure that the required version of torchruntime is present
call "%PYTHON%" -m pip install -q "torchruntime>=1.19.1"
call WHERE uvicorn > .tmp
@>nul findstr /m "uvicorn" .tmp
@if "%ERRORLEVEL%" NEQ "0" (
@echo. & echo "UI packages not found! Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
pause
exit /b
)
call "%PYTHON%" scripts\check_modules.py --launch-uvicorn
pause
exit /b
@>nul findstr /m "conda_sd_ui_deps_installed" ..\scripts\install_status.txt
@if "%ERRORLEVEL%" NEQ "0" (
@echo conda_sd_ui_deps_installed >> ..\scripts\install_status.txt
)
@>nul findstr /m "sd_install_complete" ..\scripts\install_status.txt
@if "%ERRORLEVEL%" NEQ "0" (
@echo sd_weights_downloaded >> ..\scripts\install_status.txt
@echo sd_install_complete >> ..\scripts\install_status.txt
)
@echo. & echo "Easy Diffusion installation complete! Starting the server!" & echo.
@set SD_DIR=%cd%
set PYTHONPATH=%INSTALL_ENV_DIR%\lib\site-packages
echo PYTHONPATH=%PYTHONPATH%
call where python
call python --version
@cd ..
@set SD_UI_PATH=%cd%\ui
@FOR /F "tokens=* USEBACKQ" %%F IN (`python scripts\get_config.py --default=9000 net listen_port`) DO (
@SET ED_BIND_PORT=%%F
)
@FOR /F "tokens=* USEBACKQ" %%F IN (`python scripts\get_config.py --default=False net listen_to_network`) DO (
if "%%F" EQU "True" (
@SET ED_BIND_IP=0.0.0.0
) else (
@SET ED_BIND_IP=127.0.0.1
)
)
@cd stable-diffusion
@rem set any overrides
set HF_HUB_DISABLE_SYMLINKS_WARNING=true
@uvicorn main:server_api --app-dir "%SD_UI_PATH%" --port %ED_BIND_PORT% --host %ED_BIND_IP% --log-level error
@pause

View File

@ -4,9 +4,8 @@ cp sd-ui-files/scripts/functions.sh scripts/
cp sd-ui-files/scripts/on_env_start.sh scripts/
cp sd-ui-files/scripts/bootstrap.sh scripts/
cp sd-ui-files/scripts/check_modules.py scripts/
cp sd-ui-files/scripts/check_models.py scripts/
cp sd-ui-files/scripts/get_config.py scripts/
cp sd-ui-files/scripts/config.yaml.sample scripts/
source ./scripts/functions.sh
@ -21,10 +20,6 @@ if [ -e "open_dev_console.sh" ]; then
rm "open_dev_console.sh"
fi
if [ -e "ui/plugins/ui/merge.plugin.js" ]; then
rm "ui/plugins/ui/merge.plugin.js"
fi
# set the correct installer path (current vs legacy)
if [ -e "installer_files/env" ]; then
export INSTALL_ENV_DIR="$(pwd)/installer_files/env"
@ -46,11 +41,45 @@ fi
if [ -e "src" ]; then mv src src-old; fi
if [ -e "ldm" ]; then mv ldm ldm-old; fi
# this is outside check_modules.py to ensure that the required version of torchruntime is present
python -m pip install -q "torchruntime>=1.19.1"
# Download the required packages
if ! python ../scripts/check_modules.py; then
read -p "Press any key to continue"
exit 1
fi
if ! command -v uvicorn &> /dev/null; then
fail "UI packages not found!"
fi
if [ `grep -c sd_install_complete ../scripts/install_status.txt` -gt "0" ]; then
echo sd_weights_downloaded >> ../scripts/install_status.txt
echo sd_install_complete >> ../scripts/install_status.txt
fi
printf "\n\nEasy Diffusion installation complete, starting the server!\n\n"
SD_PATH=`pwd`
export PYTORCH_ENABLE_MPS_FALLBACK=1
export PYTHONPATH="$INSTALL_ENV_DIR/lib/python3.8/site-packages"
echo "PYTHONPATH=$PYTHONPATH"
which python
python --version
cd ..
# Download the required packages
python scripts/check_modules.py --launch-uvicorn
export SD_UI_PATH=`pwd`/ui
export ED_BIND_PORT="$( python scripts/get_config.py --default=9000 net listen_port )"
case "$( python scripts/get_config.py --default=False net listen_to_network )" in
"True")
export ED_BIND_IP=0.0.0.0
;;
"False")
export ED_BIND_IP=127.0.0.1
;;
esac
cd stable-diffusion
uvicorn main:server_api --app-dir "$SD_UI_PATH" --port "$ED_BIND_PORT" --host "$ED_BIND_IP" --log-level error
read -p "Press any key to continue"

View File

@ -11,7 +11,7 @@ if [ -f "on_sd_start.bat" ]; then
echo download. This will not work.
echo
echo Recommended: Please close this window and download the installer from
echo https://easydiffusion.github.io/docs/installation/
echo https://stable-diffusion-ui.github.io/docs/installation/
echo
echo ================================================================================
echo
@ -19,7 +19,6 @@ if [ -f "on_sd_start.bat" ]; then
exit 1
fi
unset PYTHONHOME
# set legacy installer's PATH, if it exists
if [ -e "installer" ]; then export PATH="$(pwd)/installer/bin:$PATH"; fi

View File

@ -1,13 +1,9 @@
import json
import logging
import os
import shutil
import socket
import sys
import traceback
import copy
from ruamel.yaml import YAML
import urllib
import warnings
@ -32,12 +28,10 @@ logging.basicConfig(
SD_DIR = os.getcwd()
ROOT_DIR = os.path.abspath(os.path.join(SD_DIR, ".."))
SD_UI_DIR = os.getenv("SD_UI_PATH", None)
CONFIG_DIR = os.path.abspath(os.path.join(SD_UI_DIR, "..", "scripts"))
BUCKET_DIR = os.path.abspath(os.path.join(SD_DIR, "..", "bucket"))
MODELS_DIR = os.path.abspath(os.path.join(SD_DIR, "..", "models"))
USER_PLUGINS_DIR = os.path.abspath(os.path.join(SD_DIR, "..", "plugins"))
CORE_PLUGINS_DIR = os.path.abspath(os.path.join(SD_UI_DIR, "plugins"))
@ -54,12 +48,12 @@ OUTPUT_DIRNAME = "Stable Diffusion UI" # in the user's home folder
PRESERVE_CONFIG_VARS = ["FORCE_FULL_PRECISION"]
TASK_TTL = 15 * 60 # Discard last session's task timeout
APP_CONFIG_DEFAULTS = {
"render_devices": "auto",
# auto: selects the cuda device with the most free memory, cuda: use the currently active cuda device.
"render_devices": "auto", # valid entries: 'auto', 'cpu' or 'cuda:N' (where N is a GPU index)
"update_branch": "main",
"ui": {
"open_browser_on_start": True,
},
"use_v3_engine": True,
}
IMAGE_EXTENSIONS = [
@ -90,134 +84,47 @@ CUSTOM_MODIFIERS_LANDSCAPE_EXTENSIONS = [
"-landscape",
]
MODELS_DIR = os.path.abspath(os.path.join(SD_DIR, "..", "models"))
def init():
global MODELS_DIR
os.makedirs(USER_UI_PLUGINS_DIR, exist_ok=True)
os.makedirs(USER_SERVER_PLUGINS_DIR, exist_ok=True)
# https://pytorch.org/docs/stable/storage.html
warnings.filterwarnings("ignore", category=UserWarning, message="TypedStorage is deprecated")
config = getConfig()
config_models_dir = config.get("models_dir", None)
if (config_models_dir is not None and config_models_dir != ""):
MODELS_DIR = config_models_dir
def init_render_threads():
load_server_plugins()
update_render_threads()
def getConfig(default_val=APP_CONFIG_DEFAULTS):
config_yaml_path = os.path.join(CONFIG_DIR, "..", "config.yaml")
# migrate the old config yaml location
config_legacy_yaml = os.path.join(CONFIG_DIR, "config.yaml")
if os.path.isfile(config_legacy_yaml):
shutil.move(config_legacy_yaml, config_yaml_path)
def set_config_on_startup(config: dict):
if getConfig.__use_v3_engine_on_startup is None:
getConfig.__use_v3_engine_on_startup = config.get("use_v3_engine", True)
config["config_on_startup"] = {"use_v3_engine": getConfig.__use_v3_engine_on_startup}
if os.path.isfile(config_yaml_path):
try:
yaml = YAML()
with open(config_yaml_path, "r", encoding="utf-8") as f:
config = yaml.load(f)
if "net" not in config:
config["net"] = {}
if os.getenv("SD_UI_BIND_PORT") is not None:
config["net"]["listen_port"] = int(os.getenv("SD_UI_BIND_PORT"))
else:
config["net"]["listen_port"] = 9000
if os.getenv("SD_UI_BIND_IP") is not None:
config["net"]["listen_to_network"] = os.getenv("SD_UI_BIND_IP") == "0.0.0.0"
else:
config["net"]["listen_to_network"] = True
set_config_on_startup(config)
return config
except Exception as e:
log.warn(traceback.format_exc())
set_config_on_startup(default_val)
return default_val
else:
try:
config_json_path = os.path.join(CONFIG_DIR, "config.json")
if not os.path.exists(config_json_path):
return default_val
log.info("Converting old json config file to yaml")
try:
config_json_path = os.path.join(CONFIG_DIR, "config.json")
if not os.path.exists(config_json_path):
config = default_val
else:
with open(config_json_path, "r", encoding="utf-8") as f:
config = json.load(f)
# Save config in new format
setConfig(config)
with open(config_json_path + ".txt", "w") as f:
f.write("Moved to config.yaml inside the Easy Diffusion folder. You can open it in any text editor.")
os.remove(config_json_path)
return getConfig(default_val)
except Exception as e:
log.warn(traceback.format_exc())
set_config_on_startup(default_val)
return default_val
getConfig.__use_v3_engine_on_startup = None
if "net" not in config:
config["net"] = {}
if os.getenv("SD_UI_BIND_PORT") is not None:
config["net"]["listen_port"] = int(os.getenv("SD_UI_BIND_PORT"))
if os.getenv("SD_UI_BIND_IP") is not None:
config["net"]["listen_to_network"] = os.getenv("SD_UI_BIND_IP") == "0.0.0.0"
return config
except Exception:
log.warn(traceback.format_exc())
return default_val
def setConfig(config):
global MODELS_DIR
try: # config.yaml
config_yaml_path = os.path.join(CONFIG_DIR, "..", "config.yaml")
config_yaml_path = os.path.abspath(config_yaml_path)
yaml = YAML()
if not hasattr(config, "_yaml_comment"):
config_yaml_sample_path = os.path.join(CONFIG_DIR, "config.yaml.sample")
if os.path.exists(config_yaml_sample_path):
with open(config_yaml_sample_path, "r", encoding="utf-8") as f:
commented_config = yaml.load(f)
for k in config:
commented_config[k] = config[k]
config = commented_config
yaml.indent(mapping=2, sequence=4, offset=2)
if "config_on_startup" in config:
del config["config_on_startup"]
try:
f = open(config_yaml_path + ".tmp", "w", encoding="utf-8")
yaml.dump(config, f)
finally:
f.close() # do this explicitly to avoid NUL bytes (possible rare bug when using 'with')
# verify that the new file is valid, and only then overwrite the old config file
# helps prevent the rare NUL bytes error from corrupting the config file
yaml = YAML()
with open(config_yaml_path + ".tmp", "r", encoding="utf-8") as f:
yaml.load(f)
shutil.move(config_yaml_path + ".tmp", config_yaml_path)
try: # config.json
config_json_path = os.path.join(CONFIG_DIR, "config.json")
with open(config_json_path, "w", encoding="utf-8") as f:
json.dump(config, f)
except:
log.error(traceback.format_exc())
if config.get("models_dir"):
MODELS_DIR = config["models_dir"]
def save_to_config(ckpt_model_name, vae_model_name, hypernetwork_model_name, vram_usage_level):
config = getConfig()
@ -250,12 +157,10 @@ def update_render_threads():
def getUIPlugins():
plugins = []
file_names = set()
for plugins_dir, dir_prefix in UI_PLUGINS_SOURCES:
for file in os.listdir(plugins_dir):
if file.endswith(".plugin.js") and file not in file_names:
if file.endswith(".plugin.js"):
plugins.append(f"/plugins/{dir_prefix}/{file}")
file_names.add(file)
return plugins
@ -314,8 +219,6 @@ def open_browser():
if ui.get("open_browser_on_start", True):
import webbrowser
log.info("Opening browser..")
webbrowser.open(f"http://localhost:{port}")
Console().print(
@ -334,7 +237,7 @@ def fail_and_die(fail_type: str, data: str):
suggestions = [
"Run this installer again.",
"If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB",
"If that doesn't solve the problem, please file an issue at https://github.com/easydiffusion/easydiffusion/issues",
"If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues",
]
if fail_type == "model_download":

View File

@ -1,107 +0,0 @@
from typing import List
from fastapi import Depends, FastAPI, HTTPException, Response, File
from sqlalchemy.orm import Session
from easydiffusion.easydb import crud, models, schemas
from easydiffusion.easydb.database import SessionLocal, engine
from requests.compat import urlparse
import base64, json
MIME_TYPES = {
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"gif": "image/gif",
"png": "image/png",
"webp": "image/webp",
"js": "text/javascript",
"htm": "text/html",
"html": "text/html",
"css": "text/css",
"json": "application/json",
"mjs": "application/json",
"yaml": "application/yaml",
"svg": "image/svg+xml",
"txt": "text/plain",
}
def init():
from easydiffusion.server import server_api
models.BucketBase.metadata.create_all(bind=engine)
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@server_api.get("/bucket/{obj_path:path}")
def bucket_get_object(obj_path: str, db: Session = Depends(get_db)):
filename = get_filename_from_url(obj_path)
path = get_path_from_url(obj_path)
if filename==None:
bucket = crud.get_bucket_by_path(db, path=path)
if bucket == None:
raise HTTPException(status_code=404, detail="Bucket not found")
bucketfiles = db.query(models.BucketFile).with_entities(models.BucketFile.filename).filter(models.BucketFile.bucket_id == bucket.id).all()
bucketfiles = [ x.filename for x in bucketfiles ]
return bucketfiles
else:
bucket = crud.get_bucket_by_path(db, path)
if bucket == None:
raise HTTPException(status_code=404, detail="Bucket not found")
bucket_id = bucket.id
bucketfile = db.query(models.BucketFile).filter(models.BucketFile.bucket_id == bucket_id, models.BucketFile.filename == filename).first()
if bucketfile == None:
raise HTTPException(status_code=404, detail="File not found")
suffix = get_suffix_from_filename(filename)
return Response(content=bucketfile.data, media_type=MIME_TYPES.get(suffix, "application/octet-stream"))
@server_api.post("/bucket/{obj_path:path}")
def bucket_post_object(obj_path: str, file: bytes = File(), db: Session = Depends(get_db)):
filename = get_filename_from_url(obj_path)
path = get_path_from_url(obj_path)
bucket = crud.get_bucket_by_path(db, path)
if bucket == None:
bucket = crud.create_bucket(db=db, bucket=schemas.BucketCreate(path=path))
bucket_id = bucket.id
bucketfile = schemas.BucketFileCreate(filename=filename, data=file)
result = crud.create_bucketfile(db=db, bucketfile=bucketfile, bucket_id=bucket_id)
result.data = base64.encodestring(result.data)
return result
@server_api.post("/buckets/{bucket_id}/items/", response_model=schemas.BucketFile)
def create_bucketfile_in_bucket(
bucket_id: int, bucketfile: schemas.BucketFileCreate, db: Session = Depends(get_db)
):
bucketfile.data = base64.decodestring(bucketfile.data)
result = crud.create_bucketfile(db=db, bucketfile=bucketfile, bucket_id=bucket_id)
result.data = base64.encodestring(result.data)
return result
def get_filename_from_url(url):
path = urlparse(url).path
name = path[path.rfind('/')+1:]
return name or None
def get_path_from_url(url):
path = urlparse(url).path
path = path[0:path.rfind('/')]
return path or None
def get_suffix_from_filename(filename):
return filename[filename.rfind('.')+1:]

View File

@ -6,15 +6,6 @@ import traceback
import torch
from easydiffusion.utils import log
from torchruntime.utils import (
get_installed_torch_platform,
get_device,
get_device_count,
get_device_name,
SUPPORTED_BACKENDS,
)
from sdkit.utils import mem_get_info, is_cpu_device, has_half_precision_bug
"""
Set `FORCE_FULL_PRECISION` in the environment variables, or in `config.bat`/`config.sh` to set full precision (i.e. float32).
Otherwise the models will load at half-precision (i.e. float16).
@ -31,15 +22,33 @@ mem_free_threshold = 0
def get_device_delta(render_devices, active_devices):
"""
render_devices: 'auto' or backends listed in `torchruntime.utils.SUPPORTED_BACKENDS`
active_devices: [backends listed in `torchruntime.utils.SUPPORTED_BACKENDS`]
render_devices: 'cpu', or 'auto', or 'mps' or ['cuda:N'...]
active_devices: ['cpu', 'mps', 'cuda:N'...]
"""
render_devices = render_devices or "auto"
render_devices = [render_devices] if isinstance(render_devices, str) else render_devices
if render_devices in ("cpu", "auto", "mps"):
render_devices = [render_devices]
elif render_devices is not None:
if isinstance(render_devices, str):
render_devices = [render_devices]
if isinstance(render_devices, list) and len(render_devices) > 0:
render_devices = list(filter(lambda x: x.startswith("cuda:") or x == "mps", render_devices))
if len(render_devices) == 0:
raise Exception(
'Invalid render_devices value in config.json. Valid: {"render_devices": ["cuda:0", "cuda:1"...]}, or {"render_devices": "cpu"} or {"render_devices": "mps"} or {"render_devices": "auto"}'
)
# check for backend support
validate_render_devices(render_devices)
render_devices = list(filter(lambda x: is_device_compatible(x), render_devices))
if len(render_devices) == 0:
raise Exception(
"Sorry, none of the render_devices configured in config.json are compatible with Stable Diffusion"
)
else:
raise Exception(
'Invalid render_devices value in config.json. Valid: {"render_devices": ["cuda:0", "cuda:1"...]}, or {"render_devices": "cpu"} or {"render_devices": "auto"}'
)
else:
render_devices = ["auto"]
if "auto" in render_devices:
render_devices = auto_pick_devices(active_devices)
@ -55,39 +64,47 @@ def get_device_delta(render_devices, active_devices):
return devices_to_start, devices_to_stop
def validate_render_devices(render_devices):
supported_backends = ("auto",) + SUPPORTED_BACKENDS
unsupported_render_devices = [d for d in render_devices if not d.lower().startswith(supported_backends)]
def is_mps_available():
return (
platform.system() == "Darwin"
and hasattr(torch.backends, "mps")
and torch.backends.mps.is_available()
and torch.backends.mps.is_built()
)
if unsupported_render_devices:
raise ValueError(
f"Invalid render devices in config: {unsupported_render_devices}. Valid render devices: {supported_backends}"
)
def is_cuda_available():
return torch.cuda.is_available()
def auto_pick_devices(currently_active_devices):
global mem_free_threshold
torch_platform_name = get_installed_torch_platform()[0]
if is_mps_available():
return ["mps"]
if is_cpu_device(torch_platform_name):
return [torch_platform_name]
if not is_cuda_available():
return ["cpu"]
device_count = torch.cuda.device_count()
if device_count == 1:
return ["cuda:0"] if is_device_compatible("cuda:0") else ["cpu"]
device_count = get_device_count()
log.debug("Autoselecting GPU. Using most free memory.")
devices = []
for device_id in range(device_count):
device_id = f"{torch_platform_name}:{device_id}" if device_count > 1 else torch_platform_name
device = get_device(device_id)
for device in range(device_count):
device = f"cuda:{device}"
if not is_device_compatible(device):
continue
mem_free, mem_total = mem_get_info(device)
mem_free, mem_total = torch.cuda.mem_get_info(device)
mem_free /= float(10**9)
mem_total /= float(10**9)
device_name = get_device_name(device)
device_name = torch.cuda.get_device_name(device)
log.debug(
f"{device_id} detected: {device_name} - Memory (free/total): {round(mem_free, 2)}Gb / {round(mem_total, 2)}Gb"
f"{device} detected: {device_name} - Memory (free/total): {round(mem_free, 2)}Gb / {round(mem_total, 2)}Gb"
)
devices.append({"device": device_id, "device_name": device_name, "mem_free": mem_free})
devices.append({"device": device, "device_name": device_name, "mem_free": mem_free})
devices.sort(key=lambda x: x["mem_free"], reverse=True)
max_mem_free = devices[0]["mem_free"]
@ -100,45 +117,69 @@ def auto_pick_devices(currently_active_devices):
# always be very low (since their VRAM contains the model).
# These already-running devices probably aren't terrible, since they were picked in the past.
# Worst case, the user can restart the program and that'll get rid of them.
devices = [
x["device"] for x in devices if x["mem_free"] >= mem_free_threshold or x["device"] in currently_active_devices
]
devices = list(
filter(
(lambda x: x["mem_free"] > mem_free_threshold or x["device"] in currently_active_devices),
devices,
)
)
devices = list(map(lambda x: x["device"], devices))
return devices
def device_init(context, device_id):
context.device = device_id
def device_init(context, device):
"""
This function assumes the 'device' has already been verified to be compatible.
`get_device_delta()` has already filtered out incompatible devices.
"""
if is_cpu_device(context.torch_device):
validate_device_id(device, log_prefix="device_init")
if "cuda" not in device:
context.device = device
context.device_name = get_processor_name()
context.half_precision = False
else:
context.device_name = get_device_name(context.torch_device)
log.debug(f"Render device available as {context.device_name}")
return
# Some graphics cards have bugs in their firmware that prevent image generation at half precision
if needs_to_force_full_precision(context.device_name):
log.warn(f"forcing full precision on this GPU, to avoid corrupted images. GPU: {context.device_name}")
context.half_precision = False
context.device_name = torch.cuda.get_device_name(device)
context.device = device
log.info(f'Setting {device_id} as active, with precision: {"half" if context.half_precision else "full"}')
# Force full precision on 1660 and 1650 NVIDIA cards to avoid creating green images
if needs_to_force_full_precision(context):
log.warn(f"forcing full precision on this GPU, to avoid green images. GPU detected: {context.device_name}")
# Apply force_full_precision now before models are loaded.
context.half_precision = False
log.info(f'Setting {device} as active, with precision: {"half" if context.half_precision else "full"}')
torch.cuda.device(device)
def needs_to_force_full_precision(device_name):
def needs_to_force_full_precision(context):
if "FORCE_FULL_PRECISION" in os.environ:
return True
return has_half_precision_bug(device_name.lower())
device_name = context.device_name.lower()
return (
("nvidia" in device_name or "geforce" in device_name or "quadro" in device_name)
and (
" 1660" in device_name
or " 1650" in device_name
or " 1630" in device_name
or " t400" in device_name
or " t550" in device_name
or " t600" in device_name
or " t1000" in device_name
or " t1200" in device_name
or " t2000" in device_name
)
) or ("tesla k40m" in device_name)
def get_max_vram_usage_level(device):
"Expects a torch.device as the argument"
if is_cpu_device(device):
return "high"
_, mem_total = mem_get_info(device)
if mem_total < 0.001: # probably a torch platform without a mem_get_info() implementation
if "cuda" in device:
_, mem_total = torch.cuda.mem_get_info(device)
else:
return "high"
mem_total /= float(10**9)
@ -150,6 +191,51 @@ def get_max_vram_usage_level(device):
return "high"
def validate_device_id(device, log_prefix=""):
def is_valid():
if not isinstance(device, str):
return False
if device == "cpu" or device == "mps":
return True
if not device.startswith("cuda:") or not device[5:].isnumeric():
return False
return True
if not is_valid():
raise EnvironmentError(
f"{log_prefix}: device id should be 'cpu', 'mps', or 'cuda:N' (where N is an integer index for the GPU). Got: {device}"
)
def is_device_compatible(device):
"""
Returns True/False, and prints any compatibility errors
"""
# static variable "history".
is_device_compatible.history = getattr(is_device_compatible, "history", {})
try:
validate_device_id(device, log_prefix="is_device_compatible")
except:
log.error(str(e))
return False
if device in ("cpu", "mps"):
return True
# Memory check
try:
_, mem_total = torch.cuda.mem_get_info(device)
mem_total /= float(10**9)
if mem_total < 1.9:
if is_device_compatible.history.get(device) == None:
log.warn(f"GPU {device} with less than 2 GB of VRAM is not compatible with Stable Diffusion")
is_device_compatible.history[device] = 1
return False
except RuntimeError as e:
log.error(str(e))
return False
return True
def get_processor_name():
try:
import subprocess
@ -157,8 +243,7 @@ def get_processor_name():
if platform.system() == "Windows":
return platform.processor()
elif platform.system() == "Darwin":
if "/usr/sbin" not in os.environ["PATH"].split(os.pathsep):
os.environ["PATH"] = os.environ["PATH"] + os.pathsep + "/usr/sbin"
os.environ["PATH"] = os.environ["PATH"] + os.pathsep + "/usr/sbin"
command = "sysctl -n machdep.cpu.brand_string"
return subprocess.check_output(command, shell=True).decode().strip()
elif platform.system() == "Linux":

View File

@ -1,24 +0,0 @@
from sqlalchemy.orm import Session
from easydiffusion.easydb import models, schemas
def get_bucket_by_path(db: Session, path: str):
return db.query(models.Bucket).filter(models.Bucket.path == path).first()
def create_bucket(db: Session, bucket: schemas.BucketCreate):
db_bucket = models.Bucket(path=bucket.path)
db.add(db_bucket)
db.commit()
db.refresh(db_bucket)
return db_bucket
def create_bucketfile(db: Session, bucketfile: schemas.BucketFileCreate, bucket_id: int):
db_bucketfile = models.BucketFile(**bucketfile.dict(), bucket_id=bucket_id)
db.merge(db_bucketfile)
db.commit()
db_bucketfile = db.query(models.BucketFile).filter(models.BucketFile.bucket_id==bucket_id, models.BucketFile.filename==bucketfile.filename).first()
return db_bucketfile

View File

@ -1,14 +0,0 @@
import os
from easydiffusion import app
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
os.makedirs(app.BUCKET_DIR, exist_ok=True)
SQLALCHEMY_DATABASE_URL = "sqlite:///"+os.path.join(app.BUCKET_DIR, "bucket.db")
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
BucketBase = declarative_base()

View File

@ -1,25 +0,0 @@
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, BLOB
from sqlalchemy.orm import relationship
from easydiffusion.easydb.database import BucketBase
class Bucket(BucketBase):
__tablename__ = "bucket"
id = Column(Integer, primary_key=True, index=True)
path = Column(String, unique=True, index=True)
bucketfiles = relationship("BucketFile", back_populates="bucket")
class BucketFile(BucketBase):
__tablename__ = "bucketfile"
filename = Column(String, index=True, primary_key=True)
bucket_id = Column(Integer, ForeignKey("bucket.id"), primary_key=True)
data = Column(BLOB, index=False)
bucket = relationship("Bucket", back_populates="bucketfiles")

View File

@ -1,36 +0,0 @@
from typing import List, Union
from pydantic import BaseModel
class BucketFileBase(BaseModel):
filename: str
data: bytes
class BucketFileCreate(BucketFileBase):
pass
class BucketFile(BucketFileBase):
bucket_id: int
class Config:
orm_mode = True
class BucketBase(BaseModel):
path: str
class BucketCreate(BucketBase):
pass
class Bucket(BucketBase):
id: int
bucketfiles: List[BucketFile] = []
class Config:
orm_mode = True

View File

@ -2,16 +2,13 @@ import os
import shutil
from glob import glob
import traceback
from typing import Union
from easydiffusion import app
from easydiffusion.types import ModelsData
from easydiffusion.types import TaskData
from easydiffusion.utils import log
from sdkit import Context
from sdkit.models import load_model, scan_model, unload_model, download_model, get_model_info_from_db
from sdkit.models.model_loader.controlnet_filters import filters as cn_filters
from sdkit.utils import hash_file_quick
from sdkit.models.model_loader.embeddings import get_embedding_token
KNOWN_MODEL_TYPES = [
"stable-diffusion",
@ -21,8 +18,6 @@ KNOWN_MODEL_TYPES = [
"realesrgan",
"lora",
"codeformer",
"embeddings",
"controlnet",
]
MODEL_EXTENSIONS = {
"stable-diffusion": [".ckpt", ".safetensors"],
@ -30,14 +25,12 @@ MODEL_EXTENSIONS = {
"hypernetwork": [".pt", ".safetensors"],
"gfpgan": [".pth"],
"realesrgan": [".pth"],
"lora": [".ckpt", ".safetensors", ".pt"],
"lora": [".ckpt", ".safetensors"],
"codeformer": [".pth"],
"embeddings": [".pt", ".bin", ".safetensors"],
"controlnet": [".pth", ".safetensors"],
}
DEFAULT_MODELS = {
"stable-diffusion": [
{"file_name": "sd-v1-5.safetensors", "model_id": "1.5-pruned-emaonly-fp16"},
{"file_name": "sd-v1-4.ckpt", "model_id": "1.4"},
],
"gfpgan": [
{"file_name": "GFPGANv1.4.pth", "model_id": "1.4"},
@ -59,16 +52,15 @@ def init():
make_model_folders()
migrate_legacy_model_location() # if necessary
download_default_models_if_necessary()
getModels() # run this once, to cache the picklescan results
def load_default_models(context: Context):
from easydiffusion import runtime
runtime.set_vram_optimizations(context)
set_vram_optimizations(context)
# init default model paths
for model_type in MODELS_TO_LOAD_ON_START:
context.model_paths[model_type] = resolve_model_to_use(model_type=model_type, fail_if_not_found=False)
context.model_paths[model_type] = resolve_model_to_use(model_type=model_type)
try:
load_model(
context,
@ -76,20 +68,13 @@ def load_default_models(context: Context):
scan_model=context.model_paths[model_type] != None
and not context.model_paths[model_type].endswith(".safetensors"),
)
if hasattr(context, "model_load_errors") and model_type in context.model_load_errors:
if model_type in context.model_load_errors:
del context.model_load_errors[model_type]
except Exception as e:
log.error(f"[red]Error while loading {model_type} model: {context.model_paths[model_type]}[/red]")
if "DefaultCPUAllocator: not enough memory" in str(e):
log.error(
f"[red]Your PC is low on system RAM. Please add some virtual memory (or swap space) by following the instructions at this link: https://www.ibm.com/docs/en/opw/8.2.0?topic=tuning-optional-increasing-paging-file-size-windows-computers[/red]"
)
else:
log.exception(e)
log.exception(e)
del context.model_paths[model_type]
if not hasattr(context, "model_load_errors"):
context.model_load_errors = {}
context.model_load_errors[model_type] = str(e) # storing the entire Exception can lead to memory leaks
@ -100,23 +85,7 @@ def unload_all(context: Context):
del context.model_load_errors[model_type]
def resolve_model_to_use(model_name: Union[str, list] = None, model_type: str = None, fail_if_not_found: bool = True):
model_names = model_name if isinstance(model_name, list) else [model_name]
model_paths = []
for m in model_names:
if model_type == "embeddings":
try:
resolve_model_to_use_single(m, model_type)
except FileNotFoundError: # try with spaces
m = m.replace("_", " ")
path = resolve_model_to_use_single(m, model_type, fail_if_not_found)
model_paths.append(path)
return model_paths[0] if len(model_paths) == 1 else model_paths
def resolve_model_to_use_single(model_name: str = None, model_type: str = None, fail_if_not_found: bool = True):
def resolve_model_to_use(model_name: str = None, model_type: str = None):
model_extensions = MODEL_EXTENSIONS.get(model_type, [])
default_models = DEFAULT_MODELS.get(model_type, [])
config = app.getConfig()
@ -139,7 +108,7 @@ def resolve_model_to_use_single(model_name: str = None, model_type: str = None,
return os.path.abspath(model_name + model_extension)
# Can't find requested model, check the default paths.
if model_type == "stable-diffusion" and not fail_if_not_found:
if model_type == "stable-diffusion":
for default_model in default_models:
default_model_path = os.path.join(model_dir, default_model["file_name"])
if os.path.exists(default_model_path):
@ -149,69 +118,75 @@ def resolve_model_to_use_single(model_name: str = None, model_type: str = None,
)
return default_model_path
if model_name and fail_if_not_found:
raise FileNotFoundError(
f"Could not find the desired model {model_name}! Is it present in the {model_dir} folder?"
)
return None
def reload_models_if_necessary(context: Context, models_data: ModelsData, models_to_force_reload: list = []):
def reload_models_if_necessary(context: Context, task_data: TaskData):
face_fix_lower = task_data.use_face_correction.lower() if task_data.use_face_correction else ""
upscale_lower = task_data.use_upscale.lower() if task_data.use_upscale else ""
model_paths_in_req = {
"stable-diffusion": task_data.use_stable_diffusion_model,
"vae": task_data.use_vae_model,
"hypernetwork": task_data.use_hypernetwork_model,
"codeformer": task_data.use_face_correction if "codeformer" in face_fix_lower else None,
"gfpgan": task_data.use_face_correction if "gfpgan" in face_fix_lower else None,
"realesrgan": task_data.use_upscale if "realesrgan" in upscale_lower else None,
"latent_upscaler": True if "latent_upscaler" in upscale_lower else None,
"nsfw_checker": True if task_data.block_nsfw else None,
"lora": task_data.use_lora_model,
}
models_to_reload = {
model_type: path
for model_type, path in models_data.model_paths.items()
if context.model_paths.get(model_type) != path or (path is not None and context.models.get(model_type) is None)
for model_type, path in model_paths_in_req.items()
if context.model_paths.get(model_type) != path
}
if models_data.model_paths.get("codeformer"):
if "realesrgan" not in models_to_reload and "realesrgan" not in context.models:
default_realesrgan = DEFAULT_MODELS["realesrgan"][0]["file_name"]
models_to_reload["realesrgan"] = resolve_model_to_use(default_realesrgan, "realesrgan")
elif "realesrgan" in models_to_reload and models_to_reload["realesrgan"] is None:
del models_to_reload["realesrgan"] # don't unload realesrgan
if task_data.codeformer_upscale_faces and "realesrgan" not in models_to_reload.keys():
models_to_reload["realesrgan"] = resolve_model_to_use(
DEFAULT_MODELS["realesrgan"][0]["file_name"], "realesrgan"
)
for model_type in models_to_force_reload:
if model_type not in models_data.model_paths:
continue
models_to_reload[model_type] = models_data.model_paths[model_type]
if set_vram_optimizations(context) or set_clip_skip(context, task_data): # reload SD
models_to_reload["stable-diffusion"] = model_paths_in_req["stable-diffusion"]
for model_type, model_path_in_req in models_to_reload.items():
context.model_paths[model_type] = model_path_in_req
action_fn = unload_model if context.model_paths[model_type] is None else load_model
extra_params = models_data.model_params.get(model_type, {})
try:
action_fn(context, model_type, scan_model=False, **extra_params) # we've scanned them already
if hasattr(context, "model_load_errors") and model_type in context.model_load_errors:
action_fn(context, model_type, scan_model=False) # we've scanned them already
if model_type in context.model_load_errors:
del context.model_load_errors[model_type]
except Exception as e:
log.exception(e)
if action_fn == load_model:
if not hasattr(context, "model_load_errors"):
context.model_load_errors = {}
context.model_load_errors[model_type] = str(e) # storing the entire Exception can lead to memory leaks
def resolve_model_paths(models_data: ModelsData):
model_paths = models_data.model_paths
for model_type in model_paths:
skip_models = cn_filters + ["latent_upscaler", "nsfw_checker"]
if model_type in skip_models: # doesn't use model paths
continue
if model_type == "codeformer" and model_paths[model_type]:
download_if_necessary("codeformer", "codeformer.pth", "codeformer-0.1.0")
elif model_type == "controlnet" and model_paths[model_type]:
model_id = model_paths[model_type]
model_info = get_model_info_from_db(model_type=model_type, model_id=model_id)
if model_info:
filename = model_info.get("url", "").split("/")[-1]
download_if_necessary("controlnet", filename, model_id, skip_if_others_exist=False)
def resolve_model_paths(task_data: TaskData):
task_data.use_stable_diffusion_model = resolve_model_to_use(
task_data.use_stable_diffusion_model, model_type="stable-diffusion"
)
task_data.use_vae_model = resolve_model_to_use(task_data.use_vae_model, model_type="vae")
task_data.use_hypernetwork_model = resolve_model_to_use(task_data.use_hypernetwork_model, model_type="hypernetwork")
task_data.use_lora_model = resolve_model_to_use(task_data.use_lora_model, model_type="lora")
model_paths[model_type] = resolve_model_to_use(model_paths[model_type], model_type=model_type)
if task_data.use_face_correction:
if "gfpgan" in task_data.use_face_correction.lower():
model_type = "gfpgan"
elif "codeformer" in task_data.use_face_correction.lower():
model_type = "codeformer"
download_if_necessary("codeformer", "codeformer.pth", "codeformer-0.1.0")
task_data.use_face_correction = resolve_model_to_use(task_data.use_face_correction, model_type)
if task_data.use_upscale and "realesrgan" in task_data.use_upscale.lower():
task_data.use_upscale = resolve_model_to_use(task_data.use_upscale, "realesrgan")
def fail_if_models_did_not_load(context: Context):
for model_type in KNOWN_MODEL_TYPES:
if hasattr(context, "model_load_errors") and model_type in context.model_load_errors:
if model_type in context.model_load_errors:
e = context.model_load_errors[model_type]
raise Exception(f"Could not load the {model_type} model! Reason: " + e)
@ -228,17 +203,28 @@ def download_default_models_if_necessary():
print(model_type, "model(s) found.")
def download_if_necessary(model_type: str, file_name: str, model_id: str, skip_if_others_exist=True):
def download_if_necessary(model_type: str, file_name: str, model_id: str):
model_path = os.path.join(app.MODELS_DIR, model_type, file_name)
expected_hash = get_model_info_from_db(model_type=model_type, model_id=model_id)["quick_hash"]
other_models_exist = any_model_exists(model_type) and skip_if_others_exist
other_models_exist = any_model_exists(model_type)
known_model_exists = os.path.exists(model_path)
known_model_is_corrupt = known_model_exists and hash_file_quick(model_path) != expected_hash
if known_model_is_corrupt or (not other_models_exist and not known_model_exists):
print("> download", model_type, model_id)
download_model(model_type, model_id, download_base_dir=app.MODELS_DIR, download_config_if_available=False)
download_model(model_type, model_id, download_base_dir=app.MODELS_DIR)
def set_vram_optimizations(context: Context):
config = app.getConfig()
vram_usage_level = config.get("vram_usage_level", "balanced")
if vram_usage_level != context.vram_usage_level:
context.vram_usage_level = vram_usage_level
return True
return False
def migrate_legacy_model_location():
@ -261,28 +247,21 @@ def any_model_exists(model_type: str) -> bool:
return False
def set_clip_skip(context: Context, task_data: TaskData):
clip_skip = task_data.clip_skip
if clip_skip != context.clip_skip:
context.clip_skip = clip_skip
return True
return False
def make_model_folders():
for model_type in KNOWN_MODEL_TYPES:
model_dir_path = os.path.join(app.MODELS_DIR, model_type)
try:
os.makedirs(model_dir_path, exist_ok=True)
except Exception as e:
from rich.console import Console
from rich.panel import Panel
Console().print(
Panel(
"\n"
+ f"Error while creating the models directory: '{model_dir_path}'\n"
+ f"Error: {e}\n\n"
+ f"[white]Check the 'models_dir:' line in the file '{os.path.join(app.ROOT_DIR, 'config.yaml')}'.[/white]\n",
title="Fatal Error starting Easy Diffusion",
style="bold yellow on red",
)
)
input("Press Enter to terminate...")
exit(1)
os.makedirs(model_dir_path, exist_ok=True)
help_file_name = f"Place your {model_type} model files here.txt"
help_file_contents = f'Supported extensions: {" or ".join(MODEL_EXTENSIONS.get(model_type))}'
@ -293,7 +272,7 @@ def make_model_folders():
def is_malicious_model(file_path):
try:
if file_path.endswith((".safetensors", ".sft", ".gguf")):
if file_path.endswith(".safetensors"):
return False
scan_result = scan_model(file_path)
if scan_result.issues_count > 0 or scan_result.infected_files > 0:
@ -323,30 +302,14 @@ def is_malicious_model(file_path):
return False
def getModels(scan_for_malicious: bool = True):
def getModels():
models = {
"options": {
"stable-diffusion": [],
"stable-diffusion": ["sd-v1-4"],
"vae": [],
"hypernetwork": [],
"lora": [],
"codeformer": [{"codeformer": "CodeFormer"}],
"embeddings": [],
"controlnet": [
{"control_v11p_sd15_canny": "Canny (*)"},
{"control_v11p_sd15_openpose": "OpenPose (*)"},
{"control_v11p_sd15_normalbae": "Normal BAE (*)"},
{"control_v11f1p_sd15_depth": "Depth (*)"},
{"control_v11p_sd15_scribble": "Scribble"},
{"control_v11p_sd15_softedge": "Soft Edge"},
{"control_v11p_sd15_inpaint": "Inpaint"},
{"control_v11p_sd15_lineart": "Line Art"},
{"control_v11p_sd15s2_lineart_anime": "Line Art Anime"},
{"control_v11p_sd15_mlsd": "Straight Lines"},
{"control_v11p_sd15_seg": "Segment"},
{"control_v11e_sd15_shuffle": "Shuffle"},
{"control_v11f1e_sd15_tile": "Tile"},
],
"codeformer": ["codeformer"],
},
}
@ -355,11 +318,9 @@ def getModels(scan_for_malicious: bool = True):
class MaliciousModelException(Exception):
"Raised when picklescan reports a problem with a model"
def scan_directory(directory, suffixes, directoriesFirst: bool = True, default_entries=[], nameFilter=None):
def scan_directory(directory, suffixes, directoriesFirst: bool = True):
nonlocal models_scanned
tree = list(default_entries)
tree = []
for entry in sorted(
os.scandir(directory),
key=lambda entry: (entry.is_file() == directoriesFirst, entry.name.lower()),
@ -374,31 +335,18 @@ def getModels(scan_for_malicious: bool = True):
mod_time = known_models[entry.path] if entry.path in known_models else -1
if mod_time != mtime:
models_scanned += 1
if scan_for_malicious and is_malicious_model(entry.path):
if is_malicious_model(entry.path):
raise MaliciousModelException(entry.path)
if scan_for_malicious:
known_models[entry.path] = mtime
model_id = entry.name[: -len(matching_suffix)]
if callable(nameFilter):
model_id = nameFilter(model_id)
model_exists = False
for m in tree: # allows default "named" models, like CodeFormer and known ControlNet models
if (isinstance(m, str) and model_id == m) or (isinstance(m, dict) and model_id in m):
model_exists = True
break
if not model_exists:
tree.append(model_id)
known_models[entry.path] = mtime
tree.append(entry.name[: -len(matching_suffix)])
elif entry.is_dir():
scan = scan_directory(entry.path, suffixes, directoriesFirst=False, nameFilter=nameFilter)
scan = scan_directory(entry.path, suffixes, directoriesFirst=False)
if len(scan) != 0:
tree.append((entry.name, scan))
return tree
def listModels(model_type, nameFilter=None):
def listModels(model_type):
nonlocal models_scanned
model_extensions = MODEL_EXTENSIONS.get(model_type, [])
@ -407,25 +355,19 @@ def getModels(scan_for_malicious: bool = True):
os.makedirs(models_dir)
try:
default_tree = models["options"].get(model_type, [])
models["options"][model_type] = scan_directory(
models_dir, model_extensions, default_entries=default_tree, nameFilter=nameFilter
)
models["options"][model_type] = scan_directory(models_dir, model_extensions)
except MaliciousModelException as e:
models["scan-error"] = str(e)
models["scan-error"] = e
if scan_for_malicious:
log.info(f"[green]Scanning all model folders for models...[/]")
log.info(f"[green]Scanning all model folders for models...[/]")
# custom models
listModels(model_type="stable-diffusion")
listModels(model_type="vae")
listModels(model_type="hypernetwork")
listModels(model_type="gfpgan")
listModels(model_type="lora")
listModels(model_type="embeddings", nameFilter=get_embedding_token)
listModels(model_type="controlnet")
if scan_for_malicious and models_scanned > 0:
if models_scanned > 0:
log.info(f"[green]Scanned {models_scanned} models. Nothing infected[/]")
return models

View File

@ -1,103 +0,0 @@
import sys
import os
import platform
from importlib.metadata import version as pkg_version
from sdkit.utils import log
from easydiffusion import app
# was meant to be a rewrite of scripts/check_modules.py
# but probably dead for now
manifest = {
"tensorrt": {
"install": [
"wheel",
"nvidia-cudnn-cu11==8.9.4.25",
"tensorrt==9.0.0.post11.dev1 --pre --extra-index-url=https://pypi.nvidia.com --trusted-host pypi.nvidia.com",
],
"uninstall": ["tensorrt"],
# TODO also uninstall tensorrt-libs and nvidia-cudnn, but do it upon restarting (avoid 'file in use' error)
}
}
installing = []
# remove this once TRT releases on pypi
if platform.system() == "Windows":
trt_dir = os.path.join(app.ROOT_DIR, "tensorrt")
if os.path.exists(trt_dir) and os.path.isdir(trt_dir) and len(os.listdir(trt_dir)) > 0:
files = os.listdir(trt_dir)
packages = manifest["tensorrt"]["install"]
packages = tuple(p.replace("-", "_") for p in packages)
wheels = []
for p in packages:
p = p.split(" ")[0]
f = next((f for f in files if f.startswith(p) and f.endswith((".whl", ".tar.gz"))), None)
if f:
wheels.append(os.path.join(trt_dir, f))
manifest["tensorrt"]["install"] = wheels
def get_installed_packages() -> list:
return {module_name: version(module_name) for module_name in manifest if is_installed(module_name)}
def is_installed(module_name) -> bool:
return version(module_name) is not None
def install(module_name):
if is_installed(module_name):
log.info(f"{module_name} has already been installed!")
return
if module_name in installing:
log.info(f"{module_name} is already installing!")
return
if module_name not in manifest:
raise RuntimeError(f"Can't install unknown package: {module_name}!")
commands = manifest[module_name]["install"]
if module_name == "tensorrt":
commands += [
"protobuf==3.20.3 polygraphy==0.47.1 onnx==1.14.0 --extra-index-url=https://pypi.ngc.nvidia.com --trusted-host pypi.ngc.nvidia.com"
]
commands = [f"python -m pip install --upgrade {cmd}" for cmd in commands]
installing.append(module_name)
try:
for cmd in commands:
print(">", cmd)
if os.system(cmd) != 0:
raise RuntimeError(f"Error while running {cmd}. Please check the logs in the command-line.")
finally:
installing.remove(module_name)
def uninstall(module_name):
if not is_installed(module_name):
log.info(f"{module_name} hasn't been installed!")
return
if module_name not in manifest:
raise RuntimeError(f"Can't uninstall unknown package: {module_name}!")
commands = manifest[module_name]["uninstall"]
commands = [f"python -m pip uninstall -y {cmd}" for cmd in commands]
for cmd in commands:
print(">", cmd)
if os.system(cmd) != 0:
raise RuntimeError(f"Error while running {cmd}. Please check the logs in the command-line.")
def version(module_name: str) -> str:
try:
return pkg_version(module_name)
except:
return None

View File

@ -0,0 +1,262 @@
import json
import pprint
import queue
import time
from easydiffusion import device_manager
from easydiffusion.types import GenerateImageRequest
from easydiffusion.types import Image as ResponseImage
from easydiffusion.types import Response, TaskData, UserInitiatedStop
from easydiffusion.utils import get_printable_request, log, save_images_to_disk
from sdkit import Context
from sdkit.filter import apply_filters
from sdkit.generate import generate_images
from sdkit.utils import (
diffusers_latent_samples_to_images,
gc,
img_to_base64_str,
img_to_buffer,
latent_samples_to_images,
get_device_usage,
)
context = Context() # thread-local
"""
runtime data (bound locally to this thread), for e.g. device, references to loaded models, optimization flags etc
"""
def init(device):
"""
Initializes the fields that will be bound to this runtime's context, and sets the current torch device
"""
context.stop_processing = False
context.temp_images = {}
context.partial_x_samples = None
context.model_load_errors = {}
context.enable_codeformer = True
from easydiffusion import app
app_config = app.getConfig()
context.test_diffusers = (
app_config.get("test_diffusers", False) and app_config.get("update_branch", "main") != "main"
)
log.info("Device usage during initialization:")
get_device_usage(device, log_info=True, process_usage_only=False)
device_manager.device_init(context, device)
def make_images(
req: GenerateImageRequest,
task_data: TaskData,
data_queue: queue.Queue,
task_temp_images: list,
step_callback,
):
context.stop_processing = False
print_task_info(req, task_data)
images, seeds = make_images_internal(req, task_data, data_queue, task_temp_images, step_callback)
res = Response(
req,
task_data,
images=construct_response(images, seeds, task_data, base_seed=req.seed),
)
res = res.json()
data_queue.put(json.dumps(res))
log.info("Task completed")
return res
def print_task_info(req: GenerateImageRequest, task_data: TaskData):
req_str = pprint.pformat(get_printable_request(req, task_data)).replace("[", "\[")
task_str = pprint.pformat(task_data.dict()).replace("[", "\[")
log.info(f"request: {req_str}")
log.info(f"task data: {task_str}")
def make_images_internal(
req: GenerateImageRequest,
task_data: TaskData,
data_queue: queue.Queue,
task_temp_images: list,
step_callback,
):
images, user_stopped = generate_images_internal(
req,
task_data,
data_queue,
task_temp_images,
step_callback,
task_data.stream_image_progress,
task_data.stream_image_progress_interval,
)
gc(context)
filtered_images = filter_images(req, task_data, images, user_stopped)
if task_data.save_to_disk_path is not None:
save_images_to_disk(images, filtered_images, req, task_data)
seeds = [*range(req.seed, req.seed + len(images))]
if task_data.show_only_filtered_image or filtered_images is images:
return filtered_images, seeds
else:
return images + filtered_images, seeds + seeds
def generate_images_internal(
req: GenerateImageRequest,
task_data: TaskData,
data_queue: queue.Queue,
task_temp_images: list,
step_callback,
stream_image_progress: bool,
stream_image_progress_interval: int,
):
context.temp_images.clear()
callback = make_step_callback(
req,
task_data,
data_queue,
task_temp_images,
step_callback,
stream_image_progress,
stream_image_progress_interval,
)
try:
if req.init_image is not None and not context.test_diffusers:
req.sampler_name = "ddim"
images = generate_images(context, callback=callback, **req.dict())
user_stopped = False
except UserInitiatedStop:
images = []
user_stopped = True
if context.partial_x_samples is not None:
if context.test_diffusers:
images = diffusers_latent_samples_to_images(context, context.partial_x_samples)
else:
images = latent_samples_to_images(context, context.partial_x_samples)
finally:
if hasattr(context, "partial_x_samples") and context.partial_x_samples is not None:
if not context.test_diffusers:
del context.partial_x_samples
context.partial_x_samples = None
return images, user_stopped
def filter_images(req: GenerateImageRequest, task_data: TaskData, images: list, user_stopped):
if user_stopped:
return images
filters_to_apply = []
filter_params = {}
if task_data.block_nsfw:
filters_to_apply.append("nsfw_checker")
if task_data.use_face_correction and "codeformer" in task_data.use_face_correction.lower():
filters_to_apply.append("codeformer")
filter_params["upscale_faces"] = task_data.codeformer_upscale_faces
elif task_data.use_face_correction and "gfpgan" in task_data.use_face_correction.lower():
filters_to_apply.append("gfpgan")
if task_data.use_upscale:
if "realesrgan" in task_data.use_upscale.lower():
filters_to_apply.append("realesrgan")
elif task_data.use_upscale == "latent_upscaler":
filters_to_apply.append("latent_upscaler")
filter_params["latent_upscaler_options"] = {
"prompt": req.prompt,
"negative_prompt": req.negative_prompt,
"seed": req.seed,
"num_inference_steps": task_data.latent_upscaler_steps,
"guidance_scale": 0,
}
filter_params["scale"] = task_data.upscale_amount
if len(filters_to_apply) == 0:
return images
return apply_filters(context, filters_to_apply, images, **filter_params)
def construct_response(images: list, seeds: list, task_data: TaskData, base_seed: int):
return [
ResponseImage(
data=img_to_base64_str(
img,
task_data.output_format,
task_data.output_quality,
task_data.output_lossless,
),
seed=seed,
)
for img, seed in zip(images, seeds)
]
def make_step_callback(
req: GenerateImageRequest,
task_data: TaskData,
data_queue: queue.Queue,
task_temp_images: list,
step_callback,
stream_image_progress: bool,
stream_image_progress_interval: int,
):
n_steps = req.num_inference_steps if req.init_image is None else int(req.num_inference_steps * req.prompt_strength)
last_callback_time = -1
def update_temp_img(x_samples, task_temp_images: list):
partial_images = []
if context.test_diffusers:
images = diffusers_latent_samples_to_images(context, x_samples)
else:
images = latent_samples_to_images(context, x_samples)
if task_data.block_nsfw:
images = apply_filters(context, "nsfw_checker", images)
for i, img in enumerate(images):
buf = img_to_buffer(img, output_format="JPEG")
context.temp_images[f"{task_data.request_id}/{i}"] = buf
task_temp_images[i] = buf
partial_images.append({"path": f"/image/tmp/{task_data.request_id}/{i}"})
del images
return partial_images
def on_image_step(x_samples, i, *args):
nonlocal last_callback_time
if context.test_diffusers:
context.partial_x_samples = (x_samples, args[0])
else:
context.partial_x_samples = x_samples
step_time = time.time() - last_callback_time if last_callback_time != -1 else -1
last_callback_time = time.time()
progress = {"step": i, "step_time": step_time, "total_steps": n_steps}
if stream_image_progress and stream_image_progress_interval > 0 and i % stream_image_progress_interval == 0:
progress["output"] = update_temp_img(context.partial_x_samples, task_temp_images)
data_queue.put(json.dumps(progress))
step_callback()
if context.stop_processing:
raise UserInitiatedStop("User requested that we stop processing")
return on_image_step

View File

@ -1,51 +0,0 @@
"""
A runtime that runs on a specific device (in a thread).
It can run various tasks like image generation, image filtering, model merge etc by using that thread-local context.
This creates an `sdkit.Context` that's bound to the device specified while calling the `init()` function.
"""
from easydiffusion import device_manager
from easydiffusion.utils import log
from sdkit import Context
from sdkit.utils import get_device_usage
context = Context() # thread-local
"""
runtime data (bound locally to this thread), for e.g. device, references to loaded models, optimization flags etc
"""
def init(device):
"""
Initializes the fields that will be bound to this runtime's context, and sets the current torch device
"""
context.stop_processing = False
context.temp_images = {}
context.partial_x_samples = None
context.model_load_errors = {}
context.enable_codeformer = True
from easydiffusion import app
app_config = app.getConfig()
context.test_diffusers = app_config.get("use_v3_engine", True)
log.info("Device usage during initialization:")
get_device_usage(device, log_info=True, process_usage_only=False)
device_manager.device_init(context, device)
def set_vram_optimizations(context: Context):
from easydiffusion import app
config = app.getConfig()
vram_usage_level = config.get("vram_usage_level", "balanced")
if vram_usage_level != context.vram_usage_level:
context.vram_usage_level = vram_usage_level
return True
return False

View File

@ -8,25 +8,13 @@ import os
import traceback
from typing import List, Union
from easydiffusion import app, model_manager, task_manager, package_manager
from easydiffusion.tasks import RenderTask, FilterTask
from easydiffusion.types import (
GenerateImageRequest,
FilterImageRequest,
MergeRequest,
TaskData,
RenderTaskData,
ModelsData,
OutputFormatData,
SaveToDiskData,
convert_legacy_render_req_to_new,
)
from easydiffusion import app, model_manager, task_manager
from easydiffusion.types import GenerateImageRequest, MergeRequest, TaskData
from easydiffusion.utils import log
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Extra
from starlette.responses import FileResponse, JSONResponse, StreamingResponse
from pycloudflared import try_cloudflare
log.info(f"started in {app.SD_DIR}")
log.info(f"started at {datetime.datetime.now():%x %X}")
@ -38,7 +26,6 @@ NOCACHE_HEADERS = {
"Pragma": "no-cache",
"Expires": "0",
}
PROTECTED_CONFIG_KEYS = ("block_nsfw",) # can't change these via the HTTP API
class NoCacheStaticFiles(StaticFiles):
@ -66,8 +53,7 @@ class SetAppConfigRequest(BaseModel, extra=Extra.allow):
ui_open_browser_on_start: bool = None
listen_to_network: bool = None
listen_port: int = None
use_v3_engine: bool = True
models_dir: str = None
test_diffusers: bool = False
def init():
@ -99,8 +85,8 @@ def init():
return set_app_config_internal(req)
@server_api.get("/get/{key:path}")
def read_web_data(key: str = None, scan_for_malicious: bool = True):
return read_web_data_internal(key, scan_for_malicious=scan_for_malicious)
def read_web_data(key: str = None):
return read_web_data_internal(key)
@server_api.get("/ping") # Get server and optionally session status.
def ping(session_id: str = None):
@ -110,10 +96,6 @@ def init():
def render(req: dict):
return render_internal(req)
@server_api.post("/filter")
def render(req: dict):
return filter_internal(req)
@server_api.post("/model/merge")
def model_merge(req: dict):
print(req)
@ -131,22 +113,6 @@ def init():
def get_image(task_id: int, img_id: int):
return get_image_internal(task_id, img_id)
@server_api.post("/tunnel/cloudflare/start")
def start_cloudflare_tunnel(req: dict):
return start_cloudflare_tunnel_internal(req)
@server_api.post("/tunnel/cloudflare/stop")
def stop_cloudflare_tunnel(req: dict):
return stop_cloudflare_tunnel_internal(req)
@server_api.post("/package/{package_name:str}")
def modify_package(package_name: str, req: dict):
return modify_package_internal(package_name, req)
@server_api.get("/sha256/{obj_path:path}")
def get_sha256(obj_path: str):
return get_sha256_internal(obj_path)
@server_api.get("/")
def read_root():
return FileResponse(os.path.join(app.SD_UI_DIR, "index.html"), headers=NOCACHE_HEADERS)
@ -176,11 +142,10 @@ def set_app_config_internal(req: SetAppConfigRequest):
config["net"] = {}
config["net"]["listen_port"] = int(req.listen_port)
config["use_v3_engine"] = req.use_v3_engine
config["models_dir"] = req.models_dir
config["test_diffusers"] = req.test_diffusers
for property, property_value in req.dict().items():
if property_value is not None and property not in req.__fields__ and property not in PROTECTED_CONFIG_KEYS:
if property_value is not None and property not in req.__fields__:
config[property] = property_value
try:
@ -196,27 +161,20 @@ def set_app_config_internal(req: SetAppConfigRequest):
def update_render_devices_in_config(config, render_devices):
from easydiffusion.device_manager import validate_render_devices
if render_devices not in ("cpu", "auto") and not render_devices.startswith("cuda:"):
raise HTTPException(status_code=400, detail=f"Invalid render device requested: {render_devices}")
try:
if render_devices.startswith("cuda:"):
render_devices = render_devices.split(",")
validate_render_devices(render_devices)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
config["render_devices"] = render_devices
def read_web_data_internal(key: str = None, **kwargs):
def read_web_data_internal(key: str = None):
if not key: # /get without parameters, stable-diffusion easter egg.
raise HTTPException(status_code=418, detail="StableDiffusion is drawing a teapot!") # HTTP418 I'm a teapot
elif key == "app_config":
config = app.getConfig()
if "models_dir" not in config:
config["models_dir"] = app.MODELS_DIR
return JSONResponse(config, headers=NOCACHE_HEADERS)
return JSONResponse(app.getConfig(), headers=NOCACHE_HEADERS)
elif key == "system_info":
config = app.getConfig()
@ -227,13 +185,11 @@ def read_web_data_internal(key: str = None, **kwargs):
"hosts": app.getIPConfig(),
"default_output_dir": output_dir,
"enforce_output_dir": ("force_save_path" in config),
"enforce_output_metadata": ("force_save_metadata" in config),
}
system_info["devices"]["config"] = config.get("render_devices", "auto")
return JSONResponse(system_info, headers=NOCACHE_HEADERS)
elif key == "models":
scan_for_malicious = kwargs.get("scan_for_malicious", True)
return JSONResponse(model_manager.getModels(scan_for_malicious), headers=NOCACHE_HEADERS)
return JSONResponse(model_manager.getModels(), headers=NOCACHE_HEADERS)
elif key == "modifiers":
return JSONResponse(app.get_image_modifiers(), headers=NOCACHE_HEADERS)
elif key == "ui_plugins":
@ -247,94 +203,53 @@ def ping_internal(session_id: str = None):
if task_manager.current_state_error:
raise HTTPException(status_code=500, detail=str(task_manager.current_state_error))
raise HTTPException(status_code=500, detail="Render thread is dead.")
if task_manager.current_state_error and not isinstance(task_manager.current_state_error, StopAsyncIteration):
raise HTTPException(status_code=500, detail=str(task_manager.current_state_error))
# Alive
response = {"status": str(task_manager.current_state)}
if session_id:
session = task_manager.get_cached_session(session_id, update_ttl=True)
response["tasks"] = {id(t): t.status for t in session.tasks}
response["devices"] = task_manager.get_devices()
response["packages_installed"] = package_manager.get_installed_packages()
response["packages_installing"] = package_manager.installing
if cloudflare.address != None:
response["cloudflare"] = cloudflare.address
return JSONResponse(response, headers=NOCACHE_HEADERS)
def render_internal(req: dict):
try:
req = convert_legacy_render_req_to_new(req)
# separate out the request data into rendering and task-specific data
render_req: GenerateImageRequest = GenerateImageRequest.parse_obj(req)
task_data: RenderTaskData = RenderTaskData.parse_obj(req)
models_data: ModelsData = ModelsData.parse_obj(req)
output_format: OutputFormatData = OutputFormatData.parse_obj(req)
save_data: SaveToDiskData = SaveToDiskData.parse_obj(req)
task_data: TaskData = TaskData.parse_obj(req)
# Overwrite user specified save path
config = app.getConfig()
if "force_save_path" in config:
save_data.save_to_disk_path = config["force_save_path"]
task_data.save_to_disk_path = config["force_save_path"]
render_req.init_image_mask = req.get("mask") # hack: will rename this in the HTTP API in a future revision
app.save_to_config(
models_data.model_paths.get("stable-diffusion"),
models_data.model_paths.get("vae"),
models_data.model_paths.get("hypernetwork"),
task_data.use_stable_diffusion_model,
task_data.use_vae_model,
task_data.use_hypernetwork_model,
task_data.vram_usage_level,
)
# enqueue the task
task = RenderTask(render_req, task_data, models_data, output_format, save_data)
return enqueue_task(task)
except HTTPException as e:
raise e
except Exception as e:
log.error(traceback.format_exc())
raise HTTPException(status_code=500, detail=str(e))
def filter_internal(req: dict):
try:
filter_req: FilterImageRequest = FilterImageRequest.parse_obj(req)
task_data: TaskData = TaskData.parse_obj(req)
models_data: ModelsData = ModelsData.parse_obj(req)
output_format: OutputFormatData = OutputFormatData.parse_obj(req)
save_data: SaveToDiskData = SaveToDiskData.parse_obj(req)
# enqueue the task
task = FilterTask(filter_req, task_data, models_data, output_format, save_data)
return enqueue_task(task)
except HTTPException as e:
raise e
except Exception as e:
log.error(traceback.format_exc())
raise HTTPException(status_code=500, detail=str(e))
def enqueue_task(task):
try:
task_manager.enqueue_task(task)
new_task = task_manager.render(render_req, task_data)
response = {
"status": str(task_manager.current_state),
"queue": len(task_manager.tasks_queue),
"stream": f"/image/stream/{task.id}",
"task": task.id,
"stream": f"/image/stream/{id(new_task)}",
"task": id(new_task),
}
return JSONResponse(response, headers=NOCACHE_HEADERS)
except ChildProcessError as e: # Render thread is dead
raise HTTPException(status_code=500, detail=f"Rendering thread has died.") # HTTP500 Internal Server Error
except ConnectionRefusedError as e: # Unstarted task pending limit reached, deny queueing too many.
raise HTTPException(status_code=503, detail=str(e)) # HTTP503 Service Unavailable
except Exception as e:
log.error(traceback.format_exc())
raise HTTPException(status_code=500, detail=str(e))
def model_merge_internal(req: dict):
@ -407,88 +322,3 @@ def get_image_internal(task_id: int, img_id: int):
return StreamingResponse(img_data, media_type="image/jpeg")
except KeyError as e:
raise HTTPException(status_code=500, detail=str(e))
# ---- Cloudflare Tunnel ----
class CloudflareTunnel:
def __init__(self):
config = app.getConfig()
self.urls = None
self.port = config.get("net", {}).get("listen_port")
def start(self):
if self.port:
self.urls = try_cloudflare(self.port)
def stop(self):
if self.urls:
try_cloudflare.terminate(self.port)
self.urls = None
@property
def address(self):
if self.urls:
return self.urls.tunnel
else:
return None
cloudflare = CloudflareTunnel()
def start_cloudflare_tunnel_internal(req: dict):
try:
cloudflare.start()
log.info(f"- Started cloudflare tunnel. Using address: {cloudflare.address}")
return JSONResponse({"address": cloudflare.address})
except Exception as e:
log.error(str(e))
log.error(traceback.format_exc())
return HTTPException(status_code=500, detail=str(e))
def stop_cloudflare_tunnel_internal(req: dict):
try:
cloudflare.stop()
except Exception as e:
log.error(str(e))
log.error(traceback.format_exc())
return HTTPException(status_code=500, detail=str(e))
def modify_package_internal(package_name: str, req: dict):
try:
cmd = req["command"]
if cmd not in ("install", "uninstall"):
raise RuntimeError(f"Unknown command: {cmd}")
cmd = getattr(package_manager, cmd)
cmd(package_name)
return JSONResponse({"status": "OK"}, headers=NOCACHE_HEADERS)
except Exception as e:
log.error(str(e))
log.error(traceback.format_exc())
return HTTPException(status_code=500, detail=str(e))
def get_sha256_internal(obj_path):
from easydiffusion.utils import sha256sum
path = obj_path.split("/")
type = path.pop(0)
try:
model_path = model_manager.resolve_model_to_use("/".join(path), type)
except Exception as e:
log.error(str(e))
log.error(traceback.format_exc())
return HTTPException(status_code=404)
try:
digest = sha256sum(model_path)
return {"digest": digest}
except Exception as e:
log.error(str(e))
log.error(traceback.format_exc())
return HTTPException(status_code=500, detail=str(e))

View File

@ -17,20 +17,16 @@ from typing import Any, Hashable
import torch
from easydiffusion import device_manager
from easydiffusion.tasks import Task
from easydiffusion.types import GenerateImageRequest, TaskData
from easydiffusion.utils import log
from sdkit.utils import gc
from torchruntime.utils import get_device_count, get_device, get_device_name, get_installed_torch_platform
from sdkit.utils import is_cpu_device, mem_get_info
THREAD_NAME_PREFIX = ""
ERR_LOCK_FAILED = " failed to acquire lock within timeout."
LOCK_TIMEOUT = 15 # Maximum locking time in seconds before failing a task.
# It's better to get an exception than a deadlock... ALWAYS use timeout in critical paths.
DEVICE_START_TIMEOUT = 60 # seconds - Maximum time to wait for a render device to init.
MAX_OVERLOAD_ALLOWED_RATIO = 2 # i.e. 2x pending tasks compared to the number of render threads
class SymbolClass(type): # Print nicely formatted Symbol names.
@ -62,6 +58,46 @@ class ServerStates:
pass
class RenderTask: # Task with output queue and completion lock.
def __init__(self, req: GenerateImageRequest, task_data: TaskData):
task_data.request_id = id(self)
self.render_request: GenerateImageRequest = req # Initial Request
self.task_data: TaskData = task_data
self.response: Any = None # Copy of the last reponse
self.render_device = None # Select the task affinity. (Not used to change active devices).
self.temp_images: list = [None] * req.num_outputs * (1 if task_data.show_only_filtered_image else 2)
self.error: Exception = None
self.lock: threading.Lock = threading.Lock() # Locks at task start and unlocks when task is completed
self.buffer_queue: queue.Queue = queue.Queue() # Queue of JSON string segments
async def read_buffer_generator(self):
try:
while not self.buffer_queue.empty():
res = self.buffer_queue.get(block=False)
self.buffer_queue.task_done()
yield res
except queue.Empty as e:
yield
@property
def status(self):
if self.lock.locked():
return "running"
if isinstance(self.error, StopAsyncIteration):
return "stopped"
if self.error:
return "error"
if not self.buffer_queue.empty():
return "buffer"
if self.response:
return "completed"
return "pending"
@property
def is_pending(self):
return bool(not self.response and not self.error)
# Temporary cache to allow to query tasks results for a short time after they are completed.
class DataCache:
def __init__(self):
@ -87,8 +123,8 @@ class DataCache:
# Remove Items
for key in to_delete:
(_, val) = self._base[key]
if isinstance(val, Task):
log.debug(f"Task {key} expired. Data removed.")
if isinstance(val, RenderTask):
log.debug(f"RenderTask {key} expired. Data removed.")
elif isinstance(val, SessionState):
log.debug(f"Session {key} expired. Data removed.")
else:
@ -184,8 +220,8 @@ class SessionState:
tasks.append(task)
return tasks
def put(self, task: Task, ttl=TASK_TTL):
task_id = task.id
def put(self, task, ttl=TASK_TTL):
task_id = id(task)
self._tasks_ids.append(task_id)
if not task_cache.put(task_id, task, ttl):
return False
@ -194,16 +230,11 @@ class SessionState:
return True
def keep_task_alive(task: Task):
task_cache.keep(task.id, TASK_TTL)
session_cache.keep(task.session_id, TASK_TTL)
def thread_get_next_task():
from easydiffusion import runtime
from easydiffusion import renderer
if not manager_lock.acquire(blocking=True, timeout=LOCK_TIMEOUT):
log.warn(f"Render thread on device: {runtime.context.device} failed to acquire manager lock.")
log.warn(f"Render thread on device: {renderer.context.device} failed to acquire manager lock.")
return None
if len(tasks_queue) <= 0:
manager_lock.release()
@ -211,7 +242,7 @@ def thread_get_next_task():
task = None
try: # Select a render task.
for queued_task in tasks_queue:
if queued_task.render_device and runtime.context.device != queued_task.render_device:
if queued_task.render_device and renderer.context.device != queued_task.render_device:
# Is asking for a specific render device.
if is_alive(queued_task.render_device) > 0:
continue # requested device alive, skip current one.
@ -220,7 +251,7 @@ def thread_get_next_task():
queued_task.error = Exception(queued_task.render_device + " is not currently active.")
task = queued_task
break
if not queued_task.render_device and runtime.context.device == "cpu" and is_alive() > 1:
if not queued_task.render_device and renderer.context.device == "cpu" and is_alive() > 1:
# not asking for any specific devices, cpu want to grab task but other render devices are alive.
continue # Skip Tasks, don't run on CPU unless there is nothing else or user asked for it.
task = queued_task
@ -235,19 +266,19 @@ def thread_get_next_task():
def thread_render(device):
global current_state, current_state_error
from easydiffusion import model_manager, runtime
from easydiffusion import model_manager, renderer
try:
runtime.init(device)
renderer.init(device)
weak_thread_data[threading.current_thread()] = {
"device": runtime.context.device,
"device_name": runtime.context.device_name,
"device": renderer.context.device,
"device_name": renderer.context.device_name,
"alive": True,
}
current_state = ServerStates.LoadingModel
model_manager.load_default_models(runtime.context)
model_manager.load_default_models(renderer.context)
current_state = ServerStates.Online
except Exception as e:
@ -259,8 +290,8 @@ def thread_render(device):
session_cache.clean()
task_cache.clean()
if not weak_thread_data[threading.current_thread()]["alive"]:
log.info(f"Shutting down thread for device {runtime.context.device}")
model_manager.unload_all(runtime.context)
log.info(f"Shutting down thread for device {renderer.context.device}")
model_manager.unload_all(renderer.context)
return
if isinstance(current_state_error, SystemExit):
current_state = ServerStates.Unavailable
@ -280,31 +311,62 @@ def thread_render(device):
task.response = {"status": "failed", "detail": str(task.error)}
task.buffer_queue.put(json.dumps(task.response))
continue
log.info(f"Session {task.session_id} starting task {task.id} on {runtime.context.device_name}")
log.info(f"Session {task.task_data.session_id} starting task {id(task)} on {renderer.context.device_name}")
if not task.lock.acquire(blocking=False):
raise Exception("Got locked task from queue.")
try:
task.run()
def step_callback():
global current_state_error
task_cache.keep(id(task), TASK_TTL)
session_cache.keep(task.task_data.session_id, TASK_TTL)
if (
isinstance(current_state_error, SystemExit)
or isinstance(current_state_error, StopAsyncIteration)
or isinstance(task.error, StopAsyncIteration)
):
renderer.context.stop_processing = True
if isinstance(current_state_error, StopAsyncIteration):
task.error = current_state_error
current_state_error = None
log.info(f"Session {task.task_data.session_id} sent cancel signal for task {id(task)}")
current_state = ServerStates.LoadingModel
model_manager.resolve_model_paths(task.task_data)
model_manager.reload_models_if_necessary(renderer.context, task.task_data)
model_manager.fail_if_models_did_not_load(renderer.context)
current_state = ServerStates.Rendering
task.response = renderer.make_images(
task.render_request,
task.task_data,
task.buffer_queue,
task.temp_images,
step_callback,
)
# Before looping back to the generator, mark cache as still alive.
keep_task_alive(task)
task_cache.keep(id(task), TASK_TTL)
session_cache.keep(task.task_data.session_id, TASK_TTL)
except Exception as e:
task.error = str(e)
task.response = {"status": "failed", "detail": str(task.error)}
task.buffer_queue.put(json.dumps(task.response))
log.error(traceback.format_exc())
finally:
gc(runtime.context)
gc(renderer.context)
task.lock.release()
keep_task_alive(task)
task_cache.keep(id(task), TASK_TTL)
session_cache.keep(task.task_data.session_id, TASK_TTL)
if isinstance(task.error, StopAsyncIteration):
log.info(f"Session {task.session_id} task {task.id} cancelled!")
log.info(f"Session {task.task_data.session_id} task {id(task)} cancelled!")
elif task.error is not None:
log.info(f"Session {task.session_id} task {task.id} failed!")
log.info(f"Session {task.task_data.session_id} task {id(task)} failed!")
else:
log.info(f"Session {task.session_id} task {task.id} completed by {runtime.context.device_name}.")
log.info(
f"Session {task.task_data.session_id} task {id(task)} completed by {renderer.context.device_name}."
)
current_state = ServerStates.Online
@ -332,33 +394,34 @@ def get_devices():
"active": {},
}
def get_device_info(device_id):
if is_cpu_device(device_id):
def get_device_info(device):
if device in ("cpu", "mps"):
return {"name": device_manager.get_processor_name()}
device = get_device(device_id)
mem_free, mem_total = mem_get_info(device)
mem_free, mem_total = torch.cuda.mem_get_info(device)
mem_free /= float(10**9)
mem_total /= float(10**9)
return {
"name": get_device_name(device),
"name": torch.cuda.get_device_name(device),
"mem_free": mem_free,
"mem_total": mem_total,
"max_vram_usage_level": device_manager.get_max_vram_usage_level(device),
}
# list the compatible devices
torch_platform_name = get_installed_torch_platform()[0]
device_count = get_device_count()
for device_id in range(device_count):
device_id = f"{torch_platform_name}:{device_id}" if device_count > 1 else torch_platform_name
cuda_count = torch.cuda.device_count()
for device in range(cuda_count):
device = f"cuda:{device}"
if not device_manager.is_device_compatible(device):
continue
devices["all"].update({device_id: get_device_info(device_id)})
devices["all"].update({device: get_device_info(device)})
if torch_platform_name != "cpu":
devices["all"].update({"cpu": get_device_info("cpu")})
if device_manager.is_mps_available():
devices["all"].update({"mps": get_device_info("mps")})
devices["all"].update({"cpu": get_device_info("cpu")})
# list the activated devices
if not manager_lock.acquire(blocking=True, timeout=LOCK_TIMEOUT):
@ -370,17 +433,11 @@ def get_devices():
weak_data = weak_thread_data.get(rthread)
if not weak_data or not "device" in weak_data or not "device_name" in weak_data:
continue
device_id = weak_data["device"]
devices["active"].update({device_id: get_device_info(device_id)})
device = weak_data["device"]
devices["active"].update({device: get_device_info(device)})
finally:
manager_lock.release()
# temp until TRT releases
import os
from easydiffusion import app
devices["enable_trt"] = os.path.exists(os.path.join(app.ROOT_DIR, "tensorrt"))
return devices
@ -429,6 +486,12 @@ def start_render_thread(device):
def stop_render_thread(device):
try:
device_manager.validate_device_id(device, log_prefix="stop_render_thread")
except:
log.error(traceback.format_exc())
return False
if not manager_lock.acquire(blocking=True, timeout=LOCK_TIMEOUT):
raise Exception("stop_render_thread" + ERR_LOCK_FAILED)
log.info(f"Stopping Rendering Thread on device: {device}")
@ -485,27 +548,28 @@ def shutdown_event(): # Signal render thread to close on shutdown
current_state_error = SystemExit("Application shutting down.")
def enqueue_task(task: Task):
def render(render_req: GenerateImageRequest, task_data: TaskData):
current_thread_count = is_alive()
if current_thread_count <= 0: # Render thread is dead
raise ChildProcessError("Rendering thread has died.")
# Alive, check if task in cache
session = get_cached_session(task.session_id, update_ttl=True)
session = get_cached_session(task_data.session_id, update_ttl=True)
pending_tasks = list(filter(lambda t: t.is_pending, session.tasks))
if len(pending_tasks) > current_thread_count * MAX_OVERLOAD_ALLOWED_RATIO:
if current_thread_count < len(pending_tasks):
raise ConnectionRefusedError(
f"Session {task.session_id} already has {len(pending_tasks)} pending tasks, with {current_thread_count} workers."
f"Session {task_data.session_id} already has {len(pending_tasks)} pending tasks out of {current_thread_count}."
)
if session.put(task, TASK_TTL):
new_task = RenderTask(render_req, task_data)
if session.put(new_task, TASK_TTL):
# Use twice the normal timeout for adding user requests.
# Tries to force session.put to fail before tasks_queue.put would.
if manager_lock.acquire(blocking=True, timeout=LOCK_TIMEOUT * 2):
try:
tasks_queue.append(task)
tasks_queue.append(new_task)
idle_event.set()
return task
return new_task
finally:
manager_lock.release()
raise RuntimeError("Failed to add task to cache.")

View File

@ -1,3 +0,0 @@
from .task import Task
from .render_images import RenderTask
from .filter_images import FilterTask

View File

@ -1,164 +0,0 @@
import os
import json
import pprint
import time
from numpy import base_repr
from sdkit.filter import apply_filters
from sdkit.models import load_model
from sdkit.utils import img_to_base64_str, get_image, log, save_images
from easydiffusion import model_manager, runtime
from easydiffusion.types import (
FilterImageRequest,
FilterImageResponse,
ModelsData,
OutputFormatData,
SaveToDiskData,
TaskData,
GenerateImageRequest,
)
from easydiffusion.utils.save_utils import format_folder_name
from .task import Task
class FilterTask(Task):
"For applying filters to input images"
def __init__(
self,
req: FilterImageRequest,
task_data: TaskData,
models_data: ModelsData,
output_format: OutputFormatData,
save_data: SaveToDiskData,
):
super().__init__(task_data.session_id)
task_data.request_id = self.id
self.request = req
self.task_data = task_data
self.models_data = models_data
self.output_format = output_format
self.save_data = save_data
# convert to multi-filter format, if necessary
if isinstance(req.filter, str):
req.filter_params = {req.filter: req.filter_params}
req.filter = [req.filter]
if not isinstance(req.image, list):
req.image = [req.image]
def run(self):
"Runs the image filtering task on the assigned thread"
from easydiffusion import app
context = runtime.context
model_manager.resolve_model_paths(self.models_data)
model_manager.reload_models_if_necessary(context, self.models_data)
model_manager.fail_if_models_did_not_load(context)
print_task_info(self.request, self.models_data, self.output_format, self.save_data)
if isinstance(self.request.image, list):
images = [get_image(img) for img in self.request.image]
else:
images = get_image(self.request.image)
images = filter_images(context, images, self.request.filter, self.request.filter_params)
output_format = self.output_format
if self.save_data.save_to_disk_path is not None:
app_config = app.getConfig()
folder_format = app_config.get("folder_format", "$id")
dummy_req = GenerateImageRequest()
img_id = base_repr(int(time.time() * 10000), 36)[-7:] # Base 36 conversion, 0-9, A-Z
save_dir_path = os.path.join(
self.save_data.save_to_disk_path, format_folder_name(folder_format, dummy_req, self.task_data)
)
save_images(
images,
save_dir_path,
file_name=img_id,
output_format=output_format.output_format,
output_quality=output_format.output_quality,
output_lossless=output_format.output_lossless,
)
images = [
img_to_base64_str(
img, output_format.output_format, output_format.output_quality, output_format.output_lossless
)
for img in images
]
res = FilterImageResponse(self.request, self.models_data, images=images)
res = res.json()
self.buffer_queue.put(json.dumps(res))
log.info("Filter task completed")
self.response = res
def filter_images(context, images, filters, filter_params={}):
filters = filters if isinstance(filters, list) else [filters]
for filter_name in filters:
params = filter_params.get(filter_name, {})
previous_state = before_filter(context, filter_name, params)
try:
images = apply_filters(context, filter_name, images, **params)
finally:
after_filter(context, filter_name, params, previous_state)
return images
def before_filter(context, filter_name, filter_params):
if filter_name == "codeformer":
from easydiffusion.model_manager import DEFAULT_MODELS, resolve_model_to_use
default_realesrgan = DEFAULT_MODELS["realesrgan"][0]["file_name"]
prev_realesrgan_path = None
upscale_faces = filter_params.get("upscale_faces", False)
if upscale_faces and default_realesrgan not in context.model_paths["realesrgan"]:
prev_realesrgan_path = context.model_paths.get("realesrgan")
context.model_paths["realesrgan"] = resolve_model_to_use(default_realesrgan, "realesrgan")
load_model(context, "realesrgan")
return prev_realesrgan_path
def after_filter(context, filter_name, filter_params, previous_state):
if filter_name == "codeformer":
prev_realesrgan_path = previous_state
if prev_realesrgan_path:
context.model_paths["realesrgan"] = prev_realesrgan_path
load_model(context, "realesrgan")
def print_task_info(
req: FilterImageRequest, models_data: ModelsData, output_format: OutputFormatData, save_data: SaveToDiskData
):
req_str = pprint.pformat({"filter": req.filter, "filter_params": req.filter_params}).replace("[", "\[")
models_data = pprint.pformat(models_data.dict()).replace("[", "\[")
output_format = pprint.pformat(output_format.dict()).replace("[", "\[")
save_data = pprint.pformat(save_data.dict()).replace("[", "\[")
log.info(f"request: {req_str}")
log.info(f"models data: {models_data}")
log.info(f"output format: {output_format}")
log.info(f"save data: {save_data}")

View File

@ -1,378 +0,0 @@
import json
import pprint
import queue
import time
from easydiffusion import model_manager, runtime
from easydiffusion.types import GenerateImageRequest, ModelsData, OutputFormatData, SaveToDiskData
from easydiffusion.types import Image as ResponseImage
from easydiffusion.types import GenerateImageResponse, RenderTaskData, UserInitiatedStop
from easydiffusion.utils import get_printable_request, log, save_images_to_disk
from sdkit.generate import generate_images
from sdkit.utils import (
diffusers_latent_samples_to_images,
gc,
img_to_base64_str,
img_to_buffer,
latent_samples_to_images,
resize_img,
get_image,
log,
)
from .task import Task
from .filter_images import filter_images
class RenderTask(Task):
"For image generation"
def __init__(
self,
req: GenerateImageRequest,
task_data: RenderTaskData,
models_data: ModelsData,
output_format: OutputFormatData,
save_data: SaveToDiskData,
):
super().__init__(task_data.session_id)
task_data.request_id = self.id
self.render_request = req # Initial Request
self.task_data = task_data
self.models_data = models_data
self.output_format = output_format
self.save_data = save_data
self.temp_images: list = [None] * req.num_outputs * (1 if task_data.show_only_filtered_image else 2)
def run(self):
"Runs the image generation task on the assigned thread"
from easydiffusion import task_manager, app
context = runtime.context
config = app.getConfig()
if config.get("block_nsfw", False): # override if set on the server
self.task_data.block_nsfw = True
if "nsfw_checker" not in self.task_data.filters:
self.task_data.filters.append("nsfw_checker")
self.models_data.model_paths["nsfw_checker"] = "nsfw_checker"
def step_callback():
task_manager.keep_task_alive(self)
task_manager.current_state = task_manager.ServerStates.Rendering
if isinstance(task_manager.current_state_error, (SystemExit, StopAsyncIteration)) or isinstance(
self.error, StopAsyncIteration
):
context.stop_processing = True
if isinstance(task_manager.current_state_error, StopAsyncIteration):
self.error = task_manager.current_state_error
task_manager.current_state_error = None
log.info(f"Session {self.session_id} sent cancel signal for task {self.id}")
task_manager.current_state = task_manager.ServerStates.LoadingModel
model_manager.resolve_model_paths(self.models_data)
models_to_force_reload = []
if (
runtime.set_vram_optimizations(context)
or self.has_param_changed(context, "clip_skip")
or self.trt_needs_reload(context)
):
models_to_force_reload.append("stable-diffusion")
model_manager.reload_models_if_necessary(context, self.models_data, models_to_force_reload)
model_manager.fail_if_models_did_not_load(context)
task_manager.current_state = task_manager.ServerStates.Rendering
self.response = make_images(
context,
self.render_request,
self.task_data,
self.models_data,
self.output_format,
self.save_data,
self.buffer_queue,
self.temp_images,
step_callback,
)
def has_param_changed(self, context, param_name):
if not context.test_diffusers:
return False
if "stable-diffusion" not in context.models or "params" not in context.models["stable-diffusion"]:
return True
model = context.models["stable-diffusion"]
new_val = self.models_data.model_params.get("stable-diffusion", {}).get(param_name, False)
return model["params"].get(param_name) != new_val
def trt_needs_reload(self, context):
if not context.test_diffusers:
return False
if "stable-diffusion" not in context.models or "params" not in context.models["stable-diffusion"]:
return True
model = context.models["stable-diffusion"]
# curr_convert_to_trt = model["params"].get("convert_to_tensorrt")
new_convert_to_trt = self.models_data.model_params.get("stable-diffusion", {}).get("convert_to_tensorrt", False)
pipe = model["default"]
is_trt_loaded = hasattr(pipe.unet, "_allocate_trt_buffers") or hasattr(
pipe.unet, "_allocate_trt_buffers_backup"
)
if new_convert_to_trt and not is_trt_loaded:
return True
curr_build_config = model["params"].get("trt_build_config")
new_build_config = self.models_data.model_params.get("stable-diffusion", {}).get("trt_build_config", {})
return new_convert_to_trt and curr_build_config != new_build_config
def make_images(
context,
req: GenerateImageRequest,
task_data: RenderTaskData,
models_data: ModelsData,
output_format: OutputFormatData,
save_data: SaveToDiskData,
data_queue: queue.Queue,
task_temp_images: list,
step_callback,
):
context.stop_processing = False
print_task_info(req, task_data, models_data, output_format, save_data)
images, seeds = make_images_internal(
context, req, task_data, models_data, output_format, save_data, data_queue, task_temp_images, step_callback
)
res = GenerateImageResponse(
req, task_data, models_data, output_format, save_data, images=construct_response(images, seeds, output_format)
)
res = res.json()
data_queue.put(json.dumps(res))
log.info("Task completed")
return res
def print_task_info(
req: GenerateImageRequest,
task_data: RenderTaskData,
models_data: ModelsData,
output_format: OutputFormatData,
save_data: SaveToDiskData,
):
req_str = pprint.pformat(get_printable_request(req, task_data, models_data, output_format, save_data)).replace("[", "\[")
task_str = pprint.pformat(task_data.dict()).replace("[", "\[")
models_data = pprint.pformat(models_data.dict()).replace("[", "\[")
output_format = pprint.pformat(output_format.dict()).replace("[", "\[")
save_data = pprint.pformat(save_data.dict()).replace("[", "\[")
log.info(f"request: {req_str}")
log.info(f"task data: {task_str}")
# log.info(f"models data: {models_data}")
log.info(f"output format: {output_format}")
log.info(f"save data: {save_data}")
def make_images_internal(
context,
req: GenerateImageRequest,
task_data: RenderTaskData,
models_data: ModelsData,
output_format: OutputFormatData,
save_data: SaveToDiskData,
data_queue: queue.Queue,
task_temp_images: list,
step_callback,
):
images, user_stopped = generate_images_internal(
context,
req,
task_data,
models_data,
data_queue,
task_temp_images,
step_callback,
task_data.stream_image_progress,
task_data.stream_image_progress_interval,
)
gc(context)
filters, filter_params = task_data.filters, task_data.filter_params
filtered_images = filter_images(context, images, filters, filter_params) if not user_stopped else images
if save_data.save_to_disk_path is not None:
save_images_to_disk(images, filtered_images, req, task_data, models_data, output_format, save_data)
seeds = [*range(req.seed, req.seed + len(images))]
if task_data.show_only_filtered_image or filtered_images is images:
return filtered_images, seeds
else:
return images + filtered_images, seeds + seeds
def generate_images_internal(
context,
req: GenerateImageRequest,
task_data: RenderTaskData,
models_data: ModelsData,
data_queue: queue.Queue,
task_temp_images: list,
step_callback,
stream_image_progress: bool,
stream_image_progress_interval: int,
):
context.temp_images.clear()
callback = make_step_callback(
context,
req,
task_data,
data_queue,
task_temp_images,
step_callback,
stream_image_progress,
stream_image_progress_interval,
)
try:
if req.init_image is not None and not context.test_diffusers:
req.sampler_name = "ddim"
req.width, req.height = map(lambda x: x - x % 8, (req.width, req.height)) # clamp to 8
if req.control_image and task_data.control_filter_to_apply:
req.control_image = get_image(req.control_image)
req.control_image = resize_img(req.control_image.convert("RGB"), req.width, req.height, clamp_to_8=True)
req.control_image = filter_images(context, req.control_image, task_data.control_filter_to_apply)[0]
if req.init_image is not None and int(req.num_inference_steps * req.prompt_strength) == 0:
req.prompt_strength = 1 / req.num_inference_steps if req.num_inference_steps > 0 else 1
if context.test_diffusers:
pipe = context.models["stable-diffusion"]["default"]
if hasattr(pipe.unet, "_allocate_trt_buffers_backup"):
setattr(pipe.unet, "_allocate_trt_buffers", pipe.unet._allocate_trt_buffers_backup)
delattr(pipe.unet, "_allocate_trt_buffers_backup")
if hasattr(pipe.unet, "_allocate_trt_buffers"):
convert_to_trt = models_data.model_params["stable-diffusion"].get("convert_to_tensorrt", False)
if convert_to_trt:
pipe.unet.forward = pipe.unet._trt_forward
# pipe.vae.decoder.forward = pipe.vae.decoder._trt_forward
log.info(f"Setting unet.forward to TensorRT")
else:
log.info(f"Not using TensorRT for unet.forward")
pipe.unet.forward = pipe.unet._non_trt_forward
# pipe.vae.decoder.forward = pipe.vae.decoder._non_trt_forward
setattr(pipe.unet, "_allocate_trt_buffers_backup", pipe.unet._allocate_trt_buffers)
delattr(pipe.unet, "_allocate_trt_buffers")
if task_data.enable_vae_tiling:
if hasattr(pipe, "enable_vae_tiling"):
pipe.enable_vae_tiling()
else:
if hasattr(pipe, "disable_vae_tiling"):
pipe.disable_vae_tiling()
images = generate_images(context, callback=callback, **req.dict())
user_stopped = False
except UserInitiatedStop:
images = []
user_stopped = True
if context.partial_x_samples is not None:
if context.test_diffusers:
images = diffusers_latent_samples_to_images(context, context.partial_x_samples)
else:
images = latent_samples_to_images(context, context.partial_x_samples)
finally:
if hasattr(context, "partial_x_samples") and context.partial_x_samples is not None:
if not context.test_diffusers:
del context.partial_x_samples
context.partial_x_samples = None
return images, user_stopped
def construct_response(images: list, seeds: list, output_format: OutputFormatData):
return [
ResponseImage(
data=img_to_base64_str(
img,
output_format.output_format,
output_format.output_quality,
output_format.output_lossless,
),
seed=seed,
)
for img, seed in zip(images, seeds)
]
def make_step_callback(
context,
req: GenerateImageRequest,
task_data: RenderTaskData,
data_queue: queue.Queue,
task_temp_images: list,
step_callback,
stream_image_progress: bool,
stream_image_progress_interval: int,
):
n_steps = req.num_inference_steps if req.init_image is None else int(req.num_inference_steps * req.prompt_strength)
last_callback_time = -1
def update_temp_img(x_samples, task_temp_images: list):
partial_images = []
if context.test_diffusers:
images = diffusers_latent_samples_to_images(context, x_samples)
else:
images = latent_samples_to_images(context, x_samples)
if task_data.block_nsfw:
images = filter_images(context, images, "nsfw_checker")
for i, img in enumerate(images):
buf = img_to_buffer(img, output_format="JPEG")
context.temp_images[f"{task_data.request_id}/{i}"] = buf
task_temp_images[i] = buf
partial_images.append({"path": f"/image/tmp/{task_data.request_id}/{i}"})
del images
return partial_images
def on_image_step(x_samples, i, *args):
nonlocal last_callback_time
if context.test_diffusers:
context.partial_x_samples = (x_samples, args[0])
else:
context.partial_x_samples = x_samples
step_time = time.time() - last_callback_time if last_callback_time != -1 else -1
last_callback_time = time.time()
progress = {"step": i, "step_time": step_time, "total_steps": n_steps}
if stream_image_progress and stream_image_progress_interval > 0 and i % stream_image_progress_interval == 0:
progress["output"] = update_temp_img(context.partial_x_samples, task_temp_images)
data_queue.put(json.dumps(progress))
step_callback()
if context.stop_processing:
raise UserInitiatedStop("User requested that we stop processing")
return on_image_step

View File

@ -1,47 +0,0 @@
from threading import Lock
from queue import Queue, Empty as EmptyQueueException
from typing import Any
class Task:
"Task with output queue and completion lock"
def __init__(self, session_id):
self.id = id(self)
self.session_id = session_id
self.render_device = None # Select the task affinity. (Not used to change active devices).
self.error: Exception = None
self.lock: Lock = Lock() # Locks at task start and unlocks when task is completed
self.buffer_queue: Queue = Queue() # Queue of JSON string segments
self.response: Any = None # Copy of the last reponse
async def read_buffer_generator(self):
try:
while not self.buffer_queue.empty():
res = self.buffer_queue.get(block=False)
self.buffer_queue.task_done()
yield res
except EmptyQueueException as e:
yield
@property
def status(self):
if self.lock.locked():
return "running"
if isinstance(self.error, StopAsyncIteration):
return "stopped"
if self.error:
return "error"
if not self.buffer_queue.empty():
return "buffer"
if self.response:
return "completed"
return "pending"
@property
def is_pending(self):
return bool(not self.response and not self.error)
def run(self):
"Override this to implement the task's behavior"
pass

View File

@ -1,4 +1,4 @@
from typing import Any, List, Dict, Union
from typing import Any
from pydantic import BaseModel
@ -17,82 +17,41 @@ class GenerateImageRequest(BaseModel):
init_image: Any = None
init_image_mask: Any = None
control_image: Any = None
control_alpha: Union[float, List[float]] = None
prompt_strength: float = 0.8
preserve_init_image_color_profile: bool = False
strict_mask_border: bool = False
preserve_init_image_color_profile = False
sampler_name: str = None # "ddim", "plms", "heun", "euler", "euler_a", "dpm2", "dpm2_a", "lms"
hypernetwork_strength: float = 0
lora_alpha: Union[float, List[float]] = 0
tiling: str = None # None, "x", "y", "xy"
class FilterImageRequest(BaseModel):
image: Any = None
filter: Union[str, List[str]] = None
filter_params: dict = {}
class ModelsData(BaseModel):
"""
Contains the information related to the models involved in a request.
- To load a model: set the relative path(s) to the model in `model_paths`. No effect if already loaded.
- To unload a model: set the model to `None` in `model_paths`. No effect if already unloaded.
Models that aren't present in `model_paths` will not be changed.
"""
model_paths: Dict[str, Union[str, None, List[str]]] = None
"model_type to string path, or list of string paths"
model_params: Dict[str, Dict[str, Any]] = {}
"model_type to dict of parameters"
class OutputFormatData(BaseModel):
output_format: str = "jpeg" # or "png" or "webp"
output_quality: int = 75
output_lossless: bool = False
class SaveToDiskData(BaseModel):
save_to_disk_path: str = None
metadata_output_format: str = "txt" # or "json"
lora_alpha: float = 0
tiling: str = "none" # "none", "x", "y", "xy"
class TaskData(BaseModel):
request_id: str = None
session_id: str = "session"
class RenderTaskData(TaskData):
save_to_disk_path: str = None
vram_usage_level: str = "balanced" # or "low" or "medium"
use_face_correction: Union[str, List[str]] = None # or "GFPGANv1.3"
use_upscale: Union[str, List[str]] = None
use_face_correction: str = None # or "GFPGANv1.3"
use_upscale: str = None # or "RealESRGAN_x4plus" or "RealESRGAN_x4plus_anime_6B" or "latent_upscaler"
upscale_amount: int = 4 # or 2
latent_upscaler_steps: int = 10
use_stable_diffusion_model: Union[str, List[str]] = "sd-v1-4"
use_vae_model: Union[str, List[str]] = None
use_hypernetwork_model: Union[str, List[str]] = None
use_lora_model: Union[str, List[str]] = None
use_controlnet_model: Union[str, List[str]] = None
use_embeddings_model: Union[str, List[str]] = None
filters: List[str] = []
filter_params: Dict[str, Dict[str, Any]] = {}
control_filter_to_apply: Union[str, List[str]] = None
enable_vae_tiling: bool = True
use_stable_diffusion_model: str = "sd-v1-4"
# use_stable_diffusion_config: str = "v1-inference"
use_vae_model: str = None
use_hypernetwork_model: str = None
use_lora_model: str = None
show_only_filtered_image: bool = False
block_nsfw: bool = False
output_format: str = "jpeg" # or "png" or "webp"
output_quality: int = 75
output_lossless: bool = False
metadata_output_format: str = "txt" # or "json"
stream_image_progress: bool = False
stream_image_progress_interval: int = 5
clip_skip: bool = False
codeformer_upscale_faces: bool = False
codeformer_fidelity: float = 0.5
class MergeRequest(BaseModel):
@ -100,7 +59,7 @@ class MergeRequest(BaseModel):
model1: str = None
ratio: float = None
out_path: str = "mix"
use_fp16: bool = True
use_fp16 = True
class Image:
@ -121,42 +80,24 @@ class Image:
}
class GenerateImageResponse:
class Response:
render_request: GenerateImageRequest
task_data: TaskData
models_data: ModelsData
images: list
def __init__(
self,
render_request: GenerateImageRequest,
task_data: TaskData,
models_data: ModelsData,
output_format: OutputFormatData,
save_data: SaveToDiskData,
images: list,
):
def __init__(self, render_request: GenerateImageRequest, task_data: TaskData, images: list):
self.render_request = render_request
self.task_data = task_data
self.models_data = models_data
self.output_format = output_format
self.save_data = save_data
self.images = images
def json(self):
del self.render_request.init_image
del self.render_request.init_image_mask
del self.render_request.control_image
task_data = self.task_data.dict()
task_data.update(self.output_format.dict())
task_data.update(self.save_data.dict())
res = {
"status": "succeeded",
"render_request": self.render_request.dict(),
"task_data": task_data,
# "models_data": self.models_data.dict(), # haven't migrated the UI to the new format (yet)
"task_data": self.task_data.dict(),
"output": [],
}
@ -166,112 +107,5 @@ class GenerateImageResponse:
return res
class FilterImageResponse:
request: FilterImageRequest
models_data: ModelsData
images: list
def __init__(self, request: FilterImageRequest, models_data: ModelsData, images: list):
self.request = request
self.models_data = models_data
self.images = images
def json(self):
del self.request.image
res = {
"status": "succeeded",
"request": self.request.dict(),
"models_data": self.models_data.dict(),
"output": [],
}
for image in self.images:
res["output"].append(image)
return res
class UserInitiatedStop(Exception):
pass
def convert_legacy_render_req_to_new(old_req: dict):
new_req = dict(old_req)
# new keys
model_paths = new_req["model_paths"] = {}
model_params = new_req["model_params"] = {}
filters = new_req["filters"] = []
filter_params = new_req["filter_params"] = {}
# move the model info
model_paths["stable-diffusion"] = old_req.get("use_stable_diffusion_model")
model_paths["vae"] = old_req.get("use_vae_model")
model_paths["hypernetwork"] = old_req.get("use_hypernetwork_model")
model_paths["lora"] = old_req.get("use_lora_model")
model_paths["controlnet"] = old_req.get("use_controlnet_model")
model_paths["embeddings"] = old_req.get("use_embeddings_model")
model_paths["gfpgan"] = old_req.get("use_face_correction", "")
model_paths["gfpgan"] = model_paths["gfpgan"] if "gfpgan" in model_paths["gfpgan"].lower() else None
model_paths["codeformer"] = old_req.get("use_face_correction", "")
model_paths["codeformer"] = model_paths["codeformer"] if "codeformer" in model_paths["codeformer"].lower() else None
model_paths["realesrgan"] = old_req.get("use_upscale", "")
model_paths["realesrgan"] = model_paths["realesrgan"] if "realesrgan" in model_paths["realesrgan"].lower() else None
model_paths["latent_upscaler"] = old_req.get("use_upscale", "")
model_paths["latent_upscaler"] = (
model_paths["latent_upscaler"] if "latent_upscaler" in model_paths["latent_upscaler"].lower() else None
)
if "control_filter_to_apply" in old_req:
filter_model = old_req["control_filter_to_apply"]
model_paths[filter_model] = filter_model
if old_req.get("block_nsfw"):
model_paths["nsfw_checker"] = "nsfw_checker"
# move the model params
if model_paths["stable-diffusion"]:
model_params["stable-diffusion"] = {
"clip_skip": bool(old_req.get("clip_skip", False)),
"convert_to_tensorrt": bool(old_req.get("convert_to_tensorrt", False)),
"trt_build_config": old_req.get(
"trt_build_config", {"batch_size_range": (1, 1), "dimensions_range": [(768, 1024)]}
),
}
# move the filter params
if model_paths["realesrgan"]:
filter_params["realesrgan"] = {"scale": int(old_req.get("upscale_amount", 4))}
if model_paths["latent_upscaler"]:
filter_params["latent_upscaler"] = {
"prompt": old_req["prompt"],
"negative_prompt": old_req.get("negative_prompt"),
"seed": int(old_req.get("seed", 42)),
"num_inference_steps": int(old_req.get("latent_upscaler_steps", 10)),
"guidance_scale": 0,
}
if model_paths["codeformer"]:
filter_params["codeformer"] = {
"upscale_faces": bool(old_req.get("codeformer_upscale_faces", True)),
"codeformer_fidelity": float(old_req.get("codeformer_fidelity", 0.5)),
}
# set the filters
if old_req.get("block_nsfw"):
filters.append("nsfw_checker")
if model_paths["codeformer"]:
filters.append("codeformer")
elif model_paths["gfpgan"]:
filters.append("gfpgan")
if model_paths["realesrgan"]:
filters.append("realesrgan")
elif model_paths["latent_upscaler"]:
filters.append("latent_upscaler")
return new_req

View File

@ -1,5 +1,4 @@
import logging
import hashlib
log = logging.getLogger("easydiffusion")
@ -7,15 +6,3 @@ from .save_utils import (
save_images_to_disk,
get_printable_request,
)
def sha256sum(filename):
sha256 = hashlib.sha256()
with open(filename, "rb") as f:
while True:
data = f.read(8192) # Read in chunks of 8192 bytes
if not data:
break
sha256.update(data)
return sha256.hexdigest()

View File

@ -1,23 +1,13 @@
import os
import re
import time
import regex
from datetime import datetime
from functools import reduce
from easydiffusion import app
from easydiffusion.types import (
GenerateImageRequest,
TaskData,
RenderTaskData,
OutputFormatData,
SaveToDiskData,
ModelsData,
)
from easydiffusion.types import GenerateImageRequest, TaskData
from numpy import base_repr
from sdkit.utils import save_dicts, save_images
from sdkit.models.model_loader.embeddings import get_embedding_token
filename_regex = re.compile("[^a-zA-Z0-9._-]")
img_number_regex = re.compile("([0-9]{5,})")
@ -29,9 +19,6 @@ TASK_TEXT_MAPPING = {
"seed": "Seed",
"use_stable_diffusion_model": "Stable Diffusion model",
"clip_skip": "Clip Skip",
"use_controlnet_model": "ControlNet model",
"control_filter_to_apply": "ControlNet Filter",
"control_alpha": "ControlNet Strength",
"use_vae_model": "VAE model",
"sampler_name": "Sampler",
"width": "Width",
@ -43,12 +30,11 @@ TASK_TEXT_MAPPING = {
"lora_alpha": "LoRA Strength",
"use_hypernetwork_model": "Hypernetwork model",
"hypernetwork_strength": "Hypernetwork Strength",
"use_embeddings_model": "Embedding models",
"tiling": "Seamless Tiling",
"use_face_correction": "Use Face Correction",
"use_upscale": "Use Upscaling",
"upscale_amount": "Upscale By",
"latent_upscaler_steps": "Latent Upscaler Steps",
"latent_upscaler_steps": "Latent Upscaler Steps"
}
time_placeholders = {
@ -103,7 +89,7 @@ def format_folder_name(format: str, req: GenerateImageRequest, task_data: TaskDa
def format_file_name(
format: str,
req: GenerateImageRequest,
task_data: RenderTaskData,
task_data: TaskData,
now: float,
batch_file_number: int,
folder_img_number: ImageNumber,
@ -125,20 +111,12 @@ def format_file_name(
return filename_regex.sub("_", format)
def save_images_to_disk(
images: list,
filtered_images: list,
req: GenerateImageRequest,
task_data: RenderTaskData,
models_data: ModelsData,
output_format: OutputFormatData,
save_data: SaveToDiskData,
):
def save_images_to_disk(images: list, filtered_images: list, req: GenerateImageRequest, task_data: TaskData):
now = time.time()
app_config = app.getConfig()
folder_format = app_config.get("folder_format", "$id")
save_dir_path = os.path.join(save_data.save_to_disk_path, format_folder_name(folder_format, req, task_data))
metadata_entries = get_metadata_entries_for_request(req, task_data, models_data, output_format, save_data)
save_dir_path = os.path.join(task_data.save_to_disk_path, format_folder_name(folder_format, req, task_data))
metadata_entries = get_metadata_entries_for_request(req, task_data)
file_number = calculate_img_number(save_dir_path, task_data)
make_filename = make_filename_callback(
app_config.get("filename_format", "$p_$tsb64"),
@ -153,19 +131,19 @@ def save_images_to_disk(
filtered_images,
save_dir_path,
file_name=make_filename,
output_format=output_format.output_format,
output_quality=output_format.output_quality,
output_lossless=output_format.output_lossless,
output_format=task_data.output_format,
output_quality=task_data.output_quality,
output_lossless=task_data.output_lossless,
)
if save_data.metadata_output_format:
for metadata_output_format in save_data.metadata_output_format.split(","):
if task_data.metadata_output_format:
for metadata_output_format in task_data.metadata_output_format.split(","):
if metadata_output_format.lower() in ["json", "txt", "embed"]:
save_dicts(
metadata_entries,
save_dir_path,
file_name=make_filename,
output_format=metadata_output_format,
file_format=output_format.output_format,
file_format=task_data.output_format,
)
else:
make_filter_filename = make_filename_callback(
@ -181,51 +159,37 @@ def save_images_to_disk(
images,
save_dir_path,
file_name=make_filename,
output_format=output_format.output_format,
output_quality=output_format.output_quality,
output_lossless=output_format.output_lossless,
output_format=task_data.output_format,
output_quality=task_data.output_quality,
output_lossless=task_data.output_lossless,
)
save_images(
filtered_images,
save_dir_path,
file_name=make_filter_filename,
output_format=output_format.output_format,
output_quality=output_format.output_quality,
output_lossless=output_format.output_lossless,
output_format=task_data.output_format,
output_quality=task_data.output_quality,
output_lossless=task_data.output_lossless,
)
if save_data.metadata_output_format:
for metadata_output_format in save_data.metadata_output_format.split(","):
if task_data.metadata_output_format:
for metadata_output_format in task_data.metadata_output_format.split(","):
if metadata_output_format.lower() in ["json", "txt", "embed"]:
save_dicts(
metadata_entries,
save_dir_path,
file_name=make_filter_filename,
output_format=metadata_output_format,
file_format=output_format.output_format,
output_format=task_data.metadata_output_format,
file_format=task_data.output_format,
)
def get_metadata_entries_for_request(
req: GenerateImageRequest,
task_data: RenderTaskData,
models_data: ModelsData,
output_format: OutputFormatData,
save_data: SaveToDiskData,
):
metadata = get_printable_request(req, task_data, models_data, output_format, save_data)
def get_metadata_entries_for_request(req: GenerateImageRequest, task_data: TaskData):
metadata = get_printable_request(req, task_data)
# if text, format it in the text format expected by the UI
is_txt_format = save_data.metadata_output_format and "txt" in save_data.metadata_output_format.lower().split(",")
is_txt_format = task_data.metadata_output_format and "txt" in task_data.metadata_output_format.lower().split(",")
if is_txt_format:
def format_value(value):
if isinstance(value, list):
return ", ".join([str(it) for it in value])
return value
metadata = {
TASK_TEXT_MAPPING[key]: format_value(val) for key, val in metadata.items() if key in TASK_TEXT_MAPPING
}
metadata = {TASK_TEXT_MAPPING[key]: val for key, val in metadata.items() if key in TASK_TEXT_MAPPING}
entries = [metadata.copy() for _ in range(req.num_outputs)]
for i, entry in enumerate(entries):
@ -234,20 +198,9 @@ def get_metadata_entries_for_request(
return entries
def get_printable_request(
req: GenerateImageRequest,
task_data: RenderTaskData,
models_data: ModelsData,
output_format: OutputFormatData,
save_data: SaveToDiskData,
):
def get_printable_request(req: GenerateImageRequest, task_data: TaskData):
req_metadata = req.dict()
task_data_metadata = task_data.dict()
task_data_metadata.update(output_format.dict())
task_data_metadata.update(save_data.dict())
app_config = app.getConfig()
using_diffusers = app_config.get("use_v3_engine", True)
# Save the metadata in the order defined in TASK_TEXT_MAPPING
metadata = {}
@ -256,13 +209,7 @@ def get_printable_request(
metadata[key] = req_metadata[key]
elif key in task_data_metadata:
metadata[key] = task_data_metadata[key]
if key == "use_embeddings_model" and task_data_metadata[key] and using_diffusers:
embeddings_used = models_data.model_paths["embeddings"]
embeddings_used = embeddings_used if isinstance(embeddings_used, list) else [embeddings_used]
metadata["use_embeddings_model"] = embeddings_used if len(embeddings_used) > 0 else None
# Clean up the metadata
if req.init_image is None and "prompt_strength" in metadata:
del metadata["prompt_strength"]
@ -274,26 +221,10 @@ def get_printable_request(
del metadata["lora_alpha"]
if task_data.use_upscale != "latent_upscaler" and "latent_upscaler_steps" in metadata:
del metadata["latent_upscaler_steps"]
if task_data.use_controlnet_model is None and "control_filter_to_apply" in metadata:
del metadata["control_filter_to_apply"]
if using_diffusers:
for key in (x for x in ["use_hypernetwork_model", "hypernetwork_strength"] if x in metadata):
del metadata[key]
else:
for key in (
x
for x in [
"use_lora_model",
"lora_alpha",
"clip_skip",
"tiling",
"latent_upscaler_steps",
"use_controlnet_model",
"control_filter_to_apply",
]
if x in metadata
):
app_config = app.getConfig()
if not app_config.get("test_diffusers", False):
for key in (x for x in ["use_lora_model", "lora_alpha", "clip_skip", "tiling", "latent_upscaler_steps"] if x in metadata):
del metadata[key]
return metadata
@ -302,7 +233,7 @@ def get_printable_request(
def make_filename_callback(
filename_format: str,
req: GenerateImageRequest,
task_data: RenderTaskData,
task_data: TaskData,
folder_img_number: int,
suffix=None,
now=None,
@ -319,7 +250,7 @@ def make_filename_callback(
return make_filename
def _calculate_img_number(save_dir_path: str, task_data: RenderTaskData):
def _calculate_img_number(save_dir_path: str, task_data: TaskData):
def get_highest_img_number(accumulator: int, file: os.DirEntry) -> int:
if not file.is_file:
return accumulator
@ -363,5 +294,5 @@ def _calculate_img_number(save_dir_path: str, task_data: RenderTaskData):
_calculate_img_number.session_img_numbers = {}
def calculate_img_number(save_dir_path: str, task_data: RenderTaskData):
def calculate_img_number(save_dir_path: str, task_data: TaskData):
return ImageNumber(lambda: _calculate_img_number(save_dir_path, task_data))

View File

@ -16,17 +16,12 @@
<link rel="stylesheet" href="/media/css/image-editor.css">
<link rel="stylesheet" href="/media/css/searchable-models.css">
<link rel="stylesheet" href="/media/css/image-modal.css">
<link rel="stylesheet" href="/media/css/plugins.css">
<link rel="stylesheet" href="/media/css/animations.css">
<link rel="stylesheet" href="/media/css/croppr.css" rel="stylesheet"/>
<link rel="manifest" href="/media/manifest.webmanifest">
<script src="/media/js/jquery-3.6.1.min.js"></script>
<script src="/media/js/jquery-confirm.min.js"></script>
<script src="/media/js/jszip.min.js"></script>
<script src="/media/js/FileSaver.min.js"></script>
<script src="/media/js/marked.min.js"></script>
<script src="/media/js/croppr.js"></script>
<script src="/media/js/exif-reader.js"></script>
</head>
<body>
<div id="container">
@ -35,7 +30,7 @@
<h1>
<img id="logo_img" src="/media/images/icon-512x512.png" >
Easy Diffusion
<small><span id="version">v3.0.9c</span> <span id="updateBranchLabel"></span></small>
<small>v2.5.40 <span id="updateBranchLabel"></span></small>
</h1>
</div>
<div id="server-status">
@ -60,30 +55,14 @@
<div id="editor">
<div id="editor-inputs">
<div id="editor-inputs-prompt" class="row">
<div id="prompt-toolbar" class="split-toolbar">
<div id="prompt-toolbar-left" class="toolbar-left">
<label for="prompt"><b>Enter Prompt</b>
<i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip right">
You can type your prompts in the below textbox or load them from a file. You can also
reload tasks from metadata embedded in PNG, WEBP and JPEG images (enable embedding from the Settings).
</span></i>
</label>
<small>or</small>
<button id="promptsFromFileBtn" class="tertiaryButton smallButton">Load from a file</button>
</div>
<div id="prompt-toolbar-right" class="toolbar-right">
<button id="image-modifier-dropdown" class="tertiaryButton smallButton">+ Image Modifiers</button>
<button id="embeddings-button" class="tertiaryButton smallButton displayNone">+ Embedding</button>
</div>
</div>
<label for="prompt"><b>Enter Prompt</b></label> <small>or</small> <button id="promptsFromFileBtn" class="tertiaryButton">Load from a file</button>
<textarea id="prompt" class="col-free">a photograph of an astronaut riding a horse</textarea>
<input id="prompt_from_file" name="prompt_from_file" type="file" /> <!-- hidden -->
<label for="negative_prompt" class="collapsible" id="negative_prompt_handle">
Negative Prompt
<a href="https://github.com/easydiffusion/easydiffusion/wiki/Writing-prompts#negative-prompts" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top">Click to learn more about Negative Prompts</span></i></a>
<a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/Writing-prompts#negative-prompts" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top">Click to learn more about Negative Prompts</span></i></a>
<small>(optional)</small>
</label>
<button id="negative-embeddings-button" class="tertiaryButton smallButton displayNone">+ Negative Embedding</button>
<div class="collapsible-content">
<textarea id="negative_prompt" name="negative_prompt" placeholder="list the things to remove from the image (e.g. fog, green)"></textarea>
</div>
@ -91,15 +70,10 @@
<div id="editor-inputs-init-image" class="row">
<label for="init_image">Initial Image (img2img) <small>(optional)</small> </label>
<i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top">
Add img2img source image using the Browse button, via drag & drop from external file or browser image (incl.
rendered image) or by pasting an image from the clipboard using Ctrl+V.<br /><br />
You may also reload the metadata embedded in a PNG, WEBP or JPEG image (enable embedding from the Settings).
</span></i>
<div id="init_image_preview_container" class="image_preview_container">
<div id="init_image_wrapper" class="preview_image_wrapper">
<img id="init_image_preview" class="image_preview" src="" crossorigin="anonymous" />
<div id="init_image_wrapper">
<img id="init_image_preview" src="" />
<span id="init_image_size_box" class="img_bottom_label"></span>
<button class="init_image_clear image_clear_btn"><i class="fa-solid fa-xmark"></i></button>
</div>
@ -124,12 +98,11 @@
</div>
<div id="apply_color_correction_setting" class="pl-5"><input id="apply_color_correction" name="apply_color_correction" type="checkbox"> <label for="apply_color_correction">Preserve color profile <small>(helps during inpainting)</small></label></div>
<div id="strict_mask_border_setting" class="pl-5"><input id="strict_mask_border" name="strict_mask_border" type="checkbox"> <label for="strict_mask_border">Strict Mask Border <small>(won't modify outside the mask, but the mask border might be visible)</small></label></div>
</div>
<div id="editor-inputs-tags-container" class="row">
<label>Image Modifiers <i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip right">Click an Image Modifier to remove it, right-click to temporarily disable it, use Ctrl+Mouse Wheel to adjust its weight</span></i></label>
<label>Image Modifiers <i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip right">click an Image Modifier to remove it, right-click to temporarily disable it, use Ctrl+Mouse Wheel to adjust its weight</span></i></label>
<div id="editor-inputs-tags-list"></div>
</div>
@ -155,94 +128,23 @@
<div id="editor-settings-entries" class="collapsible-content">
<div><table>
<tr><b class="settings-subheader">Image Settings</b></tr>
<tr class="pl-5"><td><label for="seed">Seed:</label></td><td><input id="seed" name="seed" size="10" value="0" onkeypress="preventNonNumericalInput(event)" inputmode="numeric"> <input id="random_seed" name="random_seed" type="checkbox" checked><label for="random_seed">Random</label></td></tr>
<tr class="pl-5"><td><label for="num_outputs_total">Number of Images:</label></td>
<td><input id="num_outputs_total" name="num_outputs_total" value="1" type="number" value="1" min="1" step="1" onkeypres"="preventNonNumericalInput(event)" inputmode="numeric">
<label><small>(total)</small></label>
<input id="num_outputs_parallel" name="num_outputs_parallel" value="1" type="number" value="1" min="1" step="1" onkeypress="preventNonNumericalInput(event)" inputmode="numeric">
<label id="num_outputs_parallel_label" for="num_outputs_parallel"><small>(in parallel)</small></label></td>
</tr>
<tr class="pl-5"><td><label for="seed">Seed:</label></td><td><input id="seed" name="seed" size="10" value="0" onkeypress="preventNonNumericalInput(event)"> <input id="random_seed" name="random_seed" type="checkbox" checked><label for="random_seed">Random</label></td></tr>
<tr class="pl-5"><td><label for="num_outputs_total">Number of Images:</label></td><td><input id="num_outputs_total" name="num_outputs_total" value="1" size="1" onkeypress="preventNonNumericalInput(event)"> <label><small>(total)</small></label> <input id="num_outputs_parallel" name="num_outputs_parallel" value="1" size="1" onkeypress="preventNonNumericalInput(event)"> <label for="num_outputs_parallel"><small>(in parallel)</small></label></td></tr>
<tr class="pl-5"><td><label for="stable_diffusion_model">Model:</label></td><td class="model-input">
<input id="stable_diffusion_model" type="text" spellcheck="false" autocomplete="off" class="model-filter" data-path="" />
<button id="reload-models" class="secondaryButton reloadModels"><i class='fa-solid fa-rotate'></i></button>
<a href="https://github.com/easydiffusion/easydiffusion/wiki/Custom-Models" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Click to learn more about custom models</span></i></a>
<a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/Custom-Models" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Click to learn more about custom models</span></i></a>
</td></tr>
<tr class="pl-5 displayNone" id="enable_trt_config">
<td><label for="convert_to_tensorrt">Enable TensorRT:</label></td>
<td class="diffusers-restart-needed">
<input id="convert_to_tensorrt" name="convert_to_tensorrt" type="checkbox">
<!-- <label><small>Takes upto 20 mins the first time</small></label> -->
</td>
</tr>
<tr class="pl-5 displayNone" id="clip_skip_config">
<td><label for="clip_skip">Clip Skip:</label></td>
<td class="diffusers-restart-needed">
<td>
<input id="clip_skip" name="clip_skip" type="checkbox">
<a href="https://github.com/easydiffusion/easydiffusion/wiki/Clip-Skip" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Click to learn more about Clip Skip</span></i></a>
</td>
</tr>
<tr id="controlnet_model_container" class="pl-5">
<td><label for="controlnet_model">ControlNet Image:</label></td>
<td class="diffusers-restart-needed">
<div id="control_image_wrapper" class="preview_image_wrapper">
<img id="control_image_preview" class="image_preview" src="" crossorigin="anonymous" />
<span id="control_image_size_box" class="img_bottom_label"></span>
<button class="control_image_clear image_clear_btn"><i class="fa-solid fa-xmark"></i></button>
</div>
<input id="control_image" name="control_image" type="file" />
<a href="https://github.com/easydiffusion/easydiffusion/wiki/ControlNet" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Click to learn more about ControlNets</span></i></a>
<div id="controlnet_config" class="displayNone">
<label><small>Filter to apply:</small></label>
<select id="control_image_filter">
<option value="">None</option>
<optgroup label="Pose">
<option value="openpose">OpenPose (*)</option>
<option value="openpose_face">OpenPose face</option>
<option value="openpose_faceonly">OpenPose face-only</option>
<option value="openpose_hand">OpenPose hand</option>
<option value="openpose_full">OpenPose full</option>
</optgroup>
<optgroup label="Outline">
<option value="canny">Canny (*)</option>
<option value="mlsd">Straight lines</option>
<option value="scribble_hed">Scribble hed (*)</option>
<option value="scribble_hedsafe">Scribble hedsafe</option>
<option value="scribble_pidinet">Scribble pidinet</option>
<option value="scribble_pidsafe">Scribble pidsafe</option>
<option value="softedge_hed">Softedge hed</option>
<option value="softedge_hedsafe">Softedge hedsafe</option>
<option value="softedge_pidinet">Softedge pidinet</option>
<option value="softedge_pidsafe">Softedge pidsafe</option>
</optgroup>
<optgroup label="Depth">
<option value="normal_bae">Normal bae (*)</option>
<option value="depth_midas">Depth midas</option>
<option value="depth_zoe">Depth zoe</option>
<option value="depth_leres">Depth leres</option>
<option value="depth_leres++">Depth leres++</option>
</optgroup>
<optgroup label="Line art">
<option value="lineart_coarse">Lineart coarse</option>
<option value="lineart_realistic">Lineart realistic</option>
<option value="lineart_anime">Lineart anime</option>
</optgroup>
<optgroup label="Misc">
<option value="shuffle">Shuffle</option>
<option value="segment">Segment</option>
</optgroup>
</select>
<br/>
<label for="controlnet_model"><small>Model:</small></label> <input id="controlnet_model" type="text" spellcheck="false" autocomplete="off" class="model-filter" data-path="" />
<br/>
<label><small>Will download the necessary models, the first time.</small></label>
<br/>
<label for="controlnet_alpha_slider"><small>Strength:</small></label> <input id="controlnet_alpha_slider" name="controlnet_alpha_slider" class="editor-slider" value="10" type="range" min="0" max="10"> <input id="controlnet_alpha" name="controlnet_alpha" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)" inputmode="decimal">
</div>
<a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/Clip-Skip" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Click to learn more about Clip Skip</span></i></a>
</td>
</tr>
<tr class="pl-5"><td><label for="vae_model">Custom VAE:</label></td><td>
<input id="vae_model" type="text" spellcheck="false" autocomplete="off" class="model-filter" data-path="" />
<a href="https://github.com/easydiffusion/easydiffusion/wiki/VAE-Variational-Auto-Encoder" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Click to learn more about VAEs</span></i></a>
<a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/VAE-Variational-Auto-Encoder" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Click to learn more about VAEs</span></i></a>
</td></tr>
<tr id="samplerSelection" class="pl-5"><td><label for="sampler_name">Sampler:</label></td><td>
<select id="sampler_name" name="sampler_name">
@ -255,10 +157,10 @@
<option value="dpm2_a">DPM2 Ancestral</option>
<option value="lms">LMS</option>
<option value="dpm_solver_stability">DPM Solver (Stability AI)</option>
<option value="dpmpp_2s_a">DPM++ 2s Ancestral (Karras)</option>
<option value="dpmpp_2s_a" class="k_diffusion-only">DPM++ 2s Ancestral (Karras)</option>
<option value="dpmpp_2m">DPM++ 2m (Karras)</option>
<option value="dpmpp_2m_sde" class="diffusers-only">DPM++ 2m SDE (Karras)</option>
<option value="dpmpp_sde">DPM++ SDE (Karras)</option>
<option value="dpmpp_sde" class="k_diffusion-only">DPM++ SDE (Karras)</option>
<option value="dpm_fast" class="k_diffusion-only">DPM Fast (Karras)</option>
<option value="dpm_adaptive" class="k_diffusion-only">DPM Adaptive (Karras)</option>
<option value="ddpm" class="diffusers-only">DDPM</option>
<option value="deis" class="diffusers-only">DEIS</option>
@ -268,17 +170,17 @@
<option value="unipc_tu_2" class="k_diffusion-only">UniPC TU 2</option>
<option value="unipc_tq" class="k_diffusion-only">UniPC TQ</option>
</select>
<a href="https://github.com/easydiffusion/easydiffusion/wiki/Samplers" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Click to learn more about samplers</span></i></a>
<a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/How-to-Use#samplers" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Click to learn more about samplers</span></i></a>
</td></tr>
<tr class="pl-5"><td><label>Image Size: </label></td><td id="image-size-options">
<tr class="pl-5"><td><label>Image Size: </label></td><td>
<select id="width" name="width" value="512">
<option value="128">128</option>
<option value="128">128 (*)</option>
<option value="192">192</option>
<option value="256">256</option>
<option value="256">256 (*)</option>
<option value="320">320</option>
<option value="384">384</option>
<option value="448">448</option>
<option value="512" selected="">512 (*)</option>
<option value="512" selected>512 (*)</option>
<option value="576">576</option>
<option value="640">640</option>
<option value="704">704</option>
@ -292,18 +194,15 @@
<option value="1792">1792</option>
<option value="2048">2048</option>
</select>
<label id="widthLabel" for="width"><small><span>(width)</span></small></label>
<div class="tooltip-container">
<span id="swap-width-height" class="clickable smallButton" style="margin-left: 2px; margin-right:2px;"><i class="fa-solid fa-right-left"><span class="simple-tooltip top-left"> Swap width and height </span></i></span>
</div>
<label for="width"><small>(width)</small></label>
<select id="height" name="height" value="512">
<option value="128">128</option>
<option value="128">128 (*)</option>
<option value="192">192</option>
<option value="256">256</option>
<option value="256">256 (*)</option>
<option value="320">320</option>
<option value="384">384</option>
<option value="448">448</option>
<option value="512" selected="">512 (*)</option>
<option value="512" selected>512 (*)</option>
<option value="576">576</option>
<option value="640">640</option>
<option value="704">704</option>
@ -317,65 +216,35 @@
<option value="1792">1792</option>
<option value="2048">2048</option>
</select>
<label id="heightLabel" for="height"><small><span>(height)</span></small></label>
<div id="recent-resolutions-container">
<span id="recent-resolutions-button" class="clickable"><i class="fa-solid fa-sliders"><span class="simple-tooltip top-left"> Advanced sizes </span></i></span>
<div id="recent-resolutions-popup" class="displayNone">
<small>Custom size:</small><br>
<input id="custom-width" name="custom-width" type="number" min="128" value="512" onkeypress="preventNonNumericalInput(event)" inputmode="numeric">
&times;
<input id="custom-height" name="custom-height" type="number" min="128" value="512" onkeypress="preventNonNumericalInput(event)" inputmode="numeric"><br>
<small>Resize:</small><br>
<input id="resize-slider" name="resize-slider" class="editor-slider" value="1" type="range" min="0.4" max="2" step="0.005" style="width:100%;"><br>
<div id="enlarge-buttons"><button data-factor="0.5" class="tertiaryButton smallButton">×0.5</button>&nbsp;<button data-factor="1.2" class="tertiaryButton smallButton">×1.2</button>&nbsp;<button data-factor="1.5" class="tertiaryButton smallButton">×1.5</button>&nbsp;<button data-factor="2" class="tertiaryButton smallButton">×2</button>&nbsp;<button data-factor="3" class="tertiaryButton smallButton">×3</button></div>
<div class="two-column">
<div class="left-column">
<small>Recently&nbsp;used:</small><br>
<div id="recent-resolution-list">
</div>
</div>
<div class="right-column">
<small>Common&nbsp;sizes:</small><br>
<div id="common-resolution-list">
</div>
</div>
</div>
</div>
</div>
<label for="height"><small>(height)</small></label>
<div id="small_image_warning" class="displayNone">Small image sizes can cause bad image quality</div>
</td></tr>
<tr class="pl-5"><td><label for="num_inference_steps">Inference Steps:</label></td><td> <input id="num_inference_steps" name="num_inference_steps" type="number" min="1" step="1" style="width: 42pt" value="25" onkeypress="preventNonNumericalInput(event)" inputmode="numeric"></td></tr>
<tr class="pl-5"><td><label for="guidance_scale_slider">Guidance Scale:</label></td><td> <input id="guidance_scale_slider" name="guidance_scale_slider" class="editor-slider" value="75" type="range" min="11" max="500"> <input id="guidance_scale" name="guidance_scale" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)" inputmode="decimal"></td></tr>
<tr id="prompt_strength_container" class="pl-5"><td><label for="prompt_strength_slider">Prompt Strength:</label></td><td> <input id="prompt_strength_slider" name="prompt_strength_slider" class="editor-slider" value="80" type="range" min="0" max="99"> <input id="prompt_strength" name="prompt_strength" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)" inputmode="decimal"><br/></td></tr>
<tr id="lora_model_container" class="pl-5">
<td>
<label for="lora_model">LoRA:</label>
</td>
<td class="diffusers-restart-needed">
<div id="lora_model" data-path=""></div>
</td>
<tr class="pl-5"><td><label for="num_inference_steps">Inference Steps:</label></td><td> <input id="num_inference_steps" name="num_inference_steps" size="4" value="25" onkeypress="preventNonNumericalInput(event)"></td></tr>
<tr class="pl-5"><td><label for="guidance_scale_slider">Guidance Scale:</label></td><td> <input id="guidance_scale_slider" name="guidance_scale_slider" class="editor-slider" value="75" type="range" min="11" max="500"> <input id="guidance_scale" name="guidance_scale" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)"></td></tr>
<tr id="prompt_strength_container" class="pl-5"><td><label for="prompt_strength_slider">Prompt Strength:</label></td><td> <input id="prompt_strength_slider" name="prompt_strength_slider" class="editor-slider" value="80" type="range" min="0" max="99"> <input id="prompt_strength" name="prompt_strength" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)"><br/></td></tr>
<tr id="lora_model_container" class="pl-5"><td><label for="lora_model">LoRA:</label></td><td>
<input id="lora_model" type="text" spellcheck="false" autocomplete="off" class="model-filter" data-path="" />
</td></tr>
<tr id="lora_alpha_container" class="pl-5">
<td><label for="lora_alpha_slider">LoRA Strength:</label></td>
<td> <input id="lora_alpha_slider" name="lora_alpha_slider" class="editor-slider" value="50" type="range" min="0" max="100"> <input id="lora_alpha" name="lora_alpha" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)"><br/></td>
</tr>
<tr id="hypernetwork_model_container" class="pl-5"><td><label for="hypernetwork_model">Hypernetwork:</label></td><td>
<tr class="pl-5"><td><label for="hypernetwork_model">Hypernetwork:</label></td><td>
<input id="hypernetwork_model" type="text" spellcheck="false" autocomplete="off" class="model-filter" data-path="" />
</td></tr>
<tr id="hypernetwork_strength_container" class="pl-5">
<td><label for="hypernetwork_strength_slider">Hypernetwork Strength:</label></td>
<td> <input id="hypernetwork_strength_slider" name="hypernetwork_strength_slider" class="editor-slider" value="100" type="range" min="0" max="100"> <input id="hypernetwork_strength" name="hypernetwork_strength" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)" inputmode="decimal"><br/></td>
</tr>
<tr id="tiling_container" class="pl-5">
<td><label for="tiling">Seamless Tiling:</label></td>
<td class="diffusers-restart-needed">
<select id="tiling" name="tiling">
<option value="none" selected>None</option>
<option value="x">Horizontal</option>
<option value="y">Vertical</option>
<option value="xy">Both</option>
</select>
<a href="https://github.com/easydiffusion/easydiffusion/wiki/Seamless-Tiling" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Click to learn more about Seamless Tiling</span></i></a>
</td>
<td> <input id="hypernetwork_strength_slider" name="hypernetwork_strength_slider" class="editor-slider" value="100" type="range" min="0" max="100"> <input id="hypernetwork_strength" name="hypernetwork_strength" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)"><br/></td>
</tr>
<tr id="tiling_container" class="pl-5"><td><label for="tiling">Seamless Tiling:</label></td><td>
<select id="tiling" name="tiling">
<option value="none" selected>None</option>
<option value="x">Horizontal</option>
<option value="y">Vertical</option>
<option value="xy">Both</option>
</select>
<a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/Seamless-Tiling" target="_blank"><i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Click to learn more about Seamless Tiling</span></i></a>
</td></tr>
<tr class="pl-5"><td><label for="output_format">Output Format:</label></td><td>
<select id="output_format" name="output_format">
<option value="jpeg" selected>jpeg</option>
@ -387,26 +256,18 @@
</span>
</td></tr>
<tr class="pl-5" id="output_quality_row"><td><label for="output_quality">Image Quality:</label></td><td>
<input id="output_quality_slider" name="output_quality" class="editor-slider" value="75" type="range" min="10" max="95"> <input id="output_quality" name="output_quality" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)" inputmode="numeric">
<input id="output_quality_slider" name="output_quality" class="editor-slider" value="75" type="range" min="10" max="95"> <input id="output_quality" name="output_quality" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)">
</td></tr>
<tr class="pl-5">
<td><label for="tiling">Enable VAE Tiling:</label></td>
<td class="diffusers-restart-needed">
<input id="enable_vae_tiling" name="enable_vae_tiling" type="checkbox" checked>
<label><small>Optimizes memory for larger images</small></label>
</td>
</tr>
</table></div>
<div><ul>
<li><b class="settings-subheader">Render Settings</b></li>
<li class="pl-5"><input id="stream_image_progress" name="stream_image_progress" type="checkbox"> <label for="stream_image_progress">Show a live preview <small>(uses more VRAM, slower images)</small></label></li>
<li class="pl-5" id="use_face_correction_container">
<li class="pl-5">
<input id="use_face_correction" name="use_face_correction" type="checkbox"> <label for="use_face_correction">Fix incorrect faces and eyes</label> <div style="display:inline-block;"><input id="gfpgan_model" type="text" spellcheck="false" autocomplete="off" class="model-filter" data-path="" /></div>
<table id="codeformer_settings" class="displayNone sub-settings">
<tr class="pl-5"><td><label for="codeformer_fidelity_slider">Strength:</label></td><td><input id="codeformer_fidelity_slider" name="codeformer_fidelity_slider" class="editor-slider" value="5" type="range" min="0" max="10"> <input id="codeformer_fidelity" name="codeformer_fidelity" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)" inputmode="decimal"></td></tr>
<tr class="pl-5"><td><label for="codeformer_upscale_faces">Upscale Faces:</label></td><td><input id="codeformer_upscale_faces" name="codeformer_upscale_faces" type="checkbox" checked> <label><small>(improves the resolution of faces)</small></label></td></tr>
</table>
<div id="codeformer_settings" class="displayNone sub-settings">
<input id="codeformer_upscale_faces" name="codeformer_upscale_faces" type="checkbox"><label for="codeformer_upscale_faces">Upscale Faces <small>(improves the resolution of faces)</small></label>
</div>
</li>
<li class="pl-5">
<input id="use_upscale" name="use_upscale" type="checkbox"> <label for="use_upscale">Scale up by</label>
@ -420,16 +281,37 @@
<option value="RealESRGAN_x4plus_anime_6B">RealESRGAN_x4plus_anime_6B</option>
<option value="latent_upscaler">Latent Upscaler 2x</option>
</select>
<table id="latent_upscaler_settings" class="displayNone sub-settings">
<tr class="pl-5"><td><label for="latent_upscaler_steps_slider">Upscaling Steps:</label></td><td><input id="latent_upscaler_steps_slider" name="latent_upscaler_steps_slider" class="editor-slider" value="10" type="range" min="1" max="50"> <input id="latent_upscaler_steps" name="latent_upscaler_steps" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)" inputmode="numeric"></td></tr>
</table>
<div id="latent_upscaler_settings" class="displayNone sub-settings">
<label for="latent_upscaler_steps_slider">Upscaling Steps:</label></td><td> <input id="latent_upscaler_steps_slider" name="latent_upscaler_steps_slider" class="editor-slider" value="10" type="range" min="1" max="50"> <input id="latent_upscaler_steps" name="latent_upscaler_steps" size="4" pattern="^[0-9\.]+$" onkeypress="preventNonNumericalInput(event)">
</div>
</li>
<li class="pl-5"><input id="show_only_filtered_image" name="show_only_filtered_image" type="checkbox" checked> <label for="show_only_filtered_image">Show only the corrected/upscaled image</label></li>
</ul></div>
</div>
</div>
<label><small><b>Note:</b> The Image Modifiers section has moved to the <code>+ Image Modifiers</code> button at the top, just above the Prompt textbox.</small></label>
<div id="editor-modifiers" class="panel-box">
<h4 class="collapsible">
Image Modifiers (art styles, tags etc)
<i id="modifier-settings-btn" class="fa-solid fa-gear section-button">
<span class="simple-tooltip left">
Add Custom Modifiers
</span>
</i>
</h4>
<div id="editor-modifiers-entries" class="collapsible-content">
<div id="editor-modifiers-entries-toolbar">
<label for="preview-image">Image Style:</label>
<select id="preview-image" name="preview-image" value="portrait">
<option value="portrait" selected="">Face</option>
<option value="landscape">Landscape</option>
</select>
&nbsp;
<label for="modifier-card-size-slider">Thumbnail Size:</label>
<input id="modifier-card-size-slider" name="modifier-card-size-slider" value="0" type="range" min="-3" max="5">
</div>
</div>
</div>
</div>
<div id="preview" class="col-free">
@ -443,7 +325,7 @@
<div id="preview-content">
<div id="preview-tools" class="displayNone">
<button id="clear-all-previews" class="secondaryButton"><i class="fa-solid fa-trash-can icon"></i> Clear All</button>
<button class="tertiaryButton" id="show-download-popup"><i class="fa-solid fa-download"></i><span> Download images</span></button>
<button class="tertiaryButton" id="show-download-popup"><i class="fa-solid fa-download"></i> Download images</button>
<div class="display-settings">
<button id="undo" class="displayNone primaryButton">
Undo <i class="fa-solid fa-rotate-left icon"></i>
@ -466,15 +348,12 @@
<div class="dropdown-content">
<div class="dropdown-item">
<input id="thumbnail_size" name="thumbnail_size" class="editor-slider" type="range" value="70" min="5" max="200" oninput="sliderUpdate(event)">
<input id="thumbnail_size-input" name="thumbnail_size-input" size="3" value="70" pattern="^[0-9.]+$" onkeypress="preventNonNumericalInput(event)" oninput="sliderUpdate(event)" inputmode="numeric">&nbsp;%
<input id="thumbnail_size-input" name="thumbnail_size-input" size="3" value="70" pattern="^[0-9.]+$" onkeypress="preventNonNumericalInput(event)" oninput="sliderUpdate(event)">&nbsp;%
</div>
</div>
</div>
<div class="clearfix" style="clear: both;"></div>
</div>
<div id="supportBanner" class="displayNone">
If you found this project useful and want to help keep it alive, please consider <a href="https://ko-fi.com/easydiffusion" target="_blank">buying me a coffee</a> to help cover the cost of development and maintenance! Thanks for your support!
</div>
</div>
</div>
</div>
@ -482,22 +361,9 @@
<div id="tab-content-settings" class="tab-content">
<div id="system-settings" class="tab-content-inner">
<h1>System Settings</h1>
<div class="parameters-table" id="system-settings-table"></div>
<div class="parameters-table"></div>
<br/>
<button id="save-system-settings-btn" class="primaryButton">Save</button>
<div id="install-extras-container" class="displayNone">
<br/>
<div id="install-extras">
<h3><i class="fa fa-cubes-stacked"></i> Optional Packages</h3>
<div class="parameters-table" id="system-settings-install-extras-table"></div>
</div>
</div>
<br/><br/>
<div id="share-easy-diffusion">
<h3><i class="fa fa-user-group"></i> Share Easy Diffusion</h3>
<div class="parameters-table" id="system-settings-network-table">
</div>
</div>
<br/><br/>
<div>
<h3><i class="fa fa-microchip icon"></i> System Info</h3>
@ -519,44 +385,28 @@
<div class="float-container">
<div class="float-child">
<h1>Help</h1>
<div id="help-links">
<h4><span class="help-section"><b>Basics</b></span></h4>
<ul id="help-links">
<li><span class="help-section">Using the software</span>
<ul>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/How-To-Use" target="_blank">How to use</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/Writing-Prompts" target="_blank">Writing prompts</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/Image-Modifiers" target="_blank">Image Modifiers</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/Inpainting" target="_blank">Inpainting</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/Samplers" target="_blank">Samplers</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/UI-Overview" target="_blank">Summary of every UI option</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting" target="_blank">Common error messages (and solutions)</a></li>
<li> <a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/How-To-Use" target="_blank"><i class="fa-solid fa-book fa-fw"></i> How to use</a>
<li> <a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/UI-Overview" target="_blank"><i class="fa-solid fa-list fa-fw"></i> UI Overview</a>
<li> <a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/Writing-Prompts" target="_blank"><i class="fa-solid fa-pen-to-square fa-fw"></i> Writing prompts</a>
<li> <a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/Inpainting" target="_blank"><i class="fa-solid fa-paintbrush fa-fw"></i> Inpainting</a>
<li> <a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/Run-on-Multiple-GPUs" target="_blank"><i class="fa-solid fa-paintbrush fa-fw"></i> Run on Multiple GPUs</a>
</ul>
<h4><span class="help-section"><b>Intermediate</b></span></h4>
<li><span class="help-section">Installation</span>
<ul>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/Custom-Models" target="_blank">Custom Models</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/Prompt-Syntax" target="_blank">Prompt Syntax (weights, emphasis etc)</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/UI-Plugins" target="_blank">UI Plugins</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/Embeddings" target="_blank">Embeddings</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/LoRA" target="_blank">LoRA</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/SDXL" target="_blank">SDXL</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/ControlNet" target="_blank">ControlNet</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/Seamless-Tiling" target="_blank">Seamless Tiling</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/xFormers" target="_blank">xFormers</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/The-beta-channel" target="_blank">The beta channel</a></li>
<li> <a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" target="_blank"><i class="fa-solid fa-circle-question fa-fw"></i> Troubleshooting</a>
</ul>
<h4><span class="help-section"><b>Advanced topics</b></span></h4>
<li><span class="help-section">Downloadable Content</span>
<ul>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/Run-on-Multiple-GPUs" target="_blank">Run on Multiple GPUs</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/Model-Merging" target="_blank">Model Merging</a></li>
<li> <a href="https://github.com/easydiffusion/easydiffusion/wiki/Custom-Modifiers" target="_blank">Custom Modifiers</a></li>
<li> <a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/Custom-Models" target="_blank"><i class="fa-solid fa-images fa-fw"></i> Custom Models</a>
<li> <a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/UI-Plugins" target="_blank"><i class="fa-solid fa-puzzle-piece fa-fw"></i> UI Plugins</a>
<li> <a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/VAE-Variational-Auto-Encoder" target="_blank"><i class="fa-solid fa-hand-sparkles fa-fw"></i> VAE Variational Auto Encoder</a>
</ul>
<h4><span class="help-section"><b>Misc</b></span></h4>
<ul>
<li> <a href="https://theally.notion.site/The-Definitive-Stable-Diffusion-Glossary-1d1e6d15059c41e6a6b4306b4ecd9df9" target="_blank">Glossary of Stable Diffusion related terms</a></li>
</ul>
</div>
</ul>
</div>
<div class="float-child">
@ -564,7 +414,7 @@
<ul id="community-links">
<li><a href="https://discord.com/invite/u9yhsFmEkB" target="_blank"><i class="fa-brands fa-discord fa-fw"></i> Discord user community</a></li>
<li><a href="https://www.reddit.com/r/StableDiffusionUI/" target="_blank"><i class="fa-brands fa-reddit fa-fw"></i> Reddit community</a></li>
<li><a href="https://github.com/easydiffusion/easydiffusion" target="_blank"><i class="fa-brands fa-github fa-fw"></i> Source code on GitHub</a></li>
<li><a href="https://github.com/cmdr2/stable-diffusion-ui" target="_blank"><i class="fa-brands fa-github fa-fw"></i> Source code on GitHub</a></li>
</ul>
</div>
</div>
@ -572,85 +422,32 @@
</div>
</div>
<div class="popup" id="splash-screen" data-version="1">
<div class="popup" id="download-images-popup">
<div>
<i class="close-button fa-solid fa-xmark"></i>
<img class="splash-img" src="/media/images/icon-512x512.png" width="128" height="128">
<h1>Diffusers Tech Preview</h1>
<p>The Diffusers Tech Preview allows early access to the new features based on <a href="https://huggingface.co/docs/diffusers/index" target="_blank">Diffusers</a>.</p>
<p>This is under active development, and is missing a few features. It is experimental! Please report any bugs to the #beta channel in our <a href="https://discord.gg/QUcNZufQNZ" target="_blank">Discord</a> server!</p>
<h2>New upcoming features in our new engine</h2>
<ul>
<li><a href="https://huggingface.co/blog/lora" target="_blank">LORA</a> support - Place LORA files in the <tt>models/lora</tt> folder.</li>
<li><a href="https://github.com/damian0815/compel/blob/main/Reference.md" target="_blank">Compel Prompt Parser</a> - New, more powerful parser. In short:
<ul>
<li> no limit to the length of prompts (i.e. long prompts are supported)</li>
<li> Use <tt>+</tt> and <tt>-</tt> to increase/decrease the weight. E.g. <tt>apple</tt>, <tt>apple+</tt>, <tt>apple++</tt>, <tt>apple+++</tt>,
or <tt>apple-</tt>, <tt>apple--</tt> for different weights.</li>
<li> Use exact weights - 0.0 to 1.0 reduces the weight, 1.0 to 2.0 increases the weight.
Think of it like a multiplier, like 1.5x or 0.5x: E.g. <tt>(apple)0.8 falling from a tree</tt>,
<tt>(apple)1.5 falling from a tree</tt>, <tt>(apple falling)1.4 from a tree</tt></li>
<li> You can group tokens together using parentheses/round-brackets. E.g. <tt>(apple falling)++
from a tree</tt>. Nested parentheses are supported.</li>
</ul>
This clarifies a few things:
<ul>
<li> colon (<tt>:</tt>) is NOT used for blending. Neither is it used for weights. It has no impact and
will be considered a part of the prompt.</li>
<li> <tt>(())</tt> and <tt>[]</tt> do not affect the prompt's weights.</li>
</ul>
</li>
<li> More choices for img2img samplers</li>
<li> Support for official inpainting models</li>
<li> Generate images that tile seamlessly</li>
<li> <a href="https://github.com/cmdr2/stable-diffusion-ui/wiki/Clip-Skip" target="_blank">Clip Skip</a> support allows to skip the last CLIP layer (recommended by some LORA models)</li>
<li> New samplers: DDPM and DEIS</li>
<li> Memory optimizations that allow the use of 2GB GPUs</li>
</ul>
<h2>Known issues</h2>
<ul>
<li> Some LoRA consistently fail to load in EasyDiffusion</li>
<li> Some LoRA are far more sensitive to alpha (compared to a11)</li>
<li> Hangs sometimes on "compel is ready", while making the token.</li>
<li> Some custom inpainting models don't work</li>
<li> These samplers don't work yet: Unipc SNR, Unipc TQ, Unipc SNR2, DPM++ 2s Ancestral, DPM++ SDE, DPM Fast, DPM Adaptive, DPM2</li>
<li> Hypernetwork doesn't work</li>
<li> The time remaining in browser differs from the one in the console</li>
</ul>
</div>
</div>
<dialog id="download-images-dialog">
<div class="dialog-header">
<div class="dialog-header-left">
<h4>Download all images</h4>
<span></span>
<h1>Download all images</h1>
<div class="parameters-table">
<div>
<div><i class="fa fa-file-zipper"></i></div>
<div><label for="theme">Download as a ZIP file</label><small>Instead of downloading individual files, generate one zip file with all images</small></div>
<div><div class="input-toggle"><input id="zip_toggle" name="zip_toggle" checked="" type="checkbox"><label for="zip_toggle"></label></div></div>
</div>
<div id="download-add-folders">
<div><i class="fa fa-folder-tree"></i></div>
<div><label for="theme">Add per-job folders</label><small>Place images into job folders</small></div>
<div><div class="input-toggle"><input id="tree_toggle" name="tree_toggle" checked="" type="checkbox"><label for="tree_toggle"></label></div></div>
</div>
<div>
<div><i class="fa fa-sliders"></i></div>
<div><label for="theme">Add metadata files</label><small>For each image, also download a JSON file with all the settings used to generate the image</small></div>
<div><div class="input-toggle"><input id="json_toggle" name="json_toggle" checked="" type="checkbox"><label for="json_toggle"></label></div></div>
</div>
</div>
<div>
<i id="download-images-close-button" class="fa-solid fa-xmark fa-lg"></i>
</div>
</div>
<div class="parameters-table">
<div>
<div><i class="fa fa-file-zipper"></i></div>
<div><label for="theme">Download as a ZIP file</label><small>Instead of downloading individual files, generate one zip file with all images</small></div>
<div><div class="input-toggle"><input id="zip_toggle" name="zip_toggle" checked="" type="checkbox"><label for="zip_toggle"></label></div></div>
</div>
<div id="download-add-folders">
<div><i class="fa fa-folder-tree"></i></div>
<div><label for="theme">Add per-job folders</label><small>Place images into job folders</small></div>
<div><div class="input-toggle"><input id="tree_toggle" name="tree_toggle" checked="" type="checkbox"><label for="tree_toggle"></label></div></div>
</div>
<div>
<div><i class="fa fa-sliders"></i></div>
<div><label for="theme">Add metadata files</label><small>For each image, also download a JSON file with all the settings used to generate the image</small></div>
<div><div class="input-toggle"><input id="json_toggle" name="json_toggle" checked="" type="checkbox"><label for="json_toggle"></label></div></div>
</div>
</div>
<div class="center">
<br/>
<button id="save-all-images" class="primaryButton"><i class="fa-solid fa-images"></i> Start download</button>
</div>
</dialog>
</div>
<div id="save-settings-config" class="popup">
<div>
<i class="close-button fa-solid fa-xmark"></i>
@ -661,129 +458,16 @@
</div>
</div>
<div id="editor-modifiers">
<div id="editor-modifiers-header" class="dialog-header">
<div id="modifiers-header-left" class="dialog-header-left">
<h4>Image Modifiers</h4>
<span>(drawing style, camera, etc.)</span>
</div>
<div id="modifiers-header-right">
<i id="modifier-settings-btn" class="fa-solid fa-gear section-button">
<span class="simple-tooltip left">
Add Custom Modifiers
</span>
</i>
<i id="modifiers-container-size-btn" class="fa-solid fa-expand"></i>
<i id="modifiers-close-button" class="fa-solid fa-xmark fa-lg"></i>
</div>
<div id="modifier-settings-config" class="popup" tabindex="0">
<div>
<i class="close-button fa-solid fa-xmark"></i>
<h1>Modifier Settings</h1>
<p>Set your custom modifiers (one per line)</p>
<textarea id="custom-modifiers-input" placeholder="Enter your custom modifiers, one-per-line" spellcheck="false"></textarea>
<p><small><b>Tip:</b> You can include special characters like {} () [] and |. You can also put multiple comma-separated phrases in a single line, to make a single modifier that combines all of those.</small></p>
</div>
<div id="editor-modifiers-subheader">
<div id="modifiers-action-collapsibles-btn">
<i class="modifiers-action-icon fa-solid fa-square-plus"></i>
<span class="modifiers-action-text">
Expand Categories
</span>
</div>
<div>
<label for="preview-image">Image Style:</label>
<select id="preview-image" name="preview-image" value="portrait">
<option value="portrait" selected="">Face</option>
<option value="landscape">Landscape</option>
</select>
</div>
<div>
<label for="modifier-card-size-slider">Thumbnail Size:</label>
<input id="modifier-card-size-slider" name="modifier-card-size-slider" value="0" type="range" min="-2" max="3">
</div>
</div>
<div id="editor-modifiers-entries" class="collapsible-content"></div>
</div>
<dialog id="modifier-settings-config">
<div id="modifier-settings-header" class="dialog-header">
<div id="modifier-settings-header-left" class="dialog-header-left">
<h4>Custom Modifiers</h4>
<span>Set your custom modifiers (one per line)</span>
</div>
<div id="modifier-settings-header-right">
<i id="modifier-settings-close-button" class="fa-solid fa-xmark fa-lg"></i>
</div>
</div>
<textarea id="custom-modifiers-input" placeholder="Enter your custom modifiers, one-per-line" spellcheck="false"></textarea>
<div>
<small>
<b>Tip:</b> You can include special characters like {} () [] and |. You can also put multiple comma-separated
phrases in a single line, to make a single modifier that combines all of those.
</small>
</div>
</dialog>
<dialog id="embeddings-dialog">
<div id="embeddings-dialog-header" class="dialog-header">
<div id="embeddings-dialog-header-left" class="dialog-header-left">
<h4>Embeddings</h4>
<span>
<span class="displayNone" id="positive-embedding-text"> Add embeddings to the prompt (click) or negative prompt (shift-click)</span>
<span class="displayNone" id="negative-embedding-text"> Add embeddings to the negative prompt</span>
<span>
</div>
<div id="embeddings-dialog-header-right">
<button id="add-embeddings-thumb" class="tertiaryButton smallButton" style="background-color: var(--background-color4);"><i class="fa-solid fa-folder-plus"></i> Add thumbnail</button>
<input id="add-embeddings-thumb-input" name="add-embeddings-thumb-input" type="file" class="displayNone">
<i id="embeddings-dialog-close-button" class="fa-solid fa-xmark fa-lg"></i>
</div>
</div>
<div>
<button id="embeddings-action-collapsibles-btn" class="tertiaryButton smallButton">
<i class="embeddings-action-icon fa-solid fa-square-plus"></i>
<span class="embeddings-action-text">Expand Categories</span>
</button>
<i class="fa-solid fa-magnifying-glass"></i>
<input id="embeddings-search-box" type="text" spellcheck="false" autocomplete="off" placeholder="Search..." inputmode="search">
<label for="embedding-card-size-selector"><small>Thumbnail Size:</small></label>
<select id="embedding-card-size-selector" name="embedding-card-size-selector">
<option value="-2">0</option>
<option value="-1" selected>1</option>
<option value="0">2</option>
<option value="1">3</option>
<option value="2">4</option>
<option value="3">5</option>
</select>
<span style="float:right;"><label>Mode:</label>&nbsp;<select id="embeddings-mode"><option value="insert">Insert at cursor position</option><option value="append">Append at the end</option></select>
</div>
<div id="embeddings-list">
</div>
</div>
</dialog>
<dialog id="use-as-thumb-dialog">
<div id="use-as-thumb-dialog-header" class="dialog-header">
<div id="use-as-thumb-dialog-header-left" class="dialog-header-left">
<h4>Use as thumbnail</h4>
<span>Use a pictures as thumbnail for embeddings, LORAs, etc.</span>
</div>
<div id="use-as-thumb-dialog-header-right">
<i id="use-as-thumb-dialog-close-button" class="fa-solid fa-xmark fa-lg"></i>
</div>
</div>
<div>
<div class="use-as-thumb-grid">
<div class="use-as-thumb-preview">
<div id="use-as-thumb-img-container"><img id="use-as-thumb-image" src="/media/images/noimg.png" width="512" height="512"></div>
</div>
<div class="use-as-thumb-select">
<label for="use-as-thumb-select">Use the thumbnail for:</label><br>
<select id="use-as-thumb-select" size="16" multiple>
</select>
</div>
<div class="use-as-thumb-buttons">
<button class="tertiaryButton" id="use-as-thumb-save">Save thumbnail</button>
<button class="tertiaryButton" id="use-as-thumb-cancel">Cancel</button>
</div>
</div>
</div>
</dialog>
<div id="image-editor" class="popup image-editor-popup">
<div>
<i class="close-button fa-solid fa-xmark"></i>
@ -819,28 +503,26 @@
<div id="footer-spacer"></div>
<div id="footer">
<div class="line-separator">&nbsp;</div>
<p>Please feel free to join the <a href="https://discord.com/invite/u9yhsFmEkB" target="_blank">discord community</a> or <a href="https://github.com/easydiffusion/easydiffusion/issues" target="_blank">file an issue</a> if you have any problems or suggestions in using this interface.</p>
<p>If you found this project useful and want to help keep it alive, please <a href="https://ko-fi.com/cmdr2_stablediffusion_ui" target="_blank"><img src="/media/images/kofi.png" id="coffeeButton"></a> to help cover the cost of development and maintenance! Thank you for your support!</p>
<p>Please feel free to join the <a href="https://discord.com/invite/u9yhsFmEkB" target="_blank">discord community</a> or <a href="https://github.com/cmdr2/stable-diffusion-ui/issues" target="_blank">file an issue</a> if you have any problems or suggestions in using this interface.</p>
<div id="footer-legal">
<p><b>Disclaimer:</b> The authors of this project are not responsible for any content generated using this interface.</p>
<p>This license of this software forbids you from sharing any content that violates any laws, produce any harm to a person, disseminate any personal information that would be meant for harm, <br/>spread misinformation and target vulnerable groups. For the full list of restrictions please read <a href="https://github.com/easydiffusion/easydiffusion/blob/main/LICENSE" target="_blank">the license</a>.</p>
<p>This license of this software forbids you from sharing any content that violates any laws, produce any harm to a person, disseminate any personal information that would be meant for harm, <br/>spread misinformation and target vulnerable groups. For the full list of restrictions please read <a href="https://github.com/cmdr2/stable-diffusion-ui/blob/main/LICENSE" target="_blank">the license</a>.</p>
<p>By using this software, you consent to the terms and conditions of the license.</p>
</div>
<input id="test_diffusers" type="checkbox" style="display: none" checked />
</div>
</div>
</body>
<script src="media/js/utils.js"></script>
<script src="media/js/engine.js"></script>
<script src="media/js/parameters.js"></script>
<script src="media/js/plugins.js"></script>
<script src="media/js/image-modifiers.js"></script>
<script src="media/js/auto-save.js"></script>
<script src="media/js/searchable-models.js"></script>
<script src="media/js/multi-model-selector.js"></script>
<script src="media/js/task-manager.js"></script>
<script src="media/js/main.js"></script>
<script src="media/js/plugins.js"></script>
<script src="media/js/themes.js"></script>
<script src="media/js/dnd.js"></script>
<script src="media/js/image-editor.js"></script>
@ -848,24 +530,18 @@
<script>
async function init() {
await initSettings()
await getModels(false)
await getModels()
await getAppConfig()
await loadUIPlugins()
await loadModifiers()
await getSystemInfo()
// await initPlugins()
SD.init({
events: {
statusChange: setServerStatus,
idle: onIdle,
ping: onPing
idle: onIdle
}
})
// splashScreen()
// load models again, but scan for malicious this time
await getModels(true)
// playSound()
}

View File

@ -1,14 +1,10 @@
from easydiffusion import model_manager, app, server, bucket_manager
from easydiffusion.server import server_api # required for uvicorn
app.init()
server.init()
from easydiffusion import model_manager, app, server
from easydiffusion.server import server_api # required for uvicorn
# Init the app
model_manager.init()
app.init_render_threads()
bucket_manager.init()
app.init()
server.init()
# start the browser ui
app.open_browser()

View File

@ -1,68 +0,0 @@
@keyframes ldio-8f673ktaleu-1 {
0% { transform: rotate(0deg) }
50% { transform: rotate(-45deg) }
100% { transform: rotate(0deg) }
}
@keyframes ldio-8f673ktaleu-2 {
0% { transform: rotate(180deg) }
50% { transform: rotate(225deg) }
100% { transform: rotate(180deg) }
}
.ldio-8f673ktaleu > div:nth-child(2) {
transform: translate(-15px,0);
}
.ldio-8f673ktaleu > div:nth-child(2) div {
position: absolute;
top: 20px;
left: 20px;
width: 60px;
height: 30px;
border-radius: 60px 60px 0 0;
background: #f3b72e;
animation: ldio-8f673ktaleu-1 1s linear infinite;
transform-origin: 30px 30px
}
.ldio-8f673ktaleu > div:nth-child(2) div:nth-child(2) {
animation: ldio-8f673ktaleu-2 1s linear infinite
}
.ldio-8f673ktaleu > div:nth-child(2) div:nth-child(3) {
transform: rotate(-90deg);
animation: none;
}@keyframes ldio-8f673ktaleu-3 {
0% { transform: translate(95px,0); opacity: 0 }
20% { opacity: 1 }
100% { transform: translate(35px,0); opacity: 1 }
}
.ldio-8f673ktaleu > div:nth-child(1) {
display: block;
}
.ldio-8f673ktaleu > div:nth-child(1) div {
position: absolute;
top: 46px;
left: -4px;
width: 8px;
height: 8px;
border-radius: 50%;
background: #3869c5;
animation: ldio-8f673ktaleu-3 1s linear infinite
}
.ldio-8f673ktaleu > div:nth-child(1) div:nth-child(1) { animation-delay: -0.67s }
.ldio-8f673ktaleu > div:nth-child(1) div:nth-child(2) { animation-delay: -0.33s }
.ldio-8f673ktaleu > div:nth-child(1) div:nth-child(3) { animation-delay: 0s }
.loadingio-spinner-bean-eater-x0y3u8qky4n {
width: 58px;
height: 58px;
display: inline-block;
overflow: hidden;
background: none;
}
.ldio-8f673ktaleu {
width: 100%;
height: 100%;
position: relative;
transform: translateZ(0) scale(0.58);
backface-visibility: hidden;
transform-origin: 0 0; /* see note above */
}
.ldio-8f673ktaleu div { box-sizing: content-box; }
/* generated by https://loading.io/ */

View File

@ -69,16 +69,13 @@
}
.parameters-table > div:first-child {
border-top-left-radius: 12px;
border-top-right-radius: 12px;
border-radius: 12px 12px 0px 0px;
}
.parameters-table > div:last-child {
border-bottom-left-radius: 12px;
border-bottom-right-radius: 12px;
border-radius: 0px 0px 12px 12px;
}
.parameters-table .fa-fire,
.parameters-table .fa-bolt {
.parameters-table .fa-fire {
color: #F7630C;
}
}

View File

@ -1,58 +0,0 @@
.croppr-container * {
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
}
.croppr-container img {
vertical-align: middle;
max-width: 100%;
}
.croppr {
position: relative;
display: inline-block;
}
.croppr-overlay {
background: rgba(0,0,0,0.5);
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1;
cursor: crosshair;
}
.croppr-region {
border: 1px dashed rgba(0, 0, 0, 0.5);
position: absolute;
z-index: 3;
cursor: move;
top: 0;
}
.croppr-imageClipped {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 2;
pointer-events: none;
}
.croppr-handle {
border: 1px solid black;
background-color: white;
width: 10px;
height: 10px;
position: absolute;
z-index: 4;
top: 0;
}

View File

@ -96,7 +96,7 @@
.editor-controls-center {
/* background: var(--background-color2); */
flex: 0;
flex: 1;
display: flex;
justify-content: center;
align-items: center;
@ -105,8 +105,6 @@
.editor-controls-center > div {
position: relative;
background: black;
margin: 20pt;
margin-top: 40pt;
}
.editor-controls-center canvas {
@ -166,10 +164,8 @@
margin: var(--popup-margin);
padding: var(--popup-padding);
min-height: calc(99h - (2 * var(--popup-margin)));
max-width: fit-content;
max-width: none;
min-width: fit-content;
margin-left: auto;
margin-right: auto;
}
.image-editor-popup h1 {
@ -229,27 +225,4 @@
}
.inpainter .load_mask {
display: flex;
}
.editor-canvas-overlay {
cursor: none;
}
.image-brush-preview {
position: fixed;
background: black;
opacity: 0.3;
borderRadius: 50%;
cursor: none;
pointer-events: none;
transform: translate(-50%, -50%);
}
.editor-options-container > * > *:not(.active):not(.button) {
border: 1px dotted slategray;
}
.image_editor_opacity .editor-options-container > * > *:not(.active):not(.button) {
border: 1px dotted slategray;
}
}

View File

@ -5,8 +5,6 @@
html {
position: relative;
overscroll-behavior-y: none;
color-scheme: dark !important;
}
body {
@ -14,13 +12,12 @@ body {
font-size: 11pt;
background-color: var(--background-color1);
color: var(--text-color);
overscroll-behavior-y: contain;
}
a {
color: var(--link-color);
color: rgb(0, 102, 204);
}
a:visited {
color: var(--link-color);
color: rgb(0, 102, 204);
}
label {
font-size: 10pt;
@ -34,7 +31,6 @@ code {
width: 32px;
height: 32px;
transform: translateY(4px);
cursor: pointer;
}
#prompt {
width: 100%;
@ -148,7 +144,7 @@ code {
opacity: 0;
}
.imgPreviewItemClearBtn:hover {
background: var(--button-hover-background);
background: rgb(177, 27, 0);
}
.imgContainer:hover > .imgItemInfo {
opacity: 1;
@ -188,7 +184,7 @@ code {
#editor label {
font-weight: normal;
}
.dialog-header h4 {
#editor h4 {
margin: 0px;
white-space: nowrap;
}
@ -196,7 +192,7 @@ code {
width: 100%;
}
.settings-box label small {
color: var(--small-label-color);
color: rgb(153, 153, 153);
margin-right: 10px;
}
#preview {
@ -215,6 +211,10 @@ code {
#makeImage {
border-radius: 6px;
}
#editor-modifiers h5 {
padding: 5pt 0;
margin: 0;
}
#makeImage {
flex: 0 0 70px;
background: var(--accent-color);
@ -224,11 +224,11 @@ code {
height: 30pt;
}
#makeImage:hover {
background: var(--button-hover-background);
background: hsl(var(--accent-hue), 100%, calc(var(--accent-lightness) + 6%));
}
#stopImage {
flex: 0 0 70px;
background: var(--secondary-button-background);
background: rgb(132, 8, 0);
border: 2px solid rgb(122, 29, 0);
color: rgb(255, 221, 255);
height: 30pt;
@ -236,7 +236,7 @@ code {
flex-grow: 2;
}
#stopImage:hover {
background: var(--secondary-button-hover-background);
background: rgb(177, 27, 0);
}
#undo {
float: right;
@ -284,213 +284,14 @@ button#resume {
.collapsible:not(.active) ~ .collapsible-content {
display: none !important;
}
#image-modifier-dropdown {
margin-left: 1em;
position: relative;
cursor: pointer;
}
#editor-modifiers {
max-width: 75vw;
min-width: 50vw;
max-height: fit-content;
overflow-y: hidden;
overflow-y: auto;
overflow-x: hidden;
display: none;
background: var(--background-color1);
border: solid 1px var(--background-color3);
z-index: 1999;
border-radius: 6px;
box-shadow: 0px 0px 30px black;
border: 2px solid rgb(255 255 255 / 10%);
margin-top: 150pt;
}
@media screen and (max-height: 500px) {
#editor-modifiers {
margin-top: 50pt;
}
}
#editor-modifiers.active {
display: flex;
flex-direction: column;
position: absolute;
left: 5vw;
}
.modifiers-maximized {
position: fixed !important;
top: 0 !important;
bottom: 0px !important;
left: 0px !important;
right: 0px !important;
margin: 0px !important;
max-width: unset !important;
max-height: unset !important;
border: 0px !important;
border-radius: 0px !important;
}
.modifiers-maximized #editor-modifiers-entries {
max-height: 100%;
flex: 1;
}
.dialog-header {
background-color: var(--background-color4);
padding: 0.5em;
border-bottom: 1px solid rgb(255 255 255 / 10%);
display: flex;
justify-content: space-between;
align-items: center;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
#editor-modifiers-subheader {
background-color: var(--background-color4);
padding: 0.5em;
border-bottom: 1px solid rgb(255 255 255 / 10%);
display: flex;
align-items: center;
grid-gap: 0.8em;
flex-direction: row;
position: relative;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
transition: all 0.1s ease;
}
#editor-modifiers-subheader::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255, 255, 255, 0.02);
opacity: 1;
pointer-events: none;
}
#modifiers-header-left {
display: flex;
flex-direction: column;
grid-gap: 0.1em;
}
.dialog-header-left span {
font-size: 0.8em;
color: rgb(127 127 127);
font-weight: 200;
}
#modifiers-header-right {
display: flex;
align-items: center;
align-content: center;
justify-content: center;
grid-gap: 0.8em;
margin-right: 0.3em;
}
#editor-modifiers-subheader i,
#modifiers-header-right i {
cursor: pointer;
margin: 0;
padding: 0;
}
#modifiers-header-right .section-button,
#editor-modifiers-subheader .section-button {
margin-top: 0.3em;
}
#modifiers-action-collapsibles-btn {
display: flex;
grid-gap: 0.5em;
cursor: pointer;
}
.modifiers-action-text {
font-size: 0.8em;
color: rgb(192 192 192);
}
#modifiers-expand-btn {
z-index: 2;
}
#modifiers-expand-btn .simple-tooltip {
background-color: var(--background-color3);
border-radius: 50px;
}
.modifier-category .collapsible {
position: relative;
}
.modifier-category .collapsible::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255, 255, 255, 0.1);
opacity: 0;
transition: opacity 0.1s ease;
pointer-events: none;
}
.modifier-category:hover .collapsible::after {
opacity: 1;
pointer-events: none;
}
#editor-modifiers-entries {
overflow: auto scroll;
max-height: 50vh;
height: fit-content;
margin-bottom: 0.1em;
padding-left: 0px;
}
#editor-modifiers-entries .collapsible {
transition: opacity 0.1s ease;
padding-left: 0.5em;
}
#editor-modifiers-entries .modifier-category:nth-child(odd) .collapsible::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255, 255, 255, 0.02);
opacity: 1;
pointer-events: none;
}
#editor-modifiers .editor-modifiers-leaf {
padding-top: 10pt;
padding-bottom: 10pt;
}
#editor-modifiers h5 {
padding: 5pt 0;
margin: 0;
position: sticky;
top: -2px;
z-index: 10;
background-color: var(--background-color3);
border-bottom: 1px solid rgb(255 255 255 / 4%);
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
dialog {
background: var(--background-color2);
color: var(--text-color);
border-radius: 6px;
box-shadow: 0px 0px 30px black;
border: 2px solid rgb(255 255 255 / 10%);
padding: 0px;
}
dialog::backdrop {
background: rgba(32, 33, 36, 50%);
}
dialog > div {
padding: 0.5em;
}
img {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.15), 0 6px 20px 0 rgba(0, 0, 0, 0.15);
}
@ -509,9 +310,6 @@ div.img-preview img {
margin-top: 5pt;
display: none;
}
#editor-inputs-tags-list {
max-height: 30em;
}
#server-status {
position: absolute;
right: 16px;
@ -520,11 +318,11 @@ div.img-preview img {
}
#server-status-color {
font-size: 14pt;
color: var(--status-orange);
color: rgb(200, 139, 0);
display: inline;
}
#server-status-msg {
color: var(--status-orange);
color: rgb(200, 139, 0);
padding-left: 2pt;
font-size: 10pt;
}
@ -609,18 +407,11 @@ div.img-preview img {
margin: auto;
padding: 0px;
}
#help-links ul {
list-style-type: disc;
padding-left: 12pt;
}
#help-links li {
padding-bottom: 6pt;
padding-bottom: 12pt;
display: block;
font-size: 10pt;
}
#help-links ul li {
display: list-item;
}
#help-links li .fa-fw {
padding-right: 2pt;
}
@ -738,14 +529,14 @@ div.img-preview img {
padding: 3pt 6pt;
}
.secondaryButton {
background: var(--secondary-button-background);
background: rgb(132, 8, 0);
border: 1px solid rgb(122, 29, 0);
color: rgb(255, 221, 255);
padding: 3pt 6pt;
border-radius: 5px;
}
.secondaryButton:hover {
background: var(--secondary-button-hover-background);
background: rgb(177, 27, 0);
}
.tertiaryButton {
background: var(--tertiary-background-color);
@ -755,12 +546,12 @@ div.img-preview img {
border-radius: 5px;
}
.tertiaryButton:hover {
background: var(--button-hover-background);
background: hsl(var(--accent-hue), 100%, calc(var(--accent-lightness) + 6%));
color: var(--accent-text-color);
}
.tertiaryButton.pressed {
border-style: inset;
background: var(--button-hover-background);
background: hsl(var(--accent-hue), 100%, calc(var(--accent-lightness) + 6%));
color: var(--accent-text-color);
}
.useSettings {
@ -803,7 +594,7 @@ div.img-preview img {
margin-bottom: 8px;
}
#init_image_preview_container:not(.has-image) .preview_image_wrapper,
#init_image_preview_container:not(.has-image) #init_image_wrapper,
#init_image_preview_container:not(.has-image) #inpaint_button_container {
display: none;
}
@ -840,14 +631,14 @@ div.img-preview img {
gap: 8px;
}
.preview_image_wrapper {
#init_image_wrapper {
grid-row: span 3;
position: relative;
width: fit-content;
max-height: 150px;
}
.image_preview {
#init_image_preview {
max-height: 150px;
height: 100%;
width: 100%;
@ -881,9 +672,6 @@ div.img-preview img {
#editor-settings {
min-width: 350px;
}
.panel-box > h4 {
margin: 0;
}
#editor-settings-entries {
display: flex;
@ -909,10 +697,6 @@ div.img-preview img {
white-space: nowrap;
}
#editor-settings-entries table {
width: 93%;
}
#negative_prompt {
width: 100%;
}
@ -987,7 +771,7 @@ input::file-selector-button,
button:hover,
.button:hover {
transition-duration: 0.1s;
background: var(--button-hover-background);
background: hsl(var(--accent-hue), 100%, calc(var(--accent-lightness) + 6%));
}
input::file-selector-button {
@ -995,6 +779,7 @@ input::file-selector-button {
height: 19px;
}
.input-toggle {
display: inline-block;
position: relative;
@ -1097,7 +882,7 @@ input::file-selector-button {
.tab-content-inner {
margin: 0px;
}
#top-nav .tab {
.tab {
font-size: 0;
}
.tab .icon {
@ -1123,9 +908,6 @@ input::file-selector-button {
#preview-tools button .icon {
font-size: 12pt;
}
#show-download-popup .fa-solid {
font-size: 12pt;
}
}
@media screen and (max-width: 500px) {
@ -1155,7 +937,7 @@ input::file-selector-button {
position: relative;
}
.smallButton {
#promptsFromFileBtn {
font-size: 9pt;
display: inline;
padding: 2pt;
@ -1214,12 +996,6 @@ input::file-selector-button {
visibility: visible;
}
}
.tooltip-container {
display: inline-block;
position: relative;
}
.simple-tooltip.right {
right: 0px;
top: 50%;
@ -1307,7 +1083,6 @@ input::file-selector-button {
/* POPUPS */
.popup:not(.active) {
visibility: hidden;
overflow-x: hidden; /* fix overflow from body */
opacity: 0;
}
@ -1436,10 +1211,6 @@ div.task-fs-initimage {
display: none;
position: absolute;
}
div.task-fs-initimage img {
max-height: 70vH;
max-width: 70vW;
}
div.task-initimg:hover div.task-fs-initimage {
display: block;
position: absolute;
@ -1455,13 +1226,9 @@ div.top-right {
right: 8px;
}
.task-fs-initimage .top-right button {
margin-top: 6px;
}
#small_image_warning {
font-size: smaller;
color: var(--status-orange);
font-size: smaller;
color: var(--status-orange);
}
button#save-system-settings-btn {
@ -1474,21 +1241,10 @@ button#save-system-settings-btn {
line-height: 200%;
}
#download-images-dialog .parameters-table > div {
#download-images-popup .parameters-table > div {
background: var(--background-color1);
}
.center {
text-align: center;
}
.fa-xmark {
cursor: pointer;;
}
.validation-failed {
border: solid 2px red;
}
/* SCROLLBARS */
:root {
--scrollbar-width: 14px;
@ -1536,49 +1292,6 @@ body.wait-pause {
100% { border: solid 12px var(--accent-color); }
}
#splash-screen div {
text-align: left;
max-width: 70vw;
}
#splash-screen .splash-img {
float: right;
box-shadow: none;
margin-left: 6px;
}
#splash-screen tt {
font-family: monospace;
background: var(--input-background-color);
padding: 1px 4px 1px 4px;
border-radius: 5px;
}
#splash-screen li {
margin-bottom: 6px;
}
#splash-screen a
{
color: #ccf;
text-decoration: none;
font-weight: bold;
}
#splash-screen a[href^="http"]::after,
#splash-screen a[href^="https://"]::after
{
content: "";
width: 11px;
height: 11px;
margin-left: 4px;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='lightblue' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M8.636 3.5a.5.5 0 0 0-.5-.5H1.5A1.5 1.5 0 0 0 0 4.5v10A1.5 1.5 0 0 0 1.5 16h10a1.5 1.5 0 0 0 1.5-1.5V7.864a.5.5 0 0 0-1 0V14.5a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h6.636a.5.5 0 0 0 .5-.5z'/%3E%3Cpath fill-rule='evenodd' d='M16 .5a.5.5 0 0 0-.5-.5h-5a.5.5 0 0 0 0 1h3.793L6.146 9.146a.5.5 0 1 0 .708.708L15 1.707V5.5a.5.5 0 0 0 1 0v-5z'/%3E%3C/svg%3E");
background-position: center;
background-repeat: no-repeat;
background-size: contain;
display: inline-block;
}
.jconfirm.jconfirm-modern .jconfirm-box div.jconfirm-title-c {
color: var(--button-text-color);
}
@ -1596,30 +1309,6 @@ body.wait-pause {
padding-left: 5pt;
}
#cloudflare-address {
background-color: var(--background-color3);
padding: 6px;
border-radius: var(--input-border-radius);
border: var(--input-border-size) solid var(--input-border-color);
margin-top: 0.2em;
margin-bottom: 0.2em;
display: inline-block;
width: 80%;
}
#copy-cloudflare-address {
padding: 4px 8px;
margin-left: 0.5em;
}
.expandedSettingRow {
background: var(--background-color1);
width: 95%;
border-radius: 4pt;
margin-top: 5pt;
margin-bottom: 3pt;
}
/* TOAST NOTIFICATIONS */
.toast-notification {
position: fixed;
@ -1640,14 +1329,6 @@ body.wait-pause {
color: red;
}
.image-editor-button-label {
display: inline-block;
}
.image-editor-button-label::first-letter {
text-decoration: underline;
}
@keyframes slideInRight {
from {
right: -300px;
@ -1678,365 +1359,3 @@ body.wait-pause {
bottom: 0;
}
}
.spinner-container {
width: 80px;
height: 100px;
margin: 100px auto;
margin-top: 30vH;
}
.spinner-block {
position: relative;
box-sizing: border-box;
float: left;
margin: 0 10px 10px 0;
width: 12px;
height: 12px;
border-radius: 3px;
background: var(--accent-color);
}
.spinner-block:nth-child(4n+1) { animation: spinner-wave 2s ease .0s infinite; }
.spinner-block:nth-child(4n+2) { animation: spinner-wave 2s ease .2s infinite; }
.spinner-block:nth-child(4n+3) { animation: spinner-wave 2s ease .4s infinite; }
.spinner-block:nth-child(4n+4) { animation: spinner-wave 2s ease .6s infinite; margin-right: 0; }
@keyframes spinner-wave {
0% { top: 0; opacity: 1; }
50% { top: 30px; opacity: .2; }
100% { top: 0; opacity: 1; }
}
#embeddings-dialog {
overflow: clip;
}
#embeddings-list {
height: 70vH;
width: 50vW;
margin-left: 0px;
margin-right: 0px;
padding-left: 0px;
padding-right: 0px;
overflow-y: scroll;
}
@media screen and (max-width: 1400px) {
#embeddings-list {
width: 80vW;
}
}
#embeddings-list button {
margin: 2px;
color: var(--button-color);
background: var(--button-text-color);
font-weight: 700;
}
#embeddings-list button:hover {
background: var(--accent-color);
color: var(--button-text-color);
}
#embeddings-list .collapsible {
background: var(--background-color3);
margin: 0px;
padding: 0.5em;
position: sticky;
}
#embeddings-list .embedding-category:nth-child(odd) .collapsible::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255, 255, 255, 0.02);
opacity: 1;
pointer-events: none;
}
#embeddings-list .collapsible-content {
padding-top: 0.4em;
padding-bottom: 0.4em;
}
#embeddings-list::-webkit-scrollbar-thumb {
background: var(--background-color3);
}
.model_entry .model_name {
width: 73%;
}
.model_entry {
position: relative;
}
.model_entry .remove_model_btn {
position: absolute;
left: -23pt;
top: 4pt;
}
.split-toolbar { display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr;
gap: 0px 0px;
grid-auto-flow: row;
grid-template-areas: "toolbar-left toolbar-right";
}
.toolbar-left {
justify-self: start;
align-self: center;
grid-area: toolbar-left;
}
.toolbar-right {
justify-self: end;
align-self: center;
grid-area: toolbar-right;
}
#negative-embeddings-button {
float: right;
}
.use-as-thumb-grid { display: grid;
grid-template-columns: 1fr auto;
grid-template-rows: 1fr auto;
gap: 8px 8px;
grid-auto-flow: row;
grid-template-areas:
"uat-preview uat-select"
"uat-preview uat-buttons";
}
.use-as-thumb-preview {
justify-self: center;
align-self: center;
grid-area: uat-preview;
}
.use-as-thumb-select {
grid-area: uat-select;
}
.use-as-thumb-buttons {
justify-self: center;
grid-area: uat-buttons;
}
.diffusers-disabled-on-startup .diffusers-restart-needed {
font-size: 0;
}
.diffusers-disabled-on-startup .diffusers-restart-needed * {
display: none;
}
.diffusers-disabled-on-startup .diffusers-restart-needed::after {
content: "Please restart Easy Diffusion!";
font-size: 10pt;
}
input#custom-width, input#custom-height {
width: 47pt;
}
div#recent-resolutions-container {
position: relative;
display:inline-block;
}
div#recent-resolutions-popup {
position: absolute;
right: 0px;
margin: 3px;
padding: 0.2em 1em 0.4em 1em;
z-index: 1;
background: var(--background-color3);
border-radius: 4px;
box-shadow: 0 20px 28px 0 rgba(0, 0, 0, 0.15), 0 6px 20px 0 rgba(0, 0, 0, 0.15);
}
div#recent-resolutions-popup small {
opacity: 0.7;
}
div#common-resolution-list button {
background: var(--background-color1);
}
td#image-size-options small {
margin-right: 0px !important;
}
td#image-size-options {
white-space: nowrap;
}
div#recent-resolution-list {
text-align: center;
}
div#enlarge-buttons {
text-align: center;
}
.two-column { display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr;
gap: 0px 0.5em;
grid-auto-flow: row;
grid-template-areas:
"left-column right-column";
}
.left-column {
justify-self: center;
align-self: center;
grid-area: left-column;
}
.right-column {
justify-self: center;
align-self: center;
grid-area: right-column;
}
.clickable {
cursor: pointer;
}
.imgContainer .spinner {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
margin: 0;
padding: 0;
background: var(--background-color3);
opacity: 0.95;
border-radius: 5px;
padding: 4pt;
border: 1px solid var(--button-color);
box-shadow: 0px 0px 4px black;
}
.imgContainer .spinnerStatus {
font-size: 10pt;
}
#controlnet_model_container small {
color: var(--text-color)
}
#control_image {
width: 130pt;
}
#controlnet_model {
width: 77%;
}
.drop-area {
width: 45%;
height: 50px;
border: 2px dashed #ccc;
text-align: center;
line-height: 50px;
font-size: small;
color: #ccc;
border-radius: 10px;
display: none;
margin: 12px 10px;
}
#num_outputs_total {
width: 42pt;
}
#num_outputs_parallel {
width: 42pt;
}
.model_entry .model_weight {
width: 50pt;
}
/* hack for fixing Image Modifier Improvements plugin */
#imageTagPopupContainer {
position: absolute;
}
@media screen and (max-width: 400px) {
.editor-slider {
width: 40%;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type=number] {
-moz-appearance: textfield;
/* Firefox */
}
#num_outputs_total {
width: 27pt;
}
#num_outputs_parallel {
width: 27pt;
margin-left: -4pt;
}
.model_entry .model_weight {
width: 30pt;
}
#width {
width: 50pt;
}
#height {
width: 50pt;
}
}
@media screen and (max-width: 460px) {
#widthLabel small span {
display: none;
}
#widthLabel small:after {
content: "(w)";
}
#heightLabel small span {
display: none;
}
#heightLabel small:after {
content: "(h)";
}
#prompt-toolbar-right {
text-align: right;
}
#editor-settings label {
font-size: 9pt;
}
#editor-settings .model-filter {
width: 56%;
}
#vae_model {
width: 65% !important;
}
.model_entry .model_name {
width: 60% !important;
}
}
#supportBanner {
font-size: 9pt;
padding: 5pt;
border: 1px solid var(--background-color2);
margin-bottom: 5pt;
border-radius: 4pt;
padding-top: 6pt;
color: var(--small-label-color);
}

View File

@ -1,16 +1,14 @@
.modifier-card {
position: relative;
box-sizing: content-box; /* fixes border misalignment */
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
transition: 0.1s;
border-radius: 7px;
margin: 3pt 3pt;
float: left;
width: 6em;
height: 9.5em;
width: 8em;
height: 11.5em;
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 6em 3.5em;
grid-template-rows: 8em 3.5em;
gap: 0px 0px;
grid-auto-flow: row;
grid-template-areas:
@ -18,71 +16,82 @@
"modifier-card-container";
border: 2px solid rgba(255, 255, 255, .05);
cursor: pointer;
z-index: 2;
}
.modifier-card-size_5 {
width: 18em;
grid-template-rows: 18em 3.5em;
height: 21.5em;
}
.modifier-card-size_5 .modifier-card-image-overlay {
font-size: 8em;
}
.modifier-card-size_4 {
width: 14em;
grid-template-rows: 14em 3.5em;
height: 17.5em;
}
.modifier-card-size_4 .modifier-card-image-overlay {
font-size: 7em;
}
.modifier-card-size_3 {
width: 10em;
grid-template-rows: 10em 3.5em;
height: 13.5em;
width: 11em;
grid-template-rows: 11em 3.5em;
height: 14.5em;
}
.modifier-card-size_3 .modifier-card-image-overlay {
font-size: 6em;
}
.modifier-card-size_3 .modifier-card-label {
font-size: 1.2em;
}
.modifier-card-size_2 {
width: 10em;
grid-template-rows: 10em 3.5em;
height: 13.5em;
}
.modifier-card-size_2 .modifier-card-image-overlay {
font-size: 6em;
}
.modifier-card-size_1 {
width: 9em;
grid-template-rows: 9em 3.5em;
height: 12.5em;
}
.modifier-card-size_2 .modifier-card-image-overlay {
.modifier-card-size_1 .modifier-card-image-overlay {
font-size: 5em;
}
.modifier-card-size_2 .modifier-card-label {
font-size: 1.1em;
}
.modifier-card-size_1 {
.modifier-card-size_-1 {
width: 7em;
grid-template-rows: 7em 3.5em;
height: 10.5em;
}
.modifier-card-size_1 .modifier-card-image-overlay {
.modifier-card-size_-1 .modifier-card-image-overlay {
font-size: 4em;
}
.modifier-card-size_-1 {
width: 5em;
grid-template-rows: 5em 3.5em;
height: 8.5em;
}
.modifier-card-size_-1 .modifier-card-image-overlay {
font-size: 3em;
}
.modifier-card-size_-1 .modifier-card-label {
font-size: 0.9em;
}
.modifier-card-size_-2 {
width: 4em;
grid-template-rows: 3.5em 3em;
height: 6.5em;
width: 6em;
grid-template-rows: 6em 3.5em;
height: 9.5em;
}
.modifier-card-size_-2 .modifier-card-image-overlay {
font-size: 2em;
font-size: 3em;
}
.modifier-card-size_-2 .modifier-card-label {
font-size: 0.7em;
}
.modifier-card-tiny {
.modifier-card-size_-3 {
width: 5em;
grid-template-rows: 5em 3.5em;
height: 8.5em;
}
.modifier-card-size_-3 .modifier-card-image-overlay {
font-size: 3em;
}
.modifier-card-size_-3 .modifier-card-label {
font-size: 0.8em;
}
.modifier-card-tiny {
width: 6em;
height: 9.5em;
grid-template-rows: 6em 3.5em;
}
.modifier-card-tiny .modifier-card-image-overlay {
font-size: 4em;
}
.modifier-card-tiny .modifier-card-label {
font-size: 0.9em;
}
.modifier-card:hover {
transform: scale(1.05);
box-shadow: 0 5px 16px 5px rgba(0, 0, 0, 0.25);
@ -106,7 +115,6 @@
}
.modifier-card-image-container * {
position: absolute;
text-align: center;
}
.modifier-card-container {
text-align: center;
@ -123,7 +131,6 @@
.modifier-card-label {
padding: 4px;
word-break: break-word;
text-transform: capitalize;
}
.modifier-card-image-overlay {
width: inherit;
@ -133,7 +140,7 @@
position: absolute;
border-radius: 5px 5px 0 0;
opacity: 0;
font-size: 4em;
font-size: 5em;
font-weight: 900;
color: rgb(255 255 255 / 50%);
display: flex;
@ -146,8 +153,9 @@
position: absolute;
z-index: 3;
}
.modifier-card-active .modifier-card-overlay {
background-color: rgb(169 78 241 / 40%);
.modifier-card-overlay:hover ~ .modifier-card-container .modifier-card-label.tooltip .tooltip-text {
visibility: visible;
opacity: 1;
}
.modifier-card:hover > .modifier-card-image-container .modifier-card-image-overlay {
opacity: 1;
@ -159,30 +167,61 @@
transform: scale(0.95);
box-shadow: 0 5px 16px 5px rgba(0, 0, 0, 0.5);
}
#preview-image {
margin-top: 0.5em;
margin-bottom: 0.5em;
}
.modifier-card-active {
border: 2px solid rgb(179 82 255 / 94%);
box-shadow: 0 0px 10px 0 rgb(170 0 229 / 58%);
}
.tooltip {
position: relative;
display: inline-block;
}
.tooltip .tooltip-text {
visibility: hidden;
width: 120px;
background: rgb(101,97,181);
background: linear-gradient(180deg, rgba(101,97,181,1) 0%, rgba(47,45,85,1) 100%);
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
top: 105%;
left: 39%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
border: 2px solid rgb(90 100 177 / 94%);
box-shadow: 0px 10px 20px 5px rgb(11 0 58 / 55%);
width: 10em;
}
.tooltip .tooltip-text::after {
content: "";
position: absolute;
top: -0.9em;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent transparent rgb(90 100 177 / 94%) transparent;
}
.tooltip:hover .tooltip-text {
visibility: visible;
opacity: 1;
}
#modifier-card-size-slider {
width: 6em;
height: 4pt;
margin-bottom: 0.5em;
vertical-align: middle;
}
#modifier-settings-btn {
float: right;
}
#modifier-settings-config textarea {
margin-left: 5%;
margin-top: 2ex;
width: 90%;
height: 150px;
}
.modifier-card .hidden {
display: none;
}
.support-long-label .modifier-card-overlay:hover ~ .modifier-card-container .modifier-card-label {
font-size: 0.7em;
}
.support-long-label .modifier-card-overlay:hover ~ .modifier-card-container .long-label {
display: block;
}
.support-long-label .modifier-card-overlay:hover ~ .modifier-card-container .regular-label {
display: none;
}

View File

@ -1,288 +0,0 @@
.plugins-table {
display: flex;
flex-direction: column;
gap: 1px;
}
.plugins-table > div {
background: var(--background-color2);
display: flex;
padding: 0px 4px;
}
.plugins-table > div > div {
padding: 10px;
display: flex;
align-items: center;
justify-content: center;
}
.plugins-table small {
color: rgb(153, 153, 153);
}
.plugins-table > div > div:nth-child(1) {
font-size: 20px;
width: 45px;
}
.plugins-table > div > div:nth-child(2) {
flex: 1;
flex-direction: column;
text-align: left;
justify-content: center;
align-items: start;
gap: 4px;
}
.plugins-table > div > div:nth-child(3) {
text-align: right;
}
.plugins-table > div:first-child {
border-radius: 12px 12px 0px 0px;
}
.plugins-table > div:last-child {
border-radius: 0px 0px 12px 12px;
}
.notifications-table {
display: flex;
flex-direction: column;
gap: 1px;
}
.notifications-table > div {
background: var(--background-color2);
display: flex;
padding: 0px 4px;
}
.notifications-table > div > div {
padding: 10px;
display: flex;
align-items: center;
justify-content: center;
}
.notifications-table small {
color: rgb(153, 153, 153);
}
.notifications-table > div > div:nth-child(1) {
flex: 1;
flex-direction: column;
text-align: left;
justify-content: center;
align-items: start;
gap: 4px;
}
.notifications-table > div > div:nth-child(2) {
width: auto;
}
.notifications-table > div:first-child {
border-radius: 12px 12px 0px 0px;
}
.notifications-table > div:last-child {
border-radius: 0px 0px 12px 12px;
}
.notification-error {
color: red;
}
DIV.no-notification {
padding-top: 16px;
font-style: italic;
}
.plugin-manager-intro {
margin: 0 0 16px 0;
}
#plugin-filter {
box-sizing: border-box;
width: 100%;
margin: 4px 0 6px 0;
padding: 10px;
}
#refresh-plugins {
box-sizing: border-box;
width: 100%;
padding: 0px;
}
#refresh-plugins a {
cursor: pointer;
}
#refresh-plugins a:active {
transition-duration: 0.1s;
position: relative;
top: 1px;
left: 1px;
}
.plugin-installed-locally {
font-style: italic;
font-size: small;
}
.plugin-source {
font-size: x-small;
}
.plugin-warning {
color: orange;
font-size: smaller;
}
.plugin-warning.hide {
display: none;
}
.plugin-warning ul {
list-style: square;
margin: 0 0 8px 16px;
padding: 0;
}
.plugin-warning li {
margin-left: 8px;
padding: 0;
}
/* MODAL DIALOG */
#pluginDialog-input-dialog {
position: fixed;
z-index: 1000;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
}
.pluginDialog-dialog-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(32, 33, 36, 50%);
}
.pluginDialog-dialog-box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 80%;
max-width: 600px;
background: var(--background-color2);
border: solid 1px var(--background-color3);
border-radius: 6px;
box-shadow: 0px 0px 30px black;
}
.pluginDialog-dialog-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px;
}
.pluginDialog-dialog-header h2 {
margin: 0;
}
.pluginDialog-dialog-close-button {
font-size: 24px;
font-weight: bold;
line-height: 1;
border: none;
background-color: transparent;
cursor: pointer;
}
.pluginDialog-dialog-close-button:hover {
color: #555;
}
.pluginDialog-dialog-content {
padding: 0 16px 0 16px;
}
.pluginDialog-dialog-content textarea {
width: 100%;
height: 300px;
border-radius: var(--input-border-radius);
padding: 4px;
accent-color: var(--accent-color);
background: var(--input-background-color);
border: var(--input-border-size) solid var(--input-border-color);
color: var(--input-text-color);
font-size: 9pt;
resize: none;
}
.pluginDialog-dialog-buttons {
display: flex;
justify-content: flex-end;
padding: 16px;
}
.pluginDialog-dialog-buttons button {
margin-left: 8px;
padding: 8px 16px;
font-size: 16px;
border-radius: 4px;
/*background: var(--accent-color);*/
/*border: var(--primary-button-border);*/
/*color: rgb(255, 221, 255);*/
background-color: #3071a9;
border: none;
cursor: pointer;
}
.pluginDialog-dialog-buttons button:hover {
/*background: hsl(var(--accent-hue), 100%, 50%);*/
background-color: #428bca;
}
/* NOTIFICATION CENTER */
#plugin-notification-button {
float: right;
margin-top: 30px;
}
#plugin-notification-button:hover {
background: unset;
}
#plugin-notification-button:active {
transition-duration: 0.1s;
position: relative;
top: 1px;
left: 1px;
}
.plugin-notification-pill {
background-color: red;
border-radius: 50%;
color: white;
font-size: 10px;
font-weight: bold;
height: 12px;
line-height: 12px;
position: relative;
right: -8px;
text-align: center;
top: -20px;
width: 12px;
}

View File

@ -13,8 +13,6 @@
--accent-lightness-hover: 40%;
--text-color: #eee;
--link-color: rgb(0, 102, 204);
--small-label-color: rgb(153, 153, 153);
--input-text-color: #eee;
--input-background-color: hsl(var(--main-hue), var(--main-saturation), calc(var(--value-base) - (0.7 * var(--value-step))));
@ -23,9 +21,6 @@
--button-text-color: var(--input-text-color);
--button-color: var(--input-background-color);
--button-border: none;
--button-hover-background: hsl(var(--accent-hue), 100%, calc(var(--accent-lightness) + 6%));
--secondary-button-background: rgb(132, 8, 0);
--secondary-button-hover-background: rgb(177, 27, 0);
/* other */
--input-border-radius: 4px;

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -15,12 +15,16 @@ const SETTINGS_IDS_LIST = [
"stable_diffusion_model",
"clip_skip",
"vae_model",
"hypernetwork_model",
"lora_model",
"sampler_name",
"width",
"height",
"num_inference_steps",
"guidance_scale",
"prompt_strength",
"hypernetwork_strength",
"lora_alpha",
"tiling",
"output_format",
"output_quality",
@ -43,7 +47,6 @@ const SETTINGS_IDS_LIST = [
"sound_toggle",
"vram_usage_level",
"confirm_dangerous_actions",
"profileName",
"metadata_output_format",
"auto_save_settings",
"apply_color_correction",
@ -53,20 +56,10 @@ const SETTINGS_IDS_LIST = [
"zip_toggle",
"tree_toggle",
"json_toggle",
"extract_lora_from_prompt",
"embedding-card-size-selector",
"lora_model",
"enable_vae_tiling",
"controlnet_alpha",
]
const IGNORE_BY_DEFAULT = ["prompt"]
if (!testDiffusers.checked) {
SETTINGS_IDS_LIST.push("hypernetwork_model")
SETTINGS_IDS_LIST.push("hypernetwork_strength")
}
const SETTINGS_SECTIONS = [
// gets the "keys" property filled in with an ordered list of settings in this section via initSettings
{ id: "editor-inputs", name: "Prompt" },
@ -178,6 +171,22 @@ function loadSettings() {
}
})
CURRENTLY_LOADING_SETTINGS = false
} else if (localStorage.length < 2) {
// localStorage is too short for OldSettings
// So this is likely the first time Easy Diffusion is running.
// Initialize vram_usage_level based on the available VRAM
function initGPUProfile(event) {
if ( "detail" in event
&& "active" in event.detail
&& "cuda:0" in event.detail.active
&& event.detail.active["cuda:0"].mem_total <4.5 )
{
vramUsageLevelField.value = "low"
vramUsageLevelField.dispatchEvent(new Event("change"))
}
document.removeEventListener("system_info_update", initGPUProfile)
}
document.addEventListener("system_info_update", initGPUProfile)
} else {
CURRENTLY_LOADING_SETTINGS = true
tryLoadOldSettings()

File diff suppressed because it is too large Load Diff

View File

@ -268,11 +268,7 @@ const TASK_MAPPING = {
tiling: {
name: "Tiling",
setUI: (val) => {
if (val === null || val === "None") {
tilingField.value = "none"
} else {
tilingField.value = val
}
tilingField.value = val
},
readUI: () => tilingField.value,
parse: (val) => val,
@ -293,89 +289,32 @@ const TASK_MAPPING = {
readUI: () => vaeModelField.value,
parse: (val) => val,
},
use_controlnet_model: {
name: "ControlNet model",
setUI: (use_controlnet_model) => {
controlnetModelField.value = getModelPath(use_controlnet_model, [".pth", ".safetensors"])
},
readUI: () => controlnetModelField.value,
parse: (val) => val,
},
control_filter_to_apply: {
name: "ControlNet Filter",
setUI: (control_filter_to_apply) => {
controlImageFilterField.value = control_filter_to_apply
},
readUI: () => controlImageFilterField.value,
parse: (val) => val,
},
control_alpha: {
name: "ControlNet Strength",
setUI: (control_alpha) => {
control_alpha = control_alpha || 1.0
controlAlphaField.value = control_alpha
updateControlAlphaSlider()
},
readUI: () => parseFloat(controlAlphaField.value),
parse: (val) => val === null ? 1.0 : parseFloat(val),
},
use_lora_model: {
name: "LoRA model",
setUI: (use_lora_model) => {
let modelPaths = []
use_lora_model = use_lora_model === null ? "" : use_lora_model
use_lora_model = Array.isArray(use_lora_model) ? use_lora_model : [use_lora_model]
use_lora_model.forEach((m) => {
if (m.includes("models\\lora\\")) {
m = m.split("models\\lora\\")[1]
} else if (m.includes("models\\\\lora\\\\")) {
m = m.split("models\\\\lora\\\\")[1]
} else if (m.includes("models/lora/")) {
m = m.split("models/lora/")[1]
}
m = m.replaceAll("\\\\", "/")
m = getModelPath(m, [".ckpt", ".safetensors"])
modelPaths.push(m)
})
loraModelField.modelNames = modelPaths
},
readUI: () => {
return loraModelField.modelNames
},
parse: (val) => {
val = !val || val === "None" ? "" : val
if (typeof val === "string" && val.includes(",")) {
val = val.split(",")
val = val.map((v) => v.trim())
val = val.map((v) => v.replaceAll("\\", "\\\\"))
val = val.map((v) => v.replaceAll('"', ""))
val = val.map((v) => v.replaceAll("'", ""))
val = val.map((v) => '"' + v + '"')
val = "[" + val + "]"
val = JSON.parse(val)
const oldVal = loraModelField.value
use_lora_model =
use_lora_model === undefined || use_lora_model === null || use_lora_model === "None"
? ""
: use_lora_model
if (use_lora_model !== "") {
use_lora_model = getModelPath(use_lora_model, [".ckpt", ".safetensors"])
use_lora_model = use_lora_model !== "" ? use_lora_model : oldVal
}
val = Array.isArray(val) ? val : [val]
return val
loraModelField.value = use_lora_model
},
readUI: () => loraModelField.value,
parse: (val) => val,
},
lora_alpha: {
name: "LoRA Strength",
setUI: (lora_alpha) => {
lora_alpha = Array.isArray(lora_alpha) ? lora_alpha : [lora_alpha]
loraModelField.modelWeights = lora_alpha
},
readUI: () => {
return loraModelField.modelWeights
},
parse: (val) => {
if (typeof val === "string" && val.includes(",")) {
val = "[" + val.replaceAll("'", '"') + "]"
val = JSON.parse(val)
}
val = Array.isArray(val) ? val : [val]
val = val.map((e) => parseFloat(e))
return val
loraAlphaField.value = lora_alpha
updateLoraAlphaSlider()
},
readUI: () => parseFloat(loraAlphaField.value),
parse: (val) => parseFloat(val),
},
use_hypernetwork_model: {
name: "Hypernetwork model",
@ -487,8 +426,8 @@ function restoreTaskToUI(task, fieldsToSkip) {
}
if (!("use_lora_model" in task.reqBody)) {
loraModelField.modelNames = []
loraModelField.modelWeights = []
loraModelField.value = ""
loraModelField.dispatchEvent(new Event("change"))
}
// restore the original prompt if provided (e.g. use settings), fallback to prompt as needed (e.g. copy/paste or d&d)
@ -531,28 +470,10 @@ function restoreTaskToUI(task, fieldsToSkip) {
)
initImagePreview.src = task.reqBody.init_image
}
// hide/show controlnet picture as needed
if (IMAGE_REGEX.test(controlImagePreview.src) && task.reqBody.control_image == undefined) {
// hide source image
controlImageClearBtn.dispatchEvent(new Event("click"))
} else if (task.reqBody.control_image !== undefined) {
// listen for inpainter loading event, which happens AFTER the main image loads (which reloads the inpai
controlImagePreview.src = task.reqBody.control_image
}
if ("use_controlnet_model" in task.reqBody && task.reqBody.use_controlnet_model && !("control_alpha" in task.reqBody)) {
controlAlphaField.value = 1.0
updateControlAlphaSlider()
}
}
function readUI() {
const reqBody = {}
for (const key in TASK_MAPPING) {
if (testDiffusers.checked && (key === "use_hypernetwork_model" || key === "hypernetwork_strength")) {
continue
}
reqBody[key] = TASK_MAPPING[key].readUI()
}
return {
@ -599,12 +520,6 @@ const TASK_TEXT_MAPPING = {
use_stable_diffusion_model: "Stable Diffusion model",
use_hypernetwork_model: "Hypernetwork model",
hypernetwork_strength: "Hypernetwork Strength",
use_lora_model: "LoRA model",
lora_alpha: "LoRA Strength",
use_controlnet_model: "ControlNet model",
control_filter_to_apply: "ControlNet Filter",
control_alpha: "ControlNet Strength",
tiling: "Seamless Tiling",
}
function parseTaskFromText(str) {
const taskReqBody = {}

View File

@ -186,7 +186,6 @@
const EVENT_TASK_START = "taskStart"
const EVENT_TASK_END = "taskEnd"
const EVENT_TASK_ERROR = "task_error"
const EVENT_PING = "ping"
const EVENT_UNEXPECTED_RESPONSE = "unexpectedResponse"
const EVENTS_TYPES = [
EVENT_IDLE,
@ -197,7 +196,6 @@
EVENT_TASK_START,
EVENT_TASK_END,
EVENT_TASK_ERROR,
EVENT_PING,
EVENT_UNEXPECTED_RESPONSE,
]
@ -242,7 +240,6 @@
setServerStatus("error", "offline")
return false
}
// Set status
switch (serverState.status) {
case ServerStates.init:
@ -264,7 +261,6 @@
break
}
serverState.time = Date.now()
await eventSource.fireEvent(EVENT_PING, serverState)
return true
} catch (e) {
console.error(e)
@ -1047,9 +1043,7 @@
}
}
class FilterTask extends Task {
constructor(options = {}) {
super(options)
}
constructor(options = {}) {}
/** Send current task to server.
* @param {*} [timeout=-1] Optional timeout value in ms
* @returns the response from the render request.
@ -1057,27 +1051,9 @@
*/
async post(timeout = -1) {
let jsonResponse = await super.post("/filter", timeout)
if (typeof jsonResponse?.task !== "number") {
console.warn("Endpoint error response: ", jsonResponse)
const event = Object.assign({ task: this }, jsonResponse)
await eventSource.fireEvent(EVENT_UNEXPECTED_RESPONSE, event)
if ("continueWith" in event) {
jsonResponse = await Promise.resolve(event.continueWith)
}
if (typeof jsonResponse?.task !== "number") {
const err = new Error(jsonResponse?.detail || "Endpoint response does not contains a task ID.")
this.abort(err)
throw err
}
}
this._setId(jsonResponse.task)
if (jsonResponse.stream) {
this.streamUrl = jsonResponse.stream
}
//this._setId(jsonResponse.task)
this._setStatus(TaskStatus.waiting)
return jsonResponse
}
checkReqBody() {}
enqueue(progressCallback) {
return Task.enqueueNew(this, FilterTask, progressCallback)
}
@ -1088,65 +1064,6 @@
if (this.isStopped) {
return
}
this._setStatus(TaskStatus.pending)
progressCallback?.call(this, { reqBody: this._reqBody })
Object.freeze(this._reqBody)
// Post task request to backend
let renderRes = undefined
try {
renderRes = yield this.post()
yield progressCallback?.call(this, { renderResponse: renderRes })
} catch (e) {
yield progressCallback?.call(this, { detail: e.message })
throw e
}
try {
// Wait for task to start on server.
yield this.waitUntil({
callback: function() {
return progressCallback?.call(this, {})
},
status: TaskStatus.processing,
})
} catch (e) {
this.abort(err)
throw e
}
// Task started!
// Open the reader.
const reader = this.reader
const task = this
reader.onError = function(response) {
if (progressCallback) {
task.abort(new Error(response.statusText))
return progressCallback.call(task, { response, reader })
}
return Task.prototype.onError.call(task, response)
}
yield progressCallback?.call(this, { reader })
//Start streaming the results.
const streamGenerator = reader.open()
let value = undefined
let done = undefined
yield progressCallback?.call(this, { stream: streamGenerator })
do {
;({ value, done } = yield streamGenerator.next())
if (typeof value !== "object") {
continue
}
if (value.status !== undefined) {
yield progressCallback?.call(this, value)
if (value.status === "succeeded" || value.status === "failed") {
done = true
}
}
} while (!done)
return value
}
static start(task, progressCallback) {
if (typeof task !== "object") {
@ -1200,13 +1117,13 @@
return systemInfo.hosts
}
async function getModels(scanForMalicious = true) {
async function getModels() {
let models = {
"stable-diffusion": [],
vae: [],
}
try {
const res = await fetch("/get/models?scan_for_malicious=" + scanForMalicious)
const res = await fetch("/get/models")
if (!res.ok) {
console.error("Invalid response fetching models", res.statusText)
return models

File diff suppressed because one or more lines are too long

View File

@ -47,7 +47,6 @@ const IMAGE_EDITOR_TOOLS = [
begin: defaultToolBegin,
move: defaultToolMove,
end: defaultToolEnd,
hotkey: "d",
},
{
id: "erase",
@ -78,7 +77,6 @@ const IMAGE_EDITOR_TOOLS = [
setBrush: (editor, layer) => {
layer.ctx.globalCompositeOperation = "destination-out"
},
hotkey: "e",
},
{
id: "fill",
@ -94,7 +92,6 @@ const IMAGE_EDITOR_TOOLS = [
},
move: toolDoNothing,
end: toolDoNothing,
hotkey: "f",
},
{
id: "colorpicker",
@ -116,7 +113,6 @@ const IMAGE_EDITOR_TOOLS = [
},
move: toolDoNothing,
end: toolDoNothing,
hotkey: "p",
},
]
@ -212,10 +208,7 @@ var IMAGE_EDITOR_SECTIONS = [
var icon = document.createElement("i")
tool_info.icon.split(" ").forEach((c) => icon.classList.add(c))
sub_element.appendChild(icon)
var label_element = document.createElement("div")
label_element.classList.add("image-editor-button-label")
label_element.textContent=tool_info.name
sub_element.appendChild(label_element)
sub_element.append(tool_info.name)
element.appendChild(sub_element)
},
},
@ -626,7 +619,6 @@ class ImageEditor {
.getImageData(0, 0, this.width, this.height)
.data.some((channel) => channel !== 0)
maskSetting.checked = !is_blank
maskSetting.dispatchEvent(new Event("change"))
}
this.hide()
}
@ -710,22 +702,15 @@ class ImageEditor {
event.stopPropagation()
event.preventDefault()
}
else if (event.key == "y" && event.ctrlKey) {
if (event.key == "y" && event.ctrlKey) {
this.history.redo()
event.stopPropagation()
event.preventDefault()
}
else if (event.key === "Escape") {
if (event.key === "Escape") {
this.hide()
event.stopPropagation()
event.preventDefault()
} else {
let toolIndex = IMAGE_EDITOR_TOOLS.findIndex( t => t.hotkey ==event.key )
if (toolIndex != -1) {
this.selectOption("tool", toolIndex)
event.stopPropagation()
event.preventDefault()
}
}
}

View File

@ -1,56 +1,48 @@
let activeTags = []
let modifiers = []
let customModifiersGroupElement = undefined
let customModifiersInitialContent = ""
let modifierPanelFreezed = false
let customModifiersInitialContent
let modifiersMainContainer = document.querySelector("#editor-modifiers")
let modifierDropdown = document.querySelector("#image-modifier-dropdown")
let editorModifiersContainer = document.querySelector("#editor-modifiers")
let editorModifierEntries = document.querySelector("#editor-modifiers-entries")
let editorModifierTagsList = document.querySelector("#editor-inputs-tags-list")
let editorTagsContainer = document.querySelector("#editor-inputs-tags-container")
let modifierCardSizeSlider = document.querySelector("#modifier-card-size-slider")
let previewImageField = document.querySelector("#preview-image")
let modifierSettingsBtn = document.querySelector("#modifier-settings-btn")
let modifiersContainerSizeBtn = document.querySelector("#modifiers-container-size-btn")
let modifiersCloseBtn = document.querySelector("#modifiers-close-button")
let modifiersCollapsiblesBtn = document.querySelector("#modifiers-action-collapsibles-btn")
let modifierSettingsDialog = document.querySelector("#modifier-settings-config")
let modifierSettingsOverlay = document.querySelector("#modifier-settings-config")
let customModifiersTextBox = document.querySelector("#custom-modifiers-input")
let customModifierEntriesToolbar = document.querySelector("#editor-modifiers-subheader")
let modifierSettingsCloseBtn = document.querySelector("#modifier-settings-close-button")
let customModifierEntriesToolbar = document.querySelector("#editor-modifiers-entries-toolbar")
const modifierThumbnailPath = "media/modifier-thumbnails"
const activeCardClass = "modifier-card-active"
const CUSTOM_MODIFIERS_KEY = "customModifiers"
function createModifierCard(name, previews, removeBy) {
let cardPreviewImageType = previewImageField.value
const modifierCard = document.createElement("div")
let style = previewImageField.value
let styleIndex = style == "portrait" ? 0 : 1
modifierCard.className = "modifier-card"
modifierCard.innerHTML = `
<div class="modifier-card-overlay"></div>
<div class="modifier-card-image-container">
<div class="modifier-card-image-overlay">+</div>
<p class="modifier-card-error-label">No Image</p>
<p class="modifier-card-error-label"></p>
<img onerror="this.remove()" alt="Modifier Image" class="modifier-card-image">
</div>
<div class="modifier-card-container">
<div class="modifier-card-label">
<span class="long-label hidden"></span>
<p class="regular-label"></p>
</div>
<div class="modifier-card-label"><p></p></div>
</div>`
const image = modifierCard.querySelector(".modifier-card-image")
const longLabel = modifierCard.querySelector(".modifier-card-label span.long-label")
const regularLabel = modifierCard.querySelector(".modifier-card-label p.regular-label")
const errorText = modifierCard.querySelector(".modifier-card-error-label")
const label = modifierCard.querySelector(".modifier-card-label")
errorText.innerText = "No Image"
if (typeof previews == "object") {
image.src = previews[cardPreviewImageType == "portrait" ? 0 : 1] // 0 index is portrait, 1 landscape
image.setAttribute("preview-type", cardPreviewImageType)
image.src = previews[styleIndex] // portrait
image.setAttribute("preview-type", style)
} else {
image.remove()
}
@ -58,32 +50,24 @@ function createModifierCard(name, previews, removeBy) {
const maxLabelLength = 30
const cardLabel = removeBy ? name.replace("by ", "") : name
function getFormattedLabel(length) {
if (cardLabel?.length <= length) {
return cardLabel
} else {
return cardLabel.substring(0, length) + "..."
}
if (cardLabel.length <= maxLabelLength) {
label.querySelector("p").innerText = cardLabel
} else {
const tooltipText = document.createElement("span")
tooltipText.className = "tooltip-text"
tooltipText.innerText = name
label.classList.add("tooltip")
label.appendChild(tooltipText)
label.querySelector("p").innerText = cardLabel.substring(0, maxLabelLength) + "..."
}
label.querySelector("p").dataset.fullName = name // preserve the full name
modifierCard.dataset.fullName = name // preserve the full name
regularLabel.dataset.fullName = name // preserve the full name, legacy support for older plugins
longLabel.innerText = getFormattedLabel(maxLabelLength * 2)
regularLabel.innerText = getFormattedLabel(maxLabelLength)
if (cardLabel.length > maxLabelLength) {
modifierCard.classList.add("support-long-label")
if (cardLabel.length > maxLabelLength * 2) {
modifierCard.title = `"${name}"`
}
}
return modifierCard
}
function createModifierGroup(modifierGroup, isInitiallyOpen, removeBy) {
function createModifierGroup(modifierGroup, initiallyExpanded, removeBy) {
const title = modifierGroup.category
const modifiers = modifierGroup.modifiers
@ -94,8 +78,8 @@ function createModifierGroup(modifierGroup, isInitiallyOpen, removeBy) {
const modifiersEl = document.createElement("div")
modifiersEl.classList.add("collapsible-content", "editor-modifiers-leaf")
if (isInitiallyOpen === true) {
titleEl.classList.add("active")
if (initiallyExpanded === true) {
titleEl.className += " active"
}
modifiers.forEach((modObj) => {
@ -142,7 +126,7 @@ function createModifierGroup(modifierGroup, isInitiallyOpen, removeBy) {
e.appendChild(titleEl)
e.appendChild(modifiersEl)
editorModifierEntries.prepend(e)
editorModifierEntries.insertBefore(e, customModifierEntriesToolbar.nextSibling)
return e
}
@ -165,10 +149,7 @@ async function loadModifiers() {
res.reverse()
res.forEach((modifierGroup, idx) => {
const isInitiallyOpen = false // idx === res.length - 1
const removeBy = modifierGroup === "Artist" ? true : false // only remove "By " for artists
createModifierGroup(modifierGroup, isInitiallyOpen, removeBy)
createModifierGroup(modifierGroup, idx === res.length - 1, modifierGroup === "Artist" ? true : false) // only remove "By " for artists
})
createCollapsibles(editorModifierEntries)
@ -188,7 +169,7 @@ function refreshModifiersState(newTags, inactiveTags) {
.querySelector("#editor-modifiers")
.querySelectorAll(".modifier-card")
.forEach((modifierCard) => {
const modifierName = modifierCard.dataset.fullName // pick the full modifier name
const modifierName = modifierCard.querySelector(".modifier-card-label p").dataset.fullName // pick the full modifier name
if (activeTags.map((x) => x.name).includes(modifierName)) {
modifierCard.classList.remove(activeCardClass)
modifierCard.querySelector(".modifier-card-image-overlay").innerText = "+"
@ -203,9 +184,8 @@ function refreshModifiersState(newTags, inactiveTags) {
.querySelector("#editor-modifiers")
.querySelectorAll(".modifier-card")
.forEach((modifierCard) => {
const modifierName = modifierCard.dataset.fullName
const modifierName = modifierCard.querySelector(".modifier-card-label p").dataset.fullName
const shortModifierName = modifierCard.querySelector(".modifier-card-label p").innerText
if (trimModifiers(tag) == trimModifiers(modifierName)) {
// add modifier to active array
if (!activeTags.map((x) => x.name).includes(tag)) {
@ -262,10 +242,10 @@ function refreshInactiveTags(inactiveTags) {
}
// update cards
let overlays = editorModifierTagsList.querySelectorAll(".modifier-card-overlay")
let overlays = document.querySelector("#editor-inputs-tags-list").querySelectorAll(".modifier-card-overlay")
overlays.forEach((i) => {
let modifierName = i.parentElement.dataset.fullName
let modifierName = i.parentElement.getElementsByClassName("modifier-card-label")[0].getElementsByTagName("p")[0]
.dataset.fullName
if (inactiveTags?.find((element) => trimModifiers(element) === modifierName) !== undefined) {
i.parentElement.classList.add("modifier-toggle-inactive")
}
@ -282,12 +262,6 @@ function refreshTagsList(inactiveTags) {
editorTagsContainer.style.display = "block"
}
if(activeTags.length > 15) {
editorModifierTagsList.style["overflow-y"] = "auto"
} else {
editorModifierTagsList.style["overflow-y"] = "unset"
}
activeTags.forEach((tag, index) => {
tag.element.querySelector(".modifier-card-image-overlay").innerText = "-"
tag.element.classList.add("modifier-card-tiny")
@ -311,42 +285,48 @@ function refreshTagsList(inactiveTags) {
let brk = document.createElement("br")
brk.style.clear = "both"
editorModifierTagsList.appendChild(brk)
refreshInactiveTags(inactiveTags)
document.dispatchEvent(new Event("refreshImageModifiers")) // notify plugins that the image tags have been refreshed
}
function toggleCardState(modifierName, makeActive) {
const cards = [...document.querySelectorAll("#editor-modifiers .modifier-card")]
.filter(cardElem => trimModifiers(cardElem.dataset.fullName) == trimModifiers(modifierName))
const cardExists = typeof cards == "object" && cards?.length > 0
if (cardExists) {
const card = cards[0]
if (makeActive) {
card.classList.add(activeCardClass)
card.querySelector(".modifier-card-image-overlay").innerText = "-"
} else {
card.classList.remove(activeCardClass)
card.querySelector(".modifier-card-image-overlay").innerText = "+"
}
}
document
.querySelector("#editor-modifiers")
.querySelectorAll(".modifier-card")
.forEach((card) => {
const name = card.querySelector(".modifier-card-label").innerText
if (
trimModifiers(modifierName) == trimModifiers(name) ||
trimModifiers(modifierName) == "by " + trimModifiers(name)
) {
if (makeActive) {
card.classList.add(activeCardClass)
card.querySelector(".modifier-card-image-overlay").innerText = "-"
} else {
card.classList.remove(activeCardClass)
card.querySelector(".modifier-card-image-overlay").innerText = "+"
}
}
})
}
function changePreviewImages(val) {
const previewImages = document.querySelectorAll(".modifier-card-image-container img")
const previewArr = modifiers.flatMap((x) => x.modifiers.map((m) => m.previews))
.map((x) => x.reduce((obj, preview) => {
obj[preview.name] = preview.path
let previewArr = []
return obj
}, {}))
modifiers.map((x) => x.modifiers).forEach((x) => previewArr.push(...x.map((m) => m.previews)))
previewArr = previewArr.map((x) => {
let obj = {}
x.forEach((preview) => {
obj[preview.name] = preview.path
})
return obj
})
previewImages.forEach((previewImage) => {
const currentPreviewType = previewImage.getAttribute("preview-type")
@ -363,7 +343,7 @@ function changePreviewImages(val) {
preview = previews.landscape
}
if (preview) {
if (preview != null) {
previewImage.src = `${modifierThumbnailPath}/${preview}`
previewImage.setAttribute("preview-type", val)
}
@ -389,6 +369,34 @@ function resizeModifierCards(val) {
})
}
modifierCardSizeSlider.onchange = () => resizeModifierCards(modifierCardSizeSlider.value)
previewImageField.onchange = () => changePreviewImages(previewImageField.value)
modifierSettingsBtn.addEventListener("click", function(e) {
modifierSettingsOverlay.classList.add("active")
customModifiersTextBox.setSelectionRange(0, 0)
customModifiersTextBox.focus()
customModifiersInitialContent = customModifiersTextBox.value // preserve the initial content
e.stopPropagation()
})
modifierSettingsOverlay.addEventListener("keydown", function(e) {
switch (e.key) {
case "Escape": // Escape to cancel
customModifiersTextBox.value = customModifiersInitialContent // undo the changes
modifierSettingsOverlay.classList.remove("active")
e.stopPropagation()
break
case "Enter":
if (e.ctrlKey) {
// Ctrl+Enter to confirm
modifierSettingsOverlay.classList.remove("active")
e.stopPropagation()
break
}
}
})
function saveCustomModifiers() {
localStorage.setItem(CUSTOM_MODIFIERS_KEY, customModifiersTextBox.value.trim())
@ -399,156 +407,4 @@ function loadCustomModifiers() {
PLUGINS["MODIFIERS_LOAD"].forEach((fn) => fn.loader.call())
}
function showModifierContainer() {
document.addEventListener("mousedown", checkIfClickedOutsideDropdownElem)
modifierDropdown.dataset.active = true
editorModifiersContainer.classList.add("active")
}
function hideModifierContainer() {
document.removeEventListener("click", checkIfClickedOutsideDropdownElem)
modifierDropdown.dataset.active = false
editorModifiersContainer.classList.remove("active")
}
function checkIfClickedOutsideDropdownElem(e) {
const clickedElement = e.target
const clickedInsideSpecificElems = [modifierDropdown, editorModifiersContainer, modifierSettingsDialog].some((div) =>
div && (div.contains(clickedElement) || div === clickedElement))
if (!clickedInsideSpecificElems && !modifierPanelFreezed) {
hideModifierContainer()
}
}
function collapseAllModifierCategory() {
collapseAll(".modifier-category .collapsible")
}
function expandAllModifierCategory() {
expandAll(".modifier-category .collapsible")
}
customModifiersTextBox.addEventListener("change", saveCustomModifiers)
modifierCardSizeSlider.onchange = () => resizeModifierCards(modifierCardSizeSlider.value)
previewImageField.onchange = () => changePreviewImages(previewImageField.value)
modifierSettingsDialog.addEventListener("keydown", function(e) {
switch (e.key) {
case "Escape": // Escape to cancel
customModifiersTextBox.value = customModifiersInitialContent // undo the changes
modifierSettingsDialog.close()
e.stopPropagation()
break
case "Enter":
if (e.ctrlKey) {
// Ctrl+Enter to confirm
modifierSettingsDialog.close()
e.stopPropagation()
break
}
}
})
modifierDropdown.addEventListener("click", e => {
const targetElem = e.target
const isDropdownActive = targetElem.dataset.active == "true" ? true : false
if (!isDropdownActive)
showModifierContainer()
else
hideModifierContainer()
})
let collapsiblesBtnState = false
modifiersCollapsiblesBtn.addEventListener("click", (e) => {
const btnElem = modifiersCollapsiblesBtn
const collapseText = "Collapse Categories"
const expandText = "Expand Categories"
const collapseIconClasses = ["fa-solid", "fa-square-minus"]
const expandIconClasses = ["fa-solid", "fa-square-plus"]
const iconElem = btnElem.querySelector(".modifiers-action-icon")
const textElem = btnElem.querySelector(".modifiers-action-text")
if (collapsiblesBtnState) {
collapseAllModifierCategory()
collapsiblesBtnState = false
collapseIconClasses.forEach((c) => iconElem.classList.remove(c))
expandIconClasses.forEach((c) => iconElem.classList.add(c))
textElem.innerText = expandText
} else {
expandAllModifierCategory()
collapsiblesBtnState = true
expandIconClasses.forEach((c) => iconElem.classList.remove(c))
collapseIconClasses.forEach((c) => iconElem.classList.add(c))
textElem.innerText = collapseText
}
})
let containerSizeBtnState = false
modifiersContainerSizeBtn.addEventListener("click", (e) => {
const btnElem = modifiersContainerSizeBtn
const maximizeIconClasses = ["fa-solid", "fa-expand"]
const revertIconClasses = ["fa-solid", "fa-compress"]
modifiersMainContainer.classList.toggle("modifiers-maximized")
if(containerSizeBtnState) {
revertIconClasses.forEach((c) => btnElem.classList.remove(c))
maximizeIconClasses.forEach((c) => btnElem.classList.add(c))
containerSizeBtnState = false
} else {
maximizeIconClasses.forEach((c) => btnElem.classList.remove(c))
revertIconClasses.forEach((c) => btnElem.classList.add(c))
containerSizeBtnState = true
}
})
modifierSettingsBtn.addEventListener("click", (e) => {
modifierSettingsDialog.showModal()
customModifiersTextBox.setSelectionRange(0, 0)
customModifiersTextBox.focus()
customModifiersInitialContent = customModifiersTextBox.value // preserve the initial content
e.stopPropagation()
})
modifiersCloseBtn.addEventListener("click", (e) => {
hideModifierContainer()
})
// prevents the modifier panel closing at the same time as the settings overlay
new MutationObserver(() => {
const isActive = modifierSettingsDialog.open
if (!isActive) {
modifierPanelFreezed = true
setTimeout(() => modifierPanelFreezed = false, 25)
}
}).observe(modifierSettingsDialog, { attributes: true })
modifierSettingsCloseBtn.addEventListener("click", (e) => {
modifierSettingsDialog.close()
})
modalDialogCloseOnBackdropClick(modifierSettingsDialog)
makeDialogDraggable(modifierSettingsDialog)

File diff suppressed because it is too large Load Diff

View File

@ -1,256 +0,0 @@
/**
* A component consisting of multiple model dropdowns, along with a "weight" field per model.
*
* Behaves like a single input element, giving an object in response to the .value field.
*
* Inspired by the design of the ModelDropdown component (searchable-models.js).
*/
class MultiModelSelector {
root
modelType
modelNameFriendly
defaultWeight
weightStep
modelContainer
addNewButton
counter = 0
/* MIMIC A REGULAR INPUT FIELD */
get id() {
return this.root.id
}
get parentElement() {
return this.root.parentElement
}
get parentNode() {
return this.root.parentNode
}
get value() {
return { modelNames: this.modelNames, modelWeights: this.modelWeights }
}
set value(modelData) {
if (typeof modelData !== "object") {
throw new Error("Multi-model selector expects an object containing modelNames and modelWeights as keys!")
}
if (!("modelNames" in modelData) || !("modelWeights" in modelData)) {
throw new Error("modelNames or modelWeights not present in the data passed to the multi-model selector")
}
let newModelNames = modelData["modelNames"]
let newModelWeights = modelData["modelWeights"]
if (newModelNames.length !== newModelWeights.length) {
throw new Error("Need to pass an equal number of modelNames and modelWeights!")
}
// update weight first, name second.
// for some unholy reason this order matters for dispatch chains
// the root of all this unholiness is because searchable-models automatically dispatches an update event
// as soon as the value is updated via JS, which is against the DOM pattern of not dispatching an event automatically
// unless the caller explicitly dispatches the event.
this.modelWeights = newModelWeights
this.modelNames = newModelNames
}
get disabled() {
return false
}
set disabled(state) {
// do nothing
}
getModelElements(ignoreEmpty = false) {
let entries = this.root.querySelectorAll(".model_entry")
entries = [...entries]
let elements = entries.map((e) => {
let modelName = e.querySelector(".model_name").field
let modelWeight = e.querySelector(".model_weight")
if (ignoreEmpty && modelName.value.trim() === "") {
return null
}
return { name: modelName, weight: modelWeight }
})
elements = elements.filter((e) => e !== null)
return elements
}
addEventListener(type, listener, options) {
// do nothing
}
dispatchEvent(event) {
// do nothing
}
appendChild(option) {
// do nothing
}
// remember 'this' - http://blog.niftysnippets.org/2008/04/you-must-remember-this.html
bind(f, obj) {
return function() {
return f.apply(obj, arguments)
}
}
constructor(root, modelType, modelNameFriendly = undefined, defaultWeight = 0.5, weightStep = 0.02) {
this.root = root
this.modelType = modelType
this.modelNameFriendly = modelNameFriendly || modelType
this.defaultWeight = defaultWeight
this.weightStep = weightStep
let self = this
document.addEventListener("refreshModels", function() {
setTimeout(self.bind(self.populateModels, self), 1)
})
this.createStructure()
this.populateModels()
}
createStructure() {
this.modelContainer = document.createElement("div")
this.modelContainer.className = "model_entries"
this.root.appendChild(this.modelContainer)
this.addNewButton = document.createElement("button")
this.addNewButton.className = "add_model_entry"
this.addNewButton.innerHTML = '<i class="fa-solid fa-plus"></i> add another ' + this.modelNameFriendly
this.addNewButton.addEventListener("click", this.bind(this.addModelEntry, this))
this.root.appendChild(this.addNewButton)
}
populateModels() {
if (this.root.dataset.path === "") {
if (this.length === 0) {
this.addModelEntry() // create a single blank entry
}
} else {
this.value = JSON.parse(this.root.dataset.path)
}
}
addModelEntry() {
let idx = this.counter++
let currLength = this.length
const modelElement = document.createElement("div")
modelElement.className = "model_entry"
modelElement.innerHTML = `
<input id="${this.modelType}_${idx}" class="model_name model-filter" type="text" spellcheck="false" autocomplete="off" data-path="" />
<input class="model_weight" type="number" step="${this.weightStep}" value="${this.defaultWeight}" pattern="^-?[0-9]*\.?[0-9]*$" onkeypress="preventNonNumericalInput(event)">
`
this.modelContainer.appendChild(modelElement)
let modelNameEl = modelElement.querySelector(".model_name")
modelNameEl.field = new ModelDropdown(modelNameEl, this.modelType, "None")
let modelWeightEl = modelElement.querySelector(".model_weight")
let self = this
function makeUpdateEvent(type) {
return function(e) {
e.stopPropagation()
let modelData = self.value
self.root.dataset.path = JSON.stringify(modelData)
self.root.dispatchEvent(new Event(type))
}
}
modelNameEl.addEventListener("change", makeUpdateEvent("change"))
modelNameEl.addEventListener("input", makeUpdateEvent("input"))
modelWeightEl.addEventListener("change", makeUpdateEvent("change"))
modelWeightEl.addEventListener("input", makeUpdateEvent("input"))
let removeBtn = document.createElement("button")
removeBtn.className = "remove_model_btn"
removeBtn.setAttribute("title", "Remove model")
removeBtn.innerHTML = '<i class="fa-solid fa-minus"></i>'
if (currLength === 0) {
removeBtn.classList.add("displayNone")
}
removeBtn.addEventListener(
"click",
this.bind(function(e) {
this.modelContainer.removeChild(modelElement)
makeUpdateEvent("change")(e)
}, this)
)
modelElement.appendChild(removeBtn)
}
removeModelEntry() {
if (this.length === 0) {
return
}
let lastEntry = this.modelContainer.lastElementChild
lastEntry.remove()
}
get length() {
return this.getModelElements().length
}
get modelNames() {
return this.getModelElements(true).map((e) => e.name.value)
}
set modelNames(newModelNames) {
this.resizeEntryList(newModelNames.length)
if (newModelNames.length === 0) {
this.getModelElements()[0].name.value = ""
}
// assign to the corresponding elements
let currElements = this.getModelElements()
for (let i = 0; i < newModelNames.length; i++) {
let curr = currElements[i]
curr.name.value = newModelNames[i]
}
}
get modelWeights() {
return this.getModelElements(true).map((e) => e.weight.value)
}
set modelWeights(newModelWeights) {
this.resizeEntryList(newModelWeights.length)
if (newModelWeights.length === 0) {
this.getModelElements()[0].weight.value = this.defaultWeight
}
// assign to the corresponding elements
let currElements = this.getModelElements()
for (let i = 0; i < newModelWeights.length; i++) {
let curr = currElements[i]
curr.weight.value = newModelWeights[i]
}
}
resizeEntryList(newLength) {
if (newLength === 0) {
newLength = 1
}
let currLength = this.length
if (currLength < newLength) {
for (let i = currLength; i < newLength; i++) {
this.addModelEntry()
}
} else {
for (let i = newLength; i < currLength; i++) {
this.removeModelEntry()
}
}
}
}

View File

@ -11,13 +11,6 @@ var ParameterType = {
custom: "custom",
}
/**
* Element shortcuts
*/
let parametersTable = document.querySelector("#system-settings-table")
let networkParametersTable = document.querySelector("#system-settings-network-table")
let installExtrasTable = document.querySelector("#system-settings-install-extras-table")
/**
* JSDoc style
* @typedef {object} Parameter
@ -97,17 +90,6 @@ var PARAMETERS = [
},
],
},
{
id: "models_dir",
type: ParameterType.custom,
icon: "fa-folder-tree",
label: "Models Folder",
note: "Path to the 'models' folder. Please save and refresh the page after changing this.",
saveInAppConfig: true,
render: (parameter) => {
return `<input id="${parameter.id}" name="${parameter.id}" size="30">`
},
},
{
id: "block_nsfw",
type: ParameterType.checkbox,
@ -132,15 +114,6 @@ var PARAMETERS = [
icon: "fa-arrow-down-short-wide",
default: false,
},
{
id: "extract_lora_from_prompt",
type: ParameterType.checkbox,
label: "Extract LoRA tags from the prompt",
note:
"Automatically extract lora tags like &lt;lora:name:0.4&gt; from the prompt, and apply the correct LoRA (if present)",
icon: "fa-code",
default: true,
},
{
id: "ui_open_browser_on_start",
type: ParameterType.checkbox,
@ -205,17 +178,6 @@ var PARAMETERS = [
icon: "fa-check-double",
default: true,
},
{
id: "profileName",
type: ParameterType.custom,
label: "Profile Name",
note:
"Name of the profile for model manager settings, e.g. thumbnails for embeddings. Use this to have different settings for different users.",
render: (parameter) => {
return `<input id="${parameter.id}" name="${parameter.id}" value="default" size="12">`
},
icon: "fa-user-gear",
},
{
id: "listen_to_network",
type: ParameterType.checkbox,
@ -224,7 +186,6 @@ var PARAMETERS = [
icon: "fa-network-wired",
default: true,
saveInAppConfig: true,
table: networkParametersTable,
},
{
id: "listen_port",
@ -237,7 +198,6 @@ var PARAMETERS = [
return `<input id="${parameter.id}" name="${parameter.id}" size="6" value="9000" onkeypress="preventNonNumericalInput(event)">`
},
saveInAppConfig: true,
table: networkParametersTable,
},
{
id: "use_beta_channel",
@ -249,53 +209,15 @@ var PARAMETERS = [
default: false,
},
{
id: "use_v3_engine",
id: "test_diffusers",
type: ParameterType.checkbox,
label: "Use the new v3 engine (diffusers)",
label: "Test Diffusers",
note:
"Use our new v3 engine, with additional features like LoRA, ControlNet, SDXL, Embeddings, Tiling and lots more! Please press Save, then restart the program after changing this.",
"<b>Experimental! Can have bugs!</b> Use upcoming features (like LoRA) in our new engine. Please press Save, then restart the program after changing this.",
icon: "fa-bolt",
default: true,
default: false,
saveInAppConfig: true,
},
{
id: "cloudflare",
type: ParameterType.custom,
label: "Cloudflare tunnel",
note: `<span id="cloudflare-off">Create a VPN tunnel to share your Easy Diffusion instance with your friends. This will
generate a web server address on the public Internet for your Easy Diffusion instance. </span>
<div id="cloudflare-on" class="displayNone"><div>This Easy Diffusion server is available on the Internet using the
address:</div><div><input id="cloudflare-address" value="" readonly><button id="copy-cloudflare-address">Copy</button></div></div>
<b>Anyone knowing this address can access your server.</b> The address of your server will change each time
you share a session.<br>
Uses <a href="https://try.cloudflare.com/" target="_blank">Cloudflare services</a>.`,
icon: ["fa-brands", "fa-cloudflare"],
render: () => '<button id="toggle-cloudflare-tunnel" class="primaryButton">Start</button>',
table: networkParametersTable,
},
{
id: "nvidia_tensorrt",
type: ParameterType.custom,
label: "NVIDIA TensorRT",
note: `Faster image generation by converting your Stable Diffusion models to the NVIDIA TensorRT format. You can choose the
models to convert. Download size: approximately 2 GB.<br/><br/>
<b>Early access version:</b> support for LoRA is still under development.
<div id="trt-build-config" class="displayNone">
<h3>Build Config:</h3>
Batch size range:
<label>Min:</label> <input id="trt-build-min-batch" type="number" min="1" value="1" style="width: 40pt" />
<label>Max:</label> <input id="trt-build-max-batch" type="number" min="1" value="1" style="width: 40pt" /><br/><br/>
<b>Build for resolutions</b>:<br/>
<input id="trt-build-res-512" type="checkbox" value="1" /> 512x512 to 768x768<br/>
<input id="trt-build-res-768" type="checkbox" value="1" checked /> 768x768 to 1024x1024<br/>
<input id="trt-build-res-1024" type="checkbox" value="1" /> 1024x1024 to 1280x1280<br/>
<input id="trt-build-res-1280" type="checkbox" value="1" /> 1280x1280 to 1536x1536<br/>
<input id="trt-build-res-1536" type="checkbox" value="1" /> 1536x1536 to 1792x1792<br/>
</div>`,
icon: "fa-angles-up",
render: () => '<button id="toggle-tensorrt-install" class="primaryButton">Install</button>',
table: installExtrasTable,
},
]
function getParameterSettingsEntry(id) {
@ -344,6 +266,7 @@ function getParameterElement(parameter) {
}
}
let parametersTable = document.querySelector("#system-settings .parameters-table")
/**
* fill in the system settings popup table
* @param {Array<Parameter> | undefined} parameters
@ -370,10 +293,7 @@ function initParameters(parameters) {
noteElements.push(noteElement)
}
if (typeof parameter.icon == "string") {
parameter.icon = [parameter.icon]
}
const icon = parameter.icon ? [createElement("i", undefined, ["fa", ...parameter.icon])] : []
const icon = parameter.icon ? [createElement("i", undefined, ["fa", parameter.icon])] : []
const label = typeof parameter.label === "function" ? parameter.label(parameter) : parameter.label
const labelElement = createElement("label", { for: parameter.id })
@ -393,13 +313,7 @@ function initParameters(parameters) {
elementWrapper,
]
)
let p = parametersTable
if (parameter.table) {
p = parameter.table
}
p.appendChild(newrow)
parametersTable.appendChild(newrow)
parameter.settingsEntry = newrow
})
}
@ -431,9 +345,7 @@ let listenPortField = document.querySelector("#listen_port")
let useBetaChannelField = document.querySelector("#use_beta_channel")
let uiOpenBrowserOnStartField = document.querySelector("#ui_open_browser_on_start")
let confirmDangerousActionsField = document.querySelector("#confirm_dangerous_actions")
let testDiffusers = document.querySelector("#use_v3_engine")
let profileNameField = document.querySelector("#profileName")
let modelsDirField = document.querySelector("#models_dir")
let testDiffusers = document.querySelector("#test_diffusers")
let saveSettingsBtn = document.querySelector("#save-system-settings-btn")
@ -465,6 +377,8 @@ async function getAppConfig() {
if (config.update_branch === "beta") {
useBetaChannelField.checked = true
document.querySelector("#updateBranchLabel").innerText = "(beta)"
} else {
getParameterSettingsEntry("test_diffusers").style.display = "none"
}
if (config.ui && config.ui.open_browser_on_start === false) {
uiOpenBrowserOnStartField.checked = false
@ -475,58 +389,27 @@ async function getAppConfig() {
if (config.net && config.net.listen_port !== undefined) {
listenPortField.value = config.net.listen_port
}
modelsDirField.value = config.models_dir
let testDiffusersEnabled = true
if (config.use_v3_engine === false) {
testDiffusersEnabled = false
}
const testDiffusersEnabled = config.test_diffusers && config.update_branch !== "main"
testDiffusers.checked = testDiffusersEnabled
document.querySelector("#test_diffusers").checked = testDiffusers.checked // don't break plugins
if (config.config_on_startup) {
if (config.config_on_startup?.use_v3_engine) {
document.body.classList.add("diffusers-enabled-on-startup")
document.body.classList.remove("diffusers-disabled-on-startup")
} else {
document.body.classList.add("diffusers-disabled-on-startup")
document.body.classList.remove("diffusers-enabled-on-startup")
}
}
if (!testDiffusersEnabled) {
document.querySelector("#lora_model_container").style.display = "none"
document.querySelector("#lora_alpha_container").style.display = "none"
document.querySelector("#tiling_container").style.display = "none"
document.querySelector("#controlnet_model_container").style.display = "none"
document.querySelector("#hypernetwork_model_container").style.display = ""
document.querySelector("#hypernetwork_strength_container").style.display = ""
document.querySelector("#negative-embeddings-button").style.display = "none"
document.querySelectorAll("#sampler_name option.diffusers-only").forEach((option) => {
option.style.display = "none"
})
IMAGE_STEP_SIZE = 64
customWidthField.step = IMAGE_STEP_SIZE
customHeightField.step = IMAGE_STEP_SIZE
} else {
document.querySelector("#lora_model_container").style.display = ""
document.querySelector("#lora_alpha_container").style.display = loraModelField.value ? "" : "none"
document.querySelector("#tiling_container").style.display = ""
document.querySelector("#controlnet_model_container").style.display = ""
document.querySelector("#hypernetwork_model_container").style.display = "none"
document.querySelector("#hypernetwork_strength_container").style.display = "none"
document.querySelectorAll("#sampler_name option.k_diffusion-only").forEach((option) => {
option.style.display = "none"
option.disabled = true
})
document.querySelector("#clip_skip_config").classList.remove("displayNone")
document.querySelector("#embeddings-button").classList.remove("displayNone")
IMAGE_STEP_SIZE = 8
customWidthField.step = IMAGE_STEP_SIZE
customHeightField.step = IMAGE_STEP_SIZE
}
if (config.force_save_metadata) {
metadataOutputFormatField.value = config.force_save_metadata
}
console.log("get config status response", config)
@ -642,7 +525,7 @@ function setDeviceInfo(devices) {
function ID_TO_TEXT(d) {
let info = devices.all[d]
if ("mem_free" in info && "mem_total" in info && info["mem_total"] > 0) {
if ("mem_free" in info && "mem_total" in info) {
return `${info.name} <small>(${d}) (${info.mem_free.toFixed(1)}Gb free / ${info.mem_total.toFixed(
1
)} Gb total)</small>`
@ -658,23 +541,6 @@ function setDeviceInfo(devices) {
systemInfoEl.querySelector("#system-info-cpu").innerText = cpu
systemInfoEl.querySelector("#system-info-gpus-all").innerHTML = allGPUs.join("</br>")
systemInfoEl.querySelector("#system-info-rendering-devices").innerHTML = activeGPUs.join("</br>")
// tensorRT
if (devices.active && testDiffusers.checked && devices.enable_trt === true) {
let nvidiaGPUs = Object.keys(devices.active).filter((d) => {
let gpuName = devices.active[d].name
gpuName = gpuName.toLowerCase()
return (
gpuName.includes("nvidia") ||
gpuName.includes("geforce") ||
gpuName.includes("quadro") ||
gpuName.includes("tesla")
)
})
if (nvidiaGPUs.length > 0) {
document.querySelector("#install-extras-container").classList.remove("displayNone")
}
}
}
function setHostInfo(hosts) {
@ -740,13 +606,10 @@ async function getSystemInfo() {
force = res["enforce_output_dir"]
if (force == true) {
saveToDiskField.checked = true
metadataOutputFormatField.disabled = res["enforce_output_metadata"]
diskPathField.disabled = true
metadataOutputFormatField.disabled = false
}
saveToDiskField.disabled = force
} else {
diskPathField.disabled = !saveToDiskField.checked
metadataOutputFormatField.disabled = !saveToDiskField.checked
diskPathField.disabled = force
}
setDiskPath(res["default_output_dir"], force)
} catch (e) {
@ -770,7 +633,7 @@ saveSettingsBtn.addEventListener("click", function() {
update_branch: updateBranch,
}
document.querySelectorAll("#system-settings [data-setting-id]").forEach((parameterRow) => {
Array.from(parametersTable.children).forEach((parameterRow) => {
if (parameterRow.dataset.saveInAppConfig === "true") {
const parameterElement =
document.getElementById(parameterRow.dataset.settingId) ||
@ -804,38 +667,8 @@ saveSettingsBtn.addEventListener("click", function() {
})
const savePromise = changeAppConfig(updateAppConfigRequest)
showToast("Settings saved")
saveSettingsBtn.classList.add("active")
Promise.all([savePromise, asyncDelay(300)]).then(() => saveSettingsBtn.classList.remove("active"))
})
listenToNetworkField.addEventListener(
"change",
debounce(() => {
saveSettingsBtn.click()
}, 1000)
)
listenPortField.addEventListener(
"change",
debounce(() => {
saveSettingsBtn.click()
}, 1000)
)
let copyCloudflareAddressBtn = document.querySelector("#copy-cloudflare-address")
let cloudflareAddressField = document.getElementById("cloudflare-address")
navigator.permissions.query({ name: "clipboard-write" }).then(function(result) {
if (result.state === "granted") {
// you can read from the clipboard
copyCloudflareAddressBtn.addEventListener("click", (e) => {
navigator.clipboard.writeText(cloudflareAddressField.innerHTML)
showToast("Copied server address to clipboard")
})
} else {
copyCloudflareAddressBtn.classList.add("displayNone")
}
})
document.addEventListener("system_info_update", (e) => setDeviceInfo(e.detail))

View File

@ -1,8 +1,5 @@
const PLUGIN_API_VERSION = "1.0"
const PLUGIN_CATALOG = 'https://raw.githubusercontent.com/easydiffusion/easydiffusion-plugins/main/plugins.json'
const PLUGIN_CATALOG_GITHUB = 'https://github.com/easydiffusion/easydiffusion-plugins/blob/main/plugins.json'
const PLUGINS = {
/**
* Register new buttons to show on each output image.
@ -81,950 +78,3 @@ async function loadUIPlugins() {
console.log("error fetching plugin paths", e)
}
}
/* PLUGIN MANAGER */
/* plugin tab */
// document.querySelector('.tab-container')?.insertAdjacentHTML('beforeend', `
// <span id="tab-plugin" class="tab" style="display: none">
// <span><i class="fa fa-puzzle-piece icon"></i> Plugins</span>
// </span>
// `)
// document.querySelector('#tab-content-wrapper')?.insertAdjacentHTML('beforeend', `
// <div id="tab-content-plugin" class="tab-content">
// <div id="plugin" class="tab-content-inner">
// Loading...
// </div>
// </div>
// `)
// const tabPlugin = document.querySelector('#tab-plugin')
// if (tabPlugin) {
// linkTabContents(tabPlugin)
// }
// const plugin = document.querySelector('#plugin')
// plugin.innerHTML = `
// <div id="plugin-manager" class="tab-content-inner">
// <i id="plugin-notification-button" class="fa-solid fa-message">
// <span class="plugin-notification-pill" id="notification-pill" style="display: none"></span>
// </i>
// <div id="plugin-notification-list" style="display: none">
// <h1>Notifications</h1>
// <div class="plugin-manager-intro">The latest plugin updates are listed below</div>
// <div class="notifications-table"></div>
// <div class="no-notification">No new notifications</div>
// </div>
// <div id="plugin-manager-section">
// <h1>Plugin Manager</h1>
// <div class="plugin-manager-intro">Changes take effect after reloading the page</div>
// <div class="plugins-table"></div>
// </div>
// </div>`
// const pluginsTable = document.querySelector("#plugin-manager-section .plugins-table")
// const pluginNotificationTable = document.querySelector("#plugin-notification-list .notifications-table")
// const pluginNoNotification = document.querySelector("#plugin-notification-list .no-notification")
// /* notification center */
// const pluginNotificationButton = document.getElementById("plugin-notification-button");
// const pluginNotificationList = document.getElementById("plugin-notification-list");
// const notificationPill = document.getElementById("notification-pill");
// const pluginManagerSection = document.getElementById("plugin-manager-section");
// let pluginNotifications;
// // Add event listener to show/hide the action center
// pluginNotificationButton.addEventListener("click", function () {
// // Hide the notification pill when the action center is opened
// notificationPill.style.display = "none"
// pluginNotifications.lastUpdated = Date.now()
// // save the notifications
// setStorageData('notifications', JSON.stringify(pluginNotifications))
// renderPluginNotifications()
// if (pluginNotificationList.style.display === "none") {
// pluginNotificationList.style.display = "block"
// pluginManagerSection.style.display = "none"
// } else {
// pluginNotificationList.style.display = "none"
// pluginManagerSection.style.display = "block"
// }
// })
// document.addEventListener("tabClick", (e) => {
// if (e.detail.name == 'plugin') {
// pluginNotificationList.style.display = "none"
// pluginManagerSection.style.display = "block"
// }
// })
// async function addPluginNotification(pluginNotifications, messageText, error) {
// const now = Date.now()
// pluginNotifications.entries.unshift({ date: now, text: messageText, error: error }); // add new entry to the beginning of the array
// if (pluginNotifications.entries.length > 50) {
// pluginNotifications.entries.length = 50 // limit array length to 50 entries
// }
// pluginNotifications.lastUpdated = now
// notificationPill.style.display = "block"
// // save the notifications
// await setStorageData('notifications', JSON.stringify(pluginNotifications))
// }
// function timeAgo(inputDate) {
// const now = new Date();
// const date = new Date(inputDate);
// const diffInSeconds = Math.floor((now - date) / 1000);
// const units = [
// { name: 'year', seconds: 31536000 },
// { name: 'month', seconds: 2592000 },
// { name: 'week', seconds: 604800 },
// { name: 'day', seconds: 86400 },
// { name: 'hour', seconds: 3600 },
// { name: 'minute', seconds: 60 },
// { name: 'second', seconds: 1 }
// ];
// for (const unit of units) {
// const unitValue = Math.floor(diffInSeconds / unit.seconds);
// if (unitValue > 0) {
// return `${unitValue} ${unit.name}${unitValue > 1 ? 's' : ''} ago`;
// }
// }
// return 'just now';
// }
// function convertSeconds(seconds) {
// const hours = Math.floor(seconds / 3600);
// const minutes = Math.floor((seconds % 3600) / 60);
// const remainingSeconds = seconds % 60;
// let timeParts = [];
// if (hours === 1) {
// timeParts.push(`${hours} hour`);
// } else if (hours > 1) {
// timeParts.push(`${hours} hours`);
// }
// if (minutes === 1) {
// timeParts.push(`${minutes} minute`);
// } else if (minutes > 1) {
// timeParts.push(`${minutes} minutes`);
// }
// if (remainingSeconds === 1) {
// timeParts.push(`${remainingSeconds} second`);
// } else if (remainingSeconds > 1) {
// timeParts.push(`${remainingSeconds} seconds`);
// }
// return timeParts.join(', and ');
// }
// function renderPluginNotifications() {
// pluginNotificationTable.innerHTML = ''
// if (pluginNotifications.entries?.length > 0) {
// pluginNoNotification.style.display = "none"
// pluginNotificationTable.style.display = "block"
// }
// else {
// pluginNoNotification.style.display = "block"
// pluginNotificationTable.style.display = "none"
// }
// for (let i = 0; i < pluginNotifications.entries?.length; i++) {
// const date = pluginNotifications.entries[i].date
// const text = pluginNotifications.entries[i].text
// const error = pluginNotifications.entries[i].error
// const newRow = document.createElement('div')
// newRow.innerHTML = `
// <div${error === true ? ' class="notification-error"' : ''}>${text}</div>
// <div><small>${timeAgo(date)}</small></div>
// `;
// pluginNotificationTable.appendChild(newRow)
// }
// }
// /* search box */
// function filterPlugins() {
// let search = pluginFilter.value.toLowerCase();
// let searchTerms = search.split(' ');
// let labels = pluginsTable.querySelectorAll("label.plugin-name");
// for (let i = 0; i < labels.length; i++) {
// let label = labels[i].innerText.toLowerCase();
// let match = true;
// for (let j = 0; j < searchTerms.length; j++) {
// let term = searchTerms[j].trim();
// if (term && label.indexOf(term) === -1) {
// match = false;
// break;
// }
// }
// if (match) {
// labels[i].closest('.plugin-container').style.display = "flex";
// } else {
// labels[i].closest('.plugin-container').style.display = "none";
// }
// }
// }
// // Call debounce function on filterImageModifierList function with 200ms wait time. Thanks JeLuf!
// const debouncedFilterPlugins = debounce(filterPlugins, 200);
// // add the searchbox
// pluginsTable.insertAdjacentHTML('beforebegin', `<input type="text" id="plugin-filter" placeholder="Search for..." autocomplete="off"/>`)
// const pluginFilter = document.getElementById("plugin-filter") // search box
// // Add the debounced function to the keyup event listener
// pluginFilter.addEventListener('keyup', debouncedFilterPlugins);
// // select the text on focus
// pluginFilter.addEventListener('focus', function (event) {
// pluginFilter.select()
// });
// // empty the searchbox on escape
// pluginFilter.addEventListener('keydown', function (event) {
// if (event.key === 'Escape') {
// pluginFilter.value = '';
// filterPlugins();
// }
// });
// // focus on the search box upon tab selection
// document.addEventListener("tabClick", (e) => {
// if (e.detail.name == 'plugin') {
// pluginFilter.focus()
// }
// })
// // refresh link
// pluginsTable.insertAdjacentHTML('afterend', `<p id="refresh-plugins"><small><a id="refresh-plugins-link">Refresh plugins</a></small></p>
// <p><small>(Plugin developers, add your plugins to <a href='${PLUGIN_CATALOG_GITHUB}' target='_blank'>plugins.json</a>)</small></p>`)
// const refreshPlugins = document.getElementById("refresh-plugins")
// refreshPlugins.addEventListener("click", async function (event) {
// event.preventDefault()
// await initPlugins(true)
// })
// function showPluginToast(message, duration = 5000, error = false, addNotification = true) {
// if (addNotification === true) {
// addPluginNotification(pluginNotifications, message, error)
// }
// try {
// showToast(message, duration, error)
// } catch (error) {
// console.error('Error while trying to show toast:', error);
// }
// }
// function matchPluginFileNames(fileName1, fileName2) {
// const regex = /^(.+?)(?:-\d+(\.\d+)*)?\.plugin\.js$/;
// const match1 = fileName1.match(regex);
// const match2 = fileName2.match(regex);
// if (match1 && match2 && match1[1] === match2[1]) {
// return true; // the two file names match
// } else {
// return false; // the two file names do not match
// }
// }
// function extractFilename(filepath) {
// // Normalize the path separators to forward slashes and make the file names lowercase
// const normalizedFilePath = filepath.replace(/\\/g, "/").toLowerCase();
// // Strip off the path from the file name
// const fileName = normalizedFilePath.substring(normalizedFilePath.lastIndexOf("/") + 1);
// return fileName
// }
// function checkFileNameInArray(paths, filePath) {
// // Strip off the path from the file name
// const fileName = extractFilename(filePath);
// // Check if the file name exists in the array of paths
// return paths.some(path => {
// // Strip off the path from the file name
// const baseName = extractFilename(path);
// // Check if the file names match and return the result as a boolean
// return matchPluginFileNames(fileName, baseName);
// });
// }
// function isGitHub(url) {
// return url.startsWith("https://raw.githubusercontent.com/") === true
// }
// /* fill in the plugins table */
// function getIncompatiblePlugins(pluginId) {
// const enabledPlugins = plugins.filter(plugin => plugin.enabled && plugin.id !== pluginId);
// const incompatiblePlugins = enabledPlugins.filter(plugin => plugin.compatIssueIds?.includes(pluginId));
// const pluginNames = incompatiblePlugins.map(plugin => plugin.name);
// if (pluginNames.length === 0) {
// return null;
// }
// const pluginNamesList = pluginNames.map(name => `<li>${name}</li>`).join('');
// return `<ul>${pluginNamesList}</ul>`;
// }
// async function initPluginTable(plugins) {
// pluginsTable.innerHTML = ''
// plugins.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }))
// plugins.forEach(plugin => {
// const name = plugin.name
// const author = plugin.author ? ', by ' + plugin.author : ''
// const version = plugin.version ? ' (version: ' + plugin.version + ')' : ''
// const warning = getIncompatiblePlugins(plugin.id) ? `<span class="plugin-warning${plugin.enabled ? '' : ' hide'}">This plugin might conflict with:${getIncompatiblePlugins(plugin.id)}</span>` : ''
// const note = plugin.description ? `<small>${plugin.description.replaceAll('\n', '<br>')}</small>` : `<small>No description</small>`;
// const icon = plugin.icon ? `<i class="fa ${plugin.icon}"></i>` : '<i class="fa fa-puzzle-piece"></i>';
// const newRow = document.createElement('div')
// const localPluginFound = checkFileNameInArray(localPlugins, plugin.url)
// newRow.innerHTML = `
// <div>${icon}</div>
// <div><label class="plugin-name">${name}${author}${version}</label>${warning}${note}<span class='plugin-source'>Source: <a href="${plugin.url}" target="_blank">${extractFilename(plugin.url)}</a><span></div>
// <div>
// ${localPluginFound ? "<span class='plugin-installed-locally'>Installed locally</span>" :
// (plugin.localInstallOnly ? '<span class="plugin-installed-locally">Download and<br />install manually</span>' :
// (isGitHub(plugin.url) ?
// '<input id="plugin-' + plugin.id + '" name="plugin-' + plugin.id + '" type="checkbox">' :
// '<button id="plugin-' + plugin.id + '-install" class="tertiaryButton"></button>'
// )
// )
// }
// </div>`;
// newRow.classList.add('plugin-container')
// //console.log(plugin.id, plugin.localInstallOnly)
// pluginsTable.appendChild(newRow)
// const pluginManualInstall = pluginsTable.querySelector('#plugin-' + plugin.id + '-install')
// updateManualInstallButtonCaption()
// // checkbox event handler
// const pluginToggle = pluginsTable.querySelector('#plugin-' + plugin.id)
// if (pluginToggle !== null) {
// pluginToggle.checked = plugin.enabled // set initial state of checkbox
// pluginToggle.addEventListener('change', async () => {
// const container = pluginToggle.closest(".plugin-container");
// const warningElement = container.querySelector(".plugin-warning");
// // if the plugin got enabled, download the plugin's code
// plugin.enabled = pluginToggle.checked
// if (plugin.enabled) {
// const pluginSource = await getDocument(plugin.url);
// if (pluginSource !== null) {
// // Store the current scroll position before navigating away
// const currentPosition = window.pageYOffset;
// initPluginTable(plugins)
// // When returning to the page, set the scroll position to the stored value
// window.scrollTo(0, currentPosition);
// warningElement?.classList.remove("hide");
// plugin.code = pluginSource
// loadPlugins([plugin])
// console.log(`Plugin ${plugin.name} installed`);
// showPluginToast("Plugin " + plugin.name + " installed");
// }
// else {
// plugin.enabled = false
// pluginToggle.checked = false
// console.error(`Couldn't download plugin ${plugin.name}`);
// showPluginToast("Failed to install " + plugin.name + " (Couldn't fetch " + extractFilename(plugin.url) + ")", 5000, true);
// }
// } else {
// warningElement?.classList.add("hide");
// // Store the current scroll position before navigating away
// const currentPosition = window.pageYOffset;
// initPluginTable(plugins)
// // When returning to the page, set the scroll position to the stored value
// window.scrollTo(0, currentPosition);
// console.log(`Plugin ${plugin.name} uninstalled`);
// showPluginToast("Plugin " + plugin.name + " uninstalled");
// }
// await setStorageData('plugins', JSON.stringify(plugins))
// })
// }
// // manual install event handler
// if (pluginManualInstall !== null) {
// pluginManualInstall.addEventListener('click', async () => {
// pluginDialogOpenDialog(inputOK, inputCancel)
// pluginDialogTextarea.value = plugin.code ? plugin.code : ''
// pluginDialogTextarea.select()
// pluginDialogTextarea.focus()
// })
// }
// // Dialog OK
// async function inputOK() {
// let pluginSource = pluginDialogTextarea.value
// // remove empty lines and trim existing lines
// plugin.code = pluginSource
// if (pluginSource.trim() !== '') {
// plugin.enabled = true
// console.log(`Plugin ${plugin.name} installed`);
// showPluginToast("Plugin " + plugin.name + " installed");
// }
// else {
// plugin.enabled = false
// console.log(`No code provided for plugin ${plugin.name}, disabling the plugin`);
// showPluginToast("No code provided for plugin " + plugin.name + ", disabling the plugin");
// }
// updateManualInstallButtonCaption()
// await setStorageData('plugins', JSON.stringify(plugins))
// }
// // Dialog Cancel
// async function inputCancel() {
// plugin.enabled = false
// console.log(`Installation of plugin ${plugin.name} cancelled`);
// showPluginToast("Cancelled installation of " + plugin.name);
// }
// // update button caption
// function updateManualInstallButtonCaption() {
// if (pluginManualInstall !== null) {
// pluginManualInstall.innerHTML = plugin.code === undefined || plugin.code.trim() === '' ? 'Install' : 'Edit'
// }
// }
// })
// prettifyInputs(pluginsTable)
// filterPlugins()
// }
// /* version management. Thanks Madrang! */
// const parseVersion = function (versionString, options = {}) {
// if (typeof versionString === "undefined") {
// throw new Error("versionString is undefined.");
// }
// if (typeof versionString !== "string") {
// throw new Error("versionString is not a string.");
// }
// const lexicographical = options && options.lexicographical;
// const zeroExtend = options && options.zeroExtend;
// let versionParts = versionString.split('.');
// function isValidPart(x) {
// const re = (lexicographical ? /^\d+[A-Za-z]*$/ : /^\d+$/);
// return re.test(x);
// }
// if (!versionParts.every(isValidPart)) {
// throw new Error("Version string is invalid.");
// }
// if (zeroExtend) {
// while (versionParts.length < 4) {
// versionParts.push("0");
// }
// }
// if (!lexicographical) {
// versionParts = versionParts.map(Number);
// }
// return versionParts;
// };
// const versionCompare = function (v1, v2, options = {}) {
// if (typeof v1 == "undefined") {
// throw new Error("vi is undefined.");
// }
// if (typeof v2 === "undefined") {
// throw new Error("v2 is undefined.");
// }
// let v1parts;
// if (typeof v1 === "string") {
// v1parts = parseVersion(v1, options);
// } else if (Array.isArray(v1)) {
// v1parts = [...v1];
// if (!v1parts.every(p => typeof p === "number" && p !== NaN)) {
// throw new Error("v1 part array does not only contains numbers.");
// }
// } else {
// throw new Error("v1 is of an unexpected type: " + typeof v1);
// }
// let v2parts;
// if (typeof v2 === "string") {
// v2parts = parseVersion(v2, options);
// } else if (Array.isArray(v2)) {
// v2parts = [...v2];
// if (!v2parts.every(p => typeof p === "number" && p !== NaN)) {
// throw new Error("v2 part array does not only contains numbers.");
// }
// } else {
// throw new Error("v2 is of an unexpected type: " + typeof v2);
// }
// while (v1parts.length < v2parts.length) {
// v1parts.push("0");
// }
// while (v2parts.length < v1parts.length) {
// v2parts.push("0");
// }
// for (let i = 0; i < v1parts.length; ++i) {
// if (v2parts.length == i) {
// return 1;
// }
// if (v1parts[i] == v2parts[i]) {
// continue;
// } else if (v1parts[i] > v2parts[i]) {
// return 1;
// } else {
// return -1;
// }
// }
// return 0;
// };
// function filterPluginsByMinEDVersion(plugins, EDVersion) {
// const filteredPlugins = plugins.filter(plugin => {
// if (plugin.minEDVersion) {
// return versionCompare(plugin.minEDVersion, EDVersion) <= 0;
// }
// return true;
// });
// return filteredPlugins;
// }
// function extractVersionNumber(elem) {
// const versionStr = elem.innerHTML;
// const regex = /v(\d+\.\d+\.\d+)/;
// const matches = regex.exec(versionStr);
// if (matches && matches.length > 1) {
// return matches[1];
// } else {
// return null;
// }
// }
// const EasyDiffusionVersion = extractVersionNumber(document.querySelector('#top-nav > #logo'))
// /* PLUGIN MANAGEMENT */
// let plugins
// let localPlugins
// let initPluginsInProgress = false
// async function initPlugins(refreshPlugins = false) {
// let pluginsLoaded
// if (initPluginsInProgress === true) {
// return
// }
// initPluginsInProgress = true
// const res = await fetch('/get/ui_plugins')
// if (!res.ok) {
// console.error(`Error HTTP${res.status} while loading plugins list. - ${res.statusText}`)
// }
// else {
// localPlugins = await res.json()
// }
// if (refreshPlugins === false) {
// // load the notifications
// pluginNotifications = await getStorageData('notifications')
// if (typeof pluginNotifications === "string") {
// try {
// pluginNotifications = JSON.parse(pluginNotifications)
// } catch (e) {
// console.error("Failed to parse pluginNotifications", e);
// pluginNotifications = {};
// pluginNotifications.entries = [];
// }
// }
// if (pluginNotifications !== undefined) {
// if (pluginNotifications.entries && pluginNotifications.entries.length > 0 && pluginNotifications.entries[0].date && pluginNotifications.lastUpdated <= pluginNotifications.entries[0].date) {
// notificationPill.style.display = "block";
// }
// } else {
// pluginNotifications = {};
// pluginNotifications.entries = [];
// }
// // try and load plugins from local cache
// plugins = await getStorageData('plugins')
// if (plugins !== undefined) {
// plugins = JSON.parse(plugins)
// // remove duplicate entries if any (should not happen)
// plugins = deduplicatePluginsById(plugins)
// // remove plugins that don't meet the min ED version requirement
// plugins = filterPluginsByMinEDVersion(plugins, EasyDiffusionVersion)
// // remove from plugins the entries that don't have mandatory fields (id, name, url)
// plugins = plugins.filter((plugin) => { return plugin.id !== '' && plugin.name !== '' && plugin.url !== ''; });
// // populate the table
// initPluginTable(plugins)
// await loadPlugins(plugins)
// pluginsLoaded = true
// }
// else {
// plugins = []
// pluginsLoaded = false
// }
// }
// // update plugins asynchronously (updated versions will be available next time the UI is loaded)
// if (refreshAllowed()) {
// let pluginCatalog = await getDocument(PLUGIN_CATALOG)
// if (pluginCatalog !== null) {
// let parseError = false;
// try {
// pluginCatalog = JSON.parse(pluginCatalog);
// console.log('Plugin catalog successfully downloaded');
// } catch (error) {
// console.error('Error parsing plugin catalog:', error);
// parseError = true;
// }
// if (!parseError) {
// await downloadPlugins(pluginCatalog, plugins, refreshPlugins)
// // update compatIssueIds
// updateCompatIssueIds()
// // remove plugins that don't meet the min ED version requirement
// plugins = filterPluginsByMinEDVersion(plugins, EasyDiffusionVersion)
// // remove from plugins the entries that don't have mandatory fields (id, name, url)
// plugins = plugins.filter((plugin) => { return plugin.id !== '' && plugin.name !== '' && plugin.url !== ''; });
// // remove from plugins the entries that no longer exist in the catalog
// plugins = plugins.filter((plugin) => { return pluginCatalog.some((p) => p.id === plugin.id) });
// if (pluginCatalog.length > plugins.length) {
// const newPlugins = pluginCatalog.filter((plugin) => {
// return !plugins.some((p) => p.id === plugin.id);
// });
// newPlugins.forEach((plugin, index) => {
// setTimeout(() => {
// showPluginToast(`New plugin "${plugin.name}" is available.`);
// }, (index + 1) * 1000);
// });
// }
// let pluginsJson;
// try {
// pluginsJson = JSON.stringify(plugins); // attempt to parse plugins to JSON
// } catch (error) {
// console.error('Error converting plugins to JSON:', error);
// }
// if (pluginsJson) { // only store the data if pluginsJson is not null or undefined
// await setStorageData('plugins', pluginsJson)
// }
// // refresh the display of the plugins table
// initPluginTable(plugins)
// if (pluginsLoaded && pluginsLoaded === false) {
// loadPlugins(plugins)
// }
// }
// }
// }
// else {
// if (refreshPlugins) {
// showPluginToast('Plugins have been refreshed recently, refresh will be available in ' + convertSeconds(getTimeUntilNextRefresh()), 5000, true, false)
// }
// }
// initPluginsInProgress = false
// }
// function updateMetaTagPlugins(plugin) {
// // Update the meta tag with the list of loaded plugins
// let metaTag = document.querySelector('meta[name="plugins"]');
// if (metaTag === null) {
// metaTag = document.createElement('meta');
// metaTag.name = 'plugins';
// document.head.appendChild(metaTag);
// }
// const pluginArray = [...(metaTag.content ? metaTag.content.split(',') : []), plugin.id];
// metaTag.content = pluginArray.join(',');
// }
// function updateCompatIssueIds() {
// // Loop through each plugin
// plugins.forEach(plugin => {
// // Check if the plugin has `compatIssueIds` property
// if (plugin.compatIssueIds !== undefined) {
// // Loop through each of the `compatIssueIds`
// plugin.compatIssueIds.forEach(issueId => {
// // Find the plugin with the corresponding `issueId`
// const issuePlugin = plugins.find(p => p.id === issueId);
// // If the corresponding plugin is found, initialize its `compatIssueIds` property with an empty array if it's undefined
// if (issuePlugin) {
// if (issuePlugin.compatIssueIds === undefined) {
// issuePlugin.compatIssueIds = [];
// }
// // If the current plugin's ID is not already in the `compatIssueIds` array, add it
// if (!issuePlugin.compatIssueIds.includes(plugin.id)) {
// issuePlugin.compatIssueIds.push(plugin.id);
// }
// }
// });
// } else {
// // If the plugin doesn't have `compatIssueIds` property, initialize it with an empty array
// plugin.compatIssueIds = [];
// }
// });
// }
// function deduplicatePluginsById(plugins) {
// const seenIds = new Set();
// const deduplicatedPlugins = [];
// for (const plugin of plugins) {
// if (!seenIds.has(plugin.id)) {
// seenIds.add(plugin.id);
// deduplicatedPlugins.push(plugin);
// } else {
// // favor dupes that have enabled == true
// const index = deduplicatedPlugins.findIndex(p => p.id === plugin.id);
// if (index >= 0) {
// if (plugin.enabled) {
// deduplicatedPlugins[index] = plugin;
// }
// }
// }
// }
// return deduplicatedPlugins;
// }
// async function loadPlugins(plugins) {
// for (let i = 0; i < plugins.length; i++) {
// const plugin = plugins[i];
// if (plugin.enabled === true && plugin.localInstallOnly !== true) {
// const localPluginFound = checkFileNameInArray(localPlugins, plugin.url);
// if (!localPluginFound) {
// try {
// // Indirect eval to work around sloppy plugin implementations
// const indirectEval = { eval };
// console.log("Loading plugin " + plugin.name);
// indirectEval.eval(plugin.code);
// console.log("Plugin " + plugin.name + " loaded");
// await updateMetaTagPlugins(plugin); // add plugin to the meta tag
// } catch (err) {
// showPluginToast("Error loading plugin " + plugin.name + " (" + err.message + ")", null, true);
// console.error("Error loading plugin " + plugin.name + ": " + err.message);
// }
// } else {
// console.log("Skipping plugin " + plugin.name + " (installed locally)");
// }
// }
// }
// }
// async function getFileHash(url) {
// const regex = /^https:\/\/raw\.githubusercontent\.com\/(?<owner>[^/]+)\/(?<repo>[^/]+)\/(?<branch>[^/]+)\/(?<filePath>.+)$/;
// const match = url.match(regex);
// if (!match) {
// console.error('Invalid GitHub repository URL.');
// return Promise.resolve(null);
// }
// const owner = match.groups.owner;
// const repo = match.groups.repo;
// const branch = match.groups.branch;
// const filePath = match.groups.filePath;
// const apiUrl = `https://api.github.com/repos/${owner}/${repo}/contents/${filePath}?ref=${branch}`;
// try {
// const response = await fetch(apiUrl);
// if (!response.ok) {
// throw new Error(`HTTP error! status: ${response.status}, url: ${apiUrl}`);
// }
// const data = await response.json();
// return data.sha;
// } catch (error) {
// console.error('Error fetching data from url:', apiUrl, 'Error:', error);
// return null;
// }
// }
// // only allow two refresh per hour
// function getTimeUntilNextRefresh() {
// const lastRuns = JSON.parse(localStorage.getItem('lastRuns') || '[]');
// const currentTime = new Date().getTime();
// const numRunsLast60Min = lastRuns.filter(run => currentTime - run <= 60 * 60 * 1000).length;
// if (numRunsLast60Min >= 2) {
// return 3600 - Math.round((currentTime - lastRuns[lastRuns.length - 1]) / 1000);
// }
// return 0;
// }
// function refreshAllowed() {
// const timeUntilNextRefresh = getTimeUntilNextRefresh();
// if (timeUntilNextRefresh > 0) {
// console.log(`Next refresh available in ${timeUntilNextRefresh} seconds`);
// return false;
// }
// const lastRuns = JSON.parse(localStorage.getItem('lastRuns') || '[]');
// const currentTime = new Date().getTime();
// lastRuns.push(currentTime);
// localStorage.setItem('lastRuns', JSON.stringify(lastRuns));
// return true;
// }
// async function downloadPlugins(pluginCatalog, plugins, refreshPlugins) {
// // download the plugins as needed
// for (const plugin of pluginCatalog) {
// //console.log(plugin.id, plugin.url)
// const existingPlugin = plugins.find(p => p.id === plugin.id);
// // get the file hash in the GitHub repo
// let sha
// if (isGitHub(plugin.url) && existingPlugin?.enabled === true) {
// sha = await getFileHash(plugin.url)
// }
// if (plugin.localInstallOnly !== true && isGitHub(plugin.url) && existingPlugin?.enabled === true && (refreshPlugins || (existingPlugin.sha !== undefined && existingPlugin.sha !== null && existingPlugin.sha !== sha) || existingPlugin?.code === undefined)) {
// const pluginSource = await getDocument(plugin.url);
// if (pluginSource !== null && pluginSource !== existingPlugin.code) {
// console.log(`Plugin ${plugin.name} updated`);
// showPluginToast("Plugin " + plugin.name + " updated", 5000);
// // Update the corresponding plugin
// const updatedPlugin = {
// ...existingPlugin,
// icon: plugin.icon ? plugin.icon : "fa-puzzle-piece",
// id: plugin.id,
// name: plugin.name,
// description: plugin.description,
// url: plugin.url,
// localInstallOnly: Boolean(plugin.localInstallOnly),
// version: plugin.version,
// code: pluginSource,
// author: plugin.author,
// sha: sha,
// compatIssueIds: plugin.compatIssueIds
// };
// // Replace the old plugin in the plugins array
// const pluginIndex = plugins.indexOf(existingPlugin);
// if (pluginIndex >= 0) {
// plugins.splice(pluginIndex, 1, updatedPlugin);
// } else {
// plugins.push(updatedPlugin);
// }
// }
// }
// else if (existingPlugin !== undefined) {
// // Update the corresponding plugin's metadata
// const updatedPlugin = {
// ...existingPlugin,
// icon: plugin.icon ? plugin.icon : "fa-puzzle-piece",
// id: plugin.id,
// name: plugin.name,
// description: plugin.description,
// url: plugin.url,
// localInstallOnly: Boolean(plugin.localInstallOnly),
// version: plugin.version,
// author: plugin.author,
// compatIssueIds: plugin.compatIssueIds
// };
// // Replace the old plugin in the plugins array
// const pluginIndex = plugins.indexOf(existingPlugin);
// plugins.splice(pluginIndex, 1, updatedPlugin);
// }
// else {
// plugins.push(plugin);
// }
// }
// }
// async function getDocument(url) {
// try {
// let response = await fetch(url === PLUGIN_CATALOG ? PLUGIN_CATALOG : url, { cache: "no-cache" });
// if (!response.ok) {
// throw new Error(`Response error: ${response.status} ${response.statusText}`);
// }
// let document = await response.text();
// return document;
// } catch (error) {
// showPluginToast("Couldn't fetch " + extractFilename(url) + " (" + error + ")", null, true);
// console.error(error);
// return null;
// }
// }
// /* MODAL DIALOG */
// const pluginDialogDialog = document.createElement("div");
// pluginDialogDialog.id = "pluginDialog-input-dialog";
// pluginDialogDialog.style.display = "none";
// pluginDialogDialog.innerHTML = `
// <div class="pluginDialog-dialog-overlay"></div>
// <div class="pluginDialog-dialog-box">
// <div class="pluginDialog-dialog-header">
// <h2>Paste the plugin's code here</h2>
// <button class="pluginDialog-dialog-close-button">&times;</button>
// </div>
// <div class="pluginDialog-dialog-content">
// <textarea id="pluginDialog-input-textarea" spellcheck="false" autocomplete="off"></textarea>
// </div>
// <div class="pluginDialog-dialog-buttons">
// <button id="pluginDialog-input-ok">OK</button>
// <button id="pluginDialog-input-cancel">Cancel</button>
// </div>
// </div>
// `;
// document.body.appendChild(pluginDialogDialog);
// const pluginDialogOverlay = document.querySelector(".pluginDialog-dialog-overlay");
// const pluginDialogOkButton = document.getElementById("pluginDialog-input-ok");
// const pluginDialogCancelButton = document.getElementById("pluginDialog-input-cancel");
// const pluginDialogCloseButton = document.querySelector(".pluginDialog-dialog-close-button");
// const pluginDialogTextarea = document.getElementById("pluginDialog-input-textarea");
// let callbackOK
// let callbackCancel
// function pluginDialogOpenDialog(inputOK, inputCancel) {
// pluginDialogDialog.style.display = "block";
// callbackOK = inputOK
// callbackCancel = inputCancel
// }
// function pluginDialogCloseDialog() {
// pluginDialogDialog.style.display = "none";
// }
// function pluginDialogHandleOkClick() {
// const userInput = pluginDialogTextarea.value;
// // Do something with the user input
// callbackOK()
// pluginDialogCloseDialog();
// }
// function pluginDialogHandleCancelClick() {
// callbackCancel()
// pluginDialogCloseDialog();
// }
// function pluginDialogHandleOverlayClick(event) {
// if (event.target === pluginDialogOverlay) {
// pluginDialogCloseDialog();
// }
// }
// function pluginDialogHandleKeyDown(event) {
// if ((event.key === "Enter" && event.ctrlKey) || event.key === "Escape") {
// event.preventDefault();
// if (event.key === "Enter" && event.ctrlKey) {
// pluginDialogHandleOkClick();
// } else {
// pluginDialogCloseDialog();
// }
// }
// }
// pluginDialogTextarea.addEventListener("keydown", pluginDialogHandleKeyDown);
// pluginDialogOkButton.addEventListener("click", pluginDialogHandleOkClick);
// pluginDialogCancelButton.addEventListener("click", pluginDialogHandleCancelClick);
// pluginDialogCloseButton.addEventListener("click", pluginDialogCloseDialog);
// pluginDialogOverlay.addEventListener("click", pluginDialogHandleOverlayClick);

View File

@ -38,8 +38,6 @@ class ModelDropdown {
noneEntry //= ''
modelFilterInitialized //= undefined
sorted //= true
/* MIMIC A REGULAR INPUT FIELD */
get parentElement() {
return this.modelFilter.parentElement
@ -85,11 +83,10 @@ class ModelDropdown {
/* SEARCHABLE INPUT */
constructor(input, modelKey, noneEntry = "", sorted = true) {
constructor(input, modelKey, noneEntry = "") {
this.modelFilter = input
this.noneEntry = noneEntry
this.modelKey = modelKey
this.sorted = sorted
if (modelsOptions !== undefined) {
// reuse models from cache (only useful for plugins, which are loaded after models)
@ -97,8 +94,7 @@ class ModelDropdown {
let modelKeys = Array.isArray(this.modelKey) ? this.modelKey : [this.modelKey]
for (let i = 0; i < modelKeys.length; i++) {
let key = modelKeys[i]
let k = Array.isArray(modelsOptions[key]) ? modelsOptions[key] : [modelsOptions[key]]
this.inputModels.push(...k)
this.inputModels.push(...modelsOptions[key])
}
this.populateModels()
}
@ -106,28 +102,25 @@ class ModelDropdown {
"refreshModels",
this.bind(function(e) {
// reload the models
this.inputModels = modelsOptions[this.modelKey]
this.inputModels = []
let modelKeys = Array.isArray(this.modelKey) ? this.modelKey : [this.modelKey]
for (let i = 0; i < modelKeys.length; i++) {
let key = modelKeys[i]
let k = Array.isArray(modelsOptions[key]) ? modelsOptions[key] : [modelsOptions[key]]
this.inputModels.push(...k)
this.inputModels.push(...modelsOptions[key])
}
this.populateModels()
}, this)
)
}
saveCurrentSelection(elem, value, path, dispatchEvent = true) {
saveCurrentSelection(elem, value, path) {
this.currentSelection.elem = elem
this.currentSelection.value = value
this.currentSelection.path = path
this.modelFilter.dataset.path = path
this.modelFilter.value = value
if (dispatchEvent) {
this.modelFilter.dispatchEvent(new Event("change"))
}
this.modelFilter.dispatchEvent(new Event("change"))
}
processClick(e) {
@ -351,13 +344,13 @@ class ModelDropdown {
}
}
selectEntry(path, dispatchEvent = true) {
selectEntry(path) {
if (path !== undefined) {
const entries = this.modelElements
for (const elem of entries) {
if (elem.dataset.path == path) {
this.saveCurrentSelection(elem, elem.innerText, elem.dataset.path, dispatchEvent)
this.saveCurrentSelection(elem, elem.innerText, elem.dataset.path)
this.highlightedModelEntry = elem
elem.scrollIntoView({ block: "nearest" })
break
@ -532,7 +525,7 @@ class ModelDropdown {
rootModelList.style.minWidth = modelFilterStyle.width
})
this.selectEntry(this.activeModel, false)
this.selectEntry(this.activeModel)
}
/**
@ -555,38 +548,28 @@ class ModelDropdown {
this.createModelNodeList(`${folderName || ""}/${childFolderName}`, childModels, false)
)
} else {
let modelId = model
let modelName = model
if (typeof model === "object") {
modelId = Object.keys(model)[0]
modelName = model[modelId]
}
const classes = ["model-file"]
if (isRootFolder) {
classes.push("in-root-folder")
}
// Remove the leading slash from the model path
const fullPath = folderName ? `${folderName.substring(1)}/${modelId}` : modelId
const fullPath = folderName ? `${folderName.substring(1)}/${model}` : model
modelsMap.set(
modelId,
model,
createElement("li", { "data-path": fullPath }, classes, [
createElement("i", undefined, ["fa-regular", "fa-file", "icon"]),
modelName,
model,
])
)
}
})
const childFolderNames = Array.from(foldersMap.keys())
if (this.sorted) {
this.sortStringArray(childFolderNames)
}
this.sortStringArray(childFolderNames)
const folderElements = childFolderNames.map((name) => foldersMap.get(name))
const modelNames = Array.from(modelsMap.keys())
if (this.sorted) {
this.sortStringArray(modelNames)
}
this.sortStringArray(modelNames)
const modelElements = modelNames.map((name) => modelsMap.get(name))
if (modelElements.length && folderName) {
@ -636,9 +619,9 @@ class ModelDropdown {
}
/* (RE)LOAD THE MODELS */
async function getModels(scanForMalicious = true) {
async function getModels() {
try {
modelsCache = await SD.getModels(scanForMalicious)
modelsCache = await SD.getModels()
modelsOptions = modelsCache["options"]
if ("scan-error" in modelsCache) {
// let previewPane = document.getElementById('tab-content-wrapper')
@ -652,6 +635,22 @@ async function getModels(scanForMalicious = true) {
makeImageBtn.disabled = true
}
/* This code should no longer be needed. Commenting out for now, will cleanup later.
const sd_model_setting_key = "stable_diffusion_model"
const vae_model_setting_key = "vae_model"
const hypernetwork_model_key = "hypernetwork_model"
const stableDiffusionOptions = modelsOptions['stable-diffusion']
const vaeOptions = modelsOptions['vae']
const hypernetworkOptions = modelsOptions['hypernetwork']
// TODO: set default for model here too
SETTINGS[sd_model_setting_key].default = stableDiffusionOptions[0]
if (getSetting(sd_model_setting_key) == '' || SETTINGS[sd_model_setting_key].value == '') {
setSetting(sd_model_setting_key, stableDiffusionOptions[0])
}
*/
// notify ModelDropdown objects to refresh
document.dispatchEvent(new Event("refreshModels"))
} catch (e) {
@ -660,7 +659,4 @@ async function getModels(scanForMalicious = true) {
}
// reload models button
document.querySelector("#reload-models").addEventListener("click", (e) => {
e.stopPropagation()
getModels()
})
document.querySelector("#reload-models").addEventListener("click", getModels)

View File

@ -1,409 +0,0 @@
const htmlTaskMap = new WeakMap()
const pauseBtn = document.querySelector("#pause")
const resumeBtn = document.querySelector("#resume")
const processOrder = document.querySelector("#process_order_toggle")
let pauseClient = false
async function onIdle() {
const serverCapacity = SD.serverCapacity
if (pauseClient === true) {
await resumeClient()
}
for (const taskEntry of getUncompletedTaskEntries()) {
if (SD.activeTasks.size >= serverCapacity) {
break
}
const task = htmlTaskMap.get(taskEntry)
if (!task) {
const taskStatusLabel = taskEntry.querySelector(".taskStatusLabel")
taskStatusLabel.style.display = "none"
continue
}
await onTaskStart(task)
}
}
function getUncompletedTaskEntries() {
const taskEntries = Array.from(document.querySelectorAll("#preview .imageTaskContainer .taskStatusLabel"))
.filter((taskLabel) => taskLabel.style.display !== "none")
.map(function(taskLabel) {
let imageTaskContainer = taskLabel.parentNode
while (!imageTaskContainer.classList.contains("imageTaskContainer") && imageTaskContainer.parentNode) {
imageTaskContainer = imageTaskContainer.parentNode
}
return imageTaskContainer
})
if (!processOrder.checked) {
taskEntries.reverse()
}
return taskEntries
}
async function onTaskStart(task) {
if (!task.isProcessing || task.batchesDone >= task.batchCount) {
return
}
if (typeof task.startTime !== "number") {
task.startTime = Date.now()
}
if (!("instances" in task)) {
task["instances"] = []
}
task["stopTask"].innerHTML = '<i class="fa-solid fa-circle-stop"></i> Stop'
task["taskStatusLabel"].innerText = "Starting"
task["taskStatusLabel"].classList.add("waitingTaskLabel")
if (task.previewTaskReq !== undefined) {
let controlImagePreview = task.taskConfig.querySelector(".controlnet-img-preview > img")
try {
let result = await SD.filter(task.previewTaskReq)
controlImagePreview.src = result.output[0]
let controlImageLargePreview = task.taskConfig.querySelector(
".controlnet-img-preview .task-fs-initimage img"
)
controlImageLargePreview.src = controlImagePreview.src
} catch (error) {
console.log("filter error", error)
}
delete task.previewTaskReq
}
let newTaskReqBody = task.reqBody
if (task.batchCount > 1) {
// Each output render batch needs it's own task reqBody instance to avoid altering the other runs after they are completed.
newTaskReqBody = Object.assign({}, task.reqBody)
if (task.batchesDone == task.batchCount - 1) {
// Last batch of the task
// If the number of parallel jobs is no factor of the total number of images, the last batch must create less than "parallel jobs count" images
// E.g. with numOutputsTotal = 6 and num_outputs = 5, the last batch shall only generate 1 image.
newTaskReqBody.num_outputs = task.numOutputsTotal - task.reqBody.num_outputs * (task.batchCount - 1)
}
}
const startSeed = task.seed || newTaskReqBody.seed
const genSeeds = Boolean(
typeof newTaskReqBody.seed !== "number" || (newTaskReqBody.seed === task.seed && task.numOutputsTotal > 1)
)
if (genSeeds) {
newTaskReqBody.seed = parseInt(startSeed) + task.batchesDone * task.reqBody.num_outputs
}
const outputContainer = document.createElement("div")
outputContainer.className = "img-batch"
task.outputContainer.insertBefore(outputContainer, task.outputContainer.firstChild)
const eventInfo = { reqBody: newTaskReqBody }
const callbacksPromises = PLUGINS["TASK_CREATE"].map((hook) => {
if (typeof hook !== "function") {
console.error("The provided TASK_CREATE hook is not a function. Hook: %o", hook)
return Promise.reject(new Error("hook is not a function."))
}
try {
return Promise.resolve(hook.call(task, eventInfo))
} catch (err) {
console.error(err)
return Promise.reject(err)
}
})
await Promise.allSettled(callbacksPromises)
let instance = eventInfo.instance
if (!instance) {
const factory = PLUGINS.OUTPUTS_FORMATS.get(eventInfo.reqBody?.output_format || newTaskReqBody.output_format)
if (factory) {
instance = await Promise.resolve(factory(eventInfo.reqBody || newTaskReqBody))
}
if (!instance) {
console.error(
`${factory ? "Factory " + String(factory) : "No factory defined"} for output format ${eventInfo.reqBody
?.output_format || newTaskReqBody.output_format}. Instance is ${instance ||
"undefined"}. Using default renderer.`
)
instance = new SD.RenderTask(eventInfo.reqBody || newTaskReqBody)
}
}
task["instances"].push(instance)
task.batchesDone++
document.dispatchEvent(new CustomEvent("before_task_start", { detail: { task: task } }))
instance.enqueue(getTaskUpdater(task, newTaskReqBody, outputContainer)).then(
(renderResult) => {
onRenderTaskCompleted(task, newTaskReqBody, instance, outputContainer, renderResult)
},
(reason) => {
onTaskErrorHandler(task, newTaskReqBody, instance, reason)
}
)
document.dispatchEvent(new CustomEvent("after_task_start", { detail: { task: task } }))
}
function getTaskUpdater(task, reqBody, outputContainer) {
const outputMsg = task["outputMsg"]
const progressBar = task["progressBar"]
const progressBarInner = progressBar.querySelector("div")
const batchCount = task.batchCount
let lastStatus = undefined
return async function(event) {
if (this.status !== lastStatus) {
lastStatus = this.status
switch (this.status) {
case SD.TaskStatus.pending:
task["taskStatusLabel"].innerText = "Pending"
task["taskStatusLabel"].classList.add("waitingTaskLabel")
break
case SD.TaskStatus.waiting:
task["taskStatusLabel"].innerText = "Waiting"
task["taskStatusLabel"].classList.add("waitingTaskLabel")
task["taskStatusLabel"].classList.remove("activeTaskLabel")
break
case SD.TaskStatus.processing:
case SD.TaskStatus.completed:
task["taskStatusLabel"].innerText = "Processing"
task["taskStatusLabel"].classList.add("activeTaskLabel")
task["taskStatusLabel"].classList.remove("waitingTaskLabel")
break
case SD.TaskStatus.stopped:
break
case SD.TaskStatus.failed:
if (!SD.isServerAvailable()) {
logError(
"Stable Diffusion is still starting up, please wait. If this goes on beyond a few minutes, Stable Diffusion has probably crashed. Please check the error message in the command-line window.",
event,
outputMsg
)
} else if (typeof event?.response === "object") {
let msg = "Stable Diffusion had an error reading the response:<br/><pre>"
if (this.exception) {
msg += `Error: ${this.exception.message}<br/>`
}
try {
// 'Response': body stream already read
msg += "Read: " + (await event.response.text())
} catch (e) {
msg += "Unexpected end of stream. "
}
const bufferString = event.reader.bufferedString
if (bufferString) {
msg += "Buffered data: " + bufferString
}
msg += "</pre>"
logError(msg, event, outputMsg)
}
break
}
}
if ("update" in event) {
const stepUpdate = event.update
if (!("step" in stepUpdate)) {
return
}
// task.instances can be a mix of different tasks with uneven number of steps (Render Vs Filter Tasks)
const instancesWithProgressUpdates = task.instances.filter((instance) => instance.step !== undefined)
const overallStepCount =
instancesWithProgressUpdates.reduce(
(sum, instance) =>
sum +
(instance.isPending
? Math.max(0, instance.step || stepUpdate.step) /
(instance.total_steps || stepUpdate.total_steps)
: 1),
0 // Initial value
) * stepUpdate.total_steps // Scale to current number of steps.
const totalSteps = instancesWithProgressUpdates.reduce(
(sum, instance) => sum + (instance.total_steps || stepUpdate.total_steps),
stepUpdate.total_steps * (batchCount - task.batchesDone) // Initial value at (unstarted task count * Nbr of steps)
)
const percent = Math.min(100, 100 * (overallStepCount / totalSteps)).toFixed(0)
const timeTaken = stepUpdate.step_time // sec
const stepsRemaining = Math.max(0, totalSteps - overallStepCount)
const timeRemaining = timeTaken < 0 ? "" : millisecondsToStr(stepsRemaining * timeTaken * 1000)
outputMsg.innerHTML = `Batch ${task.batchesDone} of ${batchCount}. Generating image(s): ${percent}%. Time remaining (approx): ${timeRemaining}`
outputMsg.style.display = "block"
progressBarInner.style.width = `${percent}%`
if (stepUpdate.output) {
document.dispatchEvent(
new CustomEvent("on_task_step", {
detail: {
task: task,
reqBody: reqBody,
stepUpdate: stepUpdate,
outputContainer: outputContainer,
},
})
)
}
}
}
}
function onRenderTaskCompleted(task, reqBody, instance, outputContainer, stepUpdate) {
if (typeof stepUpdate === "object") {
if (stepUpdate.status === "succeeded") {
document.dispatchEvent(
new CustomEvent("on_render_task_success", {
detail: {
task: task,
reqBody: reqBody,
stepUpdate: stepUpdate,
outputContainer: outputContainer,
},
})
)
} else {
task.isProcessing = false
document.dispatchEvent(
new CustomEvent("on_render_task_fail", {
detail: {
task: task,
reqBody: reqBody,
stepUpdate: stepUpdate,
outputContainer: outputContainer,
},
})
)
}
}
if (task.isProcessing && task.batchesDone < task.batchCount) {
task["taskStatusLabel"].innerText = "Pending"
task["taskStatusLabel"].classList.add("waitingTaskLabel")
task["taskStatusLabel"].classList.remove("activeTaskLabel")
return
}
if ("instances" in task && task.instances.some((ins) => ins != instance && ins.isPending)) {
return
}
task.isProcessing = false
task["stopTask"].innerHTML = '<i class="fa-solid fa-trash-can"></i> Remove'
task["taskStatusLabel"].style.display = "none"
let time = millisecondsToStr(Date.now() - task.startTime)
if (task.batchesDone == task.batchCount) {
if (!task.outputMsg.innerText.toLowerCase().includes("error")) {
task.outputMsg.innerText = `Processed ${task.numOutputsTotal} images in ${time}`
}
task.progressBar.style.height = "0px"
task.progressBar.style.border = "0px solid var(--background-color3)"
task.progressBar.classList.remove("active")
// setStatus("request", "done", "success")
} else {
task.outputMsg.innerText += `. Task ended after ${time}`
}
// if (randomSeedField.checked) { // we already update this before the task starts
// seedField.value = task.seed
// }
if (SD.activeTasks.size > 0) {
return
}
const uncompletedTasks = getUncompletedTaskEntries()
if (uncompletedTasks && uncompletedTasks.length > 0) {
return
}
if (pauseClient) {
resumeBtn.click()
}
document.dispatchEvent(
new CustomEvent("on_all_tasks_complete", {
detail: {},
})
)
}
function resumeClient() {
if (pauseClient) {
document.body.classList.remove("wait-pause")
document.body.classList.add("pause")
}
return new Promise((resolve) => {
let playbuttonclick = function() {
resumeBtn.removeEventListener("click", playbuttonclick)
resolve("resolved")
}
resumeBtn.addEventListener("click", playbuttonclick)
})
}
function abortTask(task) {
if (!task.isProcessing) {
return false
}
task.isProcessing = false
task.progressBar.classList.remove("active")
task["taskStatusLabel"].style.display = "none"
task["stopTask"].innerHTML = '<i class="fa-solid fa-trash-can"></i> Remove'
if (!task.instances?.some((r) => r.isPending)) {
return
}
task.instances.forEach((instance) => {
try {
instance.abort()
} catch (e) {
console.error(e)
}
})
}
async function stopAllTasks() {
getUncompletedTaskEntries().forEach((taskEntry) => {
const taskStatusLabel = taskEntry.querySelector(".taskStatusLabel")
if (taskStatusLabel) {
taskStatusLabel.style.display = "none"
}
const task = htmlTaskMap.get(taskEntry)
if (!task) {
return
}
abortTask(task)
})
}
function onTaskErrorHandler(task, reqBody, instance, reason) {
if (!task.isProcessing) {
return
}
console.log("Render request %o, Instance: %o, Error: %s", reqBody, instance, reason)
abortTask(task)
const outputMsg = task["outputMsg"]
logError(
"Stable Diffusion had an error. Please check the logs in the command-line window. <br/><br/>" +
reason +
"<br/><pre>" +
reason.stack +
"</pre>",
task,
outputMsg
)
// setStatus("request", "error", "error")
}
pauseBtn.addEventListener("click", function() {
pauseClient = true
pauseBtn.style.display = "none"
resumeBtn.style.display = "inline"
document.body.classList.add("wait-pause")
})
resumeBtn.addEventListener("click", function() {
pauseClient = false
resumeBtn.style.display = "none"
pauseBtn.style.display = "inline"
document.body.classList.remove("pause")
document.body.classList.remove("wait-pause")
})

View File

@ -129,31 +129,6 @@ function tryLoadOldCollapsibles() {
return null
}
function collapseAll(selector) {
const collapsibleElems = document.querySelectorAll(selector); // needs to have ";"
[...collapsibleElems].forEach((elem) => {
const isActive = elem.classList.contains("active")
if(isActive) {
elem?.click()
}
})
}
function expandAll(selector) {
const collapsibleElems = document.querySelectorAll(selector); // needs to have ";"
[...collapsibleElems].forEach((elem) => {
const isActive = elem.classList.contains("active")
if (!isActive) {
elem?.click()
}
})
}
function permute(arr) {
let permutations = []
let n = arr.length
@ -178,10 +153,6 @@ function permute(arr) {
return permutations
}
function permuteNumber(arr) {
return Math.pow(2, arr.length)
}
// https://stackoverflow.com/a/8212878
function millisecondsToStr(milliseconds) {
function numberEnding(number) {
@ -431,12 +402,12 @@ function debounce(func, wait, immediate) {
function preventNonNumericalInput(e) {
e = e || window.event
const charCode = typeof e.which == "undefined" ? e.keyCode : e.which
const charStr = String.fromCharCode(charCode)
const newInputValue = `${e.target.value}${charStr}`
const re = new RegExp(e.target.getAttribute("pattern") || "^[0-9]+$")
let charCode = typeof e.which == "undefined" ? e.keyCode : e.which
let charStr = String.fromCharCode(charCode)
let re = e.target.getAttribute("pattern") || "^[0-9]+$"
re = new RegExp(re)
if (!re.test(charStr) && !re.test(newInputValue)) {
if (!charStr.match(re)) {
e.preventDefault()
}
}
@ -870,7 +841,6 @@ function createTab(request) {
})
}
/* TOAST NOTIFICATIONS */
function showToast(message, duration = 5000, error = false) {
const toast = document.createElement("div")
@ -953,282 +923,3 @@ function confirm(msg, title, fn) {
},
})
}
/* STORAGE MANAGEMENT */
// Request persistent storage
async function requestPersistentStorage() {
if (navigator.storage && navigator.storage.persist) {
const isPersisted = await navigator.storage.persist();
console.log(`Persisted storage granted: ${isPersisted}`);
}
}
requestPersistentStorage()
// Open a database
async function openDB() {
return new Promise((resolve, reject) => {
let request = indexedDB.open("EasyDiffusionSettingsDatabase", 1);
request.addEventListener("upgradeneeded", function () {
let db = request.result;
db.createObjectStore("EasyDiffusionSettings", { keyPath: "id" });
});
request.addEventListener("success", function () {
resolve(request.result);
});
request.addEventListener("error", function () {
reject(request.error);
});
});
}
// Function to write data to the object store
async function setStorageData(key, value) {
return openDB().then(db => {
let tx = db.transaction("EasyDiffusionSettings", "readwrite");
let store = tx.objectStore("EasyDiffusionSettings");
let data = { id: key, value: value };
return new Promise((resolve, reject) => {
let request = store.put(data);
request.addEventListener("success", function () {
resolve(request.result);
});
request.addEventListener("error", function () {
reject(request.error);
});
});
});
}
// Function to retrieve data from the object store
async function getStorageData(key) {
return openDB().then(db => {
let tx = db.transaction("EasyDiffusionSettings", "readonly");
let store = tx.objectStore("EasyDiffusionSettings");
return new Promise((resolve, reject) => {
let request = store.get(key);
request.addEventListener("success", function () {
if (request.result) {
resolve(request.result.value);
} else {
// entry not found
resolve();
}
});
request.addEventListener("error", function () {
reject(request.error);
});
});
});
}
function insertAtCursor(field, text) {
if (field.selectionStart || field.selectionStart == "0") {
var startPos = field.selectionStart
var endPos = field.selectionEnd
var before = field.value.substring(0, startPos)
var after = field.value.substring(endPos, field.value.length)
if (!before.endsWith(" ")) { before += " " }
if (!after.startsWith(" ")) { after = " "+after }
field.value = before + text + after
} else {
field.value += text
}
}
// indexedDB debug functions
async function getAllKeys() {
return openDB().then(db => {
let tx = db.transaction("EasyDiffusionSettings", "readonly");
let store = tx.objectStore("EasyDiffusionSettings");
let keys = [];
return new Promise((resolve, reject) => {
store.openCursor().onsuccess = function (event) {
let cursor = event.target.result;
if (cursor) {
keys.push(cursor.key);
cursor.continue();
} else {
resolve(keys);
}
};
});
});
}
async function logAllStorageKeys() {
try {
let keys = await getAllKeys();
console.log("All keys:", keys);
for (const k of keys) {
console.log(k, await getStorageData(k))
}
} catch (error) {
console.error("Error retrieving keys:", error);
}
}
// USE WITH CARE - THIS MAY DELETE ALL ENTRIES
async function deleteKeys(keyToDelete) {
let confirmationMessage = keyToDelete
? `This will delete the template with key "${keyToDelete}". Continue?`
: "This will delete ALL templates. Continue?";
if (confirm(confirmationMessage)) {
return openDB().then(db => {
let tx = db.transaction("EasyDiffusionSettings", "readwrite");
let store = tx.objectStore("EasyDiffusionSettings");
return new Promise((resolve, reject) => {
store.openCursor().onsuccess = function (event) {
let cursor = event.target.result;
if (cursor) {
if (!keyToDelete || cursor.key === keyToDelete) {
cursor.delete();
}
cursor.continue();
} else {
// refresh the dropdown and resolve
resolve();
}
};
});
});
}
}
/**
* @param {String} Data URL of the image
* @param {Integer} Top left X-coordinate of the crop area
* @param {Integer} Top left Y-coordinate of the crop area
* @param {Integer} Width of the crop area
* @param {Integer} Height of the crop area
* @return {String}
*/
function cropImageDataUrl(dataUrl, x, y, width, height) {
return new Promise((resolve, reject) => {
const image = new Image()
image.src = dataUrl
image.onload = () => {
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.drawImage(image, x, y, width, height, 0, 0, width, height)
const croppedDataUrl = canvas.toDataURL('image/png')
resolve(croppedDataUrl)
}
image.onerror = (error) => {
reject(error)
}
})
}
/**
* @param {String} HTML representing a single element
* @return {Element}
*/
function htmlToElement(html) {
var template = document.createElement('template');
html = html.trim(); // Never return a text node of whitespace as the result
template.innerHTML = html;
return template.content.firstChild;
}
function modalDialogCloseOnBackdropClick(dialog) {
dialog.addEventListener('mousedown', function (event) {
// Firefox creates an event with clientX|Y = 0|0 when choosing an <option>.
// Test whether the element interacted with is a child of the dialog, but not the
// dialog itself (the backdrop would be a part of the dialog)
if (dialog.contains(event.target) && dialog != event.target) {
return
}
var rect = dialog.getBoundingClientRect()
var isInDialog=(rect.top <= event.clientY && event.clientY <= rect.top + rect.height
&& rect.left <= event.clientX && event.clientX <= rect.left + rect.width)
if (!isInDialog) {
dialog.close()
}
})
}
function makeDialogDraggable(element) {
element.querySelector(".dialog-header").addEventListener('mousedown', (function() {
let deltaX=0
let deltaY=0
let dragStartX=0
let dragStartY=0
let oldTop=0
let oldLeft=0
function dlgDragStart(e) {
e = e || window.event;
const d = e.target.closest("dialog")
e.preventDefault();
dragStartX = e.clientX;
dragStartY = e.clientY;
oldTop = parseInt(d.style.top)
oldLeft = parseInt(d.style.left)
if (isNaN(oldTop)) { oldTop=0 }
if (isNaN(oldLeft)) { oldLeft=0 }
document.addEventListener('mouseup', dlgDragClose);
document.addEventListener('mousemove', dlgDrag);
}
function dlgDragClose(e) {
document.removeEventListener('mouseup', dlgDragClose);
document.removeEventListener('mousemove', dlgDrag);
}
function dlgDrag(e) {
e = e || window.event;
const d = e.target.closest("dialog")
e.preventDefault();
deltaX = dragStartX - e.clientX;
deltaY = dragStartY - e.clientY;
d.style.left = `${oldLeft-2*deltaX}px`
d.style.top = `${oldTop-2*deltaY}px`
}
return dlgDragStart
})() )
}
function logMsg(msg, level, outputMsg) {
if (outputMsg.hasChildNodes()) {
outputMsg.appendChild(document.createElement("br"))
}
if (level === "error") {
outputMsg.innerHTML += '<span style="color: red">Error: ' + msg + "</span>"
} else if (level === "warn") {
outputMsg.innerHTML += '<span style="color: orange">Warning: ' + msg + "</span>"
} else {
outputMsg.innerText += msg
}
console.log(level, msg)
}
function logError(msg, res, outputMsg) {
logMsg(msg, "error", outputMsg)
console.log("request error", res)
console.trace()
// setStatus("request", "error", "error")
}
function playSound() {
const audio = new Audio("/media/ding.mp3")
audio.volume = 0.2
var promise = audio.play()
if (promise !== undefined) {
promise
.then((_) => {})
.catch((error) => {
console.warn("browser blocked autoplay")
})
}
}

View File

@ -1,462 +0,0 @@
/*
Image Editor Improvements
by Patrice
Image editor improvements:
- Shows the actual brush in the image editor for increased precision.
- Add img2img source image via drag & drop from external file or browser image (incl. rendered image). Just drop the image in the editor pane.
- Add img2img source image by pasting an image from the clipboard
- Integrates seamlessly with Scrolling Panes 1.8+
- Adds support for reloading task from metadata embedded in PNG and JPEG images (use Ctrl+Drop image in the editor pane)
- Automatically sets the size of the output image to the size of the image used for img2img if its dimensions are both valid options (works with both copy/paste and drag & drop).
- makes the brushes more visible in the image/inpainting editor.
*/
(function() {
"use strict"
let imageBrushPreview
let imageCanvas
let canvasType
let activeBrush
function setupBrush() {
// capture active brush
activeBrush = document.querySelector(canvasType + ' .image_editor_brush_size .editor-options-container .active')
// create a copy of the brush if needed
if (imageBrushPreview == undefined) {
// create brush to display on canvas
imageBrushPreview = activeBrush.cloneNode(true)
imageBrushPreview.className = 'image-brush-preview'
imageBrushPreview.style.display = 'none'
imageCanvas.parentElement.appendChild(imageBrushPreview)
}
// render the brush
imageBrushPreview.style.width = activeBrush.offsetWidth + 'px'
imageBrushPreview.style.height = activeBrush.offsetWidth + 'px'
imageBrushPreview.style.display = 'block'
}
function cleanupBrush() {
// delete the brush copy if the mouse moves out of the canvas
imageCanvas.style.cursor = ''
if (imageBrushPreview !== undefined) {
imageBrushPreview.remove()
imageBrushPreview = undefined
}
}
function disableRightClick(e) {
e.preventDefault()
}
function setupCanvas(canvas) {
canvasType = canvas
imageCanvas = document.querySelector(canvas + ' .editor-canvas-overlay')
imageCanvas.addEventListener("contextmenu", disableRightClick)
imageCanvas.addEventListener("mousemove", updateMouseCursor)
imageCanvas.addEventListener("mouseenter", setupBrush)
imageCanvas.addEventListener("mouseleave", cleanupBrush)
}
document.getElementById("init_image_button_draw").addEventListener("click", () => {
setupCanvas('#image-editor')
})
document.getElementById("init_image_button_inpaint").addEventListener("click", () => {
setupCanvas('#image-inpainter')
})
function updateMouseCursor(e) {
// move the brush
if (imageBrushPreview !== undefined) {
imageBrushPreview.style.left = e.clientX + 'px'
imageBrushPreview.style.top = e.clientY + 'px'
}
}
/* ADD SUPPORT FOR PASTING SOURCE IMAGE FROM CLIPBOARD */
let imageObj = new Image()
let canvas = document.createElement('canvas')
let context = canvas.getContext('2d')
imageObj.onload = function() {
// Calculate the maximum cropped dimensions
const step = customWidthField.step
const maxCroppedWidth = Math.floor(this.width / step) * step;
const maxCroppedHeight = Math.floor(this.height / step) * step;
canvas.width = maxCroppedWidth;
canvas.height = maxCroppedHeight;
// Calculate the x and y coordinates to center the cropped image
const x = (maxCroppedWidth - this.width) / 2;
const y = (maxCroppedHeight - this.height) / 2;
// Draw the image with centered coordinates
context.drawImage(imageObj, x, y, this.width, this.height);
let bestWidth = maxCroppedWidth - maxCroppedWidth % IMAGE_STEP_SIZE
let bestHeight = maxCroppedHeight - maxCroppedHeight % IMAGE_STEP_SIZE
addImageSizeOption(bestWidth)
addImageSizeOption(bestHeight)
// Set the width and height to the closest aspect ratio and closest to original dimensions
widthField.value = bestWidth;
heightField.value = bestHeight;
initImagePreview.src = canvas.toDataURL('image/png');
};
function handlePaste(e) {
for (let i = 0 ; i < e.clipboardData.items.length ; i++) {
const item = e.clipboardData.items[i]
if (item.type.indexOf("image") != -1) {
imageObj.src = URL.createObjectURL(item.getAsFile())
}
}
}
document.addEventListener('paste', handlePaste)
// replace the default file open listener
initImageSelector.removeEventListener('change', loadImg2ImgFromFile);
function ieiLoadImg2ImgFromFile() {
if (initImageSelector.files.length === 0) {
return
}
let reader = new FileReader()
let file = initImageSelector.files[0]
reader.addEventListener('load', function(event) {
imageObj.src = reader.result
})
if (file) {
reader.readAsDataURL(file)
}
}
initImageSelector.addEventListener('change', ieiLoadImg2ImgFromFile)
/* ADD SUPPORT FOR DRAG-AND-DROPPING SOURCE IMAGE (from file or straight from UI) */
/* DROP AREAS */
function createDropAreas(container) {
// Create two drop areas
const dropAreaI2I = createElement("div", {id: "drop-area-I2I"}, ["drop-area"], "Use as Image2Image source")
container.appendChild(dropAreaI2I)
const dropAreaMD = createElement("div", {id: "drop-area-MD"}, ["drop-area"], "Extract embedded metadata")
container.appendChild(dropAreaMD)
const dropAreaCN = createElement("div", {id: "drop-area-CN"}, ["drop-area"], "Use as Controlnet image")
container.appendChild(dropAreaCN)
// Add event listeners to drop areas
dropAreaCN.addEventListener("dragenter", function(event) {
event.preventDefault()
dropAreaCN.style.backgroundColor = 'darkGreen'
})
dropAreaCN.addEventListener("dragleave", function(event) {
event.preventDefault()
dropAreaCN.style.backgroundColor = ''
})
dropAreaCN.addEventListener("drop", function(event) {
event.stopPropagation()
event.preventDefault()
hideDropAreas()
getImageFromDropEvent(event, e => controlImagePreview.src=e)
})
dropAreaI2I.addEventListener("dragenter", function(event) {
event.preventDefault()
dropAreaI2I.style.backgroundColor = 'darkGreen'
})
dropAreaI2I.addEventListener("dragleave", function(event) {
event.preventDefault()
dropAreaI2I.style.backgroundColor = ''
})
function getImageFromDropEvent(event, callback) {
// Find the first image file, uri, or moz-url in the items list
let imageItem = null
for (let i = 0; i < event.dataTransfer.items.length; i++) {
let item = event.dataTransfer.items[i]
if (item.kind === 'file' && item.type.startsWith('image/')) {
imageItem = item;
break;
}
}
if (!imageItem) {
// If no file matches, try to find a text/uri-list item
for (let i = 0; i < event.dataTransfer.items.length; i++) {
let item = event.dataTransfer.items[i];
if (item.type === 'text/uri-list') {
imageItem = item;
break;
}
}
}
if (!imageItem) {
// If there are no image files or uris, fallback to moz-url
for (let i = 0; i < event.dataTransfer.items.length; i++) {
let item = event.dataTransfer.items[i];
if (item.type === 'text/x-moz-url') {
imageItem = item;
break;
}
}
}
if (imageItem) {
if (imageItem.kind === 'file') {
// If the item is an image file, handle it as before
let file = imageItem.getAsFile();
// Create a FileReader object to read the dropped file as a data URL
let reader = new FileReader();
reader.onload = function(e) {
callback(e.target.result)
};
reader.readAsDataURL(file);
} else {
// If the item is a URL, retrieve it and use it to load the image
imageItem.getAsString(callback)
}
}
}
dropAreaI2I.addEventListener("drop", function(event) {
event.stopPropagation()
event.preventDefault()
hideDropAreas()
getImageFromDropEvent(event, e => imageObj.src=e)
})
dropAreaMD.addEventListener("dragenter", function(event) {
event.preventDefault()
dropAreaMD.style.backgroundColor = 'darkGreen'
})
dropAreaMD.addEventListener("dragleave", function(event) {
event.preventDefault()
dropAreaMD.style.backgroundColor = ''
})
dropAreaMD.addEventListener("drop", function(event) {
let items = []
hideDropAreas()
if (event?.dataTransfer?.items) { // Use DataTransferItemList interface
items = Array.from(event.dataTransfer.items)
items = items.filter(item => item.kind === 'file' && (item.type === 'image/png' || item.type === 'image/jpeg' || item.type === 'image/webp'))
items = items.map(item => item.getAsFile())
} else if (event?.dataTransfer?.files) { // Use DataTransfer interface
items = Array.from(event.dataTransfer.files)
}
// check if image has embedded metadata, load task if it does
if (items[0].type === "image/png") {
readPNGMetadata(items[0])
} else if (items[0].type === "image/jpeg" || items[0].type === "image/webp") {
readJPEGMetadata(items[0]);
} else {
console.log("File must be a PNG, WEBP or JPEG image.");
}
event.preventDefault()
})
document.addEventListener("drop", function(event) {
event.preventDefault()
hideDropAreas()
})
document.addEventListener("dragexit", function(event) {
event.preventDefault()
hideDropAreas()
})
}
function showDropAreasDnD(event) {
event.preventDefault()
// Find the first image file, uri, or moz-url in the items list
let imageItem = null;
for (let i = 0; i < event.dataTransfer.items.length; i++) {
let item = event.dataTransfer.items[i];
if ((item.kind === 'file' && item.type.startsWith('image/')) || item.type === 'text/uri-list') {
imageItem = item;
break;
} else if (item.type === 'text/x-moz-url') {
// If there are no image files or uris, fallback to moz-url
if (!imageItem) {
imageItem = item;
}
}
}
if (imageItem) {
showDropAreas()
}
}
function hideDropAreasDnD(event) {
if (event.fromElement && !document.querySelector('#editor').contains(event.fromElement) && !document.querySelector('#editor').contains(event.fromElement.parentNode.host)) {
hideDropAreas()
}
}
function showDropAreas() {
const dropAreas = document.querySelectorAll(".drop-area")
dropAreas.forEach(function(dropArea) {
dropArea.style.display = 'inline-block'
})
}
function hideDropAreas() {
const dropAreas = document.querySelectorAll(".drop-area")
dropAreas.forEach(function(dropArea) {
dropArea.style.display = 'none'
dropArea.style.backgroundColor = ''
})
}
const dndContainer = document.getElementById("editor-inputs-init-image")
createDropAreas(dndContainer)
document.querySelector('#editor').addEventListener("dragenter", showDropAreasDnD)
document.querySelector('#editor').addEventListener("dragleave", hideDropAreasDnD)
/* METADATA EXTRACTION HELPER FUNCTION */
function clearAllImageTagCards() {
// clear existing image tag cards
editorTagsContainer.style.display = 'none'
editorModifierTagsList.querySelectorAll('.modifier-card').forEach(modifierCard => {
modifierCard.remove()
})
// reset modifier cards state
document.querySelector('#editor-modifiers').querySelectorAll('.modifier-card').forEach(modifierCard => {
const modifierName = modifierCard.querySelector('.modifier-card-label').innerText
if (activeTags.map(x => x.name).includes(modifierName)) {
modifierCard.classList.remove(activeCardClass)
modifierCard.querySelector('.modifier-card-image-overlay').innerText = '+'
}
})
activeTags = []
document.dispatchEvent(new Event('refreshImageModifiers')) // notify the
}
/* PNG METADATA EXTRACTION */
function readPNGMetadata(image) {
const fileReader = new FileReader()
fileReader.onload = function () {
extractTextChunks(image).then(function (chunks) {
let reqBody = {}
for (let key in chunks) {
reqBody[key] = chunks[key]
}
if (Object.keys(reqBody).length !== 0) {
if (reqBody["seed"] !== undefined) {
let task = { numOutputsTotal: reqBody["num_outputs"], seed: reqBody["seed"] }
task['reqBody'] = reqBody
clearAllImageTagCards()
restoreTaskToUI(task, TASK_REQ_NO_EXPORT)
}
}
}).catch(function (error) {
console.error(error);
})}
fileReader.readAsArrayBuffer(image);
}
function extractTextChunks(file) {
return new Promise(function (resolve, reject) {
let reader = new FileReader();
reader.onload = function () {
let arrayBuffer = reader.result;
let dataView = new DataView(arrayBuffer);
// Verify that the PNG signature is present
let signature = new Uint8Array(arrayBuffer, 0, 8);
if (String.fromCharCode.apply(null, signature) !== "\x89PNG\r\n\x1a\n") {
reject(new Error("Invalid PNG file"));
return;
}
// Iterate through the chunks
let chunks = {};
let offset = 8;
while (offset < arrayBuffer.byteLength) {
// Get the length and type of the chunk
let length = dataView.getUint32(offset);
let type = String.fromCharCode(dataView.getUint8(offset + 4), dataView.getUint8(offset + 5), dataView.getUint8(offset + 6), dataView.getUint8(offset + 7));
offset += 8;
// Get the data of the chunk
let data = new Uint8Array(arrayBuffer, offset, length);
offset += length;
// Get the CRC of the chunk
let crc = dataView.getUint32(offset);
offset += 4;
// If it's a tEXt chunk, convert the data to a human-readable string
if (type === "tEXt") {
let nullIndex = data.indexOf(0);
let key = String.fromCharCode.apply(null, data.slice(0, nullIndex));
let value = String.fromCharCode.apply(null, data.slice(nullIndex + 1));
chunks[key] = value;
}
}
resolve(chunks);
};
reader.readAsArrayBuffer(file);
});
};
/* JPEG or WEBP METADATA EXTRACTION */
function readJPEGMetadata(image) {
const fileReader = new FileReader()
fileReader.onload = function (e) {
ExifReader.load(e.target.result).then(tags => {
const exifData = String.fromCharCode(...tags['UserComment'].value)
if (exifData !== undefined) {
try {
const isUnicode = (exifData.toLowerCase().startsWith('unicode'))
let keys = JSON.parse(isUnicode ? decodeUnicode(exifData.slice(8)) : exifData.slice(8))
let reqBody = {}
for (let key in keys) {
reqBody[key] = keys[key]
}
let task = { numOutputsTotal: reqBody["num_outputs"], seed: reqBody["seed"] }
task['reqBody'] = reqBody
clearAllImageTagCards()
restoreTaskToUI(task, TASK_REQ_NO_EXPORT)
} catch (e) {
console.error('No valid JSON in EXIF data')
}
}
})
}
fileReader.readAsDataURL(image);
}
function decodeUnicode(unicodeString) {
const encoder = new TextEncoder()
const input = new Uint16Array(encoder.encode(unicodeString))
let decodedString = ''
for (let i = 0; i < input.length; i+=2) {
decodedString += String.fromCharCode(input[i] << 8 | input[i+1])
}
return decodedString
}
})()

View File

@ -1,94 +0,0 @@
/*
LoRA Prompt Parser 1.0
by Patrice
Copying and pasting a prompt with a LoRA tag will automatically select the corresponding option in the Easy Diffusion dropdown and remove the LoRA tag from the prompt. The LoRA must be already available in the corresponding Easy Diffusion dropdown (this is not a LoRA downloader).
*/
(function() {
"use strict"
promptField.addEventListener('input', function(e) {
let loraExtractSetting = document.getElementById("extract_lora_from_prompt")
if (!loraExtractSetting.checked) {
return
}
const { LoRA, prompt } = extractLoraTags(e.target.value);
//console.log('e.target: ' + JSON.stringify(LoRA));
if (LoRA !== null && LoRA.length > 0) {
promptField.value = prompt.replace(/,+$/, ''); // remove any trailing ,
if (testDiffusers?.checked === false) {
showToast("LoRA's are only supported with diffusers. Just stripping the LoRA tag from the prompt.")
}
}
if (LoRA !== null && LoRA.length > 0 && testDiffusers?.checked) {
let modelNames = LoRA.map(e => e.lora_model_0)
let modelWeights = LoRA.map(e => e.lora_alpha_0)
loraModelField.value = {modelNames: modelNames, modelWeights: modelWeights}
showToast("Prompt successfully processed")
}
//promptField.dispatchEvent(new Event('change'));
});
// extract LoRA tags from strings
function extractLoraTags(prompt) {
// Define the regular expression for the tags
const regex = /<(?:lora|lyco):([^:>]+)(?::([^:>]*))?(?::([^:>]*))?>/gi
// Initialize an array to hold the matches
let matches = []
// Iterate over the string, finding matches
for (const match of prompt.matchAll(regex)) {
const modelFileName = match[1].trim()
const loraPathes = getAllModelPathes("lora", modelFileName)
if (loraPathes.length > 0) {
const loraPath = loraPathes[0]
// Initialize an object to hold a match
let loraTag = {
lora_model_0: loraPath,
}
//console.log("Model:" + modelFileName);
// If weight is provided, add it to the loraTag object
if (match[2] !== undefined && match[2] !== '') {
loraTag.lora_alpha_0 = parseFloat(match[2].trim())
}
else
{
loraTag.lora_alpha_0 = 0.5
}
// If blockweights are provided, add them to the loraTag object
if (match[3] !== undefined && match[3] !== '') {
loraTag.blockweights = match[3].trim()
}
// Add the loraTag object to the array of matches
matches.push(loraTag);
//console.log(JSON.stringify(matches));
}
else
{
showToast("LoRA not found: " + match[1].trim(), 5000, true)
}
}
// Clean up the prompt string, e.g. from "apple, banana, <lora:...>, orange, <lora:...> , pear <lora:...>, <lora:...>" to "apple, banana, orange, pear"
let cleanedPrompt = prompt.replace(regex, '').replace(/(\s*,\s*(?=\s*,|$))|(^\s*,\s*)|\s+/g, ' ').trim();
//console.log('Matches: ' + JSON.stringify(matches));
// Return the array of matches and cleaned prompt string
return {
LoRA: matches,
prompt: cleanedPrompt
}
}
})()

View File

@ -0,0 +1,454 @@
;(function() {
"use strict"
///////////////////// Function section
function smoothstep(x) {
return x * x * (3 - 2 * x)
}
function smootherstep(x) {
return x * x * x * (x * (x * 6 - 15) + 10)
}
function smootheststep(x) {
let y = -20 * Math.pow(x, 7)
y += 70 * Math.pow(x, 6)
y -= 84 * Math.pow(x, 5)
y += 35 * Math.pow(x, 4)
return y
}
function getCurrentTime() {
const now = new Date()
let hours = now.getHours()
let minutes = now.getMinutes()
let seconds = now.getSeconds()
hours = hours < 10 ? `0${hours}` : hours
minutes = minutes < 10 ? `0${minutes}` : minutes
seconds = seconds < 10 ? `0${seconds}` : seconds
return `${hours}:${minutes}:${seconds}`
}
function addLogMessage(message) {
const logContainer = document.getElementById("merge-log")
logContainer.innerHTML += `<i>${getCurrentTime()}</i> ${message}<br>`
// Scroll to the bottom of the log
logContainer.scrollTop = logContainer.scrollHeight
document.querySelector("#merge-log-container").style.display = "block"
}
function addLogSeparator() {
const logContainer = document.getElementById("merge-log")
logContainer.innerHTML += "<hr>"
logContainer.scrollTop = logContainer.scrollHeight
}
function drawDiagram(fn) {
const SIZE = 300
const canvas = document.getElementById("merge-canvas")
canvas.height = canvas.width = SIZE
const ctx = canvas.getContext("2d")
// Draw coordinate system
ctx.scale(1, -1)
ctx.translate(0, -canvas.height)
ctx.lineWidth = 1
ctx.beginPath()
ctx.strokeStyle = "white"
ctx.moveTo(0, 0)
ctx.lineTo(0, SIZE)
ctx.lineTo(SIZE, SIZE)
ctx.lineTo(SIZE, 0)
ctx.lineTo(0, 0)
ctx.lineTo(SIZE, SIZE)
ctx.stroke()
ctx.beginPath()
ctx.setLineDash([1, 2])
const n = SIZE / 10
for (let i = n; i < SIZE; i += n) {
ctx.moveTo(0, i)
ctx.lineTo(SIZE, i)
ctx.moveTo(i, 0)
ctx.lineTo(i, SIZE)
}
ctx.stroke()
ctx.beginPath()
ctx.setLineDash([])
ctx.beginPath()
ctx.strokeStyle = "black"
ctx.lineWidth = 3
// Plot function
const numSamples = 20
for (let i = 0; i <= numSamples; i++) {
const x = i / numSamples
const y = fn(x)
const canvasX = x * SIZE
const canvasY = y * SIZE
if (i === 0) {
ctx.moveTo(canvasX, canvasY)
} else {
ctx.lineTo(canvasX, canvasY)
}
}
ctx.stroke()
// Plot alpha values (yellow boxes)
let start = parseFloat(document.querySelector("#merge-start").value)
let step = parseFloat(document.querySelector("#merge-step").value)
let iterations = document.querySelector("#merge-count").value >> 0
ctx.beginPath()
ctx.fillStyle = "yellow"
for (let i = 0; i < iterations; i++) {
const alpha = (start + i * step) / 100
const x = alpha * SIZE
const y = fn(alpha) * SIZE
if (x <= SIZE) {
ctx.rect(x - 3, y - 3, 6, 6)
ctx.fill()
} else {
ctx.strokeStyle = "red"
ctx.moveTo(0, 0)
ctx.lineTo(0, SIZE)
ctx.lineTo(SIZE, SIZE)
ctx.lineTo(SIZE, 0)
ctx.lineTo(0, 0)
ctx.lineTo(SIZE, SIZE)
ctx.stroke()
addLogMessage("<i>Warning: maximum ratio is &#8805; 100%</i>")
}
}
}
function updateChart() {
let fn = (x) => x
switch (document.querySelector("#merge-interpolation").value) {
case "SmoothStep":
fn = smoothstep
break
case "SmootherStep":
fn = smootherstep
break
case "SmoothestStep":
fn = smootheststep
break
}
drawDiagram(fn)
}
createTab({
id: "merge",
icon: "fa-code-merge",
label: "Merge models",
css: `
#tab-content-merge .tab-content-inner {
max-width: 100%;
padding: 10pt;
}
.merge-container {
margin-left: 15%;
margin-right: 15%;
text-align: left;
display: inline-grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: auto auto auto;
gap: 0px 0px;
grid-auto-flow: row;
grid-template-areas:
"merge-input merge-config"
"merge-buttons merge-buttons";
}
.merge-container p {
margin-top: 3pt;
margin-bottom: 3pt;
}
.merge-config .tab-content {
background: var(--background-color1);
border-radius: 3pt;
}
.merge-config .tab-content-inner {
text-align: left;
}
.merge-input {
grid-area: merge-input;
padding-left:1em;
}
.merge-config {
grid-area: merge-config;
padding:1em;
}
.merge-config input {
margin-bottom: 3px;
}
.merge-config select {
margin-bottom: 3px;
}
.merge-buttons {
grid-area: merge-buttons;
padding:1em;
text-align: center;
}
#merge-button {
padding: 8px;
width:20em;
}
div#merge-log {
height:150px;
overflow-x:hidden;
overflow-y:scroll;
background:var(--background-color1);
border-radius: 3pt;
}
div#merge-log i {
color: hsl(var(--accent-hue), 100%, calc(2*var(--accent-lightness)));
font-family: monospace;
}
.disabled {
background: var(--background-color4);
color: var(--text-color);
}
#merge-type-tabs {
border-bottom: 1px solid black;
}
#merge-log-container {
display: none;
}
.merge-container #merge-warning {
color: rgb(153, 153, 153);
}`,
content: `
<div class="merge-container panel-box">
<div class="merge-input">
<p><label for="#mergeModelA">Select Model A:</label></p>
<input id="mergeModelA" type="text" spellcheck="false" autocomplete="off" class="model-filter" data-path="" />
<p><label for="#mergeModelB">Select Model B:</label></p>
<input id="mergeModelB" type="text" spellcheck="false" autocomplete="off" class="model-filter" data-path="" />
<br/><br/>
<p id="merge-warning"><small><b>Important:</b> Please merge models of similar type.<br/>For e.g. <code>SD 1.4</code> models with only <code>SD 1.4/1.5</code> models,<br/><code>SD 2.0</code> with <code>SD 2.0</code>-type, and <code>SD 2.1</code> with <code>SD 2.1</code>-type models.</small></p>
<br/>
<table>
<tr>
<td><label for="#merge-filename">Output file name:</label></td>
<td><input id="merge-filename" size=24> <i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Base name of the output file.<br>Mix ratio and file suffix will be appended to this.</span></i></td>
</tr>
<tr>
<td><label for="#merge-fp">Output precision:</label></td>
<td><select id="merge-fp">
<option value="fp16">fp16 (smaller file size)</option>
<option value="fp32">fp32 (larger file size)</option>
</select>
<i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Image generation uses fp16, so it's a good choice.<br>Use fp32 if you want to use the result models for more mixes</span></i>
</td>
</tr>
<tr>
<td><label for="#merge-format">Output file format:</label></td>
<td><select id="merge-format">
<option value="safetensors">Safetensors (recommended)</option>
<option value="ckpt">CKPT/Pickle (legacy format)</option>
</select>
</td>
</tr>
</table>
<br/>
<div id="merge-log-container">
<p><label for="#merge-log">Log messages:</label></p>
<div id="merge-log"></div>
</div>
</div>
<div class="merge-config">
<div class="tab-container">
<span id="tab-merge-opts-single" class="tab active">
<span>Make a single file</small></span>
</span>
<span id="tab-merge-opts-batch" class="tab">
<span>Make multiple variations</small></span>
</span>
</div>
<div>
<div id="tab-content-merge-opts-single" class="tab-content active">
<div class="tab-content-inner">
<small>Saves a single merged model file, at the specified merge ratio.</small><br/><br/>
<label for="#single-merge-ratio-slider">Merge ratio:</label>
<input id="single-merge-ratio-slider" name="single-merge-ratio-slider" class="editor-slider" value="50" type="range" min="1" max="1000">
<input id="single-merge-ratio" size=2 value="5">%
<i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Model A's contribution to the mix. The rest will be from Model B.</span></i>
</div>
</div>
<div id="tab-content-merge-opts-batch" class="tab-content">
<div class="tab-content-inner">
<small>Saves multiple variations of the model, at different merge ratios.<br/>Each variation will be saved as a separate file.</small><br/><br/>
<table>
<tr><td><label for="#merge-count">Number of variations:</label></td>
<td> <input id="merge-count" size=2 value="5"></td>
<td> <i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Number of models to create</span></i></td></tr>
<tr><td><label for="#merge-start">Starting merge ratio:</label></td>
<td> <input id="merge-start" size=2 value="5">%</td>
<td> <i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Smallest share of model A in the mix</span></i></td></tr>
<tr><td><label for="#merge-step">Increment each step:</label></td>
<td> <input id="merge-step" size=2 value="10">%</td>
<td> <i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Share of model A added into the mix per step</span></i></td></tr>
<tr><td><label for="#merge-interpolation">Interpolation model:</label></td>
<td> <select id="merge-interpolation">
<option>Exact</option>
<option>SmoothStep</option>
<option>SmootherStep</option>
<option>SmoothestStep</option>
</select></td>
<td> <i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Sigmoid function to be applied to the model share before mixing</span></i></td></tr>
</table>
<br/>
<small>Preview of variation ratios:</small><br/>
<canvas id="merge-canvas" width="400" height="400"></canvas>
</div>
</div>
</div>
</div>
<div class="merge-buttons">
<button id="merge-button" class="primaryButton">Merge models</button>
</div>
</div>`,
onOpen: ({ firstOpen }) => {
if (!firstOpen) {
return
}
const tabSettingsSingle = document.querySelector("#tab-merge-opts-single")
const tabSettingsBatch = document.querySelector("#tab-merge-opts-batch")
linkTabContents(tabSettingsSingle)
linkTabContents(tabSettingsBatch)
console.log("Activate")
let mergeModelAField = new ModelDropdown(document.querySelector("#mergeModelA"), "stable-diffusion")
let mergeModelBField = new ModelDropdown(document.querySelector("#mergeModelB"), "stable-diffusion")
updateChart()
// slider
const singleMergeRatioField = document.querySelector("#single-merge-ratio")
const singleMergeRatioSlider = document.querySelector("#single-merge-ratio-slider")
function updateSingleMergeRatio() {
singleMergeRatioField.value = singleMergeRatioSlider.value / 10
singleMergeRatioField.dispatchEvent(new Event("change"))
}
function updateSingleMergeRatioSlider() {
if (singleMergeRatioField.value < 0) {
singleMergeRatioField.value = 0
} else if (singleMergeRatioField.value > 100) {
singleMergeRatioField.value = 100
}
singleMergeRatioSlider.value = singleMergeRatioField.value * 10
singleMergeRatioSlider.dispatchEvent(new Event("change"))
}
singleMergeRatioSlider.addEventListener("input", updateSingleMergeRatio)
singleMergeRatioField.addEventListener("input", updateSingleMergeRatioSlider)
updateSingleMergeRatio()
document.querySelector(".merge-config").addEventListener("change", updateChart)
document.querySelector("#merge-button").addEventListener("click", async function(e) {
// Build request template
let model0 = mergeModelAField.value
let model1 = mergeModelBField.value
let request = { model0: model0, model1: model1 }
request["use_fp16"] = document.querySelector("#merge-fp").value == "fp16"
let iterations = document.querySelector("#merge-count").value >> 0
let start = parseFloat(document.querySelector("#merge-start").value)
let step = parseFloat(document.querySelector("#merge-step").value)
if (isTabActive(tabSettingsSingle)) {
start = parseFloat(singleMergeRatioField.value)
step = 0
iterations = 1
addLogMessage(`merge ratio = ${start}%`)
} else {
addLogMessage(`start = ${start}%`)
addLogMessage(`step = ${step}%`)
}
if (start + (iterations - 1) * step >= 100) {
addLogMessage("<i>Aborting: maximum ratio is &#8805; 100%</i>")
addLogMessage("Reduce the number of variations or the step size")
addLogSeparator()
document.querySelector("#merge-count").focus()
return
}
if (document.querySelector("#merge-filename").value == "") {
addLogMessage("<i>Aborting: No output file name specified</i>")
addLogSeparator()
document.querySelector("#merge-filename").focus()
return
}
// Disable merge button
e.target.disabled = true
e.target.classList.add("disabled")
let cursor = $("body").css("cursor")
let label = document.querySelector("#merge-button").innerHTML
$("body").css("cursor", "progress")
document.querySelector("#merge-button").innerHTML = "Merging models ..."
addLogMessage("Merging models")
addLogMessage("Model A: " + model0)
addLogMessage("Model B: " + model1)
// Batch main loop
for (let i = 0; i < iterations; i++) {
let alpha = (start + i * step) / 100
if (isTabActive(tabSettingsBatch)) {
switch (document.querySelector("#merge-interpolation").value) {
case "SmoothStep":
alpha = smoothstep(alpha)
break
case "SmootherStep":
alpha = smootherstep(alpha)
break
case "SmoothestStep":
alpha = smootheststep(alpha)
break
}
}
addLogMessage(`merging batch job ${i + 1}/${iterations}, alpha = ${alpha.toFixed(5)}...`)
request["out_path"] = document.querySelector("#merge-filename").value
request["out_path"] += "-" + alpha.toFixed(5) + "." + document.querySelector("#merge-format").value
addLogMessage(`&nbsp;&nbsp;filename: ${request["out_path"]}`)
// sdkit documentation: "ratio - the ratio of the second model. 1 means only the second model will be used."
request["ratio"] = 1-alpha
let res = await fetch("/model/merge", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
})
const data = await res.json()
addLogMessage(JSON.stringify(data))
}
addLogMessage(
"<b>Done.</b> The models have been saved to your <tt>models/stable-diffusion</tt> folder."
)
addLogSeparator()
// Re-enable merge button
$("body").css("cursor", cursor)
document.querySelector("#merge-button").innerHTML = label
e.target.disabled = false
e.target.classList.remove("disabled")
// Update model list
stableDiffusionModelField.innerHTML = ""
vaeModelField.innerHTML = ""
hypernetworkModelField.innerHTML = ""
await getModels()
})
},
})
})()

View File

@ -1,770 +0,0 @@
;(function() {
"use strict"
let mergeCSS = `
/*********** Main tab ***********/
.tab-centered {
justify-content: center;
}
#model-tool-tab-content {
background-color: var(--background-color3);
}
#model-tool-tab-content .tab-content-inner {
text-align: initial;
}
#model-tool-tab-bar .tab {
margin-bottom: 0px;
border-top-left-radius: var(--input-border-radius);
background-color: var(--background-color3);
padding: 6px 6px 0.8em 6px;
}
#tab-content-merge .tab-content-inner {
max-width: 100%;
padding: 10pt;
}
/*********** Merge UI ***********/
.merge-model-container {
margin-left: 15%;
margin-right: 15%;
text-align: left;
display: inline-grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: auto auto auto;
gap: 0px 0px;
grid-auto-flow: row;
grid-template-areas:
"merge-input merge-config"
"merge-buttons merge-buttons";
}
.merge-model-container p {
margin-top: 3pt;
margin-bottom: 3pt;
}
.merge-config .tab-content {
background: var(--background-color1);
border-radius: 3pt;
}
.merge-config .tab-content-inner {
text-align: left;
}
.merge-input {
grid-area: merge-input;
padding-left:1em;
}
.merge-config {
grid-area: merge-config;
padding:1em;
}
.merge-config input {
margin-bottom: 3px;
}
.merge-config select {
margin-bottom: 3px;
}
.merge-buttons {
grid-area: merge-buttons;
padding:1em;
text-align: center;
}
#merge-button {
padding: 8px;
width:20em;
}
div#merge-log {
height:150px;
overflow-x:hidden;
overflow-y:scroll;
background:var(--background-color1);
border-radius: 3pt;
}
div#merge-log i {
color: hsl(var(--accent-hue), 100%, calc(2*var(--accent-lightness)));
font-family: monospace;
}
.disabled {
background: var(--background-color4);
color: var(--text-color);
}
#merge-type-tabs {
border-bottom: 1px solid black;
}
#merge-log-container {
display: none;
}
.merge-model-container #merge-warning {
color: var(--small-label-color);
}
/*********** LORA UI ***********/
.lora-manager-grid {
display: grid;
gap: 0px 8px;
grid-auto-flow: row;
}
@media screen and (min-width: 1501px) {
.lora-manager-grid textarea {
height:350px;
}
.lora-manager-grid {
grid-template-columns: auto 1fr 1fr;
grid-template-rows: auto 1fr;
grid-template-areas:
"selector selector selector"
"thumbnail keywords notes";
}
}
@media screen and (min-width: 1001px) and (max-width: 1500px) {
.lora-manager-grid textarea {
height:250px;
}
.lora-manager-grid {
grid-template-columns: auto auto;
grid-template-rows: auto auto auto;
grid-template-areas:
"selector selector"
"thumbnail keywords"
"thumbnail notes";
}
}
@media screen and (max-width: 1000px) {
.lora-manager-grid textarea {
height:200px;
}
.lora-manager-grid {
grid-template-columns: auto;
grid-template-rows: auto auto auto auto;
grid-template-areas:
"selector"
"keywords"
"thumbnail"
"notes";
}
}
.lora-manager-grid-selector {
grid-area: selector;
justify-self: start;
}
.lora-manager-grid-thumbnail {
grid-area: thumbnail;
justify-self: center;
}
.lora-manager-grid-keywords {
grid-area: keywords;
}
.lora-manager-grid-notes {
grid-area: notes;
}
.lora-manager-grid p {
margin-bottom: 2px;
}
`
let mergeUI = `
<div class="merge-model-container panel-box">
<div class="merge-input">
<p><label for="#mergeModelA">Select Model A:</label></p>
<input id="mergeModelA" type="text" spellcheck="false" autocomplete="off" class="model-filter" data-path="" />
<p><label for="#mergeModelB">Select Model B:</label></p>
<input id="mergeModelB" type="text" spellcheck="false" autocomplete="off" class="model-filter" data-path="" />
<br/><br/>
<p id="merge-warning"><small><b>Important:</b> Please merge models of similar type.<br/>For e.g. <code>SD 1.4</code> models with only <code>SD 1.4/1.5</code> models,<br/><code>SD 2.0</code> with <code>SD 2.0</code>-type, and <code>SD 2.1</code> with <code>SD 2.1</code>-type models.</small></p>
<br/>
<table>
<tr>
<td><label for="#merge-filename">Output file name:</label></td>
<td><input id="merge-filename" size=24> <i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Base name of the output file.<br>Mix ratio and file suffix will be appended to this.</span></i></td>
</tr>
<tr>
<td><label for="#merge-fp">Output precision:</label></td>
<td><select id="merge-fp">
<option value="fp16">fp16 (smaller file size)</option>
<option value="fp32">fp32 (larger file size)</option>
</select>
<i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Image generation uses fp16, so it's a good choice.<br>Use fp32 if you want to use the result models for more mixes</span></i>
</td>
</tr>
<tr>
<td><label for="#merge-format">Output file format:</label></td>
<td><select id="merge-format">
<option value="safetensors">Safetensors (recommended)</option>
<option value="ckpt">CKPT/Pickle (legacy format)</option>
</select>
</td>
</tr>
</table>
<br/>
<div id="merge-log-container">
<p><label for="#merge-log">Log messages:</label></p>
<div id="merge-log"></div>
</div>
</div>
<div class="merge-config">
<div class="tab-container">
<span id="tab-merge-opts-single" class="tab active">
<span>Make a single file</small></span>
</span>
<span id="tab-merge-opts-batch" class="tab">
<span>Make multiple variations</small></span>
</span>
</div>
<div>
<div id="tab-content-merge-opts-single" class="tab-content active">
<div class="tab-content-inner">
<small>Saves a single merged model file, at the specified merge ratio.</small><br/><br/>
<label for="#single-merge-ratio-slider">Merge ratio:</label>
<input id="single-merge-ratio-slider" name="single-merge-ratio-slider" class="editor-slider" value="50" type="range" min="1" max="1000">
<input id="single-merge-ratio" size=2 value="5">%
<i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Model A's contribution to the mix. The rest will be from Model B.</span></i>
</div>
</div>
<div id="tab-content-merge-opts-batch" class="tab-content">
<div class="tab-content-inner">
<small>Saves multiple variations of the model, at different merge ratios.<br/>Each variation will be saved as a separate file.</small><br/><br/>
<table>
<tr><td><label for="#merge-count">Number of variations:</label></td>
<td> <input id="merge-count" size=2 value="5"></td>
<td> <i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Number of models to create</span></i></td></tr>
<tr><td><label for="#merge-start">Starting merge ratio:</label></td>
<td> <input id="merge-start" size=2 value="5">%</td>
<td> <i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Smallest share of model A in the mix</span></i></td></tr>
<tr><td><label for="#merge-step">Increment each step:</label></td>
<td> <input id="merge-step" size=2 value="10">%</td>
<td> <i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Share of model A added into the mix per step</span></i></td></tr>
<tr><td><label for="#merge-interpolation">Interpolation model:</label></td>
<td> <select id="merge-interpolation">
<option>Exact</option>
<option>SmoothStep</option>
<option>SmootherStep</option>
<option>SmoothestStep</option>
</select></td>
<td> <i class="fa-solid fa-circle-question help-btn"><span class="simple-tooltip top-left">Sigmoid function to be applied to the model share before mixing</span></i></td></tr>
</table>
<br/>
<small>Preview of variation ratios:</small><br/>
<canvas id="merge-canvas" width="400" height="400"></canvas>
</div>
</div>
</div>
</div>
<div class="merge-buttons">
<button id="merge-button" class="primaryButton">Merge models</button>
</div>
</div>`
let loraUI=`
<div class="panel-box lora-manager-grid">
<div class="lora-manager-grid-selector">
<label for="#loraModel">Select Lora:</label>
<input id="loraModel" type="text" spellcheck="false" autocomplete="off" class="model-filter" data-path="" />
</div>
<div class="lora-manager-grid-thumbnail">
<p style="height:2em;">Thumbnail:</p>
<div style="position:relative; height:256px; width:256px;background-color:#222;border-radius:1em;margin-bottom:1em;">
<i id="lora-manager-image-placeholder" class="fa-regular fa-image" style="font-size:500%;color:#555;position:absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);"></i>
<img id="lora-manager-image" class="displayNone" style="border-radius:6px;max-height:256px;max-width:256px;"/>
</div>
<div style="text-align:center;">
<button class="tertiaryButton" id="lora-manager-upload-button"><i class="fa-solid fa-upload"></i> Upload new thumbnail</button>
<input id="lora-manager-upload-input" name="lora-manager-upload-input" type="file" class="displayNone">
<!-- button class="tertiaryButton"><i class="fa-solid fa-trash-can"></i> Remove</button -->
</div>
</div>
<div class="lora-manager-grid-keywords">
<p style="height:2em;">Keywords:
<span style="float:right;margin-bottom:4px;"><button id="lora-keyword-from-civitai" class="tertiaryButton smallButton">Import from Civitai</button></span></p>
<textarea style="width:100%;resize:vertical;" id="lora-manager-keywords" placeholder="Put LORA specific keywords here..."></textarea>
<p style="color:var(--small-label-color);">
<b>LORA model keywords</b> can be used via the <code>+&nbsp;Embeddings</code> button. They get added to the embedding
keyword menu when the LORA has been selected in the image settings.
</p>
</div>
<div class="lora-manager-grid-notes">
<p style="height:2em;">Notes:</p>
<textarea style="width:100%;resize:vertical;" id="lora-manager-notes" placeholder="Place for things you want to remember..."></textarea>
<p id="civitai-section" class="displayNone">
<b>Civitai model page:</b>
<a id="civitai-model-page" target="_blank"></a>
</p>
</div>
</div>`
let tabHTML=`
<div id="model-tool-tab-bar" class="tab-container tab-centered">
<span id="tab-model-loraUI" class="tab active">
<span><i class="fa-solid fa-key"></i> Lora Keywords</small></span>
</span>
<span id="tab-model-mergeUI" class="tab">
<span><i class="fa-solid fa-code-merge"></i> Merge Models</small></span>
</span>
</div>
<div id="model-tool-tab-content" class="panel-box">
<div id="tab-content-model-loraUI" class="tab-content active">
<div class="tab-content-inner">
${loraUI}
</div>
</div>
<div id="tab-content-model-mergeUI" class="tab-content">
<div class="tab-content-inner">
${mergeUI}
</div>
</div>
</div>`
///////////////////// Function section
function smoothstep(x) {
return x * x * (3 - 2 * x)
}
function smootherstep(x) {
return x * x * x * (x * (x * 6 - 15) + 10)
}
function smootheststep(x) {
let y = -20 * Math.pow(x, 7)
y += 70 * Math.pow(x, 6)
y -= 84 * Math.pow(x, 5)
y += 35 * Math.pow(x, 4)
return y
}
function getCurrentTime() {
const now = new Date()
let hours = now.getHours()
let minutes = now.getMinutes()
let seconds = now.getSeconds()
hours = hours < 10 ? `0${hours}` : hours
minutes = minutes < 10 ? `0${minutes}` : minutes
seconds = seconds < 10 ? `0${seconds}` : seconds
return `${hours}:${minutes}:${seconds}`
}
function addLogMessage(message) {
const logContainer = document.getElementById("merge-log")
logContainer.innerHTML += `<i>${getCurrentTime()}</i> ${message}<br>`
// Scroll to the bottom of the log
logContainer.scrollTop = logContainer.scrollHeight
document.querySelector("#merge-log-container").style.display = "block"
}
function addLogSeparator() {
const logContainer = document.getElementById("merge-log")
logContainer.innerHTML += "<hr>"
logContainer.scrollTop = logContainer.scrollHeight
}
function drawDiagram(fn) {
const SIZE = 300
const canvas = document.getElementById("merge-canvas")
canvas.height = canvas.width = SIZE
const ctx = canvas.getContext("2d")
// Draw coordinate system
ctx.scale(1, -1)
ctx.translate(0, -canvas.height)
ctx.lineWidth = 1
ctx.beginPath()
ctx.strokeStyle = "white"
ctx.moveTo(0, 0)
ctx.lineTo(0, SIZE)
ctx.lineTo(SIZE, SIZE)
ctx.lineTo(SIZE, 0)
ctx.lineTo(0, 0)
ctx.lineTo(SIZE, SIZE)
ctx.stroke()
ctx.beginPath()
ctx.setLineDash([1, 2])
const n = SIZE / 10
for (let i = n; i < SIZE; i += n) {
ctx.moveTo(0, i)
ctx.lineTo(SIZE, i)
ctx.moveTo(i, 0)
ctx.lineTo(i, SIZE)
}
ctx.stroke()
ctx.beginPath()
ctx.setLineDash([])
ctx.beginPath()
ctx.strokeStyle = "black"
ctx.lineWidth = 3
// Plot function
const numSamples = 20
for (let i = 0; i <= numSamples; i++) {
const x = i / numSamples
const y = fn(x)
const canvasX = x * SIZE
const canvasY = y * SIZE
if (i === 0) {
ctx.moveTo(canvasX, canvasY)
} else {
ctx.lineTo(canvasX, canvasY)
}
}
ctx.stroke()
// Plot alpha values (yellow boxes)
let start = parseFloat(document.querySelector("#merge-start").value)
let step = parseFloat(document.querySelector("#merge-step").value)
let iterations = document.querySelector("#merge-count").value >> 0
ctx.beginPath()
ctx.fillStyle = "yellow"
for (let i = 0; i < iterations; i++) {
const alpha = (start + i * step) / 100
const x = alpha * SIZE
const y = fn(alpha) * SIZE
if (x <= SIZE) {
ctx.rect(x - 3, y - 3, 6, 6)
ctx.fill()
} else {
ctx.strokeStyle = "red"
ctx.moveTo(0, 0)
ctx.lineTo(0, SIZE)
ctx.lineTo(SIZE, SIZE)
ctx.lineTo(SIZE, 0)
ctx.lineTo(0, 0)
ctx.lineTo(SIZE, SIZE)
ctx.stroke()
addLogMessage("<i>Warning: maximum ratio is &#8805; 100%</i>")
}
}
}
function updateChart() {
let fn = (x) => x
switch (document.querySelector("#merge-interpolation").value) {
case "SmoothStep":
fn = smoothstep
break
case "SmootherStep":
fn = smootherstep
break
case "SmoothestStep":
fn = smootheststep
break
}
drawDiagram(fn)
}
function initMergeUI() {
const tabSettingsSingle = document.querySelector("#tab-merge-opts-single")
const tabSettingsBatch = document.querySelector("#tab-merge-opts-batch")
linkTabContents(tabSettingsSingle)
linkTabContents(tabSettingsBatch)
let mergeModelAField = new ModelDropdown(document.querySelector("#mergeModelA"), "stable-diffusion")
let mergeModelBField = new ModelDropdown(document.querySelector("#mergeModelB"), "stable-diffusion")
updateChart()
// slider
const singleMergeRatioField = document.querySelector("#single-merge-ratio")
const singleMergeRatioSlider = document.querySelector("#single-merge-ratio-slider")
function updateSingleMergeRatio() {
singleMergeRatioField.value = singleMergeRatioSlider.value / 10
singleMergeRatioField.dispatchEvent(new Event("change"))
}
function updateSingleMergeRatioSlider() {
if (singleMergeRatioField.value < 0) {
singleMergeRatioField.value = 0
} else if (singleMergeRatioField.value > 100) {
singleMergeRatioField.value = 100
}
singleMergeRatioSlider.value = singleMergeRatioField.value * 10
singleMergeRatioSlider.dispatchEvent(new Event("change"))
}
singleMergeRatioSlider.addEventListener("input", updateSingleMergeRatio)
singleMergeRatioField.addEventListener("input", updateSingleMergeRatioSlider)
updateSingleMergeRatio()
document.querySelector(".merge-config").addEventListener("change", updateChart)
document.querySelector("#merge-button").addEventListener("click", async function(e) {
// Build request template
let model0 = mergeModelAField.value
let model1 = mergeModelBField.value
let request = { model0: model0, model1: model1 }
request["use_fp16"] = document.querySelector("#merge-fp").value == "fp16"
let iterations = document.querySelector("#merge-count").value >> 0
let start = parseFloat(document.querySelector("#merge-start").value)
let step = parseFloat(document.querySelector("#merge-step").value)
if (isTabActive(tabSettingsSingle)) {
start = parseFloat(singleMergeRatioField.value)
step = 0
iterations = 1
addLogMessage(`merge ratio = ${start}%`)
} else {
addLogMessage(`start = ${start}%`)
addLogMessage(`step = ${step}%`)
}
if (start + (iterations - 1) * step >= 100) {
addLogMessage("<i>Aborting: maximum ratio is &#8805; 100%</i>")
addLogMessage("Reduce the number of variations or the step size")
addLogSeparator()
document.querySelector("#merge-count").focus()
return
}
if (document.querySelector("#merge-filename").value == "") {
addLogMessage("<i>Aborting: No output file name specified</i>")
addLogSeparator()
document.querySelector("#merge-filename").focus()
return
}
// Disable merge button
e.target.disabled = true
e.target.classList.add("disabled")
let cursor = $("body").css("cursor")
let label = document.querySelector("#merge-button").innerHTML
$("body").css("cursor", "progress")
document.querySelector("#merge-button").innerHTML = "Merging models ..."
addLogMessage("Merging models")
addLogMessage("Model A: " + model0)
addLogMessage("Model B: " + model1)
// Batch main loop
for (let i = 0; i < iterations; i++) {
let alpha = (start + i * step) / 100
if (isTabActive(tabSettingsBatch)) {
switch (document.querySelector("#merge-interpolation").value) {
case "SmoothStep":
alpha = smoothstep(alpha)
break
case "SmootherStep":
alpha = smootherstep(alpha)
break
case "SmoothestStep":
alpha = smootheststep(alpha)
break
}
}
addLogMessage(`merging batch job ${i + 1}/${iterations}, alpha = ${alpha.toFixed(5)}...`)
request["out_path"] = document.querySelector("#merge-filename").value
request["out_path"] += "-" + alpha.toFixed(5) + "." + document.querySelector("#merge-format").value
addLogMessage(`&nbsp;&nbsp;filename: ${request["out_path"]}`)
// sdkit documentation: "ratio - the ratio of the second model. 1 means only the second model will be used."
request["ratio"] = 1-alpha
let res = await fetch("/model/merge", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
})
const data = await res.json()
addLogMessage(JSON.stringify(data))
}
addLogMessage(
"<b>Done.</b> The models have been saved to your <tt>models/stable-diffusion</tt> folder."
)
addLogSeparator()
// Re-enable merge button
$("body").css("cursor", cursor)
document.querySelector("#merge-button").innerHTML = label
e.target.disabled = false
e.target.classList.remove("disabled")
// Update model list
stableDiffusionModelField.innerHTML = ""
vaeModelField.innerHTML = ""
hypernetworkModelField.innerHTML = ""
await getModels()
})
}
const LoraUI = {
modelField: undefined,
keywordsField: undefined,
notesField: undefined,
civitaiImportBtn: undefined,
civitaiSecion: undefined,
civitaiAnchor: undefined,
image: undefined,
imagePlaceholder: undefined,
init() {
LoraUI.modelField = new ModelDropdown(document.querySelector("#loraModel"), "lora", "None")
LoraUI.keywordsField = document.querySelector("#lora-manager-keywords")
LoraUI.notesField = document.querySelector("#lora-manager-notes")
LoraUI.civitaiImportBtn = document.querySelector("#lora-keyword-from-civitai")
LoraUI.civitaiSection = document.querySelector("#civitai-section")
LoraUI.civitaiAnchor = document.querySelector("#civitai-model-page")
LoraUI.image = document.querySelector("#lora-manager-image")
LoraUI.imagePlaceholder = document.querySelector("#lora-manager-image-placeholder")
LoraUI.uploadBtn = document.querySelector("#lora-manager-upload-button")
LoraUI.uploadInput = document.querySelector("#lora-manager-upload-input")
LoraUI.modelField.addEventListener("change", LoraUI.updateFields)
LoraUI.keywordsField.addEventListener("focusout", LoraUI.saveInfos)
LoraUI.notesField.addEventListener("focusout", LoraUI.saveInfos)
LoraUI.civitaiImportBtn.addEventListener("click", LoraUI.importFromCivitai)
LoraUI.uploadBtn.addEventListener("click", (e) => LoraUI.uploadInput.click())
LoraUI.uploadInput.addEventListener("change", LoraUI.uploadLoraThumb)
document.addEventListener("saveThumb", LoraUI.updateFields)
LoraUI.updateFields()
},
uploadLoraThumb(e) {
console.log(e)
if (LoraUI.uploadInput.files.length === 0) {
return
}
let reader = new FileReader()
let file = LoraUI.uploadInput.files[0]
reader.addEventListener("load", (event) => {
let img = document.createElement("img")
img.src = reader.result
onUseAsThumbnailClick(
{
use_lora_model: LoraUI.modelField.value,
},
img
)
})
if (file) {
reader.readAsDataURL(file)
}
},
updateFields() {
document.getElementById("civitai-section").classList.add("displayNone")
Bucket.retrieve(`modelinfo/lora/${LoraUI.modelField.value}`)
.then((info) => {
if (info == null) {
LoraUI.keywordsField.value = ""
LoraUI.notesField.value = ""
LoraUI.hideCivitaiLink()
} else {
LoraUI.keywordsField.value = info.keywords.join("\n")
LoraUI.notesField.value = info.notes
if ("civitai" in info && info["civitai"] != null) {
LoraUI.showCivitaiLink(info.civitai)
} else {
LoraUI.hideCivitaiLink()
}
}
})
Bucket.getImageAsDataURL(`${profileNameField.value}/lora/${LoraUI.modelField.value}.png`)
.then((data) => {
LoraUI.image.src=data
LoraUI.image.classList.remove("displayNone")
LoraUI.imagePlaceholder.classList.add("displayNone")
})
.catch((error) => {
LoraUI.image.classList.add("displayNone")
LoraUI.imagePlaceholder.classList.remove("displayNone")
})
},
saveInfos() {
let info = {
keywords: LoraUI.keywordsField.value
.split("\n")
.filter((x) => (x != "")),
notes: LoraUI.notesField.value,
civitai: LoraUI.civitaiSection.checkVisibility() ? LoraUI.civitaiAnchor.href : null,
}
Bucket.store(`modelinfo/lora/${LoraUI.modelField.value}`, info)
},
importFromCivitai() {
document.body.style["cursor"] = "progress"
fetch("/sha256/lora/"+LoraUI.modelField.value)
.then((result) => result.json())
.then((json) => fetch("https://civitai.com/api/v1/model-versions/by-hash/" + json.digest))
.then((result) => result.json())
.then((json) => {
document.body.style["cursor"] = "default"
if (json == null) {
return
}
if ("trainedWords" in json) {
LoraUI.keywordsField.value = json["trainedWords"].join("\n")
} else {
showToast("No keyword info found.")
}
if ("modelId" in json) {
LoraUI.showCivitaiLink("https://civitai.com/models/" + json.modelId)
} else {
LoraUI.hideCivitaiLink()
}
LoraUI.saveInfos()
})
},
showCivitaiLink(href) {
LoraUI.civitaiSection.classList.remove("displayNone")
LoraUI.civitaiAnchor.href = href
LoraUI.civitaiAnchor.innerHTML = LoraUI.civitaiAnchor.href
},
hideCivitaiLink() {
LoraUI.civitaiSection.classList.add("displayNone")
}
}
createTab({
id: "merge",
icon: "fa-toolbox",
label: "Model tools",
css: mergeCSS,
content: tabHTML,
onOpen: ({ firstOpen }) => {
if (!firstOpen) {
return
}
initMergeUI()
LoraUI.init()
const tabMergeUI = document.querySelector("#tab-model-mergeUI")
const tabLoraUI = document.querySelector("#tab-model-loraUI")
linkTabContents(tabMergeUI)
linkTabContents(tabLoraUI)
},
})
})()
async function getLoraKeywords(model) {
return Bucket.retrieve(`modelinfo/lora/${model}`)
.then((info) => info ? info.keywords : [])
}

View File

@ -4,7 +4,7 @@
PLUGINS.SELFTEST["release-notes"] = function() {
it("should be able to fetch CHANGES.md", async function() {
let releaseNotes = await fetch(
`https://raw.githubusercontent.com/easydiffusion/easydiffusion/main/CHANGES.md`
`https://raw.githubusercontent.com/cmdr2/stable-diffusion-ui/main/CHANGES.md`
)
expect(releaseNotes.status).toBe(200)
})
@ -36,7 +36,7 @@
const updateBranch = appConfig.update_branch || "main"
let releaseNotes = await fetch(
`https://raw.githubusercontent.com/easydiffusion/easydiffusion/${updateBranch}/CHANGES.md`
`https://raw.githubusercontent.com/cmdr2/stable-diffusion-ui/${updateBranch}/CHANGES.md`
)
if (!releaseNotes.ok) {
console.error("[release-notes] Failed to get CHANGES.md.")

View File

@ -1,80 +0,0 @@
// christmas hack, courtesy: https://pajasevi.github.io/CSSnowflakes/
;(function(){
"use strict";
function makeItSnow() {
const styleSheet = document.createElement("style")
styleSheet.textContent = `
/* customizable snowflake styling */
.snowflake {
color: #fff;
font-size: 1em;
font-family: Arial, sans-serif;
text-shadow: 0 0 5px #000;
}
.snowflake,.snowflake .inner{animation-iteration-count:infinite;animation-play-state:running}@keyframes snowflakes-fall{0%{transform:translateY(0)}100%{transform:translateY(110vh)}}@keyframes snowflakes-shake{0%,100%{transform:translateX(0)}50%{transform:translateX(80px)}}.snowflake{position:fixed;top:-10%;z-index:9999;-webkit-user-select:none;user-select:none;cursor:default;animation-name:snowflakes-shake;animation-duration:3s;animation-timing-function:ease-in-out}.snowflake .inner{animation-duration:10s;animation-name:snowflakes-fall;animation-timing-function:linear}.snowflake:nth-of-type(0){left:1%;animation-delay:0s}.snowflake:nth-of-type(0) .inner{animation-delay:0s}.snowflake:first-of-type{left:10%;animation-delay:1s}.snowflake:first-of-type .inner,.snowflake:nth-of-type(8) .inner{animation-delay:1s}.snowflake:nth-of-type(2){left:20%;animation-delay:.5s}.snowflake:nth-of-type(2) .inner,.snowflake:nth-of-type(6) .inner{animation-delay:6s}.snowflake:nth-of-type(3){left:30%;animation-delay:2s}.snowflake:nth-of-type(11) .inner,.snowflake:nth-of-type(3) .inner{animation-delay:4s}.snowflake:nth-of-type(4){left:40%;animation-delay:2s}.snowflake:nth-of-type(10) .inner,.snowflake:nth-of-type(4) .inner{animation-delay:2s}.snowflake:nth-of-type(5){left:50%;animation-delay:3s}.snowflake:nth-of-type(5) .inner{animation-delay:8s}.snowflake:nth-of-type(6){left:60%;animation-delay:2s}.snowflake:nth-of-type(7){left:70%;animation-delay:1s}.snowflake:nth-of-type(7) .inner{animation-delay:2.5s}.snowflake:nth-of-type(8){left:80%;animation-delay:0s}.snowflake:nth-of-type(9){left:90%;animation-delay:1.5s}.snowflake:nth-of-type(9) .inner{animation-delay:3s}.snowflake:nth-of-type(10){left:25%;animation-delay:0s}.snowflake:nth-of-type(11){left:65%;animation-delay:2.5s}
`
document.head.appendChild(styleSheet)
const snowflakes = document.createElement("div")
snowflakes.id = "snowflakes-container"
snowflakes.innerHTML = `
<div class="snowflakes" aria-hidden="true">
<div class="snowflake">
<div class="inner">❅</div>
</div>
<div class="snowflake">
<div class="inner">❅</div>
</div>
<div class="snowflake">
<div class="inner">❅</div>
</div>
<div class="snowflake">
<div class="inner">❅</div>
</div>
<div class="snowflake">
<div class="inner">❅</div>
</div>
<div class="snowflake">
<div class="inner">❅</div>
</div>
<div class="snowflake">
<div class="inner">❅</div>
</div>
<div class="snowflake">
<div class="inner">❅</div>
</div>
<div class="snowflake">
<div class="inner">❅</div>
</div>
<div class="snowflake">
<div class="inner">❅</div>
</div>
<div class="snowflake">
<div class="inner">❅</div>
</div>
<div class="snowflake">
<div class="inner">❅</div>
</div>
</div>`
document.body.appendChild(snowflakes)
const script = document.createElement("script")
script.innerHTML = `
$(document).ready(function() {
setTimeout(function() {
$("#snowflakes-container").fadeOut("slow", function() {$(this).remove()})
}, 10 * 1000)
})
`
document.body.appendChild(script)
}
let date = new Date()
if (date.getMonth() === 11 && date.getDate() >= 12) {
makeItSnow()
}
})()

View File

@ -1,317 +0,0 @@
;(function(){
"use strict";
const PAPERSIZE = [
{id: "a3p", width: 297, height: 420, unit: "mm"},
{id: "a3l", width: 420, height: 297, unit: "mm"},
{id: "a4p", width: 210, height: 297, unit: "mm"},
{id: "a4l", width: 297, height: 210, unit: "mm"},
{id: "ll", width: 279, height: 216, unit: "mm"},
{id: "lp", width: 216, height: 279, unit: "mm"},
{id: "hd", width: 1920, height: 1080, unit: "pixels"},
{id: "4k", width: 3840, height: 2160, unit: "pixels"},
]
// ---- Register plugin
PLUGINS['IMAGE_INFO_BUTTONS'].push({
html: '<i class="fa-solid fa-table-cells-large"></i> Download tiled image',
on_click: onDownloadTiledImage,
filter: (req, img) => req.tiling != "none",
})
var thisImage
function onDownloadTiledImage(req, img) {
document.getElementById("download-tiled-image-dialog").showModal()
thisImage = new Image()
thisImage.src = img.src
thisImage.dataset["prompt"] = img.dataset["prompt"]
}
// ---- Add HTML
document.getElementById('container').lastElementChild.insertAdjacentHTML("afterend",
`<dialog id="download-tiled-image-dialog">
<div class="dialog-header">
<div class="dialog-header-left">
<h4>Download tiled image</h4>
<span>Generate a larger image from this tile</span>
</div>
<div id="download-header-right">
<i id="downnload-tiled-close-button" class="fa-solid fa-xmark fa-lg"></i>
</div>
</div>
<div class="download-tiled-image dtim-container">
<div class="download-tiled-image-top">
<div class="tab-container">
<span id="tab-image-tiles" class="tab active">
<span>Number of tiles</small></span>
</span>
<span id="tab-image-size" class="tab">
<span>Image dimensions</span>
</span>
</div>
<div>
<div id="tab-content-image-tiles" class="tab-content active">
<div class="tab-content-inner">
<label for="dtim1-width">Width:</label> <input id="dtim1-width" min="1" max="99" type="number" value="2">
<label for="dtim1-height">Height:</label> <input id="dtim1-height" min="1" max="99" type="number" value="2">
</div>
</div>
<div id="tab-content-image-size" class="tab-content">
<div class="tab-content-inner">
<div class="method-2-options">
<label for="dtim2-width">Width:</label> <input id="dtim2-width" size="3" value="1920">
<label for="dtim2-height">Height:</label> <input id="dtim2-height" size="3" value="1080">
<select id="dtim2-unit">
<option>pixels</option>
<option>mm</option>
<option>inches</option>
</select>
</div>
<div class="method-2-dpi">
<label for="dtim2-dpi">DPI:</label> <input id="dtim2-dpi" size="3" value="72">
</div>
<div class="method-2-paper">
<i>Some standard sizes:</i><br>
<button id="dtim2-a3p">A3 portrait</button><button id="dtim2-a3l">A3 landscape</button><br>
<button id="dtim2-a4p">A4 portrait</button><button id="dtim2-a4l">A4 landscape</button><br>
<button id="dtim2-lp">Letter portrait</button><button id="dtim2-ll">Letter landscape</button><br>
<button id="dtim2-hd">Full HD</button><button id="dtim2-4k">4K</button>
</div>
</div>
</div>
</div>
</div>
<div class="download-tiled-image-placement">
<div class="tab-container">
<span id="tab-image-placement" class="tab active">
<span>Tile placement</span>
</span>
</div>
<div>
<div id="tab-content-image-placement" class="tab-content active">
<div class="tab-content-inner">
<img id="dtim-1tl" class="active" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA3BAMAAACiFTSCAAAAMFBMVEUCAgKIhobRz89vMJ7s6uo9PDx4d3ewra0bHR1dXV19NrLa2Nj+/f29u7uWlJQuLi7ws27qAAAACXBIWXMAAAsTAAALEwEAmpwYAAABlUlEQVQ4y7VUMU7DQBCckpYCJEpS0ByhcecuUZQUtvIHGku0vICSDtHkA9eltCylOEBKFInCRworXToK3kDJ7jpn2SYmgGESeWyPRuudvTugHTyC72momKDGMMJDLIhmgK+nWmuPXxtlxkhjExszRKqU6uRuTW7TYTwh6HTpR25+JLcngBJ5jL5wIecqu9nFbid3t27N7vhrtypqV2SfP4zc5pfu/Msb3P6U4fru1eXpVg7tcmnDZ1gb0s1ceAEcSPI3uM2B9xLf7Z3YLlfJ/WCppF1QbbqxeW0brlztjXzprBhJrW8nu4HWGlt/xz1qcrervfmT2ma3WxpTjfK5ZUioNg+VsUL+tiXuI8YJLrd8KHyENyaqPWC8QGiwwlJ4LtyvNtb9vFKrqZXXeebkrEiN3ZUNXHJnO3aJkxt2aH2gDRNTLdyzJvee1CZXUTSJrhA55itlfszUdqDrxCQmGIEu9KfFFCRJYnpIgyB4JJlPWM6cY6MjN+UW5MjdM7FKavF/pFbfRD9zv8rjBa6FT5EJn0HoA8lOiD4+8B3mAAAAAElFTkSuQmCC" />
<img id="dtim-1tr" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA3BAMAAACiFTSCAAAAMFBMVEUCAgKIhobRz89vMJ7s6uo9PDx4d3ewra0bHR1dXV19NrLa2Nj+/f29u7uWlJQuLi7ws27qAAAACXBIWXMAAAsTAAALEwEAmpwYAAABoUlEQVQ4y61UsU7CUBQ9o6uGmJgwNSQOLS7dOndrGfwEDWnC4tQNB8duxoUfYGN86fZgIWy+iVUnwwYf4Oi9lxa0tFSpB9IDXM6775773gUaYWjbtoO+IrI1VsIKnjt2CYCllJqir7Wt7SlWWmn+m+t53sQbU5hAamtJrxRr/mppUnuZOgszOlgJK7gCUS93YVbzKqx2q9U2q71Mbf1Qbxc/qqadu7y509W7nX8Pt/K6JwwKO+HCGLRNKPy4oA9mkYUnwGeSJM9IBDknOJN+PNV2rEy9XyXLvaGcktuY0FBux9AP5rVYd96SofCsWFje0NJwUd2rUse/UTfLPTspd83iFFZZYY4xbKoRsKlmaypjjoaICA+4ZYrO8SJ8mfEV0PF9P0Tb94U3wj7eheaHJ3VZLKxbcs4P6uartz/nMYlKbFnzYtWe5ze0wtSjDd1Ph7iReheucS0aRYM78pwoiiDPUc6Dpg19S9N0ipYOgiClw5TqgN6I6aGD7S2RkcsbppnKbLPnPHt7VZOpxvN/cq1cHf9BbeFeqIsL4Wt8CN/gC1XPfwv6U6jJAAAAAElFTkSuQmCC" /><br>
<img id="dtim-1bl" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA3BAMAAACiFTSCAAAAMFBMVEUCAgKIhobRz89vMJ7s6uo9PDx4d3ewra0bHR1dXV19NrLa2Nj+/f29u7uWlJQuLi7ws27qAAAACXBIWXMAAAsTAAALEwEAmpwYAAABjElEQVQ4y7WUsU7DMBCG/5GVoUiMMLC4ZcmWrVXVDq7yDiyRuvIEjGyIpS/graMVKYMBqVUkhoYOUTc2Bp6BEd+5qdI2SasGLpE/KZc/d76LD/i6JrvFPfMKGfMGDOCTGUMwA/SYA8yL7iEM8w2yzH1AHderh9D1alGuXmmtBaVGchFgQe8J69bOHZnIyCHsYu8AUkZRZLpYSClf0dAm4zCchGOEOWkNW7ggAO0+2QcY/SUS5ozZ+6uqNVHHR9Q8q1Bnm9+B1B17HdGxbDe1zn7sA1V7DskucbfmObOFb0LThrZTsjlGzHcw0iXcU6woQxFv9i3rah5UdSxvSa/+EMn6hp6iroy9+s/YL2mSjlxRE1fUkX2wZNqiPjrDTwmfDnbsjNeH0q9Y9ZRN2diJjeliJ+ksj+2v3W5j3d2N+R5b4T/fcjuvqppMvqfsdbqaxF7VCc3Vho9eUd0pZi6q1cpThemwdYB9NVVK2cy1NsLYmaqNNmZgZ6sQa7VPmWuavQG9ZkkjV+u42QH8BWe+iD71TSARAAAAAElFTkSuQmCC" />
<img id="dtim-1br" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA3BAMAAACiFTSCAAAAMFBMVEUCAgKIhobRz89vMJ7s6uo9PDx4d3ewra0bHR1dXV19NrLa2Nj+/f29u7uWlJQuLi7ws27qAAAACXBIWXMAAAsTAAALEwEAmpwYAAABkklEQVQ4y7VULU/DUBQ9EgtZSEimliWIt2Lmnq5rJ/gJkKXJDGquCGQdwewPzE2+PPeGWeaomgVF6tgPmOTe2zWkox8LC6dLT/ZuTs9957UXPQbuhTxcCF/jU/gGYBpgLH/7yIQNYuHXctniS9hhWlU+Wh03qVX1wwt1+eGKyoZXl8iYFbdmlFIj4N1au0THBUFgLTLrAvphSjcXUPk0RLNocodbpiiC3GcFT4C+7/shur4vvBX28SG0+o/UTHNqrZnXe3uVrW3oKtScuVeUvZYTK3lvyq21pBYRHihzxjlehC/3fHXqgQ5SArapAI9C63w1XR3GUuw75neuN6otV++78SOyza9Dv/lAj1Yf5T061XsQrjnUdSpMoYZ5qLSQvgG7JEmekQgOOWk9sV2l6kxqT4V3Nw1zb7IMyVsvBIcb6+w3lpfn1V+Jw1Awr5tMOq/XqzVdf1Mr9tZ7701JzZ+ia1ab352z6mc6cGO52hiapWPnlFM0U51ximbqUGu90KSOabTyyCWi5UyYO5/n6pPwDYr8fwvXgN7jAAAAAElFTkSuQmCC" /> <br>
<img id="dtim-1center" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA3BAMAAACiFTSCAAAAMFBMVEUBAQGPjY3Rz89DQ0O0sbHz8vJZJoFwbm6+vLxBHV10MqY6ODifnZ1XV1cdHR3c2trZIbFLAAAACXBIWXMAAAsTAAALEwEAmpwYAAACCElEQVQ4y7VVPWvjQBCVnZXt5JRT1LsQwwnS7YHrgLg6hTBsva4MSeUurX5CqqtTuXCVn6CAf0DgimvvJ4iFredmd2VZcqTYIWSap2V4+/HezMgDSAdgIw0cFhVeMQAPIAuUWfF44jAdOix8k8YsmCNXyEuGynzkQ4u68BE8LbKJsJGFDkvfYe6Lufe5ePi7unywUePY4Suhl4iMCaGlFOWQQGiRhw5Tc3b9MIiZe1Deehhkg3nXu5MirGW5NmnmkNjX9EFs1VKN7djgNg+bovae3a15cpg+ZIfquGP97J2h0viJ5cT6SoZaX+lspYyoX2doFBXjlyiaRtHV+XL5++5u+TiITExXQRR5XGeBQIkoyouNjadQSqm1Tn2pmg8bbe5NelFb0nQMKL25XxO7tsSoxmu/q80XbdXK/eZrs/2iR/OR4a53m1eO8ayPfWDJqHU2VuwywNbVnt6czflbttucVGOkmUbdUI2WSG0g0ZvepuNbiu22IM1NPAZ2uV2x7csnDf3FywFdhQPmttYUT6kkubv5D4+bWlOoFNWa5BRJHiJNDzTDQzUd21fqoaHdPaaO1/kp/d1mwwkdunfsIx2K7Q6lapmDIrVihqAsG41qiZ0tbq7ZFhw6jKsWtHPtz+z128zGT4c3z2cVXs5ujjn2773k9472j5vtf/pkYp2TKe/7E00A/gO7G7pwJRGqtAAAAABJRU5ErkJggg==" />
<img id="dtim-4center" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA3BAMAAACiFTSCAAAAMFBMVEUBAQGbmppqLZZ8fHzRz8+LPMZ0MqXs6upTUVE+G1q5ublubm6iRedQInH9/Pze3NzAiv2WAAAACXBIWXMAAAsTAAALEwEAmpwYAAABuUlEQVQ4y6VVvU7CUBSmCEVQao0vQDrcWWcWhiYkDsICc3OS3pmhSbfiI7C6MfgAJo4sPoCDcSdhMGFDBhI24zn3tBjh2DTy3eEj9+P0/Pa05BtMrZQbzG7KJaZFIyLqrS82hqfOnszXnUquLFv3dvLOeiP57uT69teFfHcP5CKJ+QdyN0YsF5Ul8WpUI06SjmM4Ks0Mrk+Zn86Y70+YS8fha0VY2K8GL1XmwDHXnxj54y1GXgbwwNOBrT2lPNWiyFHIEitrhYdkDaB1ay/vsjY6yiiCJJMVykq0pkt+OPoQH44gGX8IskqtFYjWgODQQAwt8y1aAygPdN8GCkHt5LSoaTH75ylnRT0ON5cEtz4nvL81Dc8nlrm+wmEax9t4YQ/0MNRhn1iHYcuJt+PxOMoib5p8uGpySzAfUxbQKqcsSov9VmlRqSPyOHBR6Q9Sx9haKci3lvsNPGtyv8Hogc3c+nkFl3iwasNBOBz0q8yBk8RJvMRXsE3HrT8YTDK2Zs942kc29I6npbZi5ilZjZg/DpaHL++WqNDiypfzt+LfO3VTaO39c6dmsp9nPZJ9Z18i19r8+hJ9A3EAErhB3eXkAAAAAElFTkSuQmCC" /> <br>
</div>
</div>
</div>
</div>
<div class="dtim-ok">
<button class="primaryButton" id="dti-ok">Download</button>
</div>
<div class="dtim-newtab">
<button class="primaryButton" id="dti-newtab">Open in new tab</button>
</div>
<div class="dtim-cancel">
<button class="primaryButton" id="dti-cancel">Cancel</button>
</div>
</div>
</dialog>`)
let downloadTiledImageDialog = document.getElementById("download-tiled-image-dialog")
let dtim1_width = document.getElementById("dtim1-width")
let dtim1_height = document.getElementById("dtim1-height")
let dtim2_width = document.getElementById("dtim2-width")
let dtim2_height = document.getElementById("dtim2-height")
let dtim2_unit = document.getElementById("dtim2-unit")
let dtim2_dpi = document.getElementById("dtim2-dpi")
let tabTiledTilesOptions = document.getElementById("tab-image-tiles")
let tabTiledSizeOptions = document.getElementById("tab-image-size")
linkTabContents(tabTiledTilesOptions)
linkTabContents(tabTiledSizeOptions)
prettifyInputs(downloadTiledImageDialog)
// ---- Predefined image dimensions
PAPERSIZE.forEach( function(p) {
document.getElementById("dtim2-" + p.id).addEventListener("click", (e) => {
dtim2_unit.value = p.unit
dtim2_width.value = p.width
dtim2_height.value = p.height
})
})
// ---- Close popup
document.getElementById("dti-cancel").addEventListener("click", (e) => downloadTiledImageDialog.close())
document.getElementById("downnload-tiled-close-button").addEventListener("click", (e) => downloadTiledImageDialog.close())
modalDialogCloseOnBackdropClick(downloadTiledImageDialog)
makeDialogDraggable(downloadTiledImageDialog)
// ---- Stylesheet
const styleSheet = document.createElement("style")
styleSheet.textContent = `
button[disabled] {
opacity: 0.5;
}
.method-2-dpi {
margin-top: 1em;
margin-bottom: 1em;
}
.method-2-paper button {
width: 10em;
padding: 4px;
margin: 4px;
}
.download-tiled-image .tab-content {
background: var(--background-color1);
border-radius: 3pt;
}
.dtim-container { display: grid;
grid-template-columns: auto auto;
grid-template-rows: auto auto;
gap: 1em 0px;
grid-auto-flow: row;
grid-template-areas:
"dtim-tab dtim-tab dtim-plc"
"dtim-ok dtim-newtab dtim-cancel";
}
.download-tiled-image-top {
justify-self: center;
grid-area: dtim-tab;
}
.download-tiled-image-placement {
justify-self: center;
grid-area: dtim-plc;
margin-left: 1em;
}
.dtim-ok {
justify-self: center;
align-self: start;
grid-area: dtim-ok;
}
.dtim-newtab {
justify-self: center;
align-self: start;
grid-area: dtim-newtab;
}
.dtim-cancel {
justify-self: center;
align-self: start;
grid-area: dtim-cancel;
}
#tab-content-image-placement img {
margin: 4px;
opacity: 0.3;
border: solid 2px var(--background-color1);
}
#tab-content-image-placement img:hover {
margin: 4px;
opacity: 1;
border: solid 2px var(--accent-color);
filter: brightness(2);
}
#tab-content-image-placement img.active {
margin: 4px;
opacity: 1;
border: solid 2px var(--background-color1);
}
`
document.head.appendChild(styleSheet)
// ---- Placement widget
function updatePlacementWidget(event) {
document.querySelector("#tab-content-image-placement img.active").classList.remove("active")
event.target.classList.add("active")
}
document.querySelectorAll("#tab-content-image-placement img").forEach(
(i) => i.addEventListener("click", updatePlacementWidget)
)
function getPlacement() {
return document.querySelector("#tab-content-image-placement img.active").id.substr(5)
}
// ---- Make the image
function downloadTiledImage(image, width, height, offsetX=0, offsetY=0, new_tab=false) {
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const context = canvas.getContext('2d')
const w = image.width
const h = image.height
for (var x = offsetX; x < width; x += w) {
for (var y = offsetY; y < height; y += h) {
context.drawImage(image, x, y, w, h)
}
}
if (new_tab) {
var newTab = window.open("")
newTab.document.write(`<html><head><title>${width}×${height}, "${image.dataset["prompt"]}"</title></head><body><img src="${canvas.toDataURL()}"></body></html>`)
} else {
const link = document.createElement('a')
link.href = canvas.toDataURL()
link.download = image.dataset["prompt"].replace(/[^a-zA-Z0-9]+/g, "-").substr(0,22)+crypto.randomUUID()+".png"
link.click()
}
}
function onDownloadTiledImageClick(e, newtab=false) {
var width, height, offsetX, offsetY
if (isTabActive(tabTiledTilesOptions)) {
width = thisImage.width * dtim1_width.value
height = thisImage.height * dtim1_height.value
} else {
if ( dtim2_unit.value == "pixels" ) {
width = dtim2_width.value
height= dtim2_height.value
} else if ( dtim2_unit.value == "mm" ) {
width = Math.floor( dtim2_width.value * dtim2_dpi.value / 25.4 )
height = Math.floor( dtim2_height.value * dtim2_dpi.value / 25.4 )
} else { // inch
width = Math.floor( dtim2_width.value * dtim2_dpi.value )
height = Math.floor( dtim2_height.value * dtim2_dpi.value )
}
}
var placement = getPlacement()
if (placement == "1tl") {
offsetX = 0
offsetY = 0
} else if (placement == "1tr") {
offsetX = width - thisImage.width * Math.ceil( width / thisImage.width )
offsetY = 0
} else if (placement == "1bl") {
offsetX = 0
offsetY = height - thisImage.height * Math.ceil( height / thisImage.height )
} else if (placement == "1br") {
offsetX = width - thisImage.width * Math.ceil( width / thisImage.width )
offsetY = height - thisImage.height * Math.ceil( height / thisImage.height )
} else if (placement == "4center") {
offsetX = width/2 - thisImage.width * Math.ceil( width/2 / thisImage.width )
offsetY = height/2 - thisImage.height * Math.ceil( height/2 / thisImage.height )
} else if (placement == "1center") {
offsetX = width/2 - thisImage.width/2 - thisImage.width * Math.ceil( (width/2 - thisImage.width/2) / thisImage.width )
offsetY = height/2 - thisImage.height/2 - thisImage.height * Math.ceil( (height/2 - thisImage.height/2) / thisImage.height )
}
downloadTiledImage(thisImage, width, height, offsetX, offsetY, newtab)
downloadTiledImageDialog.close()
}
document.getElementById("dti-ok").addEventListener("click", onDownloadTiledImageClick)
document.getElementById("dti-newtab").addEventListener("click", (e) => onDownloadTiledImageClick(e,true))
})()