diff --git a/README.md b/README.md
index 4ddb8603..3434e344 100644
--- a/README.md
+++ b/README.md
@@ -350,14 +350,12 @@ The memory optimization in this example is fully automatic. You do not need to c
```python
# Use --show-controlnet-example to see this extension.
-import os
import cv2
import gradio as gr
-import numpy as np
from modules import scripts
from modules.shared_cmd_options import cmd_opts
-from modules_forge.shared import shared_preprocessors
+from modules_forge.shared import supported_preprocessors
from modules.modelloader import load_file_from_url
from ldm_patched.modules.controlnet import load_controlnet
from modules_forge.controlnet import apply_controlnet_advanced
@@ -425,7 +423,7 @@ class ControlNetExampleForge(scripts.Script):
width = W * 8
batch_size = p.batch_size
- preprocessor = shared_preprocessors['canny']
+ preprocessor = supported_preprocessors['canny']
# detect control at certain resolution
control_image = preprocessor(
@@ -518,7 +516,8 @@ Your preprocessor will be read by all other extensions using `modules_forge.shar
Below codes are in `extensions-builtin\forge_preprocessor_normalbae\scripts\preprocessor_normalbae.py`
```python
-from modules_forge.shared import Preprocessor, PreprocessorParameter, preprocessor_dir, add_preprocessor
+from modules_forge.supported_preprocessor import Preprocessor, PreprocessorParameter
+from modules_forge.shared import preprocessor_dir, add_supported_preprocessor
from modules_forge.forge_util import resize_image_with_pad
from modules.modelloader import load_file_from_url
@@ -537,13 +536,15 @@ class PreprocessorNormalBae(Preprocessor):
super().__init__()
self.name = 'normalbae'
self.tags = ['NormalMap']
- self.slider_resolution = PreprocessorParameter(label='Resolution', minimum=128, maximum=2048, value=512, step=8, visible=True)
+ self.model_filename_filers = ['normal']
+ self.slider_resolution = PreprocessorParameter(
+ label='Resolution', minimum=128, maximum=2048, value=512, step=8, visible=True)
self.slider_1 = PreprocessorParameter(visible=False)
self.slider_2 = PreprocessorParameter(visible=False)
self.slider_3 = PreprocessorParameter(visible=False)
self.show_control_mode = True
self.do_not_need_model = False
- self.sorting_priority = 0.0 # higher goes to top in the list
+ self.sorting_priority = 100 # higher goes to top in the list
def load_model(self):
if self.model_patcher is not None:
@@ -591,7 +592,7 @@ class PreprocessorNormalBae(Preprocessor):
return remove_pad(normal_image)
-add_preprocessor(PreprocessorNormalBae)
+add_supported_preprocessor(PreprocessorNormalBae())
```
diff --git a/extensions-builtin/forge_legacy_preprocessors/scripts/legacy_preprocessors.py b/extensions-builtin/forge_legacy_preprocessors/scripts/legacy_preprocessors.py
index f4a9bb88..1db8b9eb 100644
--- a/extensions-builtin/forge_legacy_preprocessors/scripts/legacy_preprocessors.py
+++ b/extensions-builtin/forge_legacy_preprocessors/scripts/legacy_preprocessors.py
@@ -15,7 +15,26 @@ import contextlib
from annotator.util import HWC3
from modules_forge.ops import automatic_memory_management
from legacy_preprocessors.preprocessor_compiled import legacy_preprocessors
-from modules_forge.shared import Preprocessor, PreprocessorParameter, add_preprocessor
+from modules_forge.supported_preprocessor import Preprocessor, PreprocessorParameter
+from modules_forge.shared import add_supported_preprocessor
+
+
+###
+
+# This file has lots of unreasonable historical designs and should be viewed as a frozen blackbox library
+
+# If you want to add preprocessor,
+# please instead look at `extensions-builtin/forge_preprocessor_normalbae/scripts/preprocessor_normalbae`
+# If you want to use preprocessor,
+# please instead use `from modules_forge.shared import supported_preprocessors`
+# and then use any preprocessor like: depth_midas = supported_preprocessors['depth_midas']
+
+# Please do not hack/edit/modify/rely-on any codes in this file.
+
+# Never use methods in this file to add anything!
+# This file will be eventually removed but the workload is super high and we need more time to do this.
+
+###
class LegacyPreprocessor(Preprocessor):
@@ -30,6 +49,21 @@ class LegacyPreprocessor(Preprocessor):
self.sorting_priority = legacy_dict['priority']
self.tags = legacy_dict['tags']
+ filters_aliases = {
+ 'instructp2p': ['ip2p'],
+ 'segmentation': ['seg'],
+ 'normalmap': ['normal'],
+ 't2i-adapter': ['t2i_adapter', 't2iadapter', 't2ia'],
+ 'ip-adapter': ['ip_adapter', 'ipadapter'],
+ 'openpose': ['openpose', 'densepose'],
+ }
+
+ self.model_filename_filers = []
+ for tag in self.tags:
+ tag_lower = tag.lower()
+ self.model_filename_filers.append(tag_lower)
+ self.model_filename_filers += filters_aliases.get(tag_lower, [])
+
if legacy_dict['resolution'] is None:
self.resolution = PreprocessorParameter(visible=False)
else:
@@ -76,4 +110,4 @@ class LegacyPreprocessor(Preprocessor):
for k, v in legacy_preprocessors.items():
p = LegacyPreprocessor(v)
p.name = k
- add_preprocessor(p)
+ add_supported_preprocessor(p)
diff --git a/extensions-builtin/forge_preprocessor_normalbae/scripts/preprocessor_normalbae.py b/extensions-builtin/forge_preprocessor_normalbae/scripts/preprocessor_normalbae.py
index 496b5546..2c99e396 100644
--- a/extensions-builtin/forge_preprocessor_normalbae/scripts/preprocessor_normalbae.py
+++ b/extensions-builtin/forge_preprocessor_normalbae/scripts/preprocessor_normalbae.py
@@ -1,4 +1,5 @@
-from modules_forge.shared import Preprocessor, PreprocessorParameter, preprocessor_dir, add_preprocessor
+from modules_forge.supported_preprocessor import Preprocessor, PreprocessorParameter
+from modules_forge.shared import preprocessor_dir, add_supported_preprocessor
from modules_forge.forge_util import resize_image_with_pad
from modules.modelloader import load_file_from_url
@@ -17,7 +18,9 @@ class PreprocessorNormalBae(Preprocessor):
super().__init__()
self.name = 'normalbae'
self.tags = ['NormalMap']
- self.slider_resolution = PreprocessorParameter(label='Resolution', minimum=128, maximum=2048, value=512, step=8, visible=True)
+ self.model_filename_filers = ['normal']
+ self.slider_resolution = PreprocessorParameter(
+ label='Resolution', minimum=128, maximum=2048, value=512, step=8, visible=True)
self.slider_1 = PreprocessorParameter(visible=False)
self.slider_2 = PreprocessorParameter(visible=False)
self.slider_3 = PreprocessorParameter(visible=False)
@@ -71,4 +74,4 @@ class PreprocessorNormalBae(Preprocessor):
return remove_pad(normal_image)
-add_preprocessor(PreprocessorNormalBae())
+add_supported_preprocessor(PreprocessorNormalBae())
diff --git a/extensions-builtin/sd_forge_controlnet/.gitignore b/extensions-builtin/sd_forge_controlnet/.gitignore
new file mode 100644
index 00000000..60d06e51
--- /dev/null
+++ b/extensions-builtin/sd_forge_controlnet/.gitignore
@@ -0,0 +1,185 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+# For a library or package, you might want to ignore these files since the code is
+# intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+#Pipfile.lock
+
+# poetry
+# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
+# This is especially recommended for binary packages to ensure reproducibility, and is more
+# commonly ignored for libraries.
+# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
+#poetry.lock
+
+# pdm
+# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
+#pdm.lock
+# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
+# in version control.
+# https://pdm.fming.dev/#use-with-ide
+.pdm.toml
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+# PyCharm
+# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
+# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
+# and can be added to the global gitignore or merged into this file. For a more nuclear
+# option (not recommended) you can uncomment the following to ignore the entire idea folder.
+#.idea
+*.pt
+*.pth
+*.ckpt
+*.bin
+*.safetensors
+
+# Editor setting metadata
+.idea/
+.vscode/
+detected_maps/
+annotator/downloads/
+
+# test results and expectations
+web_tests/results/
+web_tests/expectations/
+tests/web_api/full_coverage/results/
+tests/web_api/full_coverage/expectations/
+
+*_diff.png
+
+# Presets
+presets/
+
+# Ignore existing dir of hand refiner if exists.
+annotator/hand_refiner_portable
\ No newline at end of file
diff --git a/extensions-builtin/sd_forge_controlnet/LICENSE b/extensions-builtin/sd_forge_controlnet/LICENSE
new file mode 100644
index 00000000..f288702d
--- /dev/null
+++ b/extensions-builtin/sd_forge_controlnet/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/extensions-builtin/sd_forge_controlnet/README.md b/extensions-builtin/sd_forge_controlnet/README.md
new file mode 100644
index 00000000..38460eca
--- /dev/null
+++ b/extensions-builtin/sd_forge_controlnet/README.md
@@ -0,0 +1,243 @@
+# ControlNet for Stable Diffusion WebUI
+
+The WebUI extension for ControlNet and other injection-based SD controls.
+
+
+
+This extension is for AUTOMATIC1111's [Stable Diffusion web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui), allows the Web UI to add [ControlNet](https://github.com/lllyasviel/ControlNet) to the original Stable Diffusion model to generate images. The addition is on-the-fly, the merging is not required.
+
+# Installation
+
+1. Open "Extensions" tab.
+2. Open "Install from URL" tab in the tab.
+3. Enter `https://github.com/Mikubill/sd-webui-controlnet.git` to "URL for extension's git repository".
+4. Press "Install" button.
+5. Wait for 5 seconds, and you will see the message "Installed into stable-diffusion-webui\extensions\sd-webui-controlnet. Use Installed tab to restart".
+6. Go to "Installed" tab, click "Check for updates", and then click "Apply and restart UI". (The next time you can also use these buttons to update ControlNet.)
+7. Completely restart A1111 webui including your terminal. (If you do not know what is a "terminal", you can reboot your computer to achieve the same effect.)
+8. Download models (see below).
+9. After you put models in the correct folder, you may need to refresh to see the models. The refresh button is right to your "Model" dropdown.
+
+# Download Models
+
+Right now all the 14 models of ControlNet 1.1 are in the beta test.
+
+Download the models from ControlNet 1.1: https://huggingface.co/lllyasviel/ControlNet-v1-1/tree/main
+
+You need to download model files ending with ".pth" .
+
+Put models in your "stable-diffusion-webui\extensions\sd-webui-controlnet\models". You only need to download "pth" files.
+
+Do not right-click the filenames in HuggingFace website to download. Some users right-clicked those HuggingFace HTML websites and saved those HTML pages as PTH/YAML files. They are not downloading correct files. Instead, please click the small download arrow “↓” icon in HuggingFace to download.
+
+# Download Models for SDXL
+
+See instructions [here](https://github.com/Mikubill/sd-webui-controlnet/discussions/2039).
+
+# Features in ControlNet 1.1
+
+### Perfect Support for All ControlNet 1.0/1.1 and T2I Adapter Models.
+
+Now we have perfect support all available models and preprocessors, including perfect support for T2I style adapter and ControlNet 1.1 Shuffle. (Make sure that your YAML file names and model file names are same, see also YAML files in "stable-diffusion-webui\extensions\sd-webui-controlnet\models".)
+
+### Perfect Support for A1111 High-Res. Fix
+
+Now if you turn on High-Res Fix in A1111, each controlnet will output two different control images: a small one and a large one. The small one is for your basic generating, and the big one is for your High-Res Fix generating. The two control images are computed by a smart algorithm called "super high-quality control image resampling". This is turned on by default, and you do not need to change any setting.
+
+### Perfect Support for All A1111 Img2Img or Inpaint Settings and All Mask Types
+
+Now ControlNet is extensively tested with A1111's different types of masks, including "Inpaint masked"/"Inpaint not masked", and "Whole picture"/"Only masked", and "Only masked padding"&"Mask blur". The resizing perfectly matches A1111's "Just resize"/"Crop and resize"/"Resize and fill". This means you can use ControlNet in nearly everywhere in your A1111 UI without difficulty!
+
+### The New "Pixel-Perfect" Mode
+
+Now if you turn on pixel-perfect mode, you do not need to set preprocessor (annotator) resolutions manually. The ControlNet will automatically compute the best annotator resolution for you so that each pixel perfectly matches Stable Diffusion.
+
+### User-Friendly GUI and Preprocessor Preview
+
+We reorganized some previously confusing UI like "canvas width/height for new canvas" and it is in the 📝 button now. Now the preview GUI is controlled by the "allow preview" option and the trigger button 💥. The preview image size is better than before, and you do not need to scroll up and down - your a1111 GUI will not be messed up anymore!
+
+### Support for Almost All Upscaling Scripts
+
+Now ControlNet 1.1 can support almost all Upscaling/Tile methods. ControlNet 1.1 support the script "Ultimate SD upscale" and almost all other tile-based extensions. Please do not confuse ["Ultimate SD upscale"](https://github.com/Coyote-A/ultimate-upscale-for-automatic1111) with "SD upscale" - they are different scripts. Note that the most recommended upscaling method is ["Tiled VAE/Diffusion"](https://github.com/pkuliyi2015/multidiffusion-upscaler-for-automatic1111) but we test as many methods/extensions as possible. Note that "SD upscale" is supported since 1.1.117, and if you use it, you need to leave all ControlNet images as blank (We do not recommend "SD upscale" since it is somewhat buggy and cannot be maintained - use the "Ultimate SD upscale" instead).
+
+### More Control Modes (previously called Guess Mode)
+
+We have fixed many bugs in previous 1.0’s Guess Mode and now it is called Control Mode
+
+
+
+Now you can control which aspect is more important (your prompt or your ControlNet):
+
+* "Balanced": ControlNet on both sides of CFG scale, same as turning off "Guess Mode" in ControlNet 1.0
+
+* "My prompt is more important": ControlNet on both sides of CFG scale, with progressively reduced SD U-Net injections (layer_weight*=0.825**I, where 0<=I <13, and the 13 means ControlNet injected SD 13 times). In this way, you can make sure that your prompts are perfectly displayed in your generated images.
+
+* "ControlNet is more important": ControlNet only on the Conditional Side of CFG scale (the cond in A1111's batch-cond-uncond). This means the ControlNet will be X times stronger if your cfg-scale is X. For example, if your cfg-scale is 7, then ControlNet is 7 times stronger. Note that here the X times stronger is different from "Control Weights" since your weights are not modified. This "stronger" effect usually has less artifact and give ControlNet more room to guess what is missing from your prompts (and in the previous 1.0, it is called "Guess Mode").
+
+
+
+
Input (depth+canny+hed)
+
"Balanced"
+
"My prompt is more important"
+
"ControlNet is more important"
+
+
+
+
+
+
+
+
+
+### Reference-Only Control
+
+Now we have a `reference-only` preprocessor that does not require any control models. It can guide the diffusion directly using images as references.
+
+(Prompt "a dog running on grassland, best quality, ...")
+
+
+
+This method is similar to inpaint-based reference but it does not make your image disordered.
+
+Many professional A1111 users know a trick to diffuse image with references by inpaint. For example, if you have a 512x512 image of a dog, and want to generate another 512x512 image with the same dog, some users will connect the 512x512 dog image and a 512x512 blank image into a 1024x512 image, send to inpaint, and mask out the blank 512x512 part to diffuse a dog with similar appearance. However, that method is usually not very satisfying since images are connected and many distortions will appear.
+
+This `reference-only` ControlNet can directly link the attention layers of your SD to any independent images, so that your SD will read arbitrary images for reference. You need at least ControlNet 1.1.153 to use it.
+
+To use, just select `reference-only` as preprocessor and put an image. Your SD will just use the image as reference.
+
+*Note that this method is as "non-opinioned" as possible. It only contains very basic connection codes, without any personal preferences, to connect the attention layers with your reference images. However, even if we tried best to not include any opinioned codes, we still need to write some subjective implementations to deal with weighting, cfg-scale, etc - tech report is on the way.*
+
+More examples [here](https://github.com/Mikubill/sd-webui-controlnet/discussions/1236).
+
+# Technical Documents
+
+See also the documents of ControlNet 1.1:
+
+https://github.com/lllyasviel/ControlNet-v1-1-nightly#model-specification
+
+# Default Setting
+
+This is my setting. If you run into any problem, you can use this setting as a sanity check
+
+
+
+# Use Previous Models
+
+### Use ControlNet 1.0 Models
+
+https://huggingface.co/lllyasviel/ControlNet/tree/main/models
+
+You can still use all previous models in the previous ControlNet 1.0. Now, the previous "depth" is now called "depth_midas", the previous "normal" is called "normal_midas", the previous "hed" is called "softedge_hed". And starting from 1.1, all line maps, edge maps, lineart maps, boundary maps will have black background and white lines.
+
+### Use T2I-Adapter Models
+
+(From TencentARC/T2I-Adapter)
+
+To use T2I-Adapter models:
+
+1. Download files from https://huggingface.co/TencentARC/T2I-Adapter/tree/main/models
+2. Put them in "stable-diffusion-webui\extensions\sd-webui-controlnet\models".
+3. Make sure that the file names of pth files and yaml files are consistent.
+
+*Note that "CoAdapter" is not implemented yet.*
+
+# Gallery
+
+The below results are from ControlNet 1.0.
+
+| Source | Input | Output |
+|:-------------------------:|:-------------------------:|:-------------------------:|
+| (no preprocessor) | | |
+| (no preprocessor) | | |
+| | | |
+| | | |
+| | | |
+| | | |
+
+The below examples are from T2I-Adapter.
+
+From `t2iadapter_color_sd14v1.pth` :
+
+| Source | Input | Output |
+|:-------------------------:|:-------------------------:|:-------------------------:|
+| | | |
+
+From `t2iadapter_style_sd14v1.pth` :
+
+| Source | Input | Output |
+|:-------------------------:|:-------------------------:|:-------------------------:|
+| | (clip, non-image) | |
+
+# Minimum Requirements
+
+* (Windows) (NVIDIA: Ampere) 4gb - with `--xformers` enabled, and `Low VRAM` mode ticked in the UI, goes up to 768x832
+
+# Multi-ControlNet
+
+This option allows multiple ControlNet inputs for a single generation. To enable this option, change `Multi ControlNet: Max models amount (requires restart)` in the settings. Note that you will need to restart the WebUI for changes to take effect.
+
+
+
+
Source A
+
Source B
+
Output
+
+
+
+
+
+
+
+
+# Control Weight/Start/End
+
+Weight is the weight of the controlnet "influence". It's analogous to prompt attention/emphasis. E.g. (myprompt: 1.2). Technically, it's the factor by which to multiply the ControlNet outputs before merging them with original SD Unet.
+
+Guidance Start/End is the percentage of total steps the controlnet applies (guidance strength = guidance end). It's analogous to prompt editing/shifting. E.g. \[myprompt::0.8\] (It applies from the beginning until 80% of total steps)
+
+# Batch Mode
+
+Put any unit into batch mode to activate batch mode for all units. Specify a batch directory for each unit, or use the new textbox in the img2img batch tab as a fallback. Although the textbox is located in the img2img batch tab, you can use it to generate images in the txt2img tab as well.
+
+Note that this feature is only available in the gradio user interface. Call the APIs as many times as you want for custom batch scheduling.
+
+# API and Script Access
+
+This extension can accept txt2img or img2img tasks via API or external extension call. Note that you may need to enable `Allow other scripts to control this extension` in settings for external calls.
+
+To use the API: start WebUI with argument `--api` and go to `http://webui-address/docs` for documents or checkout [examples](https://github.com/Mikubill/sd-webui-controlnet/blob/main/example/txt2img_example/api_txt2img.py).
+
+To use external call: Checkout [Wiki](https://github.com/Mikubill/sd-webui-controlnet/wiki/API)
+
+# Command Line Arguments
+
+This extension adds these command line arguments to the webui:
+
+```
+ --controlnet-dir ADD a controlnet models directory
+ --controlnet-annotator-models-path SET the directory for annotator models
+ --no-half-controlnet load controlnet models in full precision
+ --controlnet-preprocessor-cache-size Cache size for controlnet preprocessor results
+ --controlnet-loglevel Log level for the controlnet extension
+ --controlnet-tracemalloc Enable malloc memory tracing
+```
+
+# MacOS Support
+
+Tested with pytorch nightly: https://github.com/Mikubill/sd-webui-controlnet/pull/143#issuecomment-1435058285
+
+To use this extension with mps and normal pytorch, currently you may need to start WebUI with `--no-half`.
+
+# Archive of Deprecated Versions
+
+The previous version (sd-webui-controlnet 1.0) is archived in
+
+https://github.com/lllyasviel/webui-controlnet-v1-archived
+
+Using this version is not a temporary stop of updates. You will stop all updates forever.
+
+Please consider this version if you work with professional studios that requires 100% reproducing of all previous results pixel by pixel.
+
+# Thanks
+
+This implementation is inspired by kohya-ss/sd-webui-additional-networks
diff --git a/extensions-builtin/sd_forge_controlnet/install.py b/extensions-builtin/sd_forge_controlnet/install.py
new file mode 100644
index 00000000..5370d221
--- /dev/null
+++ b/extensions-builtin/sd_forge_controlnet/install.py
@@ -0,0 +1,66 @@
+import launch
+import pkg_resources
+import sys
+import os
+import shutil
+import platform
+from pathlib import Path
+from typing import Tuple, Optional
+
+
+repo_root = Path(__file__).parent
+main_req_file = repo_root / "requirements.txt"
+
+
+def comparable_version(version: str) -> Tuple:
+ return tuple(version.split("."))
+
+
+def get_installed_version(package: str) -> Optional[str]:
+ try:
+ return pkg_resources.get_distribution(package).version
+ except Exception:
+ return None
+
+
+def extract_base_package(package_string: str) -> str:
+ base_package = package_string.split("@git")[0]
+ return base_package
+
+
+def install_requirements(req_file):
+ with open(req_file) as file:
+ for package in file:
+ try:
+ package = package.strip()
+ if "==" in package:
+ package_name, package_version = package.split("==")
+ installed_version = get_installed_version(package_name)
+ if installed_version != package_version:
+ launch.run_pip(
+ f"install -U {package}",
+ f"sd-forge-controlnet requirement: changing {package_name} version from {installed_version} to {package_version}",
+ )
+ elif ">=" in package:
+ package_name, package_version = package.split(">=")
+ installed_version = get_installed_version(package_name)
+ if not installed_version or comparable_version(
+ installed_version
+ ) < comparable_version(package_version):
+ launch.run_pip(
+ f"install -U {package}",
+ f"sd-forge-controlnet requirement: changing {package_name} version from {installed_version} to {package_version}",
+ )
+ elif not launch.is_installed(extract_base_package(package)):
+ launch.run_pip(
+ f"install {package}",
+ f"sd-forge-controlnet requirement: {package}",
+ )
+ except Exception as e:
+ print(e)
+ print(
+ f"Warning: Failed to install {package}, some preprocessors may not work."
+ )
+
+
+install_requirements(main_req_file)
diff --git a/extensions-builtin/sd_forge_controlnet/javascript/active_units.js b/extensions-builtin/sd_forge_controlnet/javascript/active_units.js
new file mode 100644
index 00000000..a2662055
--- /dev/null
+++ b/extensions-builtin/sd_forge_controlnet/javascript/active_units.js
@@ -0,0 +1,311 @@
+/**
+ * Give a badge on ControlNet Accordion indicating total number of active
+ * units.
+ * Make active unit's tab name green.
+ * Append control type to tab name.
+ * Disable resize mode selection when A1111 img2img input is used.
+ */
+(function () {
+ const cnetAllAccordions = new Set();
+ onUiUpdate(() => {
+ const ImgChangeType = {
+ NO_CHANGE: 0,
+ REMOVE: 1,
+ ADD: 2,
+ SRC_CHANGE: 3,
+ };
+
+ function imgChangeObserved(mutationsList) {
+ // Iterate over all mutations that just occured
+ for (let mutation of mutationsList) {
+ // Check if the mutation is an addition or removal of a node
+ if (mutation.type === 'childList') {
+ // Check if nodes were added
+ if (mutation.addedNodes.length > 0) {
+ for (const node of mutation.addedNodes) {
+ if (node.tagName === 'IMG') {
+ return ImgChangeType.ADD;
+ }
+ }
+ }
+
+ // Check if nodes were removed
+ if (mutation.removedNodes.length > 0) {
+ for (const node of mutation.removedNodes) {
+ if (node.tagName === 'IMG') {
+ return ImgChangeType.REMOVE;
+ }
+ }
+ }
+ }
+ // Check if the mutation is a change of an attribute
+ else if (mutation.type === 'attributes') {
+ if (mutation.target.tagName === 'IMG' && mutation.attributeName === 'src') {
+ return ImgChangeType.SRC_CHANGE;
+ }
+ }
+ }
+ return ImgChangeType.NO_CHANGE;
+ }
+
+ function childIndex(element) {
+ // Get all child nodes of the parent
+ let children = Array.from(element.parentNode.childNodes);
+
+ // Filter out non-element nodes (like text nodes and comments)
+ children = children.filter(child => child.nodeType === Node.ELEMENT_NODE);
+
+ return children.indexOf(element);
+ }
+
+ function imageInputDisabledAlert() {
+ alert('Inpaint control type must use a1111 input in img2img mode.');
+ }
+
+ class ControlNetUnitTab {
+ constructor(tab, accordion) {
+ this.tab = tab;
+ this.accordion = accordion;
+ this.isImg2Img = tab.querySelector('.cnet-unit-enabled').id.includes('img2img');
+
+ this.enabledCheckbox = tab.querySelector('.cnet-unit-enabled input');
+ this.inputImage = tab.querySelector('.cnet-input-image-group .cnet-image input[type="file"]');
+ this.inputImageContainer = tab.querySelector('.cnet-input-image-group .cnet-image');
+ this.controlTypeRadios = tab.querySelectorAll('.controlnet_control_type_filter_group input[type="radio"]');
+ this.resizeModeRadios = tab.querySelectorAll('.controlnet_resize_mode_radio input[type="radio"]');
+ this.runPreprocessorButton = tab.querySelector('.cnet-run-preprocessor');
+
+ const tabs = tab.parentNode;
+ this.tabNav = tabs.querySelector('.tab-nav');
+ this.tabIndex = childIndex(tab) - 1; // -1 because tab-nav is also at the same level.
+
+ this.attachEnabledButtonListener();
+ this.attachControlTypeRadioListener();
+ this.attachTabNavChangeObserver();
+ this.attachImageUploadListener();
+ this.attachImageStateChangeObserver();
+ this.attachA1111SendInfoObserver();
+ this.attachPresetDropdownObserver();
+ }
+
+ getTabNavButton() {
+ return this.tabNav.querySelector(`:nth-child(${this.tabIndex + 1})`);
+ }
+
+ getActiveControlType() {
+ for (let radio of this.controlTypeRadios) {
+ if (radio.checked) {
+ return radio.value;
+ }
+ }
+ return undefined;
+ }
+
+ updateActiveState() {
+ const tabNavButton = this.getTabNavButton();
+ if (!tabNavButton) return;
+
+ if (this.enabledCheckbox.checked) {
+ tabNavButton.classList.add('cnet-unit-active');
+ } else {
+ tabNavButton.classList.remove('cnet-unit-active');
+ }
+ }
+
+ updateActiveUnitCount() {
+ function getActiveUnitCount(checkboxes) {
+ let activeUnitCount = 0;
+ for (const checkbox of checkboxes) {
+ if (checkbox.checked)
+ activeUnitCount++;
+ }
+ return activeUnitCount;
+ }
+
+ const checkboxes = this.accordion.querySelectorAll('.cnet-unit-enabled input');
+ const span = this.accordion.querySelector('.label-wrap span');
+
+ // Remove existing badge.
+ if (span.childNodes.length !== 1) {
+ span.removeChild(span.lastChild);
+ }
+ // Add new badge if necessary.
+ const activeUnitCount = getActiveUnitCount(checkboxes);
+ if (activeUnitCount > 0) {
+ const div = document.createElement('div');
+ div.classList.add('cnet-badge');
+ div.classList.add('primary');
+ div.innerHTML = `${activeUnitCount} unit${activeUnitCount > 1 ? 's' : ''}`;
+ span.appendChild(div);
+ }
+ }
+
+ /**
+ * Add the active control type to tab displayed text.
+ */
+ updateActiveControlType() {
+ const tabNavButton = this.getTabNavButton();
+ if (!tabNavButton) return;
+
+ // Remove the control if exists
+ const controlTypeSuffix = tabNavButton.querySelector('.control-type-suffix');
+ if (controlTypeSuffix) controlTypeSuffix.remove();
+
+ // Add new suffix.
+ const controlType = this.getActiveControlType();
+ if (controlType === 'All') return;
+
+ const span = document.createElement('span');
+ span.innerHTML = `[${controlType}]`;
+ span.classList.add('control-type-suffix');
+ tabNavButton.appendChild(span);
+ }
+
+ /**
+ * When 'Inpaint' control type is selected in img2img:
+ * - Make image input disabled
+ * - Clear existing image input
+ */
+ updateImageInputState() {
+ if (!this.isImg2Img) return;
+
+ const tabNavButton = this.getTabNavButton();
+ if (!tabNavButton) return;
+
+ const controlType = this.getActiveControlType();
+ if (controlType.toLowerCase() === 'inpaint') {
+ this.inputImage.disabled = true;
+ this.inputImage.parentNode.addEventListener('click', imageInputDisabledAlert);
+ const removeButton = this.tab.querySelector(
+ '.cnet-input-image-group .cnet-image button[aria-label="Remove Image"]');
+ if (removeButton) removeButton.click();
+ } else {
+ this.inputImage.disabled = false;
+ this.inputImage.parentNode.removeEventListener('click', imageInputDisabledAlert);
+ }
+ }
+
+ attachEnabledButtonListener() {
+ this.enabledCheckbox.addEventListener('change', () => {
+ this.updateActiveState();
+ this.updateActiveUnitCount();
+ });
+ }
+
+ attachControlTypeRadioListener() {
+ for (const radio of this.controlTypeRadios) {
+ radio.addEventListener('change', () => {
+ this.updateActiveControlType();
+ });
+ }
+ }
+
+ /**
+ * Each time the active tab change, all tab nav buttons are cleared and
+ * regenerated by gradio. So we need to reapply the active states on
+ * them.
+ */
+ attachTabNavChangeObserver() {
+ new MutationObserver((mutationsList) => {
+ for (const mutation of mutationsList) {
+ if (mutation.type === 'childList') {
+ this.updateActiveState();
+ this.updateActiveControlType();
+ }
+ }
+ }).observe(this.tabNav, { childList: true });
+ }
+
+ attachImageUploadListener() {
+ // Automatically check `enable` checkbox when image is uploaded.
+ this.inputImage.addEventListener('change', (event) => {
+ if (!event.target.files) return;
+ if (!this.enabledCheckbox.checked)
+ this.enabledCheckbox.click();
+ });
+
+ // Automatically check `enable` checkbox when JSON pose file is uploaded.
+ this.tab.querySelector('.cnet-upload-pose input').addEventListener('change', (event) => {
+ if (!event.target.files) return;
+ if (!this.enabledCheckbox.checked)
+ this.enabledCheckbox.click();
+ });
+ }
+
+ attachImageStateChangeObserver() {
+ new MutationObserver((mutationsList) => {
+ const changeObserved = imgChangeObserved(mutationsList);
+
+ if (changeObserved === ImgChangeType.ADD) {
+ // enabling the run preprocessor button
+ this.runPreprocessorButton.removeAttribute("disabled");
+ this.runPreprocessorButton.title = 'Run preprocessor';
+ }
+
+ if (changeObserved === ImgChangeType.REMOVE) {
+ // disabling the run preprocessor button
+ this.runPreprocessorButton.setAttribute("disabled", true);
+ this.runPreprocessorButton.title = "No ControlNet input image available";
+ }
+ }).observe(this.inputImageContainer, {
+ childList: true,
+ subtree: true,
+ });
+ }
+
+ /**
+ * Observe send PNG info buttons in A1111, as they can also directly
+ * set states of ControlNetUnit.
+ */
+ attachA1111SendInfoObserver() {
+ const pasteButtons = gradioApp().querySelectorAll('#paste');
+ const pngButtons = gradioApp().querySelectorAll(
+ this.isImg2Img ?
+ '#img2img_tab, #inpaint_tab' :
+ '#txt2img_tab'
+ );
+
+ for (const button of [...pasteButtons, ...pngButtons]) {
+ button.addEventListener('click', () => {
+ // The paste/send img generation info feature goes
+ // though gradio, which is pretty slow. Ideally we should
+ // observe the event when gradio has done the job, but
+ // that is not an easy task.
+ // Here we just do a 2 second delay until the refresh.
+ setTimeout(() => {
+ this.updateActiveState();
+ this.updateActiveUnitCount();
+ }, 2000);
+ });
+ }
+ }
+
+ attachPresetDropdownObserver() {
+ const presetDropDown = this.tab.querySelector('.cnet-preset-dropdown');
+
+ new MutationObserver((mutationsList) => {
+ for (const mutation of mutationsList) {
+ if (mutation.removedNodes.length > 0) {
+ setTimeout(() => {
+ this.updateActiveState();
+ this.updateActiveUnitCount();
+ this.updateActiveControlType();
+ }, 1000);
+ return;
+ }
+ }
+ }).observe(presetDropDown, {
+ childList: true,
+ subtree: true,
+ });
+ }
+ }
+
+ gradioApp().querySelectorAll('#controlnet').forEach(accordion => {
+ if (cnetAllAccordions.has(accordion)) return;
+ accordion.querySelectorAll('.cnet-unit-tab')
+ .forEach(tab => new ControlNetUnitTab(tab, accordion));
+ cnetAllAccordions.add(accordion);
+ });
+ });
+})();
\ No newline at end of file
diff --git a/extensions-builtin/sd_forge_controlnet/javascript/canvas.js b/extensions-builtin/sd_forge_controlnet/javascript/canvas.js
new file mode 100644
index 00000000..a122c9fa
--- /dev/null
+++ b/extensions-builtin/sd_forge_controlnet/javascript/canvas.js
@@ -0,0 +1,17 @@
+(function () {
+ var hasApplied = false;
+ onUiUpdate(function () {
+ if (!hasApplied) {
+ if (typeof window.applyZoomAndPanIntegration === "function") {
+ hasApplied = true;
+ window.applyZoomAndPanIntegration("#txt2img_controlnet", Array.from({ length: 20 }, (_, i) => `#txt2img_controlnet_ControlNet-${i}_input_image`));
+ window.applyZoomAndPanIntegration("#img2img_controlnet", Array.from({ length: 20 }, (_, i) => `#img2img_controlnet_ControlNet-${i}_input_image`));
+ window.applyZoomAndPanIntegration("#txt2img_controlnet", ["#txt2img_controlnet_ControlNet_input_image"]);
+ window.applyZoomAndPanIntegration("#img2img_controlnet", ["#img2img_controlnet_ControlNet_input_image"]);
+ //console.log("window.applyZoomAndPanIntegration applied.");
+ } else {
+ //console.log("window.applyZoomAndPanIntegration is not available.");
+ }
+ }
+ });
+})();
diff --git a/extensions-builtin/sd_forge_controlnet/javascript/modal.js b/extensions-builtin/sd_forge_controlnet/javascript/modal.js
new file mode 100644
index 00000000..dc6190de
--- /dev/null
+++ b/extensions-builtin/sd_forge_controlnet/javascript/modal.js
@@ -0,0 +1,33 @@
+(function () {
+ const cnetModalRegisteredElements = new Set();
+ onUiUpdate(() => {
+ // Get all the buttons that open a modal
+ const btns = gradioApp().querySelectorAll(".cnet-modal-open");
+
+ // Get all the elements that close a modal
+ const spans = document.querySelectorAll(".cnet-modal-close");
+
+ // For each button, add a click event listener that opens the corresponding modal
+ btns.forEach((btn) => {
+ if (cnetModalRegisteredElements.has(btn)) return;
+ cnetModalRegisteredElements.add(btn);
+
+ const modalId = btn.id.replace('cnet-modal-open-', '');
+ const modal = document.getElementById("cnet-modal-" + modalId);
+ btn.addEventListener('click', () => {
+ modal.style.display = "block";
+ });
+ });
+
+ // For each element, add a click event listener that closes the corresponding modal
+ spans.forEach((span) => {
+ if (cnetModalRegisteredElements.has(span)) return;
+ cnetModalRegisteredElements.add(span);
+
+ const modal = span.parentNode;
+ span.addEventListener('click', () => {
+ modal.style.display = "none";
+ });
+ });
+ });
+})();
diff --git a/extensions-builtin/sd_forge_controlnet/javascript/openpose_editor.js b/extensions-builtin/sd_forge_controlnet/javascript/openpose_editor.js
new file mode 100644
index 00000000..1c7b570a
--- /dev/null
+++ b/extensions-builtin/sd_forge_controlnet/javascript/openpose_editor.js
@@ -0,0 +1,152 @@
+(function () {
+ async function checkEditorAvailable() {
+ const LOCAL_EDITOR_PATH = '/openpose_editor_index';
+ const REMOTE_EDITOR_PATH = 'https://huchenlei.github.io/sd-webui-openpose-editor/';
+
+ async function testEditorPath(path) {
+ const res = await fetch(path);
+ return res.status === 200 ? path : null;
+ }
+
+ // Use local editor if the user has the extension installed. Fallback
+ // onto remote editor if the local editor is not ready yet.
+ // See https://github.com/huchenlei/sd-webui-openpose-editor/issues/53
+ // for more details.
+ return await testEditorPath(LOCAL_EDITOR_PATH) || await testEditorPath(REMOTE_EDITOR_PATH);
+ }
+
+ const cnetOpenposeEditorRegisteredElements = new Set();
+ let editorURL = null;
+ function loadOpenposeEditor() {
+ // Simulate an `input` DOM event for Gradio Textbox component. Needed after you edit its contents in javascript, otherwise your edits
+ // will only visible on web page and not sent to python.
+ function updateInput(target) {
+ let e = new Event("input", { bubbles: true })
+ Object.defineProperty(e, "target", { value: target })
+ target.dispatchEvent(e);
+ }
+
+ function navigateIframe(iframe, editorURL) {
+ function getPathname(rawURL) {
+ try {
+ return new URL(rawURL).pathname;
+ } catch (e) {
+ return rawURL;
+ }
+ }
+
+ return new Promise((resolve) => {
+ const darkThemeParam = document.body.classList.contains('dark') ?
+ new URLSearchParams({ theme: 'dark' }).toString() :
+ '';
+
+ window.addEventListener('message', (event) => {
+ const message = event.data;
+ if (message['ready']) resolve();
+ }, { once: true });
+
+ if ((editorURL.startsWith("http") ? iframe.src : getPathname(iframe.src)) !== editorURL) {
+ iframe.src = `${editorURL}?${darkThemeParam}`;
+ // By default assume 5 second is enough for the openpose editor
+ // to load.
+ setTimeout(resolve, 5000);
+ } else {
+ // If no navigation is required, immediately return.
+ resolve();
+ }
+ });
+ }
+ const tabs = gradioApp().querySelectorAll('.cnet-unit-tab');
+ tabs.forEach(tab => {
+ if (cnetOpenposeEditorRegisteredElements.has(tab)) return;
+ cnetOpenposeEditorRegisteredElements.add(tab);
+
+ const generatedImageGroup = tab.querySelector('.cnet-generated-image-group');
+ const editButton = generatedImageGroup.querySelector('.cnet-edit-pose');
+
+ editButton.addEventListener('click', async () => {
+ const inputImageGroup = tab.querySelector('.cnet-input-image-group');
+ const inputImage = inputImageGroup.querySelector('.cnet-image img');
+ const downloadLink = generatedImageGroup.querySelector('.cnet-download-pose a');
+ const modalId = editButton.id.replace('cnet-modal-open-', '');
+ const modalIframe = generatedImageGroup.querySelector('.cnet-modal iframe');
+
+ if (!editorURL) {
+ editorURL = await checkEditorAvailable();
+ if (!editorURL) {
+ alert("No openpose editor available.")
+ }
+ }
+
+ await navigateIframe(modalIframe, editorURL);
+ modalIframe.contentWindow.postMessage({
+ modalId,
+ imageURL: inputImage ? inputImage.src : undefined,
+ poseURL: downloadLink.href,
+ }, '*');
+ // Focus the iframe so that the focus is no longer on the `Edit` button.
+ // Pressing space when the focus is on `Edit` button will trigger
+ // the click again to resend the frame message.
+ modalIframe.contentWindow.focus();
+ });
+ /*
+ * Writes the pose data URL to an link element on input image group.
+ * Click a hidden button to trigger a backend rendering of the pose JSON.
+ *
+ * The backend should:
+ * - Set the rendered pose image as preprocessor generated image.
+ */
+ function updatePreviewPose(poseURL) {
+ const downloadLink = generatedImageGroup.querySelector('.cnet-download-pose a');
+ const renderButton = generatedImageGroup.querySelector('.cnet-render-pose');
+ const poseTextbox = generatedImageGroup.querySelector('.cnet-pose-json textarea');
+ const allowPreviewCheckbox = tab.querySelector('.cnet-allow-preview input');
+
+ if (!allowPreviewCheckbox.checked)
+ allowPreviewCheckbox.click();
+
+ // Only set href when download link exists and needs an update. `downloadLink`
+ // can be null when user closes preview and click `Upload JSON` button again.
+ // https://github.com/Mikubill/sd-webui-controlnet/issues/2308
+ if (downloadLink !== null)
+ downloadLink.href = poseURL;
+
+ poseTextbox.value = poseURL;
+ updateInput(poseTextbox);
+ renderButton.click();
+ }
+
+ // Updates preview image when edit is done.
+ window.addEventListener('message', (event) => {
+ const message = event.data;
+ const modalId = editButton.id.replace('cnet-modal-open-', '');
+ if (message.modalId !== modalId) return;
+ updatePreviewPose(message.poseURL);
+
+ const closeModalButton = generatedImageGroup.querySelector('.cnet-modal .cnet-modal-close');
+ closeModalButton.click();
+ });
+
+ const inputImageGroup = tab.querySelector('.cnet-input-image-group');
+ const uploadButton = inputImageGroup.querySelector('.cnet-upload-pose input');
+ // Updates preview image when JSON file is uploaded.
+ uploadButton.addEventListener('change', (event) => {
+ const file = event.target.files[0];
+ if (!file)
+ return;
+
+ const reader = new FileReader();
+ reader.onload = function (e) {
+ const contents = e.target.result;
+ const poseURL = `data:application/json;base64,${btoa(contents)}`;
+ updatePreviewPose(poseURL);
+ };
+ reader.readAsText(file);
+ // Reset the file input value so that uploading the same file still triggers callback.
+ event.target.value = '';
+ });
+ });
+ }
+
+ onUiUpdate(loadOpenposeEditor);
+})();
\ No newline at end of file
diff --git a/extensions-builtin/sd_forge_controlnet/javascript/photopea.js b/extensions-builtin/sd_forge_controlnet/javascript/photopea.js
new file mode 100644
index 00000000..d2b1ebc9
--- /dev/null
+++ b/extensions-builtin/sd_forge_controlnet/javascript/photopea.js
@@ -0,0 +1,435 @@
+(function () {
+ /*
+ MIT LICENSE
+ Copyright 2011 Jon Leighton
+ 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.
+ */
+ // From: https://gist.github.com/jonleighton/958841
+ function base64ArrayBuffer(arrayBuffer) {
+ var base64 = ''
+ var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
+
+ var bytes = new Uint8Array(arrayBuffer)
+ var byteLength = bytes.byteLength
+ var byteRemainder = byteLength % 3
+ var mainLength = byteLength - byteRemainder
+
+ var a, b, c, d
+ var chunk
+
+ // Main loop deals with bytes in chunks of 3
+ for (var i = 0; i < mainLength; i = i + 3) {
+ // Combine the three bytes into a single integer
+ chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
+
+ // Use bitmasks to extract 6-bit segments from the triplet
+ a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
+ b = (chunk & 258048) >> 12 // 258048 = (2^6 - 1) << 12
+ c = (chunk & 4032) >> 6 // 4032 = (2^6 - 1) << 6
+ d = chunk & 63 // 63 = 2^6 - 1
+
+ // Convert the raw binary segments to the appropriate ASCII encoding
+ base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
+ }
+
+ // Deal with the remaining bytes and padding
+ if (byteRemainder == 1) {
+ chunk = bytes[mainLength]
+
+ a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2
+
+ // Set the 4 least significant bits to zero
+ b = (chunk & 3) << 4 // 3 = 2^2 - 1
+
+ base64 += encodings[a] + encodings[b] + '=='
+ } else if (byteRemainder == 2) {
+ chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]
+
+ a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
+ b = (chunk & 1008) >> 4 // 1008 = (2^6 - 1) << 4
+
+ // Set the 2 least significant bits to zero
+ c = (chunk & 15) << 2 // 15 = 2^4 - 1
+
+ base64 += encodings[a] + encodings[b] + encodings[c] + '='
+ }
+
+ return base64
+ }
+
+ // Turn a base64 string into a blob.
+ // From https://gist.github.com/gauravmehla/7a7dfd87dd7d1b13697b6e894426615f
+ function b64toBlob(b64Data, contentType, sliceSize) {
+ var contentType = contentType || '';
+ var sliceSize = sliceSize || 512;
+ var byteCharacters = atob(b64Data);
+ var byteArrays = [];
+ for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
+ var slice = byteCharacters.slice(offset, offset + sliceSize);
+ var byteNumbers = new Array(slice.length);
+ for (var i = 0; i < slice.length; i++) {
+ byteNumbers[i] = slice.charCodeAt(i);
+ }
+ var byteArray = new Uint8Array(byteNumbers);
+ byteArrays.push(byteArray);
+ }
+ return new Blob(byteArrays, { type: contentType });
+ }
+
+ function createBlackImageBase64(width, height) {
+ // Create a canvas element
+ var canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+
+ // Get the context of the canvas
+ var ctx = canvas.getContext('2d');
+
+ // Fill the canvas with black color
+ ctx.fillStyle = 'black';
+ ctx.fillRect(0, 0, width, height);
+
+ // Get the base64 encoded string
+ var base64Image = canvas.toDataURL('image/png');
+
+ return base64Image;
+ }
+
+ // Functions to be called within photopea context.
+ // Start of photopea functions
+ function pasteImage(base64image) {
+ app.open(base64image, null, /* asSmart */ true);
+ app.echoToOE("success");
+ }
+
+ function setLayerNames(names) {
+ const layers = app.activeDocument.layers;
+ if (layers.length !== names.length) {
+ console.error("layer length does not match names length");
+ echoToOE("error");
+ return;
+ }
+
+ for (let i = 0; i < names.length; i++) {
+ const layer = layers[i];
+ layer.name = names[i];
+ }
+ app.echoToOE("success");
+ }
+
+ function removeLayersWithNames(names) {
+ const layers = app.activeDocument.layers;
+ for (let i = 0; i < layers.length; i++) {
+ const layer = layers[i];
+ if (names.includes(layer.name)) {
+ layer.remove();
+ }
+ }
+ app.echoToOE("success");
+ }
+
+ function getAllLayerNames() {
+ const layers = app.activeDocument.layers;
+ const names = [];
+ for (let i = 0; i < layers.length; i++) {
+ const layer = layers[i];
+ names.push(layer.name);
+ }
+ app.echoToOE(JSON.stringify(names));
+ }
+
+ // Hides all layers except the current one, outputs the whole image, then restores the previous
+ // layers state.
+ function exportSelectedLayerOnly(format, layerName) {
+ // Gets all layers recursively, including the ones inside folders.
+ function getAllArtLayers(document) {
+ let allArtLayers = [];
+
+ for (let i = 0; i < document.layers.length; i++) {
+ const currentLayer = document.layers[i];
+ allArtLayers.push(currentLayer);
+ if (currentLayer.typename === "LayerSet") {
+ allArtLayers = allArtLayers.concat(getAllArtLayers(currentLayer));
+ }
+ }
+ return allArtLayers;
+ }
+
+ function makeLayerVisible(layer) {
+ let currentLayer = layer;
+ while (currentLayer != app.activeDocument) {
+ currentLayer.visible = true;
+ if (currentLayer.parent.typename != 'Document') {
+ currentLayer = currentLayer.parent;
+ } else {
+ break;
+ }
+ }
+ }
+
+
+ const allLayers = getAllArtLayers(app.activeDocument);
+ // Make all layers except the currently selected one invisible, and store
+ // their initial state.
+ const layerStates = [];
+ for (let i = 0; i < allLayers.length; i++) {
+ const layer = allLayers[i];
+ layerStates.push(layer.visible);
+ }
+ // Hide all layers to begin with
+ for (let i = 0; i < allLayers.length; i++) {
+ const layer = allLayers[i];
+ layer.visible = false;
+ }
+ for (let i = 0; i < allLayers.length; i++) {
+ const layer = allLayers[i];
+ const selected = layer.name === layerName;
+ if (selected) {
+ makeLayerVisible(layer);
+ }
+ }
+ app.activeDocument.saveToOE(format);
+
+ for (let i = 0; i < allLayers.length; i++) {
+ const layer = allLayers[i];
+ layer.visible = layerStates[i];
+ }
+ }
+
+ function hasActiveDocument() {
+ app.echoToOE(app.documents.length > 0 ? "true" : "false");
+ }
+ // End of photopea functions
+
+ const MESSAGE_END_ACK = "done";
+ const MESSAGE_ERROR = "error";
+ const PHOTOPEA_URL = "https://www.photopea.com/";
+ class PhotopeaContext {
+ constructor(photopeaIframe) {
+ this.photopeaIframe = photopeaIframe;
+ this.timeout = 1000;
+ }
+
+ navigateIframe() {
+ const iframe = this.photopeaIframe;
+ const editorURL = PHOTOPEA_URL;
+
+ return new Promise(async (resolve) => {
+ if (iframe.src !== editorURL) {
+ iframe.src = editorURL;
+ // Stop waiting after 10s.
+ setTimeout(resolve, 10000);
+
+ // Testing whether photopea is able to accept message.
+ while (true) {
+ try {
+ await this.invoke(hasActiveDocument);
+ break;
+ } catch (e) {
+ console.log("Keep waiting for photopea to accept message.");
+ }
+ }
+ this.timeout = 5000; // Restore to a longer timeout in normal messaging.
+ }
+ resolve();
+ });
+ }
+
+ // From https://github.com/huchenlei/stable-diffusion-ps-pea/blob/main/src/Photopea.ts
+ postMessageToPhotopea(message) {
+ return new Promise((resolve, reject) => {
+ const responseDataPieces = [];
+ let hasError = false;
+ const photopeaMessageHandle = (event) => {
+ if (event.source !== this.photopeaIframe.contentWindow) {
+ return;
+ }
+ // Filter out the ping messages
+ if (typeof event.data === 'string' && event.data.includes('MSFAPI#')) {
+ return;
+ }
+ // Ignore "done" when no data has been received. The "done" can come from
+ // MSFAPI ping.
+ if (event.data === MESSAGE_END_ACK && responseDataPieces.length === 0) {
+ return;
+ }
+ if (event.data === MESSAGE_END_ACK) {
+ window.removeEventListener("message", photopeaMessageHandle);
+ if (hasError) {
+ reject('Photopea Error.');
+ } else {
+ resolve(responseDataPieces.length === 1 ? responseDataPieces[0] : responseDataPieces);
+ }
+ } else if (event.data === MESSAGE_ERROR) {
+ responseDataPieces.push(event.data);
+ hasError = true;
+ } else {
+ responseDataPieces.push(event.data);
+ }
+ };
+
+ window.addEventListener("message", photopeaMessageHandle);
+ setTimeout(() => reject("Photopea message timeout"), this.timeout);
+ this.photopeaIframe.contentWindow.postMessage(message, "*");
+ });
+ }
+
+ // From https://github.com/huchenlei/stable-diffusion-ps-pea/blob/main/src/Photopea.ts
+ async invoke(func, ...args) {
+ await this.navigateIframe();
+ const message = `${func.toString()} ${func.name}(${args.map(arg => JSON.stringify(arg)).join(',')});`;
+ try {
+ return await this.postMessageToPhotopea(message);
+ } catch (e) {
+ throw `Failed to invoke ${func.name}. ${e}.`;
+ }
+ }
+
+ /**
+ * Fetch detected maps from each ControlNet units.
+ * Create a new photopea document.
+ * Add those detected maps to the created document.
+ */
+ async fetchFromControlNet(tabs) {
+ if (tabs.length === 0) return;
+ const isImg2Img = tabs[0].querySelector('.cnet-unit-enabled').id.includes('img2img');
+ const generationType = isImg2Img ? 'img2img' : 'txt2img';
+ const width = gradioApp().querySelector(`#${generationType}_width input[type=number]`).value;
+ const height = gradioApp().querySelector(`#${generationType}_height input[type=number]`).value;
+
+ const layerNames = ["background"];
+ await this.invoke(pasteImage, createBlackImageBase64(width, height));
+ await new Promise(r => setTimeout(r, 200));
+ for (const [i, tab] of tabs.entries()) {
+ const generatedImage = tab.querySelector('.cnet-generated-image-group .cnet-image img');
+ if (!generatedImage) continue;
+ await this.invoke(pasteImage, generatedImage.src);
+ // Wait 200ms for pasting to fully complete so that we do not ended up with 2 separate
+ // documents.
+ await new Promise(r => setTimeout(r, 200));
+ layerNames.push(`unit-${i}`);
+ }
+ await this.invoke(removeLayersWithNames, layerNames);
+ await this.invoke(setLayerNames, layerNames.reverse());
+ }
+
+ /**
+ * Send the images in the active photopea document back to each ControlNet units.
+ */
+ async sendToControlNet(tabs) {
+ // Gradio's image widgets are inputs. To set the image in one, we set the image on the input and
+ // force it to refresh.
+ function setImageOnInput(imageInput, file) {
+ // Createa a data transfer element to set as the data in the input.
+ const dt = new DataTransfer();
+ dt.items.add(file);
+ const list = dt.files;
+
+ // Actually set the image in the image widget.
+ imageInput.files = list;
+
+ // Foce the image widget to update with the new image, after setting its source files.
+ const event = new Event('change', {
+ 'bubbles': true,
+ "composed": true
+ });
+ imageInput.dispatchEvent(event);
+ }
+
+ function sendToControlNetUnit(b64Image, index) {
+ const tab = tabs[index];
+ // Upload image to output image element.
+ const outputImage = tab.querySelector('.cnet-photopea-output');
+ const outputImageUpload = outputImage.querySelector('input[type="file"]');
+ setImageOnInput(outputImageUpload, new File([b64toBlob(b64Image, "image/png")], "photopea_output.png"));
+
+ // Make sure `UsePreviewAsInput` checkbox is checked.
+ const checkbox = tab.querySelector('.cnet-preview-as-input input[type="checkbox"]');
+ if (!checkbox.checked) {
+ checkbox.click();
+ }
+ }
+
+ const layerNames =
+ JSON.parse(await this.invoke(getAllLayerNames))
+ .filter(name => /unit-\d+/.test(name));
+
+ for (const layerName of layerNames) {
+ const arrayBuffer = await this.invoke(exportSelectedLayerOnly, 'PNG', layerName);
+ const b64Image = base64ArrayBuffer(arrayBuffer);
+ const layerIndex = Number.parseInt(layerName.split('-')[1]);
+ sendToControlNetUnit(b64Image, layerIndex);
+ }
+ }
+ }
+
+ let photopeaWarningShown = false;
+
+ function firstTimeUserPrompt() {
+ if (opts.controlnet_photopea_warning){
+ const photopeaPopupMsg = "you are about to connect to https://photopea.com\n" +
+ "- Click OK: proceed.\n" +
+ "- Click Cancel: abort.\n" +
+ "Photopea integration can be disabled in Settings > ControlNet > Disable photopea edit.\n" +
+ "This popup can be disabled in Settings > ControlNet > Photopea popup warning.";
+ if (photopeaWarningShown || confirm(photopeaPopupMsg)) photopeaWarningShown = true;
+ else return false;
+ }
+ return true;
+ }
+
+ const cnetRegisteredAccordions = new Set();
+ function loadPhotopea() {
+ function registerCallbacks(accordion) {
+ const photopeaMainTrigger = accordion.querySelector('.cnet-photopea-main-trigger');
+ // Photopea edit feature disabled.
+ if (!photopeaMainTrigger) {
+ console.log("ControlNet photopea edit disabled.");
+ return;
+ }
+
+ const closeModalButton = accordion.querySelector('.cnet-photopea-edit .cnet-modal-close');
+ const tabs = accordion.querySelectorAll('.cnet-unit-tab');
+ const photopeaIframe = accordion.querySelector('.photopea-iframe');
+ const photopeaContext = new PhotopeaContext(photopeaIframe, tabs);
+
+ tabs.forEach(tab => {
+ const photopeaChildTrigger = tab.querySelector('.cnet-photopea-child-trigger');
+ photopeaChildTrigger.addEventListener('click', async () => {
+ if (!firstTimeUserPrompt()) return;
+
+ photopeaMainTrigger.click();
+ if (await photopeaContext.invoke(hasActiveDocument) === "false") {
+ await photopeaContext.fetchFromControlNet(tabs);
+ }
+ });
+ });
+ accordion.querySelector('.photopea-fetch').addEventListener('click', () => photopeaContext.fetchFromControlNet(tabs));
+ accordion.querySelector('.photopea-send').addEventListener('click', () => {
+ photopeaContext.sendToControlNet(tabs)
+ closeModalButton.click();
+ });
+ }
+
+ const accordions = gradioApp().querySelectorAll('#controlnet');
+ accordions.forEach(accordion => {
+ if (cnetRegisteredAccordions.has(accordion)) return;
+ registerCallbacks(accordion);
+ cnetRegisteredAccordions.add(accordion);
+ });
+ }
+
+ onUiUpdate(loadPhotopea);
+})();
\ No newline at end of file
diff --git a/extensions-builtin/sd_forge_controlnet/lib_controlnet/controlnet_ui/controlnet_ui_group.py b/extensions-builtin/sd_forge_controlnet/lib_controlnet/controlnet_ui/controlnet_ui_group.py
new file mode 100644
index 00000000..f36ca34d
--- /dev/null
+++ b/extensions-builtin/sd_forge_controlnet/lib_controlnet/controlnet_ui/controlnet_ui_group.py
@@ -0,0 +1,1348 @@
+import json
+import gradio as gr
+import functools
+from copy import copy
+from typing import List, Optional, Union, Callable, Dict, Tuple, Literal
+from dataclasses import dataclass
+import numpy as np
+
+from lib_controlnet.utils import svg_preprocess, read_image
+from lib_controlnet import (
+ global_state,
+ external_code,
+)
+from lib_controlnet.logging import logger
+from lib_controlnet.controlnet_ui.openpose_editor import OpenposeEditor
+from lib_controlnet.controlnet_ui.preset import ControlNetPresetUI
+from lib_controlnet.controlnet_ui.tool_button import ToolButton
+from lib_controlnet.controlnet_ui.photopea import Photopea
+from lib_controlnet.enums import InputMode
+from modules import shared
+from modules.ui_components import FormRow
+from modules_forge.forge_util import HWC3
+
+
+@dataclass
+class A1111Context:
+ """Contains all components from A1111."""
+
+ img2img_batch_input_dir: Optional[gr.components.IOComponent] = None
+ img2img_batch_output_dir: Optional[gr.components.IOComponent] = None
+ txt2img_submit_button: Optional[gr.components.IOComponent] = None
+ img2img_submit_button: Optional[gr.components.IOComponent] = None
+
+ # Slider controls from A1111 WebUI.
+ txt2img_w_slider: Optional[gr.components.IOComponent] = None
+ txt2img_h_slider: Optional[gr.components.IOComponent] = None
+ img2img_w_slider: Optional[gr.components.IOComponent] = None
+ img2img_h_slider: Optional[gr.components.IOComponent] = None
+
+ img2img_img2img_tab: Optional[gr.components.IOComponent] = None
+ img2img_img2img_sketch_tab: Optional[gr.components.IOComponent] = None
+ img2img_batch_tab: Optional[gr.components.IOComponent] = None
+ img2img_inpaint_tab: Optional[gr.components.IOComponent] = None
+ img2img_inpaint_sketch_tab: Optional[gr.components.IOComponent] = None
+ img2img_inpaint_upload_tab: Optional[gr.components.IOComponent] = None
+
+ img2img_inpaint_area: Optional[gr.components.IOComponent] = None
+ # txt2img_enable_hr is only available for A1111 > 1.7.0.
+ txt2img_enable_hr: Optional[gr.components.IOComponent] = None
+ setting_sd_model_checkpoint: Optional[gr.components.IOComponent] = None
+
+ @property
+ def img2img_inpaint_tabs(self) -> Tuple[gr.components.IOComponent]:
+ return (
+ self.img2img_inpaint_tab,
+ self.img2img_inpaint_sketch_tab,
+ self.img2img_inpaint_upload_tab,
+ )
+
+ @property
+ def img2img_non_inpaint_tabs(self) -> List[gr.components.IOComponent]:
+ return (
+ self.img2img_img2img_tab,
+ self.img2img_img2img_sketch_tab,
+ self.img2img_batch_tab,
+ )
+
+ @property
+ def ui_initialized(self) -> bool:
+ optional_components = {
+ # Optional components are only available after A1111 v1.7.0.
+ "img2img_img2img_tab": "img2img_img2img_tab",
+ "img2img_img2img_sketch_tab": "img2img_img2img_sketch_tab",
+ "img2img_batch_tab": "img2img_batch_tab",
+ "img2img_inpaint_tab": "img2img_inpaint_tab",
+ "img2img_inpaint_sketch_tab": "img2img_inpaint_sketch_tab",
+ "img2img_inpaint_upload_tab": "img2img_inpaint_upload_tab",
+ # SDNext does not have this field. Temporarily disable the callback on
+ # the checkpoint change until we find a way to register an event when
+ # all A1111 UI components are ready.
+ "setting_sd_model_checkpoint": "setting_sd_model_checkpoint",
+ }
+ return all(
+ c
+ for name, c in vars(self).items()
+ if name not in optional_components.values()
+ )
+
+ def set_component(self, component: gr.components.IOComponent):
+ id_mapping = {
+ "img2img_batch_input_dir": "img2img_batch_input_dir",
+ "img2img_batch_output_dir": "img2img_batch_output_dir",
+ "txt2img_generate": "txt2img_submit_button",
+ "img2img_generate": "img2img_submit_button",
+ "txt2img_width": "txt2img_w_slider",
+ "txt2img_height": "txt2img_h_slider",
+ "img2img_width": "img2img_w_slider",
+ "img2img_height": "img2img_h_slider",
+ "img2img_img2img_tab": "img2img_img2img_tab",
+ "img2img_img2img_sketch_tab": "img2img_img2img_sketch_tab",
+ "img2img_batch_tab": "img2img_batch_tab",
+ "img2img_inpaint_tab": "img2img_inpaint_tab",
+ "img2img_inpaint_sketch_tab": "img2img_inpaint_sketch_tab",
+ "img2img_inpaint_upload_tab": "img2img_inpaint_upload_tab",
+ "img2img_inpaint_full_res": "img2img_inpaint_area",
+ "txt2img_hr-checkbox": "txt2img_enable_hr",
+ # setting_sd_model_checkpoint is expected to be initialized last.
+ # "setting_sd_model_checkpoint": "setting_sd_model_checkpoint",
+ }
+ elem_id = getattr(component, "elem_id", None)
+ # Do not set component if it has already been set.
+ # https://github.com/Mikubill/sd-webui-controlnet/issues/2587
+ if elem_id in id_mapping and getattr(self, id_mapping[elem_id]) is None:
+ setattr(self, id_mapping[elem_id], component)
+ logger.debug(f"Setting {elem_id}.")
+ logger.debug(
+ f"A1111 initialized {sum(c is not None for c in vars(self).values())}/{len(vars(self).keys())}."
+ )
+
+
+class UiControlNetUnit(external_code.ControlNetUnit):
+ """The data class that stores all states of a ControlNetUnit."""
+
+ def __init__(
+ self,
+ input_mode: InputMode = InputMode.SIMPLE,
+ batch_images: Optional[Union[str, List[external_code.InputImage]]] = None,
+ output_dir: str = "",
+ loopback: bool = False,
+ merge_gallery_files: List[
+ Dict[Union[Literal["name"], Literal["data"]], str]
+ ] = [],
+ use_preview_as_input: bool = False,
+ generated_image: Optional[np.ndarray] = None,
+ mask_image: Optional[np.ndarray] = None,
+ enabled: bool = True,
+ module: Optional[str] = None,
+ model: Optional[str] = None,
+ weight: float = 1.0,
+ image: Optional[Dict[str, np.ndarray]] = None,
+ *args,
+ **kwargs,
+ ):
+ if use_preview_as_input and generated_image is not None:
+ input_image = generated_image
+ module = "none"
+ else:
+ input_image = image
+
+ # Prefer uploaded mask_image over hand-drawn mask.
+ if input_image is not None and mask_image is not None:
+ assert isinstance(input_image, dict)
+ input_image["mask"] = mask_image
+
+ if merge_gallery_files and input_mode == InputMode.MERGE:
+ input_image = [
+ {"image": read_image(file["name"])} for file in merge_gallery_files
+ ]
+
+ super().__init__(enabled, module, model, weight, input_image, *args, **kwargs)
+ self.is_ui = True
+ self.input_mode = input_mode
+ self.batch_images = batch_images
+ self.output_dir = output_dir
+ self.loopback = loopback
+
+ def unfold_merged(self) -> List[external_code.ControlNetUnit]:
+ """Unfolds a merged unit to multiple units. Keeps the unit merged for
+ preprocessors that can accept multiple input images.
+ """
+ if self.input_mode != InputMode.MERGE:
+ return [copy(self)]
+
+ if self.accepts_multiple_inputs():
+ self.input_mode = InputMode.SIMPLE
+ return [copy(self)]
+
+ assert isinstance(self.image, list)
+ result = []
+ for image in self.image:
+ unit = copy(self)
+ unit.image = image["image"]
+ unit.input_mode = InputMode.SIMPLE
+ unit.weight = self.weight / len(self.image)
+ result.append(unit)
+ return result
+
+
+class ControlNetUiGroup(object):
+ refresh_symbol = "\U0001f504" # 🔄
+ switch_values_symbol = "\U000021C5" # ⇅
+ camera_symbol = "\U0001F4F7" # 📷
+ reverse_symbol = "\U000021C4" # ⇄
+ tossup_symbol = "\u2934"
+ trigger_symbol = "\U0001F4A5" # 💥
+ open_symbol = "\U0001F4DD" # 📝
+
+ tooltips = {
+ "🔄": "Refresh",
+ "\u2934": "Send dimensions to stable diffusion",
+ "💥": "Run preprocessor",
+ "📝": "Open new canvas",
+ "📷": "Enable webcam",
+ "⇄": "Mirror webcam",
+ }
+
+ global_batch_input_dir = gr.Textbox(
+ label="Controlnet input directory",
+ placeholder="Leave empty to use input directory",
+ **shared.hide_dirs,
+ elem_id="controlnet_batch_input_dir",
+ )
+ a1111_context = A1111Context()
+ # All ControlNetUiGroup instances created.
+ all_ui_groups: List["ControlNetUiGroup"] = []
+
+ def __init__(
+ self,
+ is_img2img: bool,
+ default_unit: external_code.ControlNetUnit,
+ photopea: Optional[Photopea],
+ ):
+ # Whether callbacks have been registered.
+ self.callbacks_registered: bool = False
+ # Whether the render method on this object has been called.
+ self.ui_initialized: bool = False
+
+ self.is_img2img = is_img2img
+ self.default_unit = default_unit
+ self.photopea = photopea
+ self.webcam_enabled = False
+ self.webcam_mirrored = False
+
+ # Note: All gradio elements declared in `render` will be defined as member variable.
+ # Update counter to trigger a force update of UiControlNetUnit.
+ # This is useful when a field with no event subscriber available changes.
+ # e.g. gr.Gallery, gr.State, etc.
+ self.update_unit_counter = None
+ self.upload_tab = None
+ self.image = None
+ self.generated_image_group = None
+ self.generated_image = None
+ self.mask_image_group = None
+ self.mask_image = None
+ self.batch_tab = None
+ self.batch_image_dir = None
+ self.merge_tab = None
+ self.merge_gallery = None
+ self.merge_upload_button = None
+ self.merge_clear_button = None
+ self.create_canvas = None
+ self.canvas_width = None
+ self.canvas_height = None
+ self.canvas_create_button = None
+ self.canvas_cancel_button = None
+ self.open_new_canvas_button = None
+ self.webcam_enable = None
+ self.webcam_mirror = None
+ self.send_dimen_button = None
+ self.enabled = None
+ self.low_vram = None
+ self.pixel_perfect = None
+ self.preprocessor_preview = None
+ self.mask_upload = None
+ self.type_filter = None
+ self.module = None
+ self.trigger_preprocessor = None
+ self.model = None
+ self.refresh_models = None
+ self.weight = None
+ self.guidance_start = None
+ self.guidance_end = None
+ self.advanced = None
+ self.processor_res = None
+ self.threshold_a = None
+ self.threshold_b = None
+ self.control_mode = None
+ self.resize_mode = None
+ self.loopback = None
+ self.use_preview_as_input = None
+ self.openpose_editor = None
+ self.preset_panel = None
+ self.upload_independent_img_in_img2img = None
+ self.image_upload_panel = None
+ self.save_detected_map = None
+ self.input_mode = gr.State(InputMode.SIMPLE)
+ self.inpaint_crop_input_image = None
+ self.hr_option = None
+ self.batch_image_dir_state = None
+ self.output_dir_state = None
+
+ # Internal states for UI state pasting.
+ self.prevent_next_n_module_update = 0
+ self.prevent_next_n_slider_value_update = 0
+
+ # API-only fields
+ self.advanced_weighting = gr.State(None)
+
+ ControlNetUiGroup.all_ui_groups.append(self)
+
+ def render(self, tabname: str, elem_id_tabname: str) -> None:
+ """The pure HTML structure of a single ControlNetUnit. Calling this
+ function will populate `self` with all gradio element declared
+ in local scope.
+
+ Args:
+ tabname:
+ elem_id_tabname:
+
+ Returns:
+ None
+ """
+ self.update_unit_counter = gr.Number(value=0, visible=False)
+ self.openpose_editor = OpenposeEditor()
+
+ with gr.Group(visible=not self.is_img2img) as self.image_upload_panel:
+ self.save_detected_map = gr.Checkbox(value=True, visible=False)
+ with gr.Tabs():
+ with gr.Tab(label="Single Image") as self.upload_tab:
+ with gr.Row(elem_classes=["cnet-image-row"], equal_height=True):
+ with gr.Group(elem_classes=["cnet-input-image-group"]):
+ self.image = gr.Image(
+ source="upload",
+ brush_radius=20,
+ mirror_webcam=False,
+ type="numpy",
+ tool="sketch",
+ elem_id=f"{elem_id_tabname}_{tabname}_input_image",
+ elem_classes=["cnet-image"],
+ brush_color=shared.opts.img2img_inpaint_mask_brush_color
+ if hasattr(
+ shared.opts, "img2img_inpaint_mask_brush_color"
+ )
+ else None,
+ )
+ self.image.preprocess = functools.partial(
+ svg_preprocess, preprocess=self.image.preprocess
+ )
+ self.openpose_editor.render_upload()
+
+ with gr.Group(
+ visible=False, elem_classes=["cnet-generated-image-group"]
+ ) as self.generated_image_group:
+ self.generated_image = gr.Image(
+ value=None,
+ label="Preprocessor Preview",
+ elem_id=f"{elem_id_tabname}_{tabname}_generated_image",
+ elem_classes=["cnet-image"],
+ interactive=True,
+ height=242,
+ ) # Gradio's magic number. Only 242 works.
+
+ with gr.Group(
+ elem_classes=["cnet-generated-image-control-group"]
+ ):
+ if self.photopea:
+ self.photopea.render_child_trigger()
+ self.openpose_editor.render_edit()
+ preview_check_elem_id = f"{elem_id_tabname}_{tabname}_controlnet_preprocessor_preview_checkbox"
+ preview_close_button_js = f"document.querySelector('#{preview_check_elem_id} input[type=\\'checkbox\\']').click();"
+ gr.HTML(
+ value=f"""Close""",
+ visible=True,
+ elem_classes=["cnet-close-preview"],
+ )
+
+ with gr.Group(
+ visible=False, elem_classes=["cnet-mask-image-group"]
+ ) as self.mask_image_group:
+ self.mask_image = gr.Image(
+ value=None,
+ label="Upload Mask",
+ elem_id=f"{elem_id_tabname}_{tabname}_mask_image",
+ elem_classes=["cnet-mask-image"],
+ interactive=True,
+ )
+
+ with gr.Tab(label="Batch") as self.batch_tab:
+ self.batch_image_dir = gr.Textbox(
+ label="Input Directory",
+ placeholder="Leave empty to use img2img batch controlnet input directory",
+ elem_id=f"{elem_id_tabname}_{tabname}_batch_image_dir",
+ )
+
+ with gr.Tab(label="Multi-Inputs") as self.merge_tab:
+ self.merge_gallery = gr.Gallery(
+ columns=[4], rows=[2], object_fit="contain", height="auto"
+ )
+ with gr.Row():
+ self.merge_upload_button = gr.UploadButton(
+ "Upload Images",
+ file_types=["image"],
+ file_count="multiple",
+ )
+ self.merge_clear_button = gr.Button("Clear Images")
+
+ if self.photopea:
+ self.photopea.attach_photopea_output(self.generated_image)
+
+ with gr.Accordion(
+ label="Open New Canvas", visible=False
+ ) as self.create_canvas:
+ self.canvas_width = gr.Slider(
+ label="New Canvas Width",
+ minimum=256,
+ maximum=1024,
+ value=512,
+ step=64,
+ elem_id=f"{elem_id_tabname}_{tabname}_controlnet_canvas_width",
+ )
+ self.canvas_height = gr.Slider(
+ label="New Canvas Height",
+ minimum=256,
+ maximum=1024,
+ value=512,
+ step=64,
+ elem_id=f"{elem_id_tabname}_{tabname}_controlnet_canvas_height",
+ )
+ with gr.Row():
+ self.canvas_create_button = gr.Button(
+ value="Create New Canvas",
+ elem_id=f"{elem_id_tabname}_{tabname}_controlnet_canvas_create_button",
+ )
+ self.canvas_cancel_button = gr.Button(
+ value="Cancel",
+ elem_id=f"{elem_id_tabname}_{tabname}_controlnet_canvas_cancel_button",
+ )
+
+ with gr.Row(elem_classes="controlnet_image_controls"):
+ gr.HTML(
+ value="
Set the preprocessor to [invert] If your image has white background and black lines.