Lakshmanaraja
commited on
Commit
·
0784e4f
1
Parent(s):
574a02e
Upload 23 files
Browse files- LICENSE +201 -0
- README.md +338 -0
- config.py +1 -0
- environment.yaml +35 -0
- gradio_annotator.py +160 -0
- gradio_canny2image.py +97 -0
- gradio_depth2image.py +98 -0
- gradio_fake_scribble2image.py +102 -0
- gradio_hed2image.py +98 -0
- gradio_hough2image.py +100 -0
- gradio_normal2image.py +99 -0
- gradio_pose2image.py +98 -0
- gradio_scribble2image.py +92 -0
- gradio_scribble2image_interactive.py +102 -0
- gradio_seg2image.py +97 -0
- share.py +8 -0
- tool_add_control.py +50 -0
- tool_add_control_sd21.py +50 -0
- tool_transfer_control.py +59 -0
- tutorial_dataset.py +39 -0
- tutorial_dataset_test.py +12 -0
- tutorial_train.py +35 -0
- tutorial_train_sd21.py +35 -0
LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright [yyyy] [name of copyright owner]
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
README.md
ADDED
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ControlNet
|
2 |
+
|
3 |
+
Official implementation of [Adding Conditional Control to Text-to-Image Diffusion Models](https://arxiv.org/abs/2302.05543).
|
4 |
+
|
5 |
+
ControlNet is a neural network structure to control diffusion models by adding extra conditions.
|
6 |
+
|
7 |
+
![img](github_page/he.png)
|
8 |
+
|
9 |
+
It copys the weights of neural network blocks into a "locked" copy and a "trainable" copy.
|
10 |
+
|
11 |
+
The "trainable" one learns your condition. The "locked" one preserves your model.
|
12 |
+
|
13 |
+
Thanks to this, training with small dataset of image pairs will not destroy the production-ready diffusion models.
|
14 |
+
|
15 |
+
The "zero convolution" is 1×1 convolution with both weight and bias initialized as zeros.
|
16 |
+
|
17 |
+
Before training, all zero convolutions output zeros, and ControlNet will not cause any distortion.
|
18 |
+
|
19 |
+
No layer is trained from scratch. You are still fine-tuning. Your original model is safe.
|
20 |
+
|
21 |
+
This allows training on small-scale or even personal devices.
|
22 |
+
|
23 |
+
This is also friendly to merge/replacement/offsetting of models/weights/blocks/layers.
|
24 |
+
|
25 |
+
### FAQ
|
26 |
+
|
27 |
+
**Q:** But wait, if the weight of a conv layer is zero, the gradient will also be zero, and the network will not learn anything. Why "zero convolution" works?
|
28 |
+
|
29 |
+
**A:** This is not true. [See an explanation here](docs/faq.md).
|
30 |
+
|
31 |
+
# Stable Diffusion + ControlNet
|
32 |
+
|
33 |
+
By repeating the above simple structure 14 times, we can control stable diffusion in this way:
|
34 |
+
|
35 |
+
![img](github_page/sd.png)
|
36 |
+
|
37 |
+
Note that the way we connect layers is computational efficient. The original SD encoder does not need to store gradients (the locked original SD Encoder Block 1234 and Middle). The required GPU memory is not much larger than original SD, although many layers are added. Great!
|
38 |
+
|
39 |
+
# Features & News
|
40 |
+
|
41 |
+
2023/02/26 - We released a blog - [Ablation Study: Why ControlNets use deep encoder? What if it was lighter? Or even an MLP?](https://github.com/lllyasviel/ControlNet/discussions/188)
|
42 |
+
|
43 |
+
2023/02/20 - Implementation for non-prompt mode released. See also [Guess Mode / Non-Prompt Mode](#guess-anchor).
|
44 |
+
|
45 |
+
2023/02/12 - Now you can play with any community model by [Transferring the ControlNet](https://github.com/lllyasviel/ControlNet/discussions/12).
|
46 |
+
|
47 |
+
2023/02/11 - [Low VRAM mode](docs/low_vram.md) is added. Please use this mode if you are using 8GB GPU(s) or if you want larger batch size.
|
48 |
+
|
49 |
+
# Production-Ready Pretrained Models
|
50 |
+
|
51 |
+
First create a new conda environment
|
52 |
+
|
53 |
+
conda env create -f environment.yaml
|
54 |
+
conda activate control
|
55 |
+
|
56 |
+
All models and detectors can be downloaded from [our Hugging Face page](https://huggingface.co/lllyasviel/ControlNet). Make sure that SD models are put in "ControlNet/models" and detectors are put in "ControlNet/annotator/ckpts". Make sure that you download all necessary pretrained weights and detector models from that Hugging Face page, including HED edge detection model, Midas depth estimation model, Openpose, and so on.
|
57 |
+
|
58 |
+
We provide 9 Gradio apps with these models.
|
59 |
+
|
60 |
+
All test images can be found at the folder "test_imgs".
|
61 |
+
|
62 |
+
## ControlNet with Canny Edge
|
63 |
+
|
64 |
+
Stable Diffusion 1.5 + ControlNet (using simple Canny edge detection)
|
65 |
+
|
66 |
+
python gradio_canny2image.py
|
67 |
+
|
68 |
+
The Gradio app also allows you to change the Canny edge thresholds. Just try it for more details.
|
69 |
+
|
70 |
+
Prompt: "bird"
|
71 |
+
![p](github_page/p1.png)
|
72 |
+
|
73 |
+
Prompt: "cute dog"
|
74 |
+
![p](github_page/p2.png)
|
75 |
+
|
76 |
+
## ControlNet with M-LSD Lines
|
77 |
+
|
78 |
+
Stable Diffusion 1.5 + ControlNet (using simple M-LSD straight line detection)
|
79 |
+
|
80 |
+
python gradio_hough2image.py
|
81 |
+
|
82 |
+
The Gradio app also allows you to change the M-LSD thresholds. Just try it for more details.
|
83 |
+
|
84 |
+
Prompt: "room"
|
85 |
+
![p](github_page/p3.png)
|
86 |
+
|
87 |
+
Prompt: "building"
|
88 |
+
![p](github_page/p4.png)
|
89 |
+
|
90 |
+
## ControlNet with HED Boundary
|
91 |
+
|
92 |
+
Stable Diffusion 1.5 + ControlNet (using soft HED Boundary)
|
93 |
+
|
94 |
+
python gradio_hed2image.py
|
95 |
+
|
96 |
+
The soft HED Boundary will preserve many details in input images, making this app suitable for recoloring and stylizing. Just try it for more details.
|
97 |
+
|
98 |
+
Prompt: "oil painting of handsome old man, masterpiece"
|
99 |
+
![p](github_page/p5.png)
|
100 |
+
|
101 |
+
Prompt: "Cyberpunk robot"
|
102 |
+
![p](github_page/p6.png)
|
103 |
+
|
104 |
+
## ControlNet with User Scribbles
|
105 |
+
|
106 |
+
Stable Diffusion 1.5 + ControlNet (using Scribbles)
|
107 |
+
|
108 |
+
python gradio_scribble2image.py
|
109 |
+
|
110 |
+
Note that the UI is based on Gradio, and Gradio is somewhat difficult to customize. Right now you need to draw scribbles outside the UI (using your favorite drawing software, for example, MS Paint) and then import the scribble image to Gradio.
|
111 |
+
|
112 |
+
Prompt: "turtle"
|
113 |
+
![p](github_page/p7.png)
|
114 |
+
|
115 |
+
Prompt: "hot air balloon"
|
116 |
+
![p](github_page/p8.png)
|
117 |
+
|
118 |
+
### Interactive Interface
|
119 |
+
|
120 |
+
We actually provide an interactive interface
|
121 |
+
|
122 |
+
python gradio_scribble2image_interactive.py
|
123 |
+
|
124 |
+
~~However, because gradio is very [buggy](https://github.com/gradio-app/gradio/issues/3166) and difficult to customize, right now, user need to first set canvas width and heights and then click "Open drawing canvas" to get a drawing area. Please do not upload image to that drawing canvas. Also, the drawing area is very small; it should be bigger. But I failed to find out how to make it larger. Again, gradio is really buggy.~~ (Now fixed, will update asap)
|
125 |
+
|
126 |
+
The below dog sketch is drawn by me. Perhaps we should draw a better dog for showcase.
|
127 |
+
|
128 |
+
Prompt: "dog in a room"
|
129 |
+
![p](github_page/p20.png)
|
130 |
+
|
131 |
+
## ControlNet with Fake Scribbles
|
132 |
+
|
133 |
+
Stable Diffusion 1.5 + ControlNet (using fake scribbles)
|
134 |
+
|
135 |
+
python gradio_fake_scribble2image.py
|
136 |
+
|
137 |
+
Sometimes we are lazy, and we do not want to draw scribbles. This script use the exactly same scribble-based model but use a simple algorithm to synthesize scribbles from input images.
|
138 |
+
|
139 |
+
Prompt: "bag"
|
140 |
+
![p](github_page/p9.png)
|
141 |
+
|
142 |
+
Prompt: "shose" (Note that "shose" is a typo; it should be "shoes". But it still seems to work.)
|
143 |
+
![p](github_page/p10.png)
|
144 |
+
|
145 |
+
## ControlNet with Human Pose
|
146 |
+
|
147 |
+
Stable Diffusion 1.5 + ControlNet (using human pose)
|
148 |
+
|
149 |
+
python gradio_pose2image.py
|
150 |
+
|
151 |
+
Apparently, this model deserves a better UI to directly manipulate pose skeleton. However, again, Gradio is somewhat difficult to customize. Right now you need to input an image and then the Openpose will detect the pose for you.
|
152 |
+
|
153 |
+
Prompt: "Chief in the kitchen"
|
154 |
+
![p](github_page/p11.png)
|
155 |
+
|
156 |
+
Prompt: "An astronaut on the moon"
|
157 |
+
![p](github_page/p12.png)
|
158 |
+
|
159 |
+
## ControlNet with Semantic Segmentation
|
160 |
+
|
161 |
+
Stable Diffusion 1.5 + ControlNet (using semantic segmentation)
|
162 |
+
|
163 |
+
python gradio_seg2image.py
|
164 |
+
|
165 |
+
This model use ADE20K's segmentation protocol. Again, this model deserves a better UI to directly draw the segmentations. However, again, Gradio is somewhat difficult to customize. Right now you need to input an image and then a model called Uniformer will detect the segmentations for you. Just try it for more details.
|
166 |
+
|
167 |
+
Prompt: "House"
|
168 |
+
![p](github_page/p13.png)
|
169 |
+
|
170 |
+
Prompt: "River"
|
171 |
+
![p](github_page/p14.png)
|
172 |
+
|
173 |
+
## ControlNet with Depth
|
174 |
+
|
175 |
+
Stable Diffusion 1.5 + ControlNet (using depth map)
|
176 |
+
|
177 |
+
python gradio_depth2image.py
|
178 |
+
|
179 |
+
Great! Now SD 1.5 also have a depth control. FINALLY. So many possibilities (considering SD1.5 has much more community models than SD2).
|
180 |
+
|
181 |
+
Note that different from Stability's model, the ControlNet receive the full 512×512 depth map, rather than 64×64 depth. Note that Stability's SD2 depth model use 64*64 depth maps. This means that the ControlNet will preserve more details in the depth map.
|
182 |
+
|
183 |
+
This is always a strength because if users do not want to preserve more details, they can simply use another SD to post-process an i2i. But if they want to preserve more details, ControlNet becomes their only choice. Again, SD2 uses 64×64 depth, we use 512×512.
|
184 |
+
|
185 |
+
Prompt: "Stormtrooper's lecture"
|
186 |
+
![p](github_page/p15.png)
|
187 |
+
|
188 |
+
## ControlNet with Normal Map
|
189 |
+
|
190 |
+
Stable Diffusion 1.5 + ControlNet (using normal map)
|
191 |
+
|
192 |
+
python gradio_normal2image.py
|
193 |
+
|
194 |
+
This model use normal map. Rightnow in the APP, the normal is computed from the midas depth map and a user threshold (to determine how many area is background with identity normal face to viewer, tune the "Normal background threshold" in the gradio app to get a feeling).
|
195 |
+
|
196 |
+
Prompt: "Cute toy"
|
197 |
+
![p](github_page/p17.png)
|
198 |
+
|
199 |
+
Prompt: "Plaster statue of Abraham Lincoln"
|
200 |
+
![p](github_page/p18.png)
|
201 |
+
|
202 |
+
Compared to depth model, this model seems to be a bit better at preserving the geometry. This is intuitive: minor details are not salient in depth maps, but are salient in normal maps. Below is the depth result with same inputs. You can see that the hairstyle of the man in the input image is modified by depth model, but preserved by the normal model.
|
203 |
+
|
204 |
+
Prompt: "Plaster statue of Abraham Lincoln"
|
205 |
+
![p](github_page/p19.png)
|
206 |
+
|
207 |
+
## ControlNet with Anime Line Drawing
|
208 |
+
|
209 |
+
We also trained a relatively simple ControlNet for anime line drawings. This tool may be useful for artistic creations. (Although the image details in the results is a bit modified, since it still diffuse latent images.)
|
210 |
+
|
211 |
+
This model is not available right now. We need to evaluate the potential risks before releasing this model. Nevertheless, you may be interested in [transferring the ControlNet to any community model](https://github.com/lllyasviel/ControlNet/discussions/12).
|
212 |
+
|
213 |
+
![p](github_page/p21.png)
|
214 |
+
|
215 |
+
<a id="guess-anchor"></a>
|
216 |
+
|
217 |
+
# Guess Mode / Non-Prompt Mode
|
218 |
+
|
219 |
+
The "guess mode" (or called non-prompt mode) will completely unleash all the power of the very powerful ControlNet encoder.
|
220 |
+
|
221 |
+
See also the blog - [Ablation Study: Why ControlNets use deep encoder? What if it was lighter? Or even an MLP?](https://github.com/lllyasviel/ControlNet/discussions/188)
|
222 |
+
|
223 |
+
You need to manually check the "Guess Mode" toggle to enable this mode.
|
224 |
+
|
225 |
+
In this mode, the ControlNet encoder will try best to recognize the content of the input control map, like depth map, edge map, scribbles, etc, even if you remove all prompts.
|
226 |
+
|
227 |
+
**Let's have fun with some very challenging experimental settings!**
|
228 |
+
|
229 |
+
**No prompts. No "positive" prompts. No "negative" prompts. No extra caption detector. One single diffusion loop.**
|
230 |
+
|
231 |
+
For this mode, we recommend to use 50 steps and guidance scale between 3 and 5.
|
232 |
+
|
233 |
+
![p](github_page/uc2a.png)
|
234 |
+
|
235 |
+
No prompts:
|
236 |
+
|
237 |
+
![p](github_page/uc2b.png)
|
238 |
+
|
239 |
+
Note that the below example is 768×768. No prompts. No "positive" prompts. No "negative" prompts.
|
240 |
+
|
241 |
+
![p](github_page/uc1.png)
|
242 |
+
|
243 |
+
By tuning the parameters, you can get some very intereting results like below:
|
244 |
+
|
245 |
+
![p](github_page/uc3.png)
|
246 |
+
|
247 |
+
Because no prompt is available, the ControlNet encoder will "guess" what is in the control map. Sometimes the guess result is really interesting. Because diffusion algorithm can essentially give multiple results, the ControlNet seems able to give multiple guesses, like this:
|
248 |
+
|
249 |
+
![p](github_page/uc4.png)
|
250 |
+
|
251 |
+
Without prompt, the HED seems good at generating images look like paintings when the control strength is relatively low:
|
252 |
+
|
253 |
+
![p](github_page/uc6.png)
|
254 |
+
|
255 |
+
The Guess Mode is also supported in [WebUI Plugin](https://github.com/Mikubill/sd-webui-controlnet):
|
256 |
+
|
257 |
+
![p](github_page/uci1.png)
|
258 |
+
|
259 |
+
No prompts. Default WebUI parameters. Pure random results with the seed being 12345. Standard SD1.5. Input scribble is in "test_imgs" folder to reproduce.
|
260 |
+
|
261 |
+
![p](github_page/uci2.png)
|
262 |
+
|
263 |
+
Below is another challenging example:
|
264 |
+
|
265 |
+
![p](github_page/uci3.png)
|
266 |
+
|
267 |
+
No prompts. Default WebUI parameters. Pure random results with the seed being 12345. Standard SD1.5. Input scribble is in "test_imgs" folder to reproduce.
|
268 |
+
|
269 |
+
![p](github_page/uci4.png)
|
270 |
+
|
271 |
+
Note that in the guess mode, you will still be able to input prompts. The only difference is that the model will "try harder" to guess what is in the control map even if you do not provide the prompt. Just try it yourself!
|
272 |
+
|
273 |
+
Besides, if you write some scripts (like BLIP) to generate image captions from the "guess mode" images, and then use the generated captions as prompts to diffuse again, you will get a SOTA pipeline for fully automatic conditional image generating.
|
274 |
+
|
275 |
+
# Combining Multiple ControlNets
|
276 |
+
|
277 |
+
ControlNets are composable: more than one ControlNet can be easily composed to multi-condition control.
|
278 |
+
|
279 |
+
Right now this feature is in experimental stage in the [Mikubill' A1111 Webui Plugin](https://github.com/Mikubill/sd-webui-controlnet):
|
280 |
+
|
281 |
+
![p](github_page/multi2.png)
|
282 |
+
|
283 |
+
![p](github_page/multi.png)
|
284 |
+
|
285 |
+
As long as the models are controlling the same SD, the "boundary" between different research projects does not even exist. This plugin also allows different methods to work together!
|
286 |
+
|
287 |
+
# Use ControlNet in Any Community Model (SD1.X)
|
288 |
+
|
289 |
+
This is an experimental feature.
|
290 |
+
|
291 |
+
[See the steps here](https://github.com/lllyasviel/ControlNet/discussions/12).
|
292 |
+
|
293 |
+
Or you may want to use the [Mikubill' A1111 Webui Plugin](https://github.com/Mikubill/sd-webui-controlnet) which is plug-and-play and does not need manual merging.
|
294 |
+
|
295 |
+
# Annotate Your Own Data
|
296 |
+
|
297 |
+
We provide simple python scripts to process images.
|
298 |
+
|
299 |
+
[See a gradio example here](docs/annotator.md).
|
300 |
+
|
301 |
+
# Train with Your Own Data
|
302 |
+
|
303 |
+
Training a ControlNet is as easy as (or even easier than) training a simple pix2pix.
|
304 |
+
|
305 |
+
[See the steps here](docs/train.md).
|
306 |
+
|
307 |
+
# Related Resources
|
308 |
+
|
309 |
+
Special Thank to the great project - [Mikubill' A1111 Webui Plugin](https://github.com/Mikubill/sd-webui-controlnet) !
|
310 |
+
|
311 |
+
We also thank Hysts for making [Hugging Face Space](https://huggingface.co/spaces/hysts/ControlNet) as well as more than 65 models in that amazing [Colab list](https://github.com/camenduru/controlnet-colab)!
|
312 |
+
|
313 |
+
Thank haofanwang for making [ControlNet-for-Diffusers](https://github.com/haofanwang/ControlNet-for-Diffusers)!
|
314 |
+
|
315 |
+
We also thank all authors for making Controlnet DEMOs, including but not limited to [fffiloni](https://huggingface.co/spaces/fffiloni/ControlNet-Video), [other-model](https://huggingface.co/spaces/hysts/ControlNet-with-other-models), [ThereforeGames](https://github.com/AUTOMATIC1111/stable-diffusion-webui/discussions/7784), [RamAnanth1](https://huggingface.co/spaces/RamAnanth1/ControlNet), etc!
|
316 |
+
|
317 |
+
Besides, you may also want to read these amazing related works:
|
318 |
+
|
319 |
+
[Composer: Creative and Controllable Image Synthesis with Composable Conditions](https://github.com/damo-vilab/composer): A much bigger model to control diffusion!
|
320 |
+
|
321 |
+
[T2I-Adapter: Learning Adapters to Dig out More Controllable Ability for Text-to-Image Diffusion Models](https://github.com/TencentARC/T2I-Adapter): A much smaller model to control stable diffusion!
|
322 |
+
|
323 |
+
[ControlLoRA: A Light Neural Network To Control Stable Diffusion Spatial Information](https://github.com/HighCWu/ControlLoRA): Implement Controlnet using LORA!
|
324 |
+
|
325 |
+
And these amazing recent projects: [InstructPix2Pix Learning to Follow Image Editing Instructions](https://www.timothybrooks.com/instruct-pix2pix), [Pix2pix-zero: Zero-shot Image-to-Image Translation](https://github.com/pix2pixzero/pix2pix-zero), [Plug-and-Play Diffusion Features for Text-Driven Image-to-Image Translation](https://github.com/MichalGeyer/plug-and-play), [MaskSketch: Unpaired Structure-guided Masked Image Generation](https://arxiv.org/abs/2302.05496), [SEGA: Instructing Diffusion using Semantic Dimensions](https://arxiv.org/abs/2301.12247), [Universal Guidance for Diffusion Models](https://github.com/arpitbansal297/Universal-Guided-Diffusion), [Region-Aware Diffusion for Zero-shot Text-driven Image Editing](https://github.com/haha-lisa/RDM-Region-Aware-Diffusion-Model), [Domain Expansion of Image Generators](https://arxiv.org/abs/2301.05225), [Image Mixer](https://twitter.com/LambdaAPI/status/1626327289288957956), [MultiDiffusion: Fusing Diffusion Paths for Controlled Image Generation](https://multidiffusion.github.io/)
|
326 |
+
|
327 |
+
# Citation
|
328 |
+
|
329 |
+
@misc{zhang2023adding,
|
330 |
+
title={Adding Conditional Control to Text-to-Image Diffusion Models},
|
331 |
+
author={Lvmin Zhang and Maneesh Agrawala},
|
332 |
+
year={2023},
|
333 |
+
eprint={2302.05543},
|
334 |
+
archivePrefix={arXiv},
|
335 |
+
primaryClass={cs.CV}
|
336 |
+
}
|
337 |
+
|
338 |
+
[Arxiv Link](https://arxiv.org/abs/2302.05543)
|
config.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
save_memory = False
|
environment.yaml
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: control
|
2 |
+
channels:
|
3 |
+
- pytorch
|
4 |
+
- defaults
|
5 |
+
dependencies:
|
6 |
+
- python=3.8.5
|
7 |
+
- pip=20.3
|
8 |
+
- cudatoolkit=11.3
|
9 |
+
- pytorch=1.12.1
|
10 |
+
- torchvision=0.13.1
|
11 |
+
- numpy=1.23.1
|
12 |
+
- pip:
|
13 |
+
- gradio==3.16.2
|
14 |
+
- albumentations==1.3.0
|
15 |
+
- opencv-contrib-python==4.3.0.36
|
16 |
+
- imageio==2.9.0
|
17 |
+
- imageio-ffmpeg==0.4.2
|
18 |
+
- pytorch-lightning==1.5.0
|
19 |
+
- omegaconf==2.1.1
|
20 |
+
- test-tube>=0.7.5
|
21 |
+
- streamlit==1.12.1
|
22 |
+
- einops==0.3.0
|
23 |
+
- transformers==4.19.2
|
24 |
+
- webdataset==0.2.5
|
25 |
+
- kornia==0.6
|
26 |
+
- open_clip_torch==2.0.2
|
27 |
+
- invisible-watermark>=0.1.5
|
28 |
+
- streamlit-drawable-canvas==0.8.0
|
29 |
+
- torchmetrics==0.6.0
|
30 |
+
- timm==0.6.12
|
31 |
+
- addict==2.4.0
|
32 |
+
- yapf==0.32.0
|
33 |
+
- prettytable==3.6.0
|
34 |
+
- safetensors==0.2.7
|
35 |
+
- basicsr==1.4.2
|
gradio_annotator.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
from annotator.util import resize_image, HWC3
|
4 |
+
|
5 |
+
|
6 |
+
model_canny = None
|
7 |
+
|
8 |
+
|
9 |
+
def canny(img, res, l, h):
|
10 |
+
img = resize_image(HWC3(img), res)
|
11 |
+
global model_canny
|
12 |
+
if model_canny is None:
|
13 |
+
from annotator.canny import CannyDetector
|
14 |
+
model_canny = CannyDetector()
|
15 |
+
result = model_canny(img, l, h)
|
16 |
+
return [result]
|
17 |
+
|
18 |
+
|
19 |
+
model_hed = None
|
20 |
+
|
21 |
+
|
22 |
+
def hed(img, res):
|
23 |
+
img = resize_image(HWC3(img), res)
|
24 |
+
global model_hed
|
25 |
+
if model_hed is None:
|
26 |
+
from annotator.hed import HEDdetector
|
27 |
+
model_hed = HEDdetector()
|
28 |
+
result = model_hed(img)
|
29 |
+
return [result]
|
30 |
+
|
31 |
+
|
32 |
+
model_mlsd = None
|
33 |
+
|
34 |
+
|
35 |
+
def mlsd(img, res, thr_v, thr_d):
|
36 |
+
img = resize_image(HWC3(img), res)
|
37 |
+
global model_mlsd
|
38 |
+
if model_mlsd is None:
|
39 |
+
from annotator.mlsd import MLSDdetector
|
40 |
+
model_mlsd = MLSDdetector()
|
41 |
+
result = model_mlsd(img, thr_v, thr_d)
|
42 |
+
return [result]
|
43 |
+
|
44 |
+
|
45 |
+
model_midas = None
|
46 |
+
|
47 |
+
|
48 |
+
def midas(img, res, a):
|
49 |
+
img = resize_image(HWC3(img), res)
|
50 |
+
global model_midas
|
51 |
+
if model_midas is None:
|
52 |
+
from annotator.midas import MidasDetector
|
53 |
+
model_midas = MidasDetector()
|
54 |
+
results = model_midas(img, a)
|
55 |
+
return results
|
56 |
+
|
57 |
+
|
58 |
+
model_openpose = None
|
59 |
+
|
60 |
+
|
61 |
+
def openpose(img, res, has_hand):
|
62 |
+
img = resize_image(HWC3(img), res)
|
63 |
+
global model_openpose
|
64 |
+
if model_openpose is None:
|
65 |
+
from annotator.openpose import OpenposeDetector
|
66 |
+
model_openpose = OpenposeDetector()
|
67 |
+
result, _ = model_openpose(img, has_hand)
|
68 |
+
return [result]
|
69 |
+
|
70 |
+
|
71 |
+
model_uniformer = None
|
72 |
+
|
73 |
+
|
74 |
+
def uniformer(img, res):
|
75 |
+
img = resize_image(HWC3(img), res)
|
76 |
+
global model_uniformer
|
77 |
+
if model_uniformer is None:
|
78 |
+
from annotator.uniformer import UniformerDetector
|
79 |
+
model_uniformer = UniformerDetector()
|
80 |
+
result = model_uniformer(img)
|
81 |
+
return [result]
|
82 |
+
|
83 |
+
|
84 |
+
block = gr.Blocks().queue()
|
85 |
+
with block:
|
86 |
+
with gr.Row():
|
87 |
+
gr.Markdown("## Canny Edge")
|
88 |
+
with gr.Row():
|
89 |
+
with gr.Column():
|
90 |
+
input_image = gr.Image(source='upload', type="numpy")
|
91 |
+
low_threshold = gr.Slider(label="low_threshold", minimum=1, maximum=255, value=100, step=1)
|
92 |
+
high_threshold = gr.Slider(label="high_threshold", minimum=1, maximum=255, value=200, step=1)
|
93 |
+
resolution = gr.Slider(label="resolution", minimum=256, maximum=1024, value=512, step=64)
|
94 |
+
run_button = gr.Button(label="Run")
|
95 |
+
with gr.Column():
|
96 |
+
gallery = gr.Gallery(label="Generated images", show_label=False).style(height="auto")
|
97 |
+
run_button.click(fn=canny, inputs=[input_image, resolution, low_threshold, high_threshold], outputs=[gallery])
|
98 |
+
|
99 |
+
with gr.Row():
|
100 |
+
gr.Markdown("## HED Edge")
|
101 |
+
with gr.Row():
|
102 |
+
with gr.Column():
|
103 |
+
input_image = gr.Image(source='upload', type="numpy")
|
104 |
+
resolution = gr.Slider(label="resolution", minimum=256, maximum=1024, value=512, step=64)
|
105 |
+
run_button = gr.Button(label="Run")
|
106 |
+
with gr.Column():
|
107 |
+
gallery = gr.Gallery(label="Generated images", show_label=False).style(height="auto")
|
108 |
+
run_button.click(fn=hed, inputs=[input_image, resolution], outputs=[gallery])
|
109 |
+
|
110 |
+
with gr.Row():
|
111 |
+
gr.Markdown("## MLSD Edge")
|
112 |
+
with gr.Row():
|
113 |
+
with gr.Column():
|
114 |
+
input_image = gr.Image(source='upload', type="numpy")
|
115 |
+
value_threshold = gr.Slider(label="value_threshold", minimum=0.01, maximum=2.0, value=0.1, step=0.01)
|
116 |
+
distance_threshold = gr.Slider(label="distance_threshold", minimum=0.01, maximum=20.0, value=0.1, step=0.01)
|
117 |
+
resolution = gr.Slider(label="resolution", minimum=256, maximum=1024, value=384, step=64)
|
118 |
+
run_button = gr.Button(label="Run")
|
119 |
+
with gr.Column():
|
120 |
+
gallery = gr.Gallery(label="Generated images", show_label=False).style(height="auto")
|
121 |
+
run_button.click(fn=mlsd, inputs=[input_image, resolution, value_threshold, distance_threshold], outputs=[gallery])
|
122 |
+
|
123 |
+
with gr.Row():
|
124 |
+
gr.Markdown("## MIDAS Depth and Normal")
|
125 |
+
with gr.Row():
|
126 |
+
with gr.Column():
|
127 |
+
input_image = gr.Image(source='upload', type="numpy")
|
128 |
+
alpha = gr.Slider(label="alpha", minimum=0.1, maximum=20.0, value=6.2, step=0.01)
|
129 |
+
resolution = gr.Slider(label="resolution", minimum=256, maximum=1024, value=384, step=64)
|
130 |
+
run_button = gr.Button(label="Run")
|
131 |
+
with gr.Column():
|
132 |
+
gallery = gr.Gallery(label="Generated images", show_label=False).style(height="auto")
|
133 |
+
run_button.click(fn=midas, inputs=[input_image, resolution, alpha], outputs=[gallery])
|
134 |
+
|
135 |
+
with gr.Row():
|
136 |
+
gr.Markdown("## Openpose")
|
137 |
+
with gr.Row():
|
138 |
+
with gr.Column():
|
139 |
+
input_image = gr.Image(source='upload', type="numpy")
|
140 |
+
hand = gr.Checkbox(label='detect hand', value=False)
|
141 |
+
resolution = gr.Slider(label="resolution", minimum=256, maximum=1024, value=512, step=64)
|
142 |
+
run_button = gr.Button(label="Run")
|
143 |
+
with gr.Column():
|
144 |
+
gallery = gr.Gallery(label="Generated images", show_label=False).style(height="auto")
|
145 |
+
run_button.click(fn=openpose, inputs=[input_image, resolution, hand], outputs=[gallery])
|
146 |
+
|
147 |
+
|
148 |
+
with gr.Row():
|
149 |
+
gr.Markdown("## Uniformer Segmentation")
|
150 |
+
with gr.Row():
|
151 |
+
with gr.Column():
|
152 |
+
input_image = gr.Image(source='upload', type="numpy")
|
153 |
+
resolution = gr.Slider(label="resolution", minimum=256, maximum=1024, value=512, step=64)
|
154 |
+
run_button = gr.Button(label="Run")
|
155 |
+
with gr.Column():
|
156 |
+
gallery = gr.Gallery(label="Generated images", show_label=False).style(height="auto")
|
157 |
+
run_button.click(fn=uniformer, inputs=[input_image, resolution], outputs=[gallery])
|
158 |
+
|
159 |
+
|
160 |
+
block.launch(server_name='0.0.0.0')
|
gradio_canny2image.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.canny import CannyDetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_canny = CannyDetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_canny.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, low_threshold, high_threshold):
|
27 |
+
with torch.no_grad():
|
28 |
+
img = resize_image(HWC3(input_image), image_resolution)
|
29 |
+
H, W, C = img.shape
|
30 |
+
|
31 |
+
detected_map = apply_canny(img, low_threshold, high_threshold)
|
32 |
+
detected_map = HWC3(detected_map)
|
33 |
+
|
34 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
35 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
36 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
37 |
+
|
38 |
+
if seed == -1:
|
39 |
+
seed = random.randint(0, 65535)
|
40 |
+
seed_everything(seed)
|
41 |
+
|
42 |
+
if config.save_memory:
|
43 |
+
model.low_vram_shift(is_diffusing=False)
|
44 |
+
|
45 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
46 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
47 |
+
shape = (4, H // 8, W // 8)
|
48 |
+
|
49 |
+
if config.save_memory:
|
50 |
+
model.low_vram_shift(is_diffusing=True)
|
51 |
+
|
52 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
53 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
54 |
+
shape, cond, verbose=False, eta=eta,
|
55 |
+
unconditional_guidance_scale=scale,
|
56 |
+
unconditional_conditioning=un_cond)
|
57 |
+
|
58 |
+
if config.save_memory:
|
59 |
+
model.low_vram_shift(is_diffusing=False)
|
60 |
+
|
61 |
+
x_samples = model.decode_first_stage(samples)
|
62 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
63 |
+
|
64 |
+
results = [x_samples[i] for i in range(num_samples)]
|
65 |
+
return [255 - detected_map] + results
|
66 |
+
|
67 |
+
|
68 |
+
block = gr.Blocks().queue()
|
69 |
+
with block:
|
70 |
+
with gr.Row():
|
71 |
+
gr.Markdown("## Control Stable Diffusion with Canny Edge Maps")
|
72 |
+
with gr.Row():
|
73 |
+
with gr.Column():
|
74 |
+
input_image = gr.Image(source='upload', type="numpy")
|
75 |
+
prompt = gr.Textbox(label="Prompt")
|
76 |
+
run_button = gr.Button(label="Run")
|
77 |
+
with gr.Accordion("Advanced options", open=False):
|
78 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
79 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
80 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
81 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
82 |
+
low_threshold = gr.Slider(label="Canny low threshold", minimum=1, maximum=255, value=100, step=1)
|
83 |
+
high_threshold = gr.Slider(label="Canny high threshold", minimum=1, maximum=255, value=200, step=1)
|
84 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
85 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
86 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
87 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
88 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
89 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
90 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
91 |
+
with gr.Column():
|
92 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
93 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, low_threshold, high_threshold]
|
94 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
95 |
+
|
96 |
+
|
97 |
+
block.launch(server_name='0.0.0.0')
|
gradio_depth2image.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.midas import MidasDetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_midas = MidasDetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_depth.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
detected_map, _ = apply_midas(resize_image(input_image, detect_resolution))
|
30 |
+
detected_map = HWC3(detected_map)
|
31 |
+
img = resize_image(input_image, image_resolution)
|
32 |
+
H, W, C = img.shape
|
33 |
+
|
34 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
|
35 |
+
|
36 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
37 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
38 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
39 |
+
|
40 |
+
if seed == -1:
|
41 |
+
seed = random.randint(0, 65535)
|
42 |
+
seed_everything(seed)
|
43 |
+
|
44 |
+
if config.save_memory:
|
45 |
+
model.low_vram_shift(is_diffusing=False)
|
46 |
+
|
47 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
48 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
49 |
+
shape = (4, H // 8, W // 8)
|
50 |
+
|
51 |
+
if config.save_memory:
|
52 |
+
model.low_vram_shift(is_diffusing=True)
|
53 |
+
|
54 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
55 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
56 |
+
shape, cond, verbose=False, eta=eta,
|
57 |
+
unconditional_guidance_scale=scale,
|
58 |
+
unconditional_conditioning=un_cond)
|
59 |
+
|
60 |
+
if config.save_memory:
|
61 |
+
model.low_vram_shift(is_diffusing=False)
|
62 |
+
|
63 |
+
x_samples = model.decode_first_stage(samples)
|
64 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
65 |
+
|
66 |
+
results = [x_samples[i] for i in range(num_samples)]
|
67 |
+
return [detected_map] + results
|
68 |
+
|
69 |
+
|
70 |
+
block = gr.Blocks().queue()
|
71 |
+
with block:
|
72 |
+
with gr.Row():
|
73 |
+
gr.Markdown("## Control Stable Diffusion with Depth Maps")
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
input_image = gr.Image(source='upload', type="numpy")
|
77 |
+
prompt = gr.Textbox(label="Prompt")
|
78 |
+
run_button = gr.Button(label="Run")
|
79 |
+
with gr.Accordion("Advanced options", open=False):
|
80 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
81 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
82 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
83 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
84 |
+
detect_resolution = gr.Slider(label="Depth Resolution", minimum=128, maximum=1024, value=384, step=1)
|
85 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
86 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
87 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
88 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
89 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
90 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
91 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
92 |
+
with gr.Column():
|
93 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
94 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
95 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
96 |
+
|
97 |
+
|
98 |
+
block.launch(server_name='0.0.0.0')
|
gradio_fake_scribble2image.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.hed import HEDdetector, nms
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_hed = HEDdetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_scribble.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
detected_map = apply_hed(resize_image(input_image, detect_resolution))
|
30 |
+
detected_map = HWC3(detected_map)
|
31 |
+
img = resize_image(input_image, image_resolution)
|
32 |
+
H, W, C = img.shape
|
33 |
+
|
34 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
|
35 |
+
detected_map = nms(detected_map, 127, 3.0)
|
36 |
+
detected_map = cv2.GaussianBlur(detected_map, (0, 0), 3.0)
|
37 |
+
detected_map[detected_map > 4] = 255
|
38 |
+
detected_map[detected_map < 255] = 0
|
39 |
+
|
40 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
41 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
42 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
43 |
+
|
44 |
+
if seed == -1:
|
45 |
+
seed = random.randint(0, 65535)
|
46 |
+
seed_everything(seed)
|
47 |
+
|
48 |
+
if config.save_memory:
|
49 |
+
model.low_vram_shift(is_diffusing=False)
|
50 |
+
|
51 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
52 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
53 |
+
shape = (4, H // 8, W // 8)
|
54 |
+
|
55 |
+
if config.save_memory:
|
56 |
+
model.low_vram_shift(is_diffusing=True)
|
57 |
+
|
58 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
59 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
60 |
+
shape, cond, verbose=False, eta=eta,
|
61 |
+
unconditional_guidance_scale=scale,
|
62 |
+
unconditional_conditioning=un_cond)
|
63 |
+
|
64 |
+
if config.save_memory:
|
65 |
+
model.low_vram_shift(is_diffusing=False)
|
66 |
+
|
67 |
+
x_samples = model.decode_first_stage(samples)
|
68 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
69 |
+
|
70 |
+
results = [x_samples[i] for i in range(num_samples)]
|
71 |
+
return [255 - detected_map] + results
|
72 |
+
|
73 |
+
|
74 |
+
block = gr.Blocks().queue()
|
75 |
+
with block:
|
76 |
+
with gr.Row():
|
77 |
+
gr.Markdown("## Control Stable Diffusion with Fake Scribble Maps")
|
78 |
+
with gr.Row():
|
79 |
+
with gr.Column():
|
80 |
+
input_image = gr.Image(source='upload', type="numpy")
|
81 |
+
prompt = gr.Textbox(label="Prompt")
|
82 |
+
run_button = gr.Button(label="Run")
|
83 |
+
with gr.Accordion("Advanced options", open=False):
|
84 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
85 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
86 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
87 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
88 |
+
detect_resolution = gr.Slider(label="HED Resolution", minimum=128, maximum=1024, value=512, step=1)
|
89 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
90 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
91 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
92 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
93 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
94 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
95 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
96 |
+
with gr.Column():
|
97 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
98 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
99 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
100 |
+
|
101 |
+
|
102 |
+
block.launch(server_name='0.0.0.0')
|
gradio_hed2image.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.hed import HEDdetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_hed = HEDdetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_hed.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
detected_map = apply_hed(resize_image(input_image, detect_resolution))
|
30 |
+
detected_map = HWC3(detected_map)
|
31 |
+
img = resize_image(input_image, image_resolution)
|
32 |
+
H, W, C = img.shape
|
33 |
+
|
34 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
|
35 |
+
|
36 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
37 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
38 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
39 |
+
|
40 |
+
if seed == -1:
|
41 |
+
seed = random.randint(0, 65535)
|
42 |
+
seed_everything(seed)
|
43 |
+
|
44 |
+
if config.save_memory:
|
45 |
+
model.low_vram_shift(is_diffusing=False)
|
46 |
+
|
47 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
48 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
49 |
+
shape = (4, H // 8, W // 8)
|
50 |
+
|
51 |
+
if config.save_memory:
|
52 |
+
model.low_vram_shift(is_diffusing=True)
|
53 |
+
|
54 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
55 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
56 |
+
shape, cond, verbose=False, eta=eta,
|
57 |
+
unconditional_guidance_scale=scale,
|
58 |
+
unconditional_conditioning=un_cond)
|
59 |
+
|
60 |
+
if config.save_memory:
|
61 |
+
model.low_vram_shift(is_diffusing=False)
|
62 |
+
|
63 |
+
x_samples = model.decode_first_stage(samples)
|
64 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
65 |
+
|
66 |
+
results = [x_samples[i] for i in range(num_samples)]
|
67 |
+
return [detected_map] + results
|
68 |
+
|
69 |
+
|
70 |
+
block = gr.Blocks().queue()
|
71 |
+
with block:
|
72 |
+
with gr.Row():
|
73 |
+
gr.Markdown("## Control Stable Diffusion with HED Maps")
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
input_image = gr.Image(source='upload', type="numpy")
|
77 |
+
prompt = gr.Textbox(label="Prompt")
|
78 |
+
run_button = gr.Button(label="Run")
|
79 |
+
with gr.Accordion("Advanced options", open=False):
|
80 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
81 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
82 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
83 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
84 |
+
detect_resolution = gr.Slider(label="HED Resolution", minimum=128, maximum=1024, value=512, step=1)
|
85 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
86 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
87 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
88 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
89 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
90 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
91 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
92 |
+
with gr.Column():
|
93 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
94 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
95 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
96 |
+
|
97 |
+
|
98 |
+
block.launch(server_name='0.0.0.0')
|
gradio_hough2image.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.mlsd import MLSDdetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_mlsd = MLSDdetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_mlsd.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, value_threshold, distance_threshold):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
detected_map = apply_mlsd(resize_image(input_image, detect_resolution), value_threshold, distance_threshold)
|
30 |
+
detected_map = HWC3(detected_map)
|
31 |
+
img = resize_image(input_image, image_resolution)
|
32 |
+
H, W, C = img.shape
|
33 |
+
|
34 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_NEAREST)
|
35 |
+
|
36 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
37 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
38 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
39 |
+
|
40 |
+
if seed == -1:
|
41 |
+
seed = random.randint(0, 65535)
|
42 |
+
seed_everything(seed)
|
43 |
+
|
44 |
+
if config.save_memory:
|
45 |
+
model.low_vram_shift(is_diffusing=False)
|
46 |
+
|
47 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
48 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
49 |
+
shape = (4, H // 8, W // 8)
|
50 |
+
|
51 |
+
if config.save_memory:
|
52 |
+
model.low_vram_shift(is_diffusing=True)
|
53 |
+
|
54 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
55 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
56 |
+
shape, cond, verbose=False, eta=eta,
|
57 |
+
unconditional_guidance_scale=scale,
|
58 |
+
unconditional_conditioning=un_cond)
|
59 |
+
|
60 |
+
if config.save_memory:
|
61 |
+
model.low_vram_shift(is_diffusing=False)
|
62 |
+
|
63 |
+
x_samples = model.decode_first_stage(samples)
|
64 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
65 |
+
|
66 |
+
results = [x_samples[i] for i in range(num_samples)]
|
67 |
+
return [255 - cv2.dilate(detected_map, np.ones(shape=(3, 3), dtype=np.uint8), iterations=1)] + results
|
68 |
+
|
69 |
+
|
70 |
+
block = gr.Blocks().queue()
|
71 |
+
with block:
|
72 |
+
with gr.Row():
|
73 |
+
gr.Markdown("## Control Stable Diffusion with Hough Line Maps")
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
input_image = gr.Image(source='upload', type="numpy")
|
77 |
+
prompt = gr.Textbox(label="Prompt")
|
78 |
+
run_button = gr.Button(label="Run")
|
79 |
+
with gr.Accordion("Advanced options", open=False):
|
80 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
81 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
82 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
83 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
84 |
+
detect_resolution = gr.Slider(label="Hough Resolution", minimum=128, maximum=1024, value=512, step=1)
|
85 |
+
value_threshold = gr.Slider(label="Hough value threshold (MLSD)", minimum=0.01, maximum=2.0, value=0.1, step=0.01)
|
86 |
+
distance_threshold = gr.Slider(label="Hough distance threshold (MLSD)", minimum=0.01, maximum=20.0, value=0.1, step=0.01)
|
87 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
88 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
89 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
90 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
91 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
92 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
93 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
94 |
+
with gr.Column():
|
95 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
96 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, value_threshold, distance_threshold]
|
97 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
98 |
+
|
99 |
+
|
100 |
+
block.launch(server_name='0.0.0.0')
|
gradio_normal2image.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.midas import MidasDetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_midas = MidasDetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_normal.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, bg_threshold):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
_, detected_map = apply_midas(resize_image(input_image, detect_resolution), bg_th=bg_threshold)
|
30 |
+
detected_map = HWC3(detected_map)
|
31 |
+
img = resize_image(input_image, image_resolution)
|
32 |
+
H, W, C = img.shape
|
33 |
+
|
34 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
|
35 |
+
|
36 |
+
control = torch.from_numpy(detected_map[:, :, ::-1].copy()).float().cuda() / 255.0
|
37 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
38 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
39 |
+
|
40 |
+
if seed == -1:
|
41 |
+
seed = random.randint(0, 65535)
|
42 |
+
seed_everything(seed)
|
43 |
+
|
44 |
+
if config.save_memory:
|
45 |
+
model.low_vram_shift(is_diffusing=False)
|
46 |
+
|
47 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
48 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
49 |
+
shape = (4, H // 8, W // 8)
|
50 |
+
|
51 |
+
if config.save_memory:
|
52 |
+
model.low_vram_shift(is_diffusing=True)
|
53 |
+
|
54 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
55 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
56 |
+
shape, cond, verbose=False, eta=eta,
|
57 |
+
unconditional_guidance_scale=scale,
|
58 |
+
unconditional_conditioning=un_cond)
|
59 |
+
|
60 |
+
if config.save_memory:
|
61 |
+
model.low_vram_shift(is_diffusing=False)
|
62 |
+
|
63 |
+
x_samples = model.decode_first_stage(samples)
|
64 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
65 |
+
|
66 |
+
results = [x_samples[i] for i in range(num_samples)]
|
67 |
+
return [detected_map] + results
|
68 |
+
|
69 |
+
|
70 |
+
block = gr.Blocks().queue()
|
71 |
+
with block:
|
72 |
+
with gr.Row():
|
73 |
+
gr.Markdown("## Control Stable Diffusion with Normal Maps")
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
input_image = gr.Image(source='upload', type="numpy")
|
77 |
+
prompt = gr.Textbox(label="Prompt")
|
78 |
+
run_button = gr.Button(label="Run")
|
79 |
+
with gr.Accordion("Advanced options", open=False):
|
80 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
81 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
82 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
83 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
84 |
+
detect_resolution = gr.Slider(label="Normal Resolution", minimum=128, maximum=1024, value=384, step=1)
|
85 |
+
bg_threshold = gr.Slider(label="Normal background threshold", minimum=0.0, maximum=1.0, value=0.4, step=0.01)
|
86 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
87 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
88 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
89 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
90 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
91 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
92 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
93 |
+
with gr.Column():
|
94 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
95 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, bg_threshold]
|
96 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
97 |
+
|
98 |
+
|
99 |
+
block.launch(server_name='0.0.0.0')
|
gradio_pose2image.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.openpose import OpenposeDetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_openpose = OpenposeDetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_openpose.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
detected_map, _ = apply_openpose(resize_image(input_image, detect_resolution))
|
30 |
+
detected_map = HWC3(detected_map)
|
31 |
+
img = resize_image(input_image, image_resolution)
|
32 |
+
H, W, C = img.shape
|
33 |
+
|
34 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_NEAREST)
|
35 |
+
|
36 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
37 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
38 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
39 |
+
|
40 |
+
if seed == -1:
|
41 |
+
seed = random.randint(0, 65535)
|
42 |
+
seed_everything(seed)
|
43 |
+
|
44 |
+
if config.save_memory:
|
45 |
+
model.low_vram_shift(is_diffusing=False)
|
46 |
+
|
47 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
48 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
49 |
+
shape = (4, H // 8, W // 8)
|
50 |
+
|
51 |
+
if config.save_memory:
|
52 |
+
model.low_vram_shift(is_diffusing=True)
|
53 |
+
|
54 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
55 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
56 |
+
shape, cond, verbose=False, eta=eta,
|
57 |
+
unconditional_guidance_scale=scale,
|
58 |
+
unconditional_conditioning=un_cond)
|
59 |
+
|
60 |
+
if config.save_memory:
|
61 |
+
model.low_vram_shift(is_diffusing=False)
|
62 |
+
|
63 |
+
x_samples = model.decode_first_stage(samples)
|
64 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
65 |
+
|
66 |
+
results = [x_samples[i] for i in range(num_samples)]
|
67 |
+
return [detected_map] + results
|
68 |
+
|
69 |
+
|
70 |
+
block = gr.Blocks().queue()
|
71 |
+
with block:
|
72 |
+
with gr.Row():
|
73 |
+
gr.Markdown("## Control Stable Diffusion with Human Pose")
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
input_image = gr.Image(source='upload', type="numpy")
|
77 |
+
prompt = gr.Textbox(label="Prompt")
|
78 |
+
run_button = gr.Button(label="Run")
|
79 |
+
with gr.Accordion("Advanced options", open=False):
|
80 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
81 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
82 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
83 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
84 |
+
detect_resolution = gr.Slider(label="OpenPose Resolution", minimum=128, maximum=1024, value=512, step=1)
|
85 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
86 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
87 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
88 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
89 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
90 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
91 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
92 |
+
with gr.Column():
|
93 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
94 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
95 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
96 |
+
|
97 |
+
|
98 |
+
block.launch(server_name='0.0.0.0')
|
gradio_scribble2image.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from cldm.model import create_model, load_state_dict
|
14 |
+
from cldm.ddim_hacked import DDIMSampler
|
15 |
+
|
16 |
+
|
17 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
18 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_scribble.pth', location='cuda'))
|
19 |
+
model = model.cuda()
|
20 |
+
ddim_sampler = DDIMSampler(model)
|
21 |
+
|
22 |
+
|
23 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
24 |
+
with torch.no_grad():
|
25 |
+
img = resize_image(HWC3(input_image), image_resolution)
|
26 |
+
H, W, C = img.shape
|
27 |
+
|
28 |
+
detected_map = np.zeros_like(img, dtype=np.uint8)
|
29 |
+
detected_map[np.min(img, axis=2) < 127] = 255
|
30 |
+
|
31 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
32 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
33 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
34 |
+
|
35 |
+
if seed == -1:
|
36 |
+
seed = random.randint(0, 65535)
|
37 |
+
seed_everything(seed)
|
38 |
+
|
39 |
+
if config.save_memory:
|
40 |
+
model.low_vram_shift(is_diffusing=False)
|
41 |
+
|
42 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
43 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
44 |
+
shape = (4, H // 8, W // 8)
|
45 |
+
|
46 |
+
if config.save_memory:
|
47 |
+
model.low_vram_shift(is_diffusing=True)
|
48 |
+
|
49 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
50 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
51 |
+
shape, cond, verbose=False, eta=eta,
|
52 |
+
unconditional_guidance_scale=scale,
|
53 |
+
unconditional_conditioning=un_cond)
|
54 |
+
|
55 |
+
if config.save_memory:
|
56 |
+
model.low_vram_shift(is_diffusing=False)
|
57 |
+
|
58 |
+
x_samples = model.decode_first_stage(samples)
|
59 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
60 |
+
|
61 |
+
results = [x_samples[i] for i in range(num_samples)]
|
62 |
+
return [255 - detected_map] + results
|
63 |
+
|
64 |
+
|
65 |
+
block = gr.Blocks().queue()
|
66 |
+
with block:
|
67 |
+
with gr.Row():
|
68 |
+
gr.Markdown("## Control Stable Diffusion with Scribble Maps")
|
69 |
+
with gr.Row():
|
70 |
+
with gr.Column():
|
71 |
+
input_image = gr.Image(source='upload', type="numpy")
|
72 |
+
prompt = gr.Textbox(label="Prompt")
|
73 |
+
run_button = gr.Button(label="Run")
|
74 |
+
with gr.Accordion("Advanced options", open=False):
|
75 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
76 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
77 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
78 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
79 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
80 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
81 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
82 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
83 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
84 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
85 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
86 |
+
with gr.Column():
|
87 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
88 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
89 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
90 |
+
|
91 |
+
|
92 |
+
block.launch(server_name='0.0.0.0')
|
gradio_scribble2image_interactive.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from cldm.model import create_model, load_state_dict
|
14 |
+
from cldm.ddim_hacked import DDIMSampler
|
15 |
+
|
16 |
+
|
17 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
18 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_scribble.pth', location='cuda'))
|
19 |
+
model = model.cuda()
|
20 |
+
ddim_sampler = DDIMSampler(model)
|
21 |
+
|
22 |
+
|
23 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
24 |
+
with torch.no_grad():
|
25 |
+
img = resize_image(HWC3(input_image['mask'][:, :, 0]), image_resolution)
|
26 |
+
H, W, C = img.shape
|
27 |
+
|
28 |
+
detected_map = np.zeros_like(img, dtype=np.uint8)
|
29 |
+
detected_map[np.min(img, axis=2) > 127] = 255
|
30 |
+
|
31 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
32 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
33 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
34 |
+
|
35 |
+
if seed == -1:
|
36 |
+
seed = random.randint(0, 65535)
|
37 |
+
seed_everything(seed)
|
38 |
+
|
39 |
+
if config.save_memory:
|
40 |
+
model.low_vram_shift(is_diffusing=False)
|
41 |
+
|
42 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
43 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
44 |
+
shape = (4, H // 8, W // 8)
|
45 |
+
|
46 |
+
if config.save_memory:
|
47 |
+
model.low_vram_shift(is_diffusing=True)
|
48 |
+
|
49 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
50 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
51 |
+
shape, cond, verbose=False, eta=eta,
|
52 |
+
unconditional_guidance_scale=scale,
|
53 |
+
unconditional_conditioning=un_cond)
|
54 |
+
|
55 |
+
if config.save_memory:
|
56 |
+
model.low_vram_shift(is_diffusing=False)
|
57 |
+
|
58 |
+
x_samples = model.decode_first_stage(samples)
|
59 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
60 |
+
|
61 |
+
results = [x_samples[i] for i in range(num_samples)]
|
62 |
+
return [255 - detected_map] + results
|
63 |
+
|
64 |
+
|
65 |
+
def create_canvas(w, h):
|
66 |
+
return np.zeros(shape=(h, w, 3), dtype=np.uint8) + 255
|
67 |
+
|
68 |
+
|
69 |
+
block = gr.Blocks().queue()
|
70 |
+
with block:
|
71 |
+
with gr.Row():
|
72 |
+
gr.Markdown("## Control Stable Diffusion with Interactive Scribbles")
|
73 |
+
with gr.Row():
|
74 |
+
with gr.Column():
|
75 |
+
canvas_width = gr.Slider(label="Canvas Width", minimum=256, maximum=1024, value=512, step=1)
|
76 |
+
canvas_height = gr.Slider(label="Canvas Height", minimum=256, maximum=1024, value=512, step=1)
|
77 |
+
create_button = gr.Button(label="Start", value='Open drawing canvas!')
|
78 |
+
input_image = gr.Image(source='upload', type='numpy', tool='sketch')
|
79 |
+
gr.Markdown(value='Do not forget to change your brush width to make it thinner. (Gradio do not allow developers to set brush width so you need to do it manually.) '
|
80 |
+
'Just click on the small pencil icon in the upper right corner of the above block.')
|
81 |
+
create_button.click(fn=create_canvas, inputs=[canvas_width, canvas_height], outputs=[input_image])
|
82 |
+
prompt = gr.Textbox(label="Prompt")
|
83 |
+
run_button = gr.Button(label="Run")
|
84 |
+
with gr.Accordion("Advanced options", open=False):
|
85 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
86 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
87 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
88 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
89 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
90 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
91 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
92 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
93 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
94 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
95 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
96 |
+
with gr.Column():
|
97 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
98 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
99 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
100 |
+
|
101 |
+
|
102 |
+
block.launch(server_name='0.0.0.0')
|
gradio_seg2image.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.uniformer import UniformerDetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_uniformer = UniformerDetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_seg.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
detected_map = apply_uniformer(resize_image(input_image, detect_resolution))
|
30 |
+
img = resize_image(input_image, image_resolution)
|
31 |
+
H, W, C = img.shape
|
32 |
+
|
33 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_NEAREST)
|
34 |
+
|
35 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
36 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
37 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
38 |
+
|
39 |
+
if seed == -1:
|
40 |
+
seed = random.randint(0, 65535)
|
41 |
+
seed_everything(seed)
|
42 |
+
|
43 |
+
if config.save_memory:
|
44 |
+
model.low_vram_shift(is_diffusing=False)
|
45 |
+
|
46 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
47 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
48 |
+
shape = (4, H // 8, W // 8)
|
49 |
+
|
50 |
+
if config.save_memory:
|
51 |
+
model.low_vram_shift(is_diffusing=True)
|
52 |
+
|
53 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
54 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
55 |
+
shape, cond, verbose=False, eta=eta,
|
56 |
+
unconditional_guidance_scale=scale,
|
57 |
+
unconditional_conditioning=un_cond)
|
58 |
+
|
59 |
+
if config.save_memory:
|
60 |
+
model.low_vram_shift(is_diffusing=False)
|
61 |
+
|
62 |
+
x_samples = model.decode_first_stage(samples)
|
63 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
64 |
+
|
65 |
+
results = [x_samples[i] for i in range(num_samples)]
|
66 |
+
return [detected_map] + results
|
67 |
+
|
68 |
+
|
69 |
+
block = gr.Blocks().queue()
|
70 |
+
with block:
|
71 |
+
with gr.Row():
|
72 |
+
gr.Markdown("## Control Stable Diffusion with Segmentation Maps")
|
73 |
+
with gr.Row():
|
74 |
+
with gr.Column():
|
75 |
+
input_image = gr.Image(source='upload', type="numpy")
|
76 |
+
prompt = gr.Textbox(label="Prompt")
|
77 |
+
run_button = gr.Button(label="Run")
|
78 |
+
with gr.Accordion("Advanced options", open=False):
|
79 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
80 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
81 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
82 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
83 |
+
detect_resolution = gr.Slider(label="Segmentation Resolution", minimum=128, maximum=1024, value=512, step=1)
|
84 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
85 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
86 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
87 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
88 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
89 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
90 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
91 |
+
with gr.Column():
|
92 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
93 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
94 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
95 |
+
|
96 |
+
|
97 |
+
block.launch(server_name='0.0.0.0')
|
share.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import config
|
2 |
+
from cldm.hack import disable_verbosity, enable_sliced_attention
|
3 |
+
|
4 |
+
|
5 |
+
disable_verbosity()
|
6 |
+
|
7 |
+
if config.save_memory:
|
8 |
+
enable_sliced_attention()
|
tool_add_control.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import os
|
3 |
+
|
4 |
+
assert len(sys.argv) == 3, 'Args are wrong.'
|
5 |
+
|
6 |
+
input_path = sys.argv[1]
|
7 |
+
output_path = sys.argv[2]
|
8 |
+
|
9 |
+
assert os.path.exists(input_path), 'Input model does not exist.'
|
10 |
+
assert not os.path.exists(output_path), 'Output filename already exists.'
|
11 |
+
assert os.path.exists(os.path.dirname(output_path)), 'Output path is not valid.'
|
12 |
+
|
13 |
+
import torch
|
14 |
+
from share import *
|
15 |
+
from cldm.model import create_model
|
16 |
+
|
17 |
+
|
18 |
+
def get_node_name(name, parent_name):
|
19 |
+
if len(name) <= len(parent_name):
|
20 |
+
return False, ''
|
21 |
+
p = name[:len(parent_name)]
|
22 |
+
if p != parent_name:
|
23 |
+
return False, ''
|
24 |
+
return True, name[len(parent_name):]
|
25 |
+
|
26 |
+
|
27 |
+
model = create_model(config_path='./models/cldm_v15.yaml')
|
28 |
+
|
29 |
+
pretrained_weights = torch.load(input_path,map_location=torch.device('cuda'))
|
30 |
+
if 'state_dict' in pretrained_weights:
|
31 |
+
pretrained_weights = pretrained_weights['state_dict']
|
32 |
+
|
33 |
+
scratch_dict = model.state_dict()
|
34 |
+
|
35 |
+
target_dict = {}
|
36 |
+
for k in scratch_dict.keys():
|
37 |
+
is_control, name = get_node_name(k, 'control_')
|
38 |
+
if is_control:
|
39 |
+
copy_k = 'model.diffusion_' + name
|
40 |
+
else:
|
41 |
+
copy_k = k
|
42 |
+
if copy_k in pretrained_weights:
|
43 |
+
target_dict[k] = pretrained_weights[copy_k].clone()
|
44 |
+
else:
|
45 |
+
target_dict[k] = scratch_dict[k].clone()
|
46 |
+
print(f'These weights are newly added: {k}')
|
47 |
+
|
48 |
+
model.load_state_dict(target_dict, strict=True)
|
49 |
+
torch.save(model.state_dict(), output_path)
|
50 |
+
print('Done.')
|
tool_add_control_sd21.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import os
|
3 |
+
|
4 |
+
assert len(sys.argv) == 3, 'Args are wrong.'
|
5 |
+
|
6 |
+
input_path = sys.argv[1]
|
7 |
+
output_path = sys.argv[2]
|
8 |
+
|
9 |
+
assert os.path.exists(input_path), 'Input model does not exist.'
|
10 |
+
assert not os.path.exists(output_path), 'Output filename already exists.'
|
11 |
+
assert os.path.exists(os.path.dirname(output_path)), 'Output path is not valid.'
|
12 |
+
|
13 |
+
import torch
|
14 |
+
from share import *
|
15 |
+
from cldm.model import create_model
|
16 |
+
|
17 |
+
|
18 |
+
def get_node_name(name, parent_name):
|
19 |
+
if len(name) <= len(parent_name):
|
20 |
+
return False, ''
|
21 |
+
p = name[:len(parent_name)]
|
22 |
+
if p != parent_name:
|
23 |
+
return False, ''
|
24 |
+
return True, name[len(parent_name):]
|
25 |
+
|
26 |
+
|
27 |
+
model = create_model(config_path='./models/cldm_v21.yaml')
|
28 |
+
|
29 |
+
pretrained_weights = torch.load(input_path)
|
30 |
+
if 'state_dict' in pretrained_weights:
|
31 |
+
pretrained_weights = pretrained_weights['state_dict']
|
32 |
+
|
33 |
+
scratch_dict = model.state_dict()
|
34 |
+
|
35 |
+
target_dict = {}
|
36 |
+
for k in scratch_dict.keys():
|
37 |
+
is_control, name = get_node_name(k, 'control_')
|
38 |
+
if is_control:
|
39 |
+
copy_k = 'model.diffusion_' + name
|
40 |
+
else:
|
41 |
+
copy_k = k
|
42 |
+
if copy_k in pretrained_weights:
|
43 |
+
target_dict[k] = pretrained_weights[copy_k].clone()
|
44 |
+
else:
|
45 |
+
target_dict[k] = scratch_dict[k].clone()
|
46 |
+
print(f'These weights are newly added: {k}')
|
47 |
+
|
48 |
+
model.load_state_dict(target_dict, strict=True)
|
49 |
+
torch.save(model.state_dict(), output_path)
|
50 |
+
print('Done.')
|
tool_transfer_control.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
path_sd15 = './models/v1-5-pruned.ckpt'
|
2 |
+
path_sd15_with_control = './models/control_sd15_openpose.pth'
|
3 |
+
path_input = './models/anything-v3-full.safetensors'
|
4 |
+
path_output = './models/control_any3_openpose.pth'
|
5 |
+
|
6 |
+
|
7 |
+
import os
|
8 |
+
|
9 |
+
|
10 |
+
assert os.path.exists(path_sd15), 'Input path_sd15 does not exists!'
|
11 |
+
assert os.path.exists(path_sd15_with_control), 'Input path_sd15_with_control does not exists!'
|
12 |
+
assert os.path.exists(path_input), 'Input path_input does not exists!'
|
13 |
+
assert os.path.exists(os.path.dirname(path_output)), 'Output folder not exists!'
|
14 |
+
|
15 |
+
|
16 |
+
import torch
|
17 |
+
from share import *
|
18 |
+
from cldm.model import load_state_dict
|
19 |
+
|
20 |
+
|
21 |
+
sd15_state_dict = load_state_dict(path_sd15)
|
22 |
+
sd15_with_control_state_dict = load_state_dict(path_sd15_with_control)
|
23 |
+
input_state_dict = load_state_dict(path_input)
|
24 |
+
|
25 |
+
|
26 |
+
def get_node_name(name, parent_name):
|
27 |
+
if len(name) <= len(parent_name):
|
28 |
+
return False, ''
|
29 |
+
p = name[:len(parent_name)]
|
30 |
+
if p != parent_name:
|
31 |
+
return False, ''
|
32 |
+
return True, name[len(parent_name):]
|
33 |
+
|
34 |
+
|
35 |
+
keys = sd15_with_control_state_dict.keys()
|
36 |
+
|
37 |
+
final_state_dict = {}
|
38 |
+
for key in keys:
|
39 |
+
is_first_stage, _ = get_node_name(key, 'first_stage_model')
|
40 |
+
is_cond_stage, _ = get_node_name(key, 'cond_stage_model')
|
41 |
+
if is_first_stage or is_cond_stage:
|
42 |
+
final_state_dict[key] = input_state_dict[key]
|
43 |
+
continue
|
44 |
+
p = sd15_with_control_state_dict[key]
|
45 |
+
is_control, node_name = get_node_name(key, 'control_')
|
46 |
+
if is_control:
|
47 |
+
sd15_key_name = 'model.diffusion_' + node_name
|
48 |
+
else:
|
49 |
+
sd15_key_name = key
|
50 |
+
if sd15_key_name in input_state_dict:
|
51 |
+
p_new = p + input_state_dict[sd15_key_name] - sd15_state_dict[sd15_key_name]
|
52 |
+
# print(f'Offset clone from [{sd15_key_name}] to [{key}]')
|
53 |
+
else:
|
54 |
+
p_new = p
|
55 |
+
# print(f'Direct clone to [{key}]')
|
56 |
+
final_state_dict[key] = p_new
|
57 |
+
|
58 |
+
torch.save(final_state_dict, path_output)
|
59 |
+
print('Transferred model saved at ' + path_output)
|
tutorial_dataset.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
from torch.utils.data import Dataset
|
6 |
+
|
7 |
+
|
8 |
+
class MyDataset(Dataset):
|
9 |
+
def __init__(self):
|
10 |
+
self.data = []
|
11 |
+
with open('./training/fill50k/prompt.json', 'rt') as f:
|
12 |
+
for line in f:
|
13 |
+
self.data.append(json.loads(line))
|
14 |
+
|
15 |
+
def __len__(self):
|
16 |
+
return len(self.data)
|
17 |
+
|
18 |
+
def __getitem__(self, idx):
|
19 |
+
item = self.data[idx]
|
20 |
+
|
21 |
+
source_filename = item['source']
|
22 |
+
target_filename = item['target']
|
23 |
+
prompt = item['prompt']
|
24 |
+
|
25 |
+
source = cv2.imread('./training/fill50k/' + source_filename)
|
26 |
+
target = cv2.imread('./training/fill50k/' + target_filename)
|
27 |
+
|
28 |
+
# Do not forget that OpenCV read images in BGR order.
|
29 |
+
source = cv2.cvtColor(source, cv2.COLOR_BGR2RGB)
|
30 |
+
target = cv2.cvtColor(target, cv2.COLOR_BGR2RGB)
|
31 |
+
|
32 |
+
# Normalize source images to [0, 1].
|
33 |
+
source = source.astype(np.float32) / 255.0
|
34 |
+
|
35 |
+
# Normalize target images to [-1, 1].
|
36 |
+
target = (target.astype(np.float32) / 127.5) - 1.0
|
37 |
+
|
38 |
+
return dict(jpg=target, txt=prompt, hint=source)
|
39 |
+
|
tutorial_dataset_test.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from tutorial_dataset import MyDataset
|
2 |
+
|
3 |
+
dataset = MyDataset()
|
4 |
+
print(len(dataset))
|
5 |
+
|
6 |
+
item = dataset[1234]
|
7 |
+
jpg = item['jpg']
|
8 |
+
txt = item['txt']
|
9 |
+
hint = item['hint']
|
10 |
+
print(txt)
|
11 |
+
print(jpg.shape)
|
12 |
+
print(hint.shape)
|
tutorial_train.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
|
3 |
+
import pytorch_lightning as pl
|
4 |
+
from torch.utils.data import DataLoader
|
5 |
+
from tutorial_dataset import MyDataset
|
6 |
+
from cldm.logger import ImageLogger
|
7 |
+
from cldm.model import create_model, load_state_dict
|
8 |
+
|
9 |
+
|
10 |
+
# Configs
|
11 |
+
resume_path = './models/control_sd15_ini.ckpt'
|
12 |
+
batch_size = 4
|
13 |
+
logger_freq = 300
|
14 |
+
learning_rate = 1e-5
|
15 |
+
sd_locked = True
|
16 |
+
only_mid_control = False
|
17 |
+
|
18 |
+
|
19 |
+
# First use cpu to load models. Pytorch Lightning will automatically move it to GPUs.
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict(resume_path, location='cpu'))
|
22 |
+
model.learning_rate = learning_rate
|
23 |
+
model.sd_locked = sd_locked
|
24 |
+
model.only_mid_control = only_mid_control
|
25 |
+
|
26 |
+
|
27 |
+
# Misc
|
28 |
+
dataset = MyDataset()
|
29 |
+
dataloader = DataLoader(dataset, num_workers=0, batch_size=batch_size, shuffle=True)
|
30 |
+
logger = ImageLogger(batch_frequency=logger_freq)
|
31 |
+
trainer = pl.Trainer(gpus=1, precision=32, callbacks=[logger])
|
32 |
+
|
33 |
+
|
34 |
+
# Train!
|
35 |
+
trainer.fit(model, dataloader)
|
tutorial_train_sd21.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
|
3 |
+
import pytorch_lightning as pl
|
4 |
+
from torch.utils.data import DataLoader
|
5 |
+
from tutorial_dataset import MyDataset
|
6 |
+
from cldm.logger import ImageLogger
|
7 |
+
from cldm.model import create_model, load_state_dict
|
8 |
+
|
9 |
+
|
10 |
+
# Configs
|
11 |
+
resume_path = './models/control_sd21_ini.ckpt'
|
12 |
+
batch_size = 4
|
13 |
+
logger_freq = 300
|
14 |
+
learning_rate = 1e-5
|
15 |
+
sd_locked = True
|
16 |
+
only_mid_control = False
|
17 |
+
|
18 |
+
|
19 |
+
# First use cpu to load models. Pytorch Lightning will automatically move it to GPUs.
|
20 |
+
model = create_model('./models/cldm_v21.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict(resume_path, location='cpu'))
|
22 |
+
model.learning_rate = learning_rate
|
23 |
+
model.sd_locked = sd_locked
|
24 |
+
model.only_mid_control = only_mid_control
|
25 |
+
|
26 |
+
|
27 |
+
# Misc
|
28 |
+
dataset = MyDataset()
|
29 |
+
dataloader = DataLoader(dataset, num_workers=0, batch_size=batch_size, shuffle=True)
|
30 |
+
logger = ImageLogger(batch_frequency=logger_freq)
|
31 |
+
trainer = pl.Trainer(gpus=1, precision=32, callbacks=[logger])
|
32 |
+
|
33 |
+
|
34 |
+
# Train!
|
35 |
+
trainer.fit(model, dataloader)
|