benskibenski commited on
Commit
b68433c
·
verified ·
1 Parent(s): 988c0bd

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ Comic_Generation.ipynb filter=lfs diff=lfs merge=lfs -text
37
+ results_examples/image1.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compile / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Jupyter Notebook
55
+ .ipynb_checkpoints
56
+
57
+ # pyenv
58
+ .python-version
59
+
60
+ # celery beat schedule file
61
+ celerybeat-schedule
62
+
63
+ # SageMath parsed files
64
+ *.sage.py
65
+
66
+ # Environments
67
+ .env
68
+ .venv
69
+ env/
70
+ venv/
71
+ ENV/
72
+ env.bak/
73
+ venv.bak/
74
+
75
+ # Spyder project settings
76
+ .spyderproject
77
+ .spyproject
78
+
79
+ # Rope project settings
80
+ .ropeproject
81
+
82
+ # mkdocs documentation
83
+ /site
84
+
85
+ # mypy
86
+ .mypy_cache/
87
+ .aider*
88
+
89
+ # ignore ALL .log files
90
+ *.log
91
+ # ignore ALL files in ANY directory named temp
92
+ .ipynb_checkpoints/
93
+ images/.ipynb_checkpoints/
Comic_Generation.ipynb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c6376c7f98b4d0419d9310a3debfaa76b403c6f5a994f8f0de687a65adc6564c
3
+ size 19371692
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 CHANGED
@@ -1,12 +1,158 @@
1
- ---
2
- title: JingleSharkStories
3
- emoji: 😻
4
- colorFrom: green
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 4.31.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: JingleSharkStories
3
+ app_file: app.py
4
+ sdk: gradio
5
+ sdk_version: 4.31.0
6
+ ---
7
+ <p align="center">
8
+ <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/f79da6b7-0b3b-4dd7-8dd0-ba0b15306fe6" height=100>
9
+ </p>
10
+
11
+ <div align="center">
12
+
13
+ ## StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation [![Paper page](https://huggingface.co/datasets/huggingface/badges/resolve/main/paper-page-md-dark.svg)]()
14
+ [[Paper](https://arxiv.org/abs/2405.01434)] &emsp; [[Project Page](https://storydiffusion.github.io/)] &emsp; [[🤗 Comic Generation Demo ](https://huggingface.co/spaces/YupengZhou/StoryDiffusion)] [![Replicate](https://replicate.com/cjwbw/StoryDiffusion/badge)](https://replicate.com/cjwbw/StoryDiffusion) <br>
15
+
16
+
17
+ </div>
18
+
19
+ <div align="left">
20
+
21
+ #### For results sharing and discussion: https://discord.gg/hSJZ35fV
22
+ #### For codebase and deployment-related discussion: https://discord.gg/2HFUHT9p
23
+ </div>
24
+
25
+ ---
26
+
27
+ Official implementation of **[StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation]()**.
28
+
29
+ ### **Demo Video**
30
+
31
+
32
+
33
+
34
+ https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/d5b80f8f-09b0-48cd-8b10-daff46d422af
35
+
36
+
37
+ ### Update History
38
+
39
+ You can visit [here](update.md) to visit update history.
40
+
41
+ ### 🌠 **Key Features:**
42
+ StoryDiffusion can create a magic story by generating consistent images and videos. Our work mainly has two parts:
43
+ 1. Consistent self-attention for character-consistent image generation over long-range sequences. It is hot-pluggable and compatible with all SD1.5 and SDXL-based image diffusion models. For the current implementation, the user needs to provide at least 3 text prompts for the consistent self-attention module. We recommend at least 5 - 6 text prompts for better layout arrangement.
44
+ 2. Motion predictor for long-range video generation, which predicts motion between Condition Images in a compressed image semantic space, achieving larger motion prediction.
45
+
46
+
47
+
48
+ ## 🔥 **Examples**
49
+
50
+
51
+ ### Comics generation
52
+
53
+
54
+ ![1](https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/b3771cbc-b6ca-4e26-bdc5-d944daf9f266)
55
+
56
+
57
+
58
+ ### Image-to-Video generation (Results are HIGHLY compressed for speed)
59
+ Leveraging the images produced through our Consistent Self-Attention mechanism, we can extend the process to create videos by seamlessly transitioning between these images. This can be considered as a two-stage long video generation approach.
60
+
61
+ Note: results are **highly compressed** for speed, you can visit [our website](https://storydiffusion.github.io/) for the high-quality version.
62
+ #### Two-stage Long Videos Generation (New Update)
63
+ Combining the two parts, we can generate very long and high-quality AIGC videos.
64
+ | Video1 | Video2 | Video3 |
65
+ | --- | --- | --- |
66
+ | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/4e7e0f24-5f90-419b-9a1e-cdf36d361b26" width=224> | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/f509343d-d691-4e2a-b615-7d96381ef7c1" width=224> | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/4f0f7abb-4ae4-47a6-b692-5bdd8d9c8006" width=224> |
67
+
68
+
69
+ #### Long Video Results using Condition Images
70
+ Our Image-to-Video model can generate a video by providing a sequence of user-input condition images.
71
+ | Video1 | Video2 | Video3 |
72
+ | --- | --- | --- |
73
+ | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/af6f5c50-c773-4ef2-a757-6d7a46393f39" width=224> | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/d58e4037-d8df-4f90-8c81-ce4b6d2d868e" width=224> | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/40da15ba-f5c1-48d8-84d6-8d327207d696" width=224> |
74
+
75
+ | Video4 | Video5 | Video6 |
76
+ | --- | --- | --- |
77
+ | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/8f04c9fc-3031-49e3-9de8-83d582b80a1f" width=224> | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/604107fb-8afe-4052-bda4-362c646a756e" width=224> | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/b05fa6a0-12e6-4111-abf8-18b8cd84f3ff" width=224> |
78
+
79
+
80
+
81
+
82
+ #### Short Videos
83
+
84
+ | Video1 | Video2 | Video3 |
85
+ | --- | --- | --- |
86
+ | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/5e7f717f-daad-46f6-b3ba-c087bd843158" width=224> | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/79aa52b2-bf37-4c9c-8555-c7050aec0cdf" width=224> | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/9fdfd091-10e6-434e-9ce7-6d6e6d8f4b22" width=224> |
87
+
88
+
89
+
90
+ | Video4 | Video5 | Video6 |
91
+ | --- | --- | --- |
92
+ | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/0b219b60-a998-4820-9657-6abe1747cb6b" width=224> | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/d387aef0-ffc8-41b0-914f-4b0392d9f8c5" width=224> | <img src="https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/3c64958a-1079-4ca0-a9cf-e0486adbc57f" width=224> |
93
+
94
+
95
+
96
+
97
+ ## 🚩 **TODO/Updates**
98
+ - [x] Comic Results of StoryDiffusion.
99
+ - [x] Video Results of StoryDiffusion.
100
+ - [x] Source code of Comic Generation
101
+ - [x] Source code of gradio demo
102
+ - [ ] Source code of Video Generation Model
103
+ - [ ] Pretrained weight of Video Generation Model
104
+ ---
105
+
106
+ # 🔧 Dependencies and Installation
107
+
108
+ - Python >= 3.8 (Recommend to use [Anaconda](https://www.anaconda.com/download/#linux) or [Miniconda](https://docs.conda.io/en/latest/miniconda.html))
109
+ - [PyTorch >= 2.0.0](https://pytorch.org/)
110
+ ```bash
111
+ conda create --name storydiffusion python=3.10
112
+ conda activate storydiffusion
113
+ pip install -U pip
114
+
115
+ # Install requirements
116
+ pip install -r requirements.txt
117
+ ```
118
+ # How to use
119
+
120
+ Currently, we provide two ways for you to generate comics.
121
+
122
+ ## Use the jupyter notebook
123
+
124
+ You can open the `Comic_Generation.ipynb` and run the code.
125
+
126
+ ## Start a local gradio demo
127
+ Run the following command:
128
+
129
+ ```python
130
+ python gradio_app_sdxl_specific_id.py
131
+ ```
132
+
133
+ **(Recommend)** We provide a low GPU Memory cost version, it was tested on a machine with 24GB GPU-memory(Tesla A10) and 30GB RAM, and expected to work well with >20 G GPU-memory.
134
+
135
+ ```python
136
+ python gradio_app_sdxl_specific_id_low_vram.py
137
+ ```
138
+
139
+
140
+ ## Contact
141
+ If you have any questions, you are very welcome to email ypzhousdu@gmail.com and zhoudaquan21@gmail.com
142
+
143
+
144
+
145
+
146
+ # Disclaimer
147
+ This project strives to impact the domain of AI-driven image and video generation positively. Users are granted the freedom to create images and videos using this tool, but they are expected to comply with local laws and utilize it responsibly. The developers do not assume any responsibility for potential misuse by users.
148
+
149
+ # BibTeX
150
+ If you find StoryDiffusion useful for your research and applications, please cite using this BibTeX:
151
+
152
+ ```BibTeX
153
+ @article{zhou2024storydiffusion,
154
+ title={StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation},
155
+ author={Zhou, Yupeng and Zhou, Daquan and Cheng, Ming-Ming and Feng, Jiashi and Hou, Qibin},
156
+ journal={arXiv preprint arXiv:2405.01434},
157
+ year={2024}
158
+ }
app.py ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from email.policy import default
2
+ import gradio as gr
3
+ import numpy as np
4
+ import spaces
5
+ import torch
6
+ import requests
7
+ import random
8
+ import os
9
+ import sys
10
+ import pickle
11
+ from PIL import Image
12
+ from tqdm.auto import tqdm
13
+ from datetime import datetime
14
+ from utils.gradio_utils import is_torch2_available
15
+ if is_torch2_available():
16
+ from utils.gradio_utils import \
17
+ AttnProcessor2_0 as AttnProcessor
18
+ # from utils.gradio_utils import SpatialAttnProcessor2_0
19
+ else:
20
+ from utils.gradio_utils import AttnProcessor
21
+
22
+ import diffusers
23
+ from diffusers import StableDiffusionXLPipeline
24
+ from utils import PhotoMakerStableDiffusionXLPipeline
25
+ from diffusers import DDIMScheduler
26
+ import torch.nn.functional as F
27
+ from utils.gradio_utils import cal_attn_mask_xl
28
+ import copy
29
+ import os
30
+ from huggingface_hub import hf_hub_download
31
+ from diffusers.utils import load_image
32
+ from utils.utils import get_comic
33
+ from utils.style_template import styles
34
+ image_encoder_path = "./data/models/ip_adapter/sdxl_models/image_encoder"
35
+ ip_ckpt = "./data/models/ip_adapter/sdxl_models/ip-adapter_sdxl_vit-h.bin"
36
+ os.environ["no_proxy"] = "localhost,127.0.0.1,::1"
37
+ STYLE_NAMES = list(styles.keys())
38
+ DEFAULT_STYLE_NAME = "Japanese Anime"
39
+ global models_dict
40
+ use_va = True
41
+ models_dict = {
42
+ # "Juggernaut": "RunDiffusion/Juggernaut-XL-v8",
43
+ # "RealVision": "SG161222/RealVisXL_V4.0" ,
44
+ # "SDXL":"stabilityai/stable-diffusion-xl-base-1.0" ,
45
+ "Unstable": "stablediffusionapi/sdxl-unstable-diffusers-y"
46
+ }
47
+ photomaker_path = hf_hub_download(repo_id="TencentARC/PhotoMaker", filename="photomaker-v1.bin", repo_type="model")
48
+ MAX_SEED = np.iinfo(np.int32).max
49
+ def setup_seed(seed):
50
+ torch.manual_seed(seed)
51
+ torch.cuda.manual_seed_all(seed)
52
+ np.random.seed(seed)
53
+ random.seed(seed)
54
+ torch.backends.cudnn.deterministic = True
55
+ def set_text_unfinished():
56
+ return gr.update(visible=True, value="<h3>(Not Finished) Generating ··· The intermediate results will be shown.</h3>")
57
+ def set_text_finished():
58
+ return gr.update(visible=True, value="<h3>Generation Finished</h3>")
59
+ #################################################
60
+ def get_image_path_list(folder_name):
61
+ image_basename_list = os.listdir(folder_name)
62
+ image_path_list = sorted([os.path.join(folder_name, basename) for basename in image_basename_list])
63
+ return image_path_list
64
+
65
+ #################################################
66
+ class SpatialAttnProcessor2_0(torch.nn.Module):
67
+ r"""
68
+ Attention processor for IP-Adapater for PyTorch 2.0.
69
+ Args:
70
+ hidden_size (`int`):
71
+ The hidden size of the attention layer.
72
+ cross_attention_dim (`int`):
73
+ The number of channels in the `encoder_hidden_states`.
74
+ text_context_len (`int`, defaults to 77):
75
+ The context length of the text features.
76
+ scale (`float`, defaults to 1.0):
77
+ the weight scale of image prompt.
78
+ """
79
+
80
+ def __init__(self, hidden_size = None, cross_attention_dim=None,id_length = 4,device = "cuda",dtype = torch.float16):
81
+ super().__init__()
82
+ if not hasattr(F, "scaled_dot_product_attention"):
83
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
84
+ self.device = device
85
+ self.dtype = dtype
86
+ self.hidden_size = hidden_size
87
+ self.cross_attention_dim = cross_attention_dim
88
+ self.total_length = id_length + 1
89
+ self.id_length = id_length
90
+ self.id_bank = {}
91
+
92
+ def __call__(
93
+ self,
94
+ attn,
95
+ hidden_states,
96
+ encoder_hidden_states=None,
97
+ attention_mask=None,
98
+ temb=None):
99
+ # un_cond_hidden_states, cond_hidden_states = hidden_states.chunk(2)
100
+ # un_cond_hidden_states = self.__call2__(attn, un_cond_hidden_states,encoder_hidden_states,attention_mask,temb)
101
+ # 生成一个0到1之间的随机数
102
+ global total_count,attn_count,cur_step,mask1024,mask4096
103
+ global sa32, sa64
104
+ global write
105
+ global height,width
106
+ if write:
107
+ # print(f"white:{cur_step}")
108
+ self.id_bank[cur_step] = [hidden_states[:self.id_length], hidden_states[self.id_length:]]
109
+ else:
110
+ encoder_hidden_states = torch.cat((self.id_bank[cur_step][0].to(self.device),hidden_states[:1],self.id_bank[cur_step][1].to(self.device),hidden_states[1:]))
111
+ # 判断随机数是否大于0.5
112
+ if cur_step <5:
113
+ hidden_states = self.__call2__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
114
+ else: # 256 1024 4096
115
+ random_number = random.random()
116
+ if cur_step <20:
117
+ rand_num = 0.3
118
+ else:
119
+ rand_num = 0.1
120
+ # print(f"hidden state shape {hidden_states.shape[1]}")
121
+ if random_number > rand_num:
122
+ # print("mask shape",mask1024.shape,mask4096.shape)
123
+ if not write:
124
+ if hidden_states.shape[1] == (height//32) * (width//32):
125
+ attention_mask = mask1024[mask1024.shape[0] // self.total_length * self.id_length:]
126
+ else:
127
+ attention_mask = mask4096[mask4096.shape[0] // self.total_length * self.id_length:]
128
+ else:
129
+ # print(self.total_length,self.id_length,hidden_states.shape,(height//32) * (width//32))
130
+ if hidden_states.shape[1] == (height//32) * (width//32):
131
+ attention_mask = mask1024[:mask1024.shape[0] // self.total_length * self.id_length,:mask1024.shape[0] // self.total_length * self.id_length]
132
+ else:
133
+ attention_mask = mask4096[:mask4096.shape[0] // self.total_length * self.id_length,:mask4096.shape[0] // self.total_length * self.id_length]
134
+ # print(attention_mask.shape)
135
+ # print("before attention",hidden_states.shape,attention_mask.shape,encoder_hidden_states.shape if encoder_hidden_states is not None else "None")
136
+ hidden_states = self.__call1__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
137
+ else:
138
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
139
+ attn_count +=1
140
+ if attn_count == total_count:
141
+ attn_count = 0
142
+ cur_step += 1
143
+ mask1024,mask4096 = cal_attn_mask_xl(self.total_length,self.id_length,sa32,sa64,height,width, device=self.device, dtype= self.dtype)
144
+
145
+ return hidden_states
146
+ def __call1__(
147
+ self,
148
+ attn,
149
+ hidden_states,
150
+ encoder_hidden_states=None,
151
+ attention_mask=None,
152
+ temb=None,
153
+ ):
154
+ # print("hidden state shape",hidden_states.shape,self.id_length)
155
+ residual = hidden_states
156
+ # if encoder_hidden_states is not None:
157
+ # raise Exception("not implement")
158
+ if attn.spatial_norm is not None:
159
+ hidden_states = attn.spatial_norm(hidden_states, temb)
160
+ input_ndim = hidden_states.ndim
161
+
162
+ if input_ndim == 4:
163
+ total_batch_size, channel, height, width = hidden_states.shape
164
+ hidden_states = hidden_states.view(total_batch_size, channel, height * width).transpose(1, 2)
165
+ total_batch_size,nums_token,channel = hidden_states.shape
166
+ img_nums = total_batch_size//2
167
+ hidden_states = hidden_states.view(-1,img_nums,nums_token,channel).reshape(-1,img_nums * nums_token,channel)
168
+
169
+ batch_size, sequence_length, _ = hidden_states.shape
170
+
171
+ if attn.group_norm is not None:
172
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
173
+
174
+ query = attn.to_q(hidden_states)
175
+
176
+ if encoder_hidden_states is None:
177
+ encoder_hidden_states = hidden_states # B, N, C
178
+ else:
179
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,nums_token,channel).reshape(-1,(self.id_length+1) * nums_token,channel)
180
+
181
+ key = attn.to_k(encoder_hidden_states)
182
+ value = attn.to_v(encoder_hidden_states)
183
+
184
+
185
+ inner_dim = key.shape[-1]
186
+ head_dim = inner_dim // attn.heads
187
+
188
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
189
+
190
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
191
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
192
+ # print(key.shape,value.shape,query.shape,attention_mask.shape)
193
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
194
+ # TODO: add support for attn.scale when we move to Torch 2.1
195
+ #print(query.shape,key.shape,value.shape,attention_mask.shape)
196
+ hidden_states = F.scaled_dot_product_attention(
197
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
198
+ )
199
+
200
+ hidden_states = hidden_states.transpose(1, 2).reshape(total_batch_size, -1, attn.heads * head_dim)
201
+ hidden_states = hidden_states.to(query.dtype)
202
+
203
+
204
+
205
+ # linear proj
206
+ hidden_states = attn.to_out[0](hidden_states)
207
+ # dropout
208
+ hidden_states = attn.to_out[1](hidden_states)
209
+
210
+ # if input_ndim == 4:
211
+ # tile_hidden_states = tile_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
212
+
213
+ # if attn.residual_connection:
214
+ # tile_hidden_states = tile_hidden_states + residual
215
+
216
+ if input_ndim == 4:
217
+ hidden_states = hidden_states.transpose(-1, -2).reshape(total_batch_size, channel, height, width)
218
+ if attn.residual_connection:
219
+ hidden_states = hidden_states + residual
220
+ hidden_states = hidden_states / attn.rescale_output_factor
221
+ # print(hidden_states.shape)
222
+ return hidden_states
223
+ def __call2__(
224
+ self,
225
+ attn,
226
+ hidden_states,
227
+ encoder_hidden_states=None,
228
+ attention_mask=None,
229
+ temb=None):
230
+ residual = hidden_states
231
+
232
+ if attn.spatial_norm is not None:
233
+ hidden_states = attn.spatial_norm(hidden_states, temb)
234
+
235
+ input_ndim = hidden_states.ndim
236
+
237
+ if input_ndim == 4:
238
+ batch_size, channel, height, width = hidden_states.shape
239
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
240
+
241
+ batch_size, sequence_length, channel = (
242
+ hidden_states.shape
243
+ )
244
+ # print(hidden_states.shape)
245
+ if attention_mask is not None:
246
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
247
+ # scaled_dot_product_attention expects attention_mask shape to be
248
+ # (batch, heads, source_length, target_length)
249
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
250
+
251
+ if attn.group_norm is not None:
252
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
253
+
254
+ query = attn.to_q(hidden_states)
255
+
256
+ if encoder_hidden_states is None:
257
+ encoder_hidden_states = hidden_states # B, N, C
258
+ else:
259
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,sequence_length,channel).reshape(-1,(self.id_length+1) * sequence_length,channel)
260
+
261
+ key = attn.to_k(encoder_hidden_states)
262
+ value = attn.to_v(encoder_hidden_states)
263
+
264
+ inner_dim = key.shape[-1]
265
+ head_dim = inner_dim // attn.heads
266
+
267
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
268
+
269
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
270
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
271
+
272
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
273
+ # TODO: add support for attn.scale when we move to Torch 2.1
274
+ hidden_states = F.scaled_dot_product_attention(
275
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
276
+ )
277
+
278
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
279
+ hidden_states = hidden_states.to(query.dtype)
280
+
281
+ # linear proj
282
+ hidden_states = attn.to_out[0](hidden_states)
283
+ # dropout
284
+ hidden_states = attn.to_out[1](hidden_states)
285
+
286
+ if input_ndim == 4:
287
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
288
+
289
+ if attn.residual_connection:
290
+ hidden_states = hidden_states + residual
291
+
292
+ hidden_states = hidden_states / attn.rescale_output_factor
293
+
294
+ return hidden_states
295
+
296
+ def set_attention_processor(unet,id_length,is_ipadapter = False):
297
+ global total_count
298
+ total_count = 0
299
+ attn_procs = {}
300
+ for name in unet.attn_processors.keys():
301
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
302
+ if name.startswith("mid_block"):
303
+ hidden_size = unet.config.block_out_channels[-1]
304
+ elif name.startswith("up_blocks"):
305
+ block_id = int(name[len("up_blocks.")])
306
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
307
+ elif name.startswith("down_blocks"):
308
+ block_id = int(name[len("down_blocks.")])
309
+ hidden_size = unet.config.block_out_channels[block_id]
310
+ if cross_attention_dim is None:
311
+ if name.startswith("up_blocks") :
312
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length = id_length)
313
+ total_count +=1
314
+ else:
315
+ attn_procs[name] = AttnProcessor()
316
+ else:
317
+ if is_ipadapter:
318
+ attn_procs[name] = IPAttnProcessor2_0(
319
+ hidden_size=hidden_size,
320
+ cross_attention_dim=cross_attention_dim,
321
+ scale=1,
322
+ num_tokens=4,
323
+ ).to(unet.device, dtype=torch.float16)
324
+ else:
325
+ attn_procs[name] = AttnProcessor()
326
+
327
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
328
+ print("successsfully load paired self-attention")
329
+ print(f"number of the processor : {total_count}")
330
+ #################################################
331
+ #################################################
332
+ canvas_html = "<div id='canvas-root' style='max-width:400px; margin: 0 auto'></div>"
333
+ load_js = """
334
+ async () => {
335
+ const url = "https://huggingface.co/datasets/radames/gradio-components/raw/main/sketch-canvas.js"
336
+ fetch(url)
337
+ .then(res => res.text())
338
+ .then(text => {
339
+ const script = document.createElement('script');
340
+ script.type = "module"
341
+ script.src = URL.createObjectURL(new Blob([text], { type: 'application/javascript' }));
342
+ document.head.appendChild(script);
343
+ });
344
+ }
345
+ """
346
+
347
+ get_js_colors = """
348
+ async (canvasData) => {
349
+ const canvasEl = document.getElementById("canvas-root");
350
+ return [canvasEl._data]
351
+ }
352
+ """
353
+
354
+ css = '''
355
+ #color-bg{display:flex;justify-content: center;align-items: center;}
356
+ .color-bg-item{width: 100%; height: 32px}
357
+ #main_button{width:100%}
358
+ <style>
359
+ '''
360
+
361
+
362
+ #################################################
363
+ title = r"""
364
+ <h1 align="center">StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</h1>
365
+ """
366
+
367
+ description = r"""
368
+ <b>Official 🤗 Gradio demo</b> for <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'><b>StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</b></a>.<br>
369
+ ❗️❗️❗️[<b>Important</b>] Personalization steps:<br>
370
+ 1️⃣ Enter a Textual Description for Character, if you add the Ref-Image, making sure to <b>follow the class word</b> you want to customize with the <b>trigger word</b>: `img`, such as: `man img` or `woman img` or `girl img`.<br>
371
+ 2️⃣ Enter the prompt array, each line corrsponds to one generated image.<br>
372
+ 3️⃣ Choose your preferred style template.<br>
373
+ 4️⃣ Click the <b>Submit</b> button to start customizing.
374
+ """
375
+
376
+ article = r"""
377
+
378
+ If StoryDiffusion is helpful, please help to ⭐ the <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'>Github Repo</a>. Thanks!
379
+ [![GitHub Stars](https://img.shields.io/github/stars/HVision-NKU/StoryDiffusion?style=social)](https://github.com/HVision-NKU/StoryDiffusion)
380
+ ---
381
+ 📝 **Citation**
382
+ <br>
383
+ If our work is useful for your research, please consider citing:
384
+
385
+ ```bibtex
386
+ @article{Zhou2024storydiffusion,
387
+ title={StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation},
388
+ author={Zhou, Yupeng and Zhou, Daquan and Cheng, Ming-Ming and Feng, Jiashi and Hou, Qibin},
389
+ year={2024}
390
+ }
391
+ ```
392
+ 📋 **License**
393
+ <br>
394
+ The Contents you create are under Apache-2.0 LICENSE. The Code are under Attribution-NonCommercial 4.0 International.
395
+
396
+ 📧 **Contact**
397
+ <br>
398
+ If you have any questions, please feel free to reach me out at <b>ypzhousdu@gmail.com</b>.
399
+ """
400
+ version = r"""
401
+ <h3 align="center">StoryDiffusion Version 0.01 (test version)</h3>
402
+
403
+ <h5 >1. Support image ref image. (Cartoon Ref image is not support now)</h5>
404
+ <h5 >2. Support Typesetting Style and Captioning.(By default, the prompt is used as the caption for each image. If you need to change the caption, add a # at the end of each line. Only the part after the # will be added as a caption to the image.)</h5>
405
+ <h5 >3. [NC]symbol (The [NC] symbol is used as a flag to indicate that no characters should be present in the generated scene images. If you want do that, prepend the "[NC]" at the beginning of the line. For example, to generate a scene of falling leaves without any character, write: "[NC] The leaves are falling."),Currently, support is only using Textual Description</h5>
406
+ <h5 align="center">Tips: Not Ready Now! Just Test</h5>
407
+ """
408
+ #################################################
409
+ global attn_count, total_count, id_length, total_length,cur_step, cur_model_type
410
+ global write
411
+ global sa32, sa64
412
+ global height,width
413
+ attn_count = 0
414
+ total_count = 0
415
+ cur_step = 0
416
+ id_length = 4
417
+ total_length = 5
418
+ cur_model_type = ""
419
+ device="cuda"
420
+ global attn_procs,unet
421
+ attn_procs = {}
422
+ ###
423
+ write = False
424
+ ###
425
+ sa32 = 0.5
426
+ sa64 = 0.5
427
+ height = 768
428
+ width = 768
429
+ ###
430
+ global sd_model_path
431
+ sd_model_path = models_dict["Unstable"]#"SG161222/RealVisXL_V4.0"
432
+ use_safetensors= False
433
+ ### LOAD Stable Diffusion Pipeline
434
+ pipe1 = StableDiffusionXLPipeline.from_pretrained(sd_model_path, torch_dtype=torch.float16, use_safetensors= use_safetensors)
435
+ pipe1 = pipe1.to("cuda")
436
+ pipe1.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
437
+ # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
438
+ pipe1.scheduler.set_timesteps(50)
439
+ ###
440
+ pipe2 = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
441
+ sd_model_path, torch_dtype=torch.float16, use_safetensors=use_safetensors)
442
+ pipe2 = pipe2.to("cuda")
443
+ pipe2.load_photomaker_adapter(
444
+ os.path.dirname(photomaker_path),
445
+ subfolder="",
446
+ weight_name=os.path.basename(photomaker_path),
447
+ trigger_word="img" # define the trigger word
448
+ )
449
+ pipe2 = pipe2.to("cuda")
450
+ pipe2.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
451
+ pipe2.fuse_lora()
452
+
453
+ ######### Gradio Fuction #############
454
+
455
+ def swap_to_gallery(images):
456
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
457
+
458
+ def upload_example_to_gallery(images, prompt, style, negative_prompt):
459
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
460
+
461
+ def remove_back_to_files():
462
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
463
+
464
+ def remove_tips():
465
+ return gr.update(visible=False)
466
+
467
+ def apply_style_positive(style_name: str, positive: str):
468
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
469
+ return p.replace("{prompt}", positive)
470
+
471
+ def apply_style(style_name: str, positives: list, negative: str = ""):
472
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
473
+ return [p.replace("{prompt}", positive) for positive in positives], n + ' ' + negative
474
+
475
+ def change_visiale_by_model_type(_model_type):
476
+ if _model_type == "Only Using Textual Description":
477
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
478
+ elif _model_type == "Using Ref Images":
479
+ return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False)
480
+ else:
481
+ raise ValueError("Invalid model type",_model_type)
482
+
483
+
484
+ ######### Image Generation ##############
485
+ @spaces.GPU
486
+ def process_generation(_sd_type,_model_type,_upload_images, _num_steps,style_name, _Ip_Adapter_Strength ,_style_strength_ratio, guidance_scale, seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt,prompt_array,G_height,G_width,_comic_type):
487
+ _model_type = "Photomaker" if _model_type == "Using Ref Images" else "original"
488
+ if _model_type == "Photomaker" and "img" not in general_prompt:
489
+ raise gr.Error("Please add the triger word \" img \" behind the class word you want to customize, such as: man img or woman img")
490
+ if _upload_images is None and _model_type != "original":
491
+ raise gr.Error(f"Cannot find any input face image!")
492
+ global sa32, sa64,id_length,total_length,attn_procs,unet,cur_model_type,device
493
+ global write
494
+ global cur_step,attn_count
495
+ global height,width
496
+ height = G_height
497
+ width = G_width
498
+ global pipe1,pipe2
499
+ global sd_model_path,models_dict
500
+ sd_model_path = models_dict[_sd_type]
501
+ use_safe_tensor = True
502
+ if _model_type == "original":
503
+ pipe = pipe1
504
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
505
+ elif _model_type == "Photomaker":
506
+ pipe = pipe2
507
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
508
+ else:
509
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
510
+ ##### ########################
511
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
512
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
513
+ cur_model_type = _sd_type+"-"+_model_type+""+str(id_length_)
514
+ if _model_type != "original":
515
+ input_id_images = []
516
+ for img in _upload_images:
517
+ print(img)
518
+ input_id_images.append(load_image(img))
519
+ prompts = prompt_array.splitlines()
520
+ start_merge_step = int(float(_style_strength_ratio) / 100 * _num_steps)
521
+ if start_merge_step > 30:
522
+ start_merge_step = 30
523
+ print(f"start_merge_step:{start_merge_step}")
524
+ generator = torch.Generator(device="cuda").manual_seed(seed_)
525
+ sa32, sa64 = sa32_, sa64_
526
+ id_length = id_length_
527
+ clipped_prompts = prompts[:]
528
+ prompts = [general_prompt + "," + prompt if "[NC]" not in prompt else prompt.replace("[NC]","") for prompt in clipped_prompts]
529
+ prompts = [prompt.rpartition('#')[0] if "#" in prompt else prompt for prompt in prompts]
530
+ print(prompts)
531
+ id_prompts = prompts[:id_length]
532
+ real_prompts = prompts[id_length:]
533
+ torch.cuda.empty_cache()
534
+ write = True
535
+ cur_step = 0
536
+
537
+ attn_count = 0
538
+ id_prompts, negative_prompt = apply_style(style_name, id_prompts, negative_prompt)
539
+ setup_seed(seed_)
540
+ total_results = []
541
+ if _model_type == "original":
542
+ id_images = pipe(id_prompts, num_inference_steps=_num_steps, guidance_scale=guidance_scale, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images
543
+ elif _model_type == "Photomaker":
544
+ id_images = pipe(id_prompts,input_id_images=input_id_images, num_inference_steps=_num_steps, guidance_scale=guidance_scale, start_merge_step = start_merge_step, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images
545
+ else:
546
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
547
+ total_results = id_images + total_results
548
+ yield total_results
549
+ real_images = []
550
+ write = False
551
+ for real_prompt in real_prompts:
552
+ setup_seed(seed_)
553
+ cur_step = 0
554
+ real_prompt = apply_style_positive(style_name, real_prompt)
555
+ if _model_type == "original":
556
+ real_images.append(pipe(real_prompt, num_inference_steps=_num_steps, guidance_scale=guidance_scale, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images[0])
557
+ elif _model_type == "Photomaker":
558
+ real_images.append(pipe(real_prompt, input_id_images=input_id_images, num_inference_steps=_num_steps, guidance_scale=guidance_scale, start_merge_step = start_merge_step, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images[0])
559
+ else:
560
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
561
+ total_results = [real_images[-1]] + total_results
562
+ yield total_results
563
+ if _comic_type != "No typesetting (default)":
564
+ captions= prompt_array.splitlines()
565
+ captions = [caption.replace("[NC]","") for caption in captions]
566
+ captions = [caption.split('#')[-1] if "#" in caption else caption for caption in captions]
567
+ from PIL import ImageFont
568
+ total_results = get_comic(id_images + real_images, _comic_type,captions= captions,font=ImageFont.truetype("./fonts/Inkfree.ttf", int(45))) + total_results
569
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
570
+ yield total_results
571
+
572
+
573
+
574
+ def array2string(arr):
575
+ stringtmp = ""
576
+ for i,part in enumerate(arr):
577
+ if i != len(arr)-1:
578
+ stringtmp += part +"\n"
579
+ else:
580
+ stringtmp += part
581
+
582
+ return stringtmp
583
+
584
+
585
+ #################################################
586
+ #################################################
587
+ ### define the interface
588
+ with gr.Blocks(css=css) as demo:
589
+ binary_matrixes = gr.State([])
590
+ color_layout = gr.State([])
591
+
592
+ # gr.Markdown(logo)
593
+ gr.Markdown(title)
594
+ gr.Markdown(description)
595
+
596
+ with gr.Row():
597
+ with gr.Group(elem_id="main-image"):
598
+ # button_run = gr.Button("generate id images ! 😺", elem_id="main_button", interactive=True)
599
+
600
+ prompts = []
601
+ colors = []
602
+ # with gr.Column(visible=False) as post_sketch:
603
+ # for n in range(MAX_COLORS):
604
+ # if n == 0 :
605
+ # with gr.Row(visible=False) as color_row[n]:
606
+ # colors.append(gr.Image(shape=(100, 100), label="background", type="pil", image_mode="RGB", width=100, height=100))
607
+ # prompts.append(gr.Textbox(label="Prompt for the background (white region)", value=""))
608
+ # else:
609
+ # with gr.Row(visible=False) as color_row[n]:
610
+ # colors.append(gr.Image(shape=(100, 100), label="segment "+str(n), type="pil", image_mode="RGB", width=100, height=100))
611
+ # prompts.append(gr.Textbox(label="Prompt for the segment "+str(n)))
612
+
613
+ # get_genprompt_run = gr.Button("(2) I've finished segment labeling ! 😺", elem_id="prompt_button", interactive=True)
614
+
615
+ with gr.Column(visible=True) as gen_prompt_vis:
616
+ sd_type = gr.Dropdown(choices=list(models_dict.keys()), value = "Unstable",label="sd_type", info="Select pretrained model")
617
+ model_type = gr.Radio(["Only Using Textual Description", "Using Ref Images"], label="model_type", value = "Only Using Textual Description", info="Control type of the Character")
618
+ with gr.Group(visible=False) as control_image_input:
619
+ files = gr.Files(
620
+ label="Drag (Select) 1 or more photos of your face",
621
+ file_types=["image"],
622
+ )
623
+ uploaded_files = gr.Gallery(label="Your images", visible=False, columns=5, rows=1, height=200)
624
+ with gr.Column(visible=False) as clear_button:
625
+ remove_and_reupload = gr.ClearButton(value="Remove and upload new ones", components=files, size="sm")
626
+ general_prompt = gr.Textbox(value='', label="(1) Textual Description for Character", interactive=True)
627
+ negative_prompt = gr.Textbox(value='', label="(2) Negative_prompt", interactive=True)
628
+ style = gr.Dropdown(label="Style template", choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME)
629
+ prompt_array = gr.Textbox(lines = 3,value='', label="(3) Comic Description (each line corresponds to a frame).", interactive=True)
630
+ with gr.Accordion("(4) Tune the hyperparameters", open=True):
631
+ #sa16_ = gr.Slider(label=" (The degree of Paired Attention at 16 x 16 self-attention layers) ", minimum=0, maximum=1., value=0.3, step=0.1)
632
+ sa32_ = gr.Slider(label=" (The degree of Paired Attention at 32 x 32 self-attention layers) ", minimum=0, maximum=1., value=0.7, step=0.1)
633
+ sa64_ = gr.Slider(label=" (The degree of Paired Attention at 64 x 64 self-attention layers) ", minimum=0, maximum=1., value=0.7, step=0.1)
634
+ id_length_ = gr.Slider(label= "Number of id images in total images" , minimum=2, maximum=4, value=2, step=1)
635
+ # total_length_ = gr.Slider(label= "Number of total images", minimum=1, maximum=20, value=1, step=1)
636
+ seed_ = gr.Slider(label="Seed", minimum=-1, maximum=MAX_SEED, value=0, step=1)
637
+ num_steps = gr.Slider(
638
+ label="Number of sample steps",
639
+ minimum=20,
640
+ maximum=100,
641
+ step=1,
642
+ value=50,
643
+ )
644
+ G_height = gr.Slider(
645
+ label="height",
646
+ minimum=256,
647
+ maximum=1024,
648
+ step=32,
649
+ value=768,
650
+ )
651
+ G_width = gr.Slider(
652
+ label="width",
653
+ minimum=256,
654
+ maximum=1024,
655
+ step=32,
656
+ value=768,
657
+ )
658
+ comic_type = gr.Radio(["No typesetting (default)", "Four Pannel", "Classic Comic Style"], value = "Classic Comic Style", label="Typesetting Style", info="Select the typesetting style ")
659
+ guidance_scale = gr.Slider(
660
+ label="Guidance scale",
661
+ minimum=0.1,
662
+ maximum=10.0,
663
+ step=0.1,
664
+ value=5,
665
+ )
666
+ style_strength_ratio = gr.Slider(
667
+ label="Style strength of Ref Image (%)",
668
+ minimum=15,
669
+ maximum=50,
670
+ step=1,
671
+ value=20,
672
+ visible=False
673
+ )
674
+ Ip_Adapter_Strength = gr.Slider(
675
+ label="Ip_Adapter_Strength",
676
+ minimum=0,
677
+ maximum=1,
678
+ step=0.1,
679
+ value=0.5,
680
+ visible=False
681
+ )
682
+ final_run_btn = gr.Button("Generate ! 😺")
683
+
684
+
685
+ with gr.Column():
686
+ out_image = gr.Gallery(label="Result", columns=2, height='auto')
687
+ generated_information = gr.Markdown(label="Generation Details", value="",visible=False)
688
+ gr.Markdown(version)
689
+ model_type.change(fn = change_visiale_by_model_type , inputs = model_type, outputs=[control_image_input,style_strength_ratio,Ip_Adapter_Strength])
690
+ files.upload(fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files])
691
+ remove_and_reupload.click(fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files])
692
+
693
+ final_run_btn.click(fn=set_text_unfinished, outputs = generated_information
694
+ ).then(process_generation, inputs=[sd_type,model_type,files, num_steps,style, Ip_Adapter_Strength,style_strength_ratio, guidance_scale, seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,G_height,G_width,comic_type], outputs=out_image
695
+ ).then(fn=set_text_finished,outputs = generated_information)
696
+
697
+
698
+ gr.Examples(
699
+ examples=[
700
+ [1,0.5,0.5,3,"a woman img, wearing a white T-shirt, blue loose hair",
701
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
702
+ array2string(["wake up in the bed",
703
+ "have breakfast",
704
+ "is on the road, go to company",
705
+ "work in the company",
706
+ "Take a walk next to the company at noon",
707
+ "lying in bed at night"]),
708
+ "Japanese Anime", "Using Ref Images",get_image_path_list('./examples/taylor'),768,768
709
+ ],
710
+ [0,0.5,0.5,2,"a man, wearing black jacket",
711
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
712
+ array2string(["wake up in the bed",
713
+ "have breakfast",
714
+ "is on the road, go to the company, close look",
715
+ "work in the company",
716
+ "laughing happily",
717
+ "lying in bed at night"
718
+ ]),
719
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
720
+ ],
721
+ [0,0.3,0.5,2,"a girl, wearing white shirt, black skirt, black tie, yellow hair",
722
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
723
+ array2string([
724
+ "at home #at home, began to go to drawing",
725
+ "sitting alone on a park bench.",
726
+ "reading a book on a park bench.",
727
+ "[NC]A squirrel approaches, peeking over the bench. ",
728
+ "look around in the park. # She looks around and enjoys the beauty of nature.",
729
+ "[NC]leaf falls from the tree, landing on the sketchbook.",
730
+ "picks up the leaf, examining its details closely.",
731
+ "starts sketching the leaf with intricate lines.",
732
+ "holds up the sketch drawing of the leaf.",
733
+ "[NC]The brown squirrel appear.",
734
+ "is very happy # She is very happy to see the squirrel again",
735
+ "[NC]The brown squirrel takes the cracker and scampers up a tree. # She gives the squirrel cracker",
736
+ "laughs and tucks the leaf into her book as a keepsake.",
737
+ "ready to leave.",]),
738
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
739
+ ]
740
+ ],
741
+ inputs=[seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,style,model_type,files,G_height,G_width],
742
+ # outputs=[post_sketch, binary_matrixes, *color_row, *colors, *prompts, gen_prompt_vis, general_prompt, seed_],
743
+ # run_on_click=True,
744
+ label='😺 Examples 😺',
745
+ )
746
+ gr.Markdown(article)
747
+
748
+ # demo.load(None, None, None, _js=load_js)
749
+
750
+ demo.launch(server_name="0.0.0.0", share = True if use_va else False)
cog.yaml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration for Cog ⚙️
2
+ # Reference: https://cog.run/yaml
3
+
4
+ build:
5
+ gpu: true
6
+ system_packages:
7
+ - "libgl1-mesa-glx"
8
+ - "libglib2.0-0"
9
+ python_version: "3.11"
10
+ python_packages:
11
+ - xformers==0.0.20
12
+ - torch==2.0.1
13
+ - torchvision==0.15.2
14
+ - diffusers==0.25.0
15
+ - transformers==4.36.2
16
+ - gradio==3.48.0
17
+ - accelerate
18
+ - safetensors
19
+ - peft
20
+ - Pillow==9.5.0
21
+ run:
22
+ - curl -o /usr/local/bin/pget -L "https://github.com/replicate/pget/releases/download/v0.6.0/pget_linux_x86_64" && chmod +x /usr/local/bin/pget
23
+ predict: "predict.py:Predictor"
config/models.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Juggernaut:
2
+ path: "https://huggingface.co/RunDiffusion/Juggernaut-XL-v9/blob/main/Juggernaut-XL_v9_RunDiffusionPhoto_v2.safetensors"
3
+ single_files: true ### if true, is a civitai model
4
+ use_safetensors: true
5
+
6
+ RealVision:
7
+ path: "SG161222/RealVisXL_V4.0"
8
+ single_files: false
9
+ use_safetensors: true
10
+
11
+ SDXL:
12
+ path: "stabilityai/stable-diffusion-xl-base-1.0"
13
+ single_files: false
14
+ use_safetensors: true
15
+
16
+ Unstable:
17
+ path: "stablediffusionapi/sdxl-unstable-diffusers-y"
18
+ single_files: false
19
+ use_safetensors: false
examples/Robert/images.jpeg ADDED
examples/lecun/yann-lecun2.png ADDED
examples/taylor/1-1.png ADDED
fonts/Inkfree.ttf ADDED
Binary file (41.2 kB). View file
 
gradio_app_sdxl_specific_id_low_vram.py ADDED
@@ -0,0 +1,807 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from email.policy import default
2
+ from this import d
3
+ from webbrowser import get
4
+ import gradio as gr
5
+ import numpy as np
6
+ import torch
7
+ import gc
8
+ from huggingface_hub import hf_hub_download
9
+ import requests
10
+ import random
11
+ import os
12
+ import sys
13
+ import pickle
14
+ from PIL import Image
15
+ from tqdm.auto import tqdm
16
+ from datetime import datetime
17
+ from utils.gradio_utils import is_torch2_available
18
+ if is_torch2_available():
19
+ from utils.gradio_utils import \
20
+ AttnProcessor2_0 as AttnProcessor
21
+ else:
22
+ from utils.gradio_utils import AttnProcessor
23
+
24
+ import diffusers
25
+ from diffusers import StableDiffusionXLPipeline
26
+ from utils import PhotoMakerStableDiffusionXLPipeline
27
+ from diffusers import DDIMScheduler
28
+ import torch.nn.functional as F
29
+ from utils.gradio_utils import cal_attn_mask_xl,cal_attn_indice_xl_effcient_memory
30
+ import copy
31
+ import os
32
+ from diffusers.utils import load_image
33
+ from utils.utils import get_comic
34
+ from utils.style_template import styles
35
+ image_encoder_path = "./data/models/ip_adapter/sdxl_models/image_encoder"
36
+ ip_ckpt = "./data/models/ip_adapter/sdxl_models/ip-adapter_sdxl_vit-h.bin"
37
+ os.environ["no_proxy"] = "localhost,127.0.0.1,::1"
38
+ STYLE_NAMES = list(styles.keys())
39
+ DEFAULT_STYLE_NAME = "Japanese Anime"
40
+ global models_dict
41
+ from utils.load_models_utils import get_models_dict,load_models
42
+ models_dict = get_models_dict()
43
+
44
+
45
+ photomaker_path = hf_hub_download(repo_id="TencentARC/PhotoMaker", filename="photomaker-v1.bin", repo_type="model")
46
+ MAX_SEED = np.iinfo(np.int32).max
47
+ def setup_seed(seed):
48
+ torch.manual_seed(seed)
49
+ torch.cuda.manual_seed_all(seed)
50
+ np.random.seed(seed)
51
+ random.seed(seed)
52
+ torch.backends.cudnn.deterministic = True
53
+ def set_text_unfinished():
54
+ return gr.update(visible=True, value="<h3>(Not Finished) Generating ··· The intermediate results will be shown.</h3>")
55
+ def set_text_finished():
56
+ return gr.update(visible=True, value="<h3>Generation Finished</h3>")
57
+ #################################################
58
+ def get_image_path_list(folder_name):
59
+ image_basename_list = os.listdir(folder_name)
60
+ image_path_list = sorted([os.path.join(folder_name, basename) for basename in image_basename_list])
61
+ return image_path_list
62
+
63
+ #################################################
64
+ class SpatialAttnProcessor2_0(torch.nn.Module):
65
+ r"""
66
+ Attention processor for IP-Adapater for PyTorch 2.0.
67
+ Args:
68
+ hidden_size (`int`):
69
+ The hidden size of the attention layer.
70
+ cross_attention_dim (`int`):
71
+ The number of channels in the `encoder_hidden_states`.
72
+ text_context_len (`int`, defaults to 77):
73
+ The context length of the text features.
74
+ scale (`float`, defaults to 1.0):
75
+ the weight scale of image prompt.
76
+ """
77
+
78
+ def __init__(self, hidden_size = None, cross_attention_dim=None,id_length = 4,device = "cuda",dtype = torch.float16):
79
+ super().__init__()
80
+ if not hasattr(F, "scaled_dot_product_attention"):
81
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
82
+ self.device = device
83
+ self.dtype = dtype
84
+ self.hidden_size = hidden_size
85
+ self.cross_attention_dim = cross_attention_dim
86
+ self.total_length = id_length + 1
87
+ self.id_length = id_length
88
+ self.id_bank = {}
89
+
90
+ def __call__(
91
+ self,
92
+ attn,
93
+ hidden_states,
94
+ encoder_hidden_states=None,
95
+ attention_mask=None,
96
+ temb=None):
97
+ # un_cond_hidden_states, cond_hidden_states = hidden_states.chunk(2)
98
+ # un_cond_hidden_states = self.__call2__(attn, un_cond_hidden_states,encoder_hidden_states,attention_mask,temb)
99
+ # 生成一个0到1之间的随机数
100
+ global total_count,attn_count,cur_step, indices1024,indices4096
101
+ global sa32, sa64
102
+ global write
103
+ global height,width
104
+ if attn_count == 0 and cur_step == 0:
105
+ indices1024,indices4096 = cal_attn_indice_xl_effcient_memory(self.total_length,self.id_length,sa32,sa64,height,width, device=self.device, dtype= self.dtype)
106
+ if write:
107
+ if hidden_states.shape[1] == (height//32) * (width//32):
108
+ indices = indices1024
109
+ else:
110
+ indices = indices4096
111
+ # print(f"white:{cur_step}")
112
+ total_batch_size,nums_token,channel = hidden_states.shape
113
+ img_nums = total_batch_size // 2
114
+ hidden_states = hidden_states.reshape(-1,img_nums,nums_token,channel)
115
+ self.id_bank[cur_step] = [hidden_states[:,img_ind,indices[img_ind],:].reshape(2,-1,channel).clone() for img_ind in range(img_nums)]
116
+ hidden_states = hidden_states.reshape(-1,nums_token,channel)
117
+ #self.id_bank[cur_step] = [hidden_states[:self.id_length].clone(), hidden_states[self.id_length:].clone()]
118
+ else:
119
+ #encoder_hidden_states = torch.cat((self.id_bank[cur_step][0].to(self.device),self.id_bank[cur_step][1].to(self.device)))
120
+ encoder_arr = [tensor.to(self.device) for tensor in self.id_bank[cur_step]]
121
+ # 判断随机数是否大于0.5
122
+ if cur_step <1:
123
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
124
+ else: # 256 1024 4096
125
+ random_number = random.random()
126
+ if cur_step <20:
127
+ rand_num = 0.3
128
+ else:
129
+ rand_num = 0.1
130
+ # print(f"hidden state shape {hidden_states.shape[1]}")
131
+ if random_number > rand_num:
132
+ if hidden_states.shape[1] == (height//32) * (width//32):
133
+ indices = indices1024
134
+ else:
135
+ indices = indices4096
136
+ # print("before attention",hidden_states.shape,attention_mask.shape,encoder_hidden_states.shape if encoder_hidden_states is not None else "None")
137
+ if write:
138
+ total_batch_size,nums_token,channel = hidden_states.shape
139
+ img_nums = total_batch_size // 2
140
+ hidden_states = hidden_states.reshape(-1,img_nums,nums_token,channel)
141
+ encoder_arr = [hidden_states[:,img_ind,indices[img_ind],:].reshape(2,-1,channel) for img_ind in range(img_nums)]
142
+ for img_ind in range(img_nums):
143
+ encoder_hidden_states_tmp = torch.cat(encoder_arr[0:img_ind] + encoder_arr[img_ind+1:] + [hidden_states[:,img_ind,:,:]],dim=1)
144
+ hidden_states[:,img_ind,:,:] = self.__call2__(attn, hidden_states[:,img_ind,:,:],encoder_hidden_states_tmp,None,temb)
145
+ else:
146
+ _,nums_token,channel = hidden_states.shape
147
+ # img_nums = total_batch_size // 2
148
+ # encoder_hidden_states = encoder_hidden_states.reshape(-1,img_nums,nums_token,channel)
149
+ hidden_states = hidden_states.reshape(2,-1,nums_token,channel)
150
+ # print(len(indices))
151
+ # encoder_arr = [encoder_hidden_states[:,img_ind,indices[img_ind],:].reshape(2,-1,channel) for img_ind in range(img_nums)]
152
+ encoder_hidden_states_tmp = torch.cat(encoder_arr+[hidden_states[:,0,:,:]],dim=1)
153
+ hidden_states[:,0,:,:] = self.__call2__(attn, hidden_states[:,0,:,:],encoder_hidden_states_tmp,None,temb)
154
+ hidden_states = hidden_states.reshape(-1,nums_token,channel)
155
+ else:
156
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
157
+ attn_count +=1
158
+ if attn_count == total_count:
159
+ attn_count = 0
160
+ cur_step += 1
161
+ indices1024,indices4096 = cal_attn_indice_xl_effcient_memory(self.total_length,self.id_length,sa32,sa64,height,width, device=self.device, dtype= self.dtype)
162
+
163
+ return hidden_states
164
+ def __call1__(
165
+ self,
166
+ attn,
167
+ hidden_states,
168
+ encoder_hidden_states=None,
169
+ attention_mask=None,
170
+ temb=None,
171
+ attn_indices = None,
172
+ ):
173
+ # print("hidden state shape",hidden_states.shape,self.id_length)
174
+ residual = hidden_states
175
+ # if encoder_hidden_states is not None:
176
+ # raise Exception("not implement")
177
+ if attn.spatial_norm is not None:
178
+ hidden_states = attn.spatial_norm(hidden_states, temb)
179
+ input_ndim = hidden_states.ndim
180
+
181
+ if input_ndim == 4:
182
+ total_batch_size, channel, height, width = hidden_states.shape
183
+ hidden_states = hidden_states.view(total_batch_size, channel, height * width).transpose(1, 2)
184
+ total_batch_size,nums_token,channel = hidden_states.shape
185
+ img_nums = total_batch_size//2
186
+ hidden_states = hidden_states.view(-1,img_nums,nums_token,channel).reshape(-1,img_nums * nums_token,channel)
187
+ batch_size, sequence_length, _ = hidden_states.shape
188
+
189
+ if attn.group_norm is not None:
190
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
191
+
192
+ query = attn.to_q(hidden_states)
193
+
194
+ if encoder_hidden_states is None:
195
+ encoder_hidden_states = hidden_states # B, N, C
196
+ else:
197
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,nums_token,channel).reshape(-1,(self.id_length+1) * nums_token,channel)
198
+
199
+ key = attn.to_k(encoder_hidden_states)
200
+ value = attn.to_v(encoder_hidden_states)
201
+
202
+
203
+ inner_dim = key.shape[-1]
204
+ head_dim = inner_dim // attn.heads
205
+
206
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
207
+
208
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
209
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
210
+ # print(key.shape,value.shape,query.shape,attention_mask.shape)
211
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
212
+ # TODO: add support for attn.scale when we move to Torch 2.1
213
+ #print(query.shape,key.shape,value.shape,attention_mask.shape)
214
+ hidden_states = F.scaled_dot_product_attention(
215
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
216
+ )
217
+
218
+ hidden_states = hidden_states.transpose(1, 2).reshape(total_batch_size, -1, attn.heads * head_dim)
219
+ hidden_states = hidden_states.to(query.dtype)
220
+
221
+
222
+
223
+ # linear proj
224
+ hidden_states = attn.to_out[0](hidden_states)
225
+ # dropout
226
+ hidden_states = attn.to_out[1](hidden_states)
227
+
228
+ # if input_ndim == 4:
229
+ # tile_hidden_states = tile_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
230
+
231
+ # if attn.residual_connection:
232
+ # tile_hidden_states = tile_hidden_states + residual
233
+
234
+ if input_ndim == 4:
235
+ hidden_states = hidden_states.transpose(-1, -2).reshape(total_batch_size, channel, height, width)
236
+ if attn.residual_connection:
237
+ hidden_states = hidden_states + residual
238
+ hidden_states = hidden_states / attn.rescale_output_factor
239
+ # print(hidden_states.shape)
240
+ return hidden_states
241
+ def __call2__(
242
+ self,
243
+ attn,
244
+ hidden_states,
245
+ encoder_hidden_states=None,
246
+ attention_mask=None,
247
+ temb=None):
248
+ residual = hidden_states
249
+
250
+ if attn.spatial_norm is not None:
251
+ hidden_states = attn.spatial_norm(hidden_states, temb)
252
+
253
+ input_ndim = hidden_states.ndim
254
+
255
+ if input_ndim == 4:
256
+ batch_size, channel, height, width = hidden_states.shape
257
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
258
+
259
+ batch_size, sequence_length, channel = (
260
+ hidden_states.shape
261
+ )
262
+ # print(hidden_states.shape)
263
+ if attention_mask is not None:
264
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
265
+ # scaled_dot_product_attention expects attention_mask shape to be
266
+ # (batch, heads, source_length, target_length)
267
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
268
+
269
+ if attn.group_norm is not None:
270
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
271
+
272
+ query = attn.to_q(hidden_states)
273
+
274
+ if encoder_hidden_states is None:
275
+ encoder_hidden_states = hidden_states # B, N, C
276
+ # else:
277
+ # encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,sequence_length,channel).reshape(-1,(self.id_length+1) * sequence_length,channel)
278
+
279
+ key = attn.to_k(encoder_hidden_states)
280
+ value = attn.to_v(encoder_hidden_states)
281
+
282
+ inner_dim = key.shape[-1]
283
+ head_dim = inner_dim // attn.heads
284
+
285
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
286
+
287
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
288
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
289
+
290
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
291
+ # TODO: add support for attn.scale when we move to Torch 2.1
292
+ hidden_states = F.scaled_dot_product_attention(
293
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
294
+ )
295
+
296
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
297
+ hidden_states = hidden_states.to(query.dtype)
298
+
299
+ # linear proj
300
+ hidden_states = attn.to_out[0](hidden_states)
301
+ # dropout
302
+ hidden_states = attn.to_out[1](hidden_states)
303
+
304
+ if input_ndim == 4:
305
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
306
+
307
+ if attn.residual_connection:
308
+ hidden_states = hidden_states + residual
309
+
310
+ hidden_states = hidden_states / attn.rescale_output_factor
311
+
312
+ return hidden_states
313
+
314
+ def set_attention_processor(unet,id_length,is_ipadapter = False):
315
+ global attn_procs
316
+ attn_procs = {}
317
+ for name in unet.attn_processors.keys():
318
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
319
+ if name.startswith("mid_block"):
320
+ hidden_size = unet.config.block_out_channels[-1]
321
+ elif name.startswith("up_blocks"):
322
+ block_id = int(name[len("up_blocks.")])
323
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
324
+ elif name.startswith("down_blocks"):
325
+ block_id = int(name[len("down_blocks.")])
326
+ hidden_size = unet.config.block_out_channels[block_id]
327
+ if cross_attention_dim is None:
328
+ if name.startswith("up_blocks") :
329
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length = id_length)
330
+ else:
331
+ attn_procs[name] = AttnProcessor()
332
+ else:
333
+ if is_ipadapter:
334
+ attn_procs[name] = IPAttnProcessor2_0(
335
+ hidden_size=hidden_size,
336
+ cross_attention_dim=cross_attention_dim,
337
+ scale=1,
338
+ num_tokens=4,
339
+ ).to(unet.device, dtype=torch.float16)
340
+ else:
341
+ attn_procs[name] = AttnProcessor()
342
+
343
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
344
+ #################################################
345
+ #################################################
346
+ canvas_html = "<div id='canvas-root' style='max-width:400px; margin: 0 auto'></div>"
347
+ load_js = """
348
+ async () => {
349
+ const url = "https://huggingface.co/datasets/radames/gradio-components/raw/main/sketch-canvas.js"
350
+ fetch(url)
351
+ .then(res => res.text())
352
+ .then(text => {
353
+ const script = document.createElement('script');
354
+ script.type = "module"
355
+ script.src = URL.createObjectURL(new Blob([text], { type: 'application/javascript' }));
356
+ document.head.appendChild(script);
357
+ });
358
+ }
359
+ """
360
+
361
+ get_js_colors = """
362
+ async (canvasData) => {
363
+ const canvasEl = document.getElementById("canvas-root");
364
+ return [canvasEl._data]
365
+ }
366
+ """
367
+
368
+ css = '''
369
+ #color-bg{display:flex;justify-content: center;align-items: center;}
370
+ .color-bg-item{width: 100%; height: 32px}
371
+ #main_button{width:100%}
372
+ <style>
373
+ '''
374
+
375
+
376
+ #################################################
377
+ title = r"""
378
+ <h1 align="center">StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</h1>
379
+ """
380
+
381
+ description = r"""
382
+ <b>Official 🤗 Gradio demo</b> for <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'><b>StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</b></a>.<br>
383
+ ❗️❗️❗️[<b>Important</b>] Personalization steps:<br>
384
+ 1️⃣ Enter a Textual Description for Character, if you add the Ref-Image, making sure to <b>follow the class word</b> you want to customize with the <b>trigger word</b>: `img`, such as: `man img` or `woman img` or `girl img`.<br>
385
+ 2️⃣ Enter the prompt array, each line corrsponds to one generated image.<br>
386
+ 3️⃣ Choose your preferred style template.<br>
387
+ 4️⃣ Click the <b>Submit</b> button to start customizing.
388
+ """
389
+
390
+ article = r"""
391
+
392
+ If StoryDiffusion is helpful, please help to ⭐ the <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'>Github Repo</a>. Thanks!
393
+ [![GitHub Stars](https://img.shields.io/github/stars/HVision-NKU/StoryDiffusion?style=social)](https://github.com/HVision-NKU/StoryDiffusion)
394
+ ---
395
+ 📝 **Citation**
396
+ <br>
397
+ If our work is useful for your research, please consider citing:
398
+
399
+ ```bibtex
400
+ @article{Zhou2024storydiffusion,
401
+ title={StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation},
402
+ author={Zhou, Yupeng and Zhou, Daquan and Cheng, Ming-Ming and Feng, Jiashi and Hou, Qibin},
403
+ year={2024}
404
+ }
405
+ ```
406
+ 📋 **License**
407
+ <br>
408
+ The Contents you create are under Apache-2.0 LICENSE. The Code are under Attribution-NonCommercial 4.0 International.
409
+
410
+ 📧 **Contact**
411
+ <br>
412
+ If you have any questions, please feel free to reach me out at <b>ypzhousdu@gmail.com</b>.
413
+ """
414
+ version = r"""
415
+ <h3 align="center">StoryDiffusion Version 0.01 (test version)</h3>
416
+
417
+ <h5 >1. Support image ref image. (Cartoon Ref image is not support now)</h5>
418
+ <h5 >2. Support Typesetting Style and Captioning.(By default, the prompt is used as the caption for each image. If you need to change the caption, add a # at the end of each line. Only the part after the # will be added as a caption to the image.)</h5>
419
+ <h5 >3. [NC]symbol (The [NC] symbol is used as a flag to indicate that no characters should be present in the generated scene images. If you want do that, prepend the "[NC]" at the beginning of the line. For example, to generate a scene of falling leaves without any character, write: "[NC] The leaves are falling.")</h5>
420
+ <h5 align="center">Tips: </h4>
421
+ """
422
+ #################################################
423
+ global attn_count, total_count, id_length, total_length,cur_step, cur_model_type
424
+ global write
425
+ global sa32, sa64
426
+ global height,width
427
+ attn_count = 0
428
+ total_count = 0
429
+ cur_step = 0
430
+ id_length = 4
431
+ total_length = 5
432
+ cur_model_type = ""
433
+ device="cuda"
434
+ global attn_procs,unet
435
+ attn_procs = {}
436
+ ###
437
+ write = False
438
+ ###
439
+ sa32 = 0.5
440
+ sa64 = 0.5
441
+ height = 768
442
+ width = 768
443
+ ###
444
+ global pipe
445
+ global sd_model_path
446
+ pipe = None
447
+ sd_model_path = models_dict["Unstable"]["path"] #"SG161222/RealVisXL_V4.0"
448
+ ### LOAD Stable Diffusion Pipeline
449
+ pipe = StableDiffusionXLPipeline.from_pretrained(sd_model_path, torch_dtype=torch.float16, use_safetensors = False)
450
+ pipe = pipe.to(device)
451
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
452
+ # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
453
+ pipe.scheduler.set_timesteps(50)
454
+ pipe.enable_vae_slicing()
455
+ pipe.enable_model_cpu_offload()
456
+ unet = pipe.unet
457
+ cur_model_type = "Unstable"+"-"+"original"
458
+ ### Insert PairedAttention
459
+ for name in unet.attn_processors.keys():
460
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
461
+ if name.startswith("mid_block"):
462
+ hidden_size = unet.config.block_out_channels[-1]
463
+ elif name.startswith("up_blocks"):
464
+ block_id = int(name[len("up_blocks.")])
465
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
466
+ elif name.startswith("down_blocks"):
467
+ block_id = int(name[len("down_blocks.")])
468
+ hidden_size = unet.config.block_out_channels[block_id]
469
+ if cross_attention_dim is None and (name.startswith("up_blocks") ) :
470
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length = id_length)
471
+ total_count +=1
472
+ else:
473
+ attn_procs[name] = AttnProcessor()
474
+ print("successsfully load paired self-attention")
475
+ print(f"number of the processor : {total_count}")
476
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
477
+ global mask1024,mask4096
478
+ mask1024, mask4096 = cal_attn_mask_xl(total_length,id_length,sa32,sa64,height,width,device=device,dtype= torch.float16)
479
+
480
+ ######### Gradio Fuction #############
481
+
482
+ def swap_to_gallery(images):
483
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
484
+
485
+ def upload_example_to_gallery(images, prompt, style, negative_prompt):
486
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
487
+
488
+ def remove_back_to_files():
489
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
490
+
491
+ def remove_tips():
492
+ return gr.update(visible=False)
493
+
494
+ def apply_style_positive(style_name: str, positive: str):
495
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
496
+ return p.replace("{prompt}", positive)
497
+
498
+ def apply_style(style_name: str, positives: list, negative: str = ""):
499
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
500
+ return [p.replace("{prompt}", positive) for positive in positives], n + ' ' + negative
501
+
502
+ def change_visiale_by_model_type(_model_type):
503
+ if _model_type == "Only Using Textual Description":
504
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
505
+ elif _model_type == "Using Ref Images":
506
+ return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False)
507
+ else:
508
+ raise ValueError("Invalid model type",_model_type)
509
+
510
+
511
+ ######### Image Generation ##############
512
+ def process_generation(_sd_type,_model_type,_upload_images, _num_steps,style_name, _Ip_Adapter_Strength ,_style_strength_ratio, guidance_scale, seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt,prompt_array,G_height,G_width,_comic_type, font_choice): # Corrected font_choice usage
513
+ _model_type = "Photomaker" if _model_type == "Using Ref Images" else "original"
514
+ if _model_type == "Photomaker" and "img" not in general_prompt:
515
+ raise gr.Error("Please add the triger word \" img \" behind the class word you want to customize, such as: man img or woman img")
516
+ if _upload_images is None and _model_type != "original":
517
+ raise gr.Error(f"Cannot find any input face image!")
518
+ global sa32, sa64,id_length,total_length,attn_procs,unet,cur_model_type
519
+ global write
520
+ global cur_step,attn_count
521
+ global height,width
522
+ height = G_height
523
+ width = G_width
524
+ global pipe
525
+ global sd_model_path,models_dict
526
+ sd_model_path = models_dict[_sd_type]
527
+ use_safe_tensor = True
528
+ for attn_processor in pipe.unet.attn_processors.values():
529
+ if isinstance(attn_processor, SpatialAttnProcessor2_0):
530
+ for values in attn_processor.id_bank.values():
531
+ del values
532
+ attn_processor.id_bank = {}
533
+ attn_processor.id_length = id_length
534
+ attn_processor.total_length = id_length + 1
535
+ gc.collect()
536
+ if cur_model_type != _sd_type+"-"+_model_type:
537
+ # apply the style template
538
+ ##### load pipe
539
+ del pipe
540
+ gc.collect()
541
+ torch.cuda.empty_cache()
542
+ model_info = models_dict[_sd_type]
543
+ model_info["model_type"] = _model_type
544
+ pipe = load_models(model_info,device=device,photomaker_path=photomaker_path)
545
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
546
+ ##### ########################
547
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
548
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
549
+ cur_model_type = _sd_type+"-"+_model_type
550
+ pipe.enable_vae_slicing()
551
+ pipe.enable_model_cpu_offload()
552
+ else:
553
+ unet = pipe.unet
554
+ # unet.set_attn_processor(copy.deepcopy(attn_procs))
555
+ if _model_type != "original":
556
+ input_id_images = []
557
+ for img in _upload_images:
558
+ print(img)
559
+ input_id_images.append(load_image(img))
560
+ prompts = prompt_array.splitlines()
561
+ start_merge_step = int(float(_style_strength_ratio) / 100 * _num_steps)
562
+ if start_merge_step > 30:
563
+ start_merge_step = 30
564
+ print(f"start_merge_step:{start_merge_step}")
565
+ generator = torch.Generator(device="cuda").manual_seed(seed_)
566
+ sa32, sa64 = sa32_, sa64_
567
+ id_length = id_length_
568
+ clipped_prompts = prompts[:]
569
+ nc_indexs = []
570
+ for ind,prompt in enumerate(clipped_prompts):
571
+ if "[NC]" in prompt:
572
+ nc_indexs.append(ind)
573
+ if ind < id_length:
574
+ raise gr.Error(f"The first {id_length} row is id prompts, cannot use [NC]!")
575
+ prompts = [general_prompt + "," + prompt if "[NC]" not in prompt else prompt.replace("[NC]","") for prompt in clipped_prompts]
576
+ prompts = [prompt.rpartition('#')[0] if "#" in prompt else prompt for prompt in prompts]
577
+ print(prompts)
578
+ id_prompts = prompts[:id_length]
579
+ real_prompts = prompts[id_length:]
580
+ torch.cuda.empty_cache()
581
+ write = True
582
+ cur_step = 0
583
+
584
+ attn_count = 0
585
+ id_prompts, negative_prompt = apply_style(style_name, id_prompts, negative_prompt)
586
+ setup_seed(seed_)
587
+ total_results = []
588
+ if _model_type == "original":
589
+ id_images = pipe(id_prompts, num_inference_steps=_num_steps, guidance_scale=guidance_scale, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images
590
+ elif _model_type == "Photomaker":
591
+ id_images = pipe(id_prompts,input_id_images=input_id_images, num_inference_steps=_num_steps, guidance_scale=guidance_scale, start_merge_step = start_merge_step, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images
592
+ else:
593
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
594
+ total_results = id_images + total_results
595
+ yield total_results
596
+ real_images = []
597
+ write = False
598
+ for ind,real_prompt in enumerate(real_prompts):
599
+ setup_seed(seed_)
600
+ cur_step = 0
601
+ real_prompt = apply_style_positive(style_name, real_prompt)
602
+ if _model_type == "original":
603
+ real_images.append(pipe(real_prompt, num_inference_steps=_num_steps, guidance_scale=guidance_scale, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images[0])
604
+ elif _model_type == "Photomaker":
605
+ real_images.append(pipe(real_prompt, input_id_images=input_id_images, num_inference_steps=_num_steps, guidance_scale=guidance_scale, start_merge_step = start_merge_step, height = height, width = width,negative_prompt = negative_prompt,generator = generator,nc_flag = True if ind+id_length in nc_indexs else False).images[0])
606
+ else:
607
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
608
+ total_results = [real_images[-1]] + total_results
609
+ yield total_results
610
+ if _comic_type != "No typesetting (default)":
611
+ captions= prompt_array.splitlines()
612
+ captions = [caption.replace("[NC]","") for caption in captions]
613
+ captions = [caption.split('#')[-1] if "#" in caption else caption for caption in captions]
614
+ from PIL import ImageFont
615
+
616
+ font_path = os.path.join("fonts", font_choice)
617
+ print(f"Attempting to load font from path: {font_path}")
618
+ font = ImageFont.truetype(font_path, int(45))
619
+ total_results = get_comic(id_images + real_images, _comic_type, captions=captions, font=font) + total_results
620
+ yield total_results
621
+
622
+
623
+
624
+ def array2string(arr):
625
+ stringtmp = ""
626
+ for i,part in enumerate(arr):
627
+ if i != len(arr)-1:
628
+ stringtmp += part +"\n"
629
+ else:
630
+ stringtmp += part
631
+
632
+ return stringtmp
633
+
634
+
635
+ #################################################
636
+ #################################################
637
+ ### define the interface
638
+ with gr.Blocks(css=css) as demo:
639
+ binary_matrixes = gr.State([])
640
+ color_layout = gr.State([])
641
+
642
+ # gr.Markdown(logo)
643
+ gr.Markdown(title)
644
+ gr.Markdown(description)
645
+
646
+ with gr.Row():
647
+ with gr.Group(elem_id="main-image"):
648
+
649
+ prompts = []
650
+ colors = []
651
+
652
+ with gr.Column(visible=True) as gen_prompt_vis:
653
+ sd_type = gr.Dropdown(choices=list(models_dict.keys()), value = "Unstable",label="sd_type", info="Select pretrained model")
654
+ model_type = gr.Radio(["Only Using Textual Description", "Using Ref Images"], label="model_type", value = "Only Using Textual Description", info="Control type of the Character")
655
+ with gr.Group(visible=False) as control_image_input:
656
+ files = gr.Files(
657
+ label="Drag (Select) 1 or more photos of your face",
658
+ file_types=["image"],
659
+ )
660
+ uploaded_files = gr.Gallery(label="Your images", visible=False, columns=5, rows=1, height=200)
661
+ with gr.Column(visible=False) as clear_button:
662
+ remove_and_reupload = gr.ClearButton(value="Remove and upload new ones", components=files, size="sm")
663
+ general_prompt = gr.Textbox(value='', label="(1) Textual Description for Character", interactive=True)
664
+ negative_prompt = gr.Textbox(value='', label="(2) Negative_prompt", interactive=True)
665
+ style = gr.Dropdown(label="Style template", choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME)
666
+ prompt_array = gr.Textbox(lines = 3,value='', label="(3) Comic Description (each line corresponds to a frame).", interactive=True)
667
+ with gr.Accordion("(4) Tune the hyperparameters", open=True):
668
+ font_choice = gr.Dropdown(label="Select Font", choices=[f for f in os.listdir("./fonts") if f.endswith('.ttf')], value="Inkfree.ttf", info="Select font for the final slide.", interactive=True)
669
+ sa32_ = gr.Slider(label=" (The degree of Paired Attention at 32 x 32 self-attention layers) ", minimum=0, maximum=1., value=0.5, step=0.1)
670
+ sa64_ = gr.Slider(label=" (The degree of Paired Attention at 64 x 64 self-attention layers) ", minimum=0, maximum=1., value=0.5, step=0.1)
671
+ id_length_ = gr.Slider(label= "Number of id images in total images" , minimum=2, maximum=4, value=2, step=1)
672
+ seed_ = gr.Slider(label="Seed", minimum=-1, maximum=MAX_SEED, value=0, step=1)
673
+ num_steps = gr.Slider(
674
+ label="Number of sample steps",
675
+ minimum=20,
676
+ maximum=100,
677
+ step=1,
678
+ value=50,
679
+ )
680
+ G_height = gr.Slider(
681
+ label="height",
682
+ minimum=256,
683
+ maximum=1024,
684
+ step=32,
685
+ value=768,
686
+ )
687
+ G_width = gr.Slider(
688
+ label="width",
689
+ minimum=256,
690
+ maximum=1024,
691
+ step=32,
692
+ value=768,
693
+ )
694
+ comic_type = gr.Radio(["No typesetting (default)", "Four Pannel", "Classic Comic Style"], value = "Classic Comic Style", label="Typesetting Style", info="Select the typesetting style ")
695
+ guidance_scale = gr.Slider(
696
+ label="Guidance scale",
697
+ minimum=0.1,
698
+ maximum=10.0,
699
+ step=0.1,
700
+ value=5,
701
+ )
702
+ style_strength_ratio = gr.Slider(
703
+ label="Style strength of Ref Image (%)",
704
+ minimum=15,
705
+ maximum=50,
706
+ step=1,
707
+ value=20,
708
+ visible=False
709
+ )
710
+ Ip_Adapter_Strength = gr.Slider(
711
+ label="Ip_Adapter_Strength",
712
+ minimum=0,
713
+ maximum=1,
714
+ step=0.1,
715
+ value=0.5,
716
+ visible=False
717
+ )
718
+ final_run_btn = gr.Button("Generate ! 😺")
719
+
720
+
721
+ with gr.Column():
722
+ out_image = gr.Gallery(label="Result", columns=2, height='auto')
723
+ generated_information = gr.Markdown(label="Generation Details", value="",visible=False)
724
+ gr.Markdown(version)
725
+ model_type.change(fn = change_visiale_by_model_type , inputs = model_type, outputs=[control_image_input,style_strength_ratio,Ip_Adapter_Strength])
726
+ files.upload(fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files])
727
+ remove_and_reupload.click(fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files])
728
+
729
+ final_run_btn.click(fn=set_text_unfinished, outputs=generated_information
730
+ ).then(process_generation, inputs=[sd_type,model_type,files, num_steps,style, Ip_Adapter_Strength,style_strength_ratio, guidance_scale, seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,G_height,G_width,comic_type, font_choice], outputs=out_image
731
+ ).then(fn=set_text_finished,outputs=generated_information)
732
+
733
+
734
+ gr.Examples(
735
+ examples=[
736
+ [0,0.5,0.5,2,"a man, wearing black suit",
737
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
738
+ array2string(["at home, read new paper #at home, The newspaper says there is a treasure house in the forest.",
739
+ "on the road, near the forest",
740
+ "[NC] The car on the road, near the forest #He drives to the forest in search of treasure.",
741
+ "[NC]A tiger appeared in the forest, at night ",
742
+ "very frightened, open mouth, in the forest, at night",
743
+ "running very fast, in the forest, at night",
744
+ "[NC] A house in the forest, at night #Suddenly, he discovers the treasure house!",
745
+ "in the house filled with treasure, laughing, at night #He is overjoyed inside the house."
746
+ ]),
747
+ "Comic book","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
748
+ ],
749
+ [0,0.5,0.5,2,"a man, wearing black suit",
750
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
751
+ array2string(["at home, read new paper #at home, The newspaper says there is a treasure house in the forest.",
752
+ "on the road, near the forest",
753
+ "[NC] The car on the road, near the forest #He drives to the forest in search of treasure.",
754
+ "[NC]A tiger appeared in the forest, at night ",
755
+ "very frightened, open mouth, in the forest, at night",
756
+ "running very fast, in the forest, at night",
757
+ "[NC] A house in the forest, at night #Suddenly, he discovers the treasure house!",
758
+ "in the house filled with treasure, laughing, at night #He is overjoyed inside the house."
759
+ ]),
760
+ "Comic book","Using Ref Images",get_image_path_list('./examples/Robert'),1024,1024
761
+ ],
762
+ [1,0.5,0.5,3,"a woman img, wearing a white T-shirt, blue loose hair",
763
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
764
+ array2string(["wake up in the bed",
765
+ "have breakfast",
766
+ "is on the road, go to company",
767
+ "work in the company",
768
+ "Take a walk next to the company at noon",
769
+ "lying in bed at night"]),
770
+ "Japanese Anime", "Using Ref Images",get_image_path_list('./examples/taylor'),768,768
771
+ ],
772
+ [0,0.5,0.5,3,"a man, wearing black jacket",
773
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
774
+ array2string(["wake up in the bed",
775
+ "have breakfast",
776
+ "is on the road, go to the company, close look",
777
+ "work in the company",
778
+ "laughing happily",
779
+ "lying in bed at night"
780
+ ]),
781
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
782
+ ],
783
+ [0,0.3,0.5,3,"a girl, wearing white shirt, black skirt, black tie, yellow hair",
784
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
785
+ array2string([
786
+ "at home #at home, began to go to drawing",
787
+ "sitting alone on a park bench.",
788
+ "reading a book on a park bench.",
789
+ "[NC]A squirrel approaches, peeking over the bench. ",
790
+ "look around in the park. # She looks around and enjoys the beauty of nature.",
791
+ "[NC]leaf falls from the tree, landing on the sketchbook.",
792
+ "picks up the leaf, examining its details closely.",
793
+ "[NC]The brown squirrel appear.",
794
+ "is very happy # She is very happy to see the squirrel again",
795
+ "[NC]The brown squirrel takes the cracker and scampers up a tree. # She gives the squirrel cracker"]),
796
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
797
+ ]
798
+ ],
799
+ inputs=[seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,style,model_type,files,G_height,G_width],
800
+ # outputs=[post_sketch, binary_matrixes, *color_row, *colors, *prompts, gen_prompt_vis, general_prompt, seed_],
801
+ # run_on_click=True,
802
+ label='😺 Examples 😺',
803
+ )
804
+ gr.Markdown(article)
805
+
806
+
807
+ demo.launch(server_name="0.0.0.0", share = False)
gradio_app_sdxl_specific_id_mps.py ADDED
@@ -0,0 +1,767 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from email.policy import default
2
+ from this import d
3
+ import gradio as gr
4
+ import numpy as np
5
+ import torch
6
+ import gc
7
+ from huggingface_hub import hf_hub_download
8
+ import requests
9
+ import random
10
+ import os
11
+ import sys
12
+ import pickle
13
+ from PIL import Image
14
+ from tqdm.auto import tqdm
15
+ from datetime import datetime
16
+ from utils.gradio_utils import is_torch2_available
17
+ if is_torch2_available():
18
+ from utils.gradio_utils import \
19
+ AttnProcessor2_0 as AttnProcessor
20
+ else:
21
+ from utils.gradio_utils import AttnProcessor
22
+
23
+ import diffusers
24
+ from diffusers import StableDiffusionXLPipeline
25
+ from utils import PhotoMakerStableDiffusionXLPipeline
26
+ from diffusers import DDIMScheduler
27
+ import torch.nn.functional as F
28
+ from utils.gradio_utils import cal_attn_mask_xl
29
+ import copy
30
+ import os
31
+ from diffusers.utils import load_image
32
+ from utils.utils import get_comic
33
+ from utils.style_template import styles
34
+ import torch.nn.functional as F
35
+ image_encoder_path = "./data/models/ip_adapter/sdxl_models/image_encoder"
36
+ ip_ckpt = "./data/models/ip_adapter/sdxl_models/ip-adapter_sdxl_vit-h.bin"
37
+ os.environ["no_proxy"] = "localhost,127.0.0.1,::1"
38
+ STYLE_NAMES = list(styles.keys())
39
+ DEFAULT_STYLE_NAME = "Japanese Anime"
40
+ global models_dict
41
+ use_va = False
42
+ models_dict = {
43
+ # "Juggernaut": "RunDiffusion/Juggernaut-XL-v8",
44
+ "RealVision": "SG161222/RealVisXL_V4.0" ,
45
+ "SDXL": "stabilityai/stable-diffusion-xl-base-1.0" ,
46
+ "Unstable": "stablediffusionapi/sdxl-unstable-diffusers-y"
47
+ }
48
+ photomaker_path = hf_hub_download(repo_id="TencentARC/PhotoMaker", filename="photomaker-v1.bin", repo_type="model")
49
+ MAX_SEED = np.iinfo(np.int32).max
50
+ def setup_seed(seed):
51
+ torch.manual_seed(seed)
52
+ #torch.cuda.manual_seed_all(seed)
53
+ np.random.seed(seed)
54
+ random.seed(seed)
55
+ torch.backends.cudnn.deterministic = True
56
+ def set_text_unfinished():
57
+ return gr.update(visible=True, value="<h3>(Not Finished) Generating ··· The intermediate results will be shown.</h3>")
58
+ def set_text_finished():
59
+ return gr.update(visible=True, value="<h3>Generation Finished</h3>")
60
+ #################################################
61
+ def get_image_path_list(folder_name):
62
+ image_basename_list = os.listdir(folder_name)
63
+ image_path_list = sorted([os.path.join(folder_name, basename) for basename in image_basename_list])
64
+ return image_path_list
65
+
66
+ #################################################
67
+ class SpatialAttnProcessor2_0(torch.nn.Module):
68
+ r"""
69
+ Attention processor for IP-Adapater for PyTorch 2.0.
70
+ Args:
71
+ hidden_size (`int`):
72
+ The hidden size of the attention layer.
73
+ cross_attention_dim (`int`):
74
+ The number of channels in the `encoder_hidden_states`.
75
+ text_context_len (`int`, defaults to 77):
76
+ The context length of the text features.
77
+ scale (`float`, defaults to 1.0):
78
+ the weight scale of image prompt.
79
+ """
80
+
81
+ def __init__(self, hidden_size=None, cross_attention_dim=None, id_length=4, device="mps", dtype=torch.float32):
82
+ super().__init__()
83
+ if not hasattr(F, "scaled_dot_product_attention"):
84
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
85
+ self.device = device
86
+ self.dtype = dtype
87
+ self.hidden_size = hidden_size
88
+ self.cross_attention_dim = cross_attention_dim
89
+ self.total_length = id_length + 1
90
+ self.id_length = id_length
91
+ self.id_bank = {}
92
+
93
+ def __call__(
94
+ self,
95
+ attn,
96
+ hidden_states,
97
+ encoder_hidden_states=None,
98
+ attention_mask=None,
99
+ temb=None):
100
+ # un_cond_hidden_states, cond_hidden_states = hidden_states.chunk(2)
101
+ # un_cond_hidden_states = self.__call2__(attn, un_cond_hidden_states,encoder_hidden_states,attention_mask,temb)
102
+ # 生成一个0到1之间的随机数
103
+ global total_count,attn_count,cur_step,mask1024,mask4096
104
+ global sa32, sa64
105
+ global write
106
+ global height,width
107
+ if write:
108
+ # print(f"white:{cur_step}")
109
+ self.id_bank[cur_step] = [hidden_states[:self.id_length].clone(), hidden_states[self.id_length:].clone()]
110
+ else:
111
+ encoder_hidden_states = torch.cat((self.id_bank[cur_step][0].to(self.device),hidden_states[:1],self.id_bank[cur_step][1].to(self.device),hidden_states[1:]))
112
+ # 判断随机数是否大于0.5
113
+ if cur_step <1:
114
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
115
+ else: # 256 1024 4096
116
+ random_number = random.random()
117
+ if cur_step <20:
118
+ rand_num = 0.3
119
+ else:
120
+ rand_num = 0.1
121
+ # print(f"hidden state shape {hidden_states.shape[1]}")
122
+ if random_number > rand_num:
123
+ # print("mask shape",mask1024.shape,mask4096.shape)
124
+ if not write:
125
+ if hidden_states.shape[1] == (height//32) * (width//32):
126
+ attention_mask = mask1024[mask1024.shape[0] // self.total_length * self.id_length:]
127
+ else:
128
+ attention_mask = mask4096[mask4096.shape[0] // self.total_length * self.id_length:]
129
+ else:
130
+ # print(self.total_length,self.id_length,hidden_states.shape,(height//32) * (width//32))
131
+ if hidden_states.shape[1] == (height//32) * (width//32):
132
+ attention_mask = mask1024[:mask1024.shape[0] // self.total_length * self.id_length,:mask1024.shape[0] // self.total_length * self.id_length]
133
+ else:
134
+ attention_mask = mask4096[:mask4096.shape[0] // self.total_length * self.id_length,:mask4096.shape[0] // self.total_length * self.id_length]
135
+ # print(attention_mask.shape)
136
+ # print("before attention",hidden_states.shape,attention_mask.shape,encoder_hidden_states.shape if encoder_hidden_states is not None else "None")
137
+ hidden_states = self.__call1__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
138
+ else:
139
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
140
+ attn_count +=1
141
+ if attn_count == total_count:
142
+ attn_count = 0
143
+ cur_step += 1
144
+ mask1024,mask4096 = cal_attn_mask_xl(self.total_length,self.id_length,sa32,sa64,height,width, device=self.device, dtype= self.dtype)
145
+
146
+ return hidden_states
147
+ def __call1__(
148
+ self,
149
+ attn,
150
+ hidden_states,
151
+ encoder_hidden_states=None,
152
+ attention_mask=None,
153
+ temb=None,
154
+ ):
155
+ # print("hidden state shape",hidden_states.shape,self.id_length)
156
+ residual = hidden_states
157
+ # if encoder_hidden_states is not None:
158
+ # raise Exception("not implement")
159
+ if attn.spatial_norm is not None:
160
+ hidden_states = attn.spatial_norm(hidden_states, temb)
161
+ input_ndim = hidden_states.ndim
162
+
163
+ if input_ndim == 4:
164
+ total_batch_size, channel, height, width = hidden_states.shape
165
+ hidden_states = hidden_states.view(total_batch_size, channel, height * width).transpose(1, 2)
166
+ total_batch_size,nums_token,channel = hidden_states.shape
167
+ img_nums = total_batch_size//2
168
+ hidden_states = hidden_states.view(-1,img_nums,nums_token,channel).reshape(-1,img_nums * nums_token,channel)
169
+
170
+ batch_size, sequence_length, _ = hidden_states.shape
171
+
172
+ if attn.group_norm is not None:
173
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
174
+
175
+ query = attn.to_q(hidden_states)
176
+
177
+ if encoder_hidden_states is None:
178
+ encoder_hidden_states = hidden_states # B, N, C
179
+ else:
180
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,nums_token,channel).reshape(-1,(self.id_length+1) * nums_token,channel)
181
+
182
+ key = attn.to_k(encoder_hidden_states)
183
+ value = attn.to_v(encoder_hidden_states)
184
+
185
+
186
+ inner_dim = key.shape[-1]
187
+ head_dim = inner_dim // attn.heads
188
+
189
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
190
+
191
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
192
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
193
+ # print(key.shape,value.shape,query.shape,attention_mask.shape)
194
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
195
+ # TODO: add support for attn.scale when we move to Torch 2.1
196
+ #print(query.shape,key.shape,value.shape,attention_mask.shape)
197
+ hidden_states = F.scaled_dot_product_attention(
198
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
199
+ )
200
+
201
+ hidden_states = hidden_states.transpose(1, 2).reshape(total_batch_size, -1, attn.heads * head_dim)
202
+ hidden_states = hidden_states.to(query.dtype)
203
+
204
+
205
+
206
+ # linear proj
207
+ hidden_states = attn.to_out[0](hidden_states)
208
+ # dropout
209
+ hidden_states = attn.to_out[1](hidden_states)
210
+
211
+ # if input_ndim == 4:
212
+ # tile_hidden_states = tile_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
213
+
214
+ # if attn.residual_connection:
215
+ # tile_hidden_states = tile_hidden_states + residual
216
+
217
+ if input_ndim == 4:
218
+ hidden_states = hidden_states.transpose(-1, -2).reshape(total_batch_size, channel, height, width)
219
+ if attn.residual_connection:
220
+ hidden_states = hidden_states + residual
221
+ hidden_states = hidden_states / attn.rescale_output_factor
222
+ # print(hidden_states.shape)
223
+ return hidden_states
224
+ def __call2__(
225
+ self,
226
+ attn,
227
+ hidden_states,
228
+ encoder_hidden_states=None,
229
+ attention_mask=None,
230
+ temb=None):
231
+ residual = hidden_states
232
+
233
+ if attn.spatial_norm is not None:
234
+ hidden_states = attn.spatial_norm(hidden_states, temb)
235
+
236
+ input_ndim = hidden_states.ndim
237
+
238
+ if input_ndim == 4:
239
+ batch_size, channel, height, width = hidden_states.shape
240
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
241
+
242
+ batch_size, sequence_length, channel = (
243
+ hidden_states.shape
244
+ )
245
+ # print(hidden_states.shape)
246
+ if attention_mask is not None:
247
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
248
+ # scaled_dot_product_attention expects attention_mask shape to be
249
+ # (batch, heads, source_length, target_length)
250
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
251
+
252
+ if attn.group_norm is not None:
253
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
254
+
255
+ query = attn.to_q(hidden_states)
256
+
257
+ if encoder_hidden_states is None:
258
+ encoder_hidden_states = hidden_states # B, N, C
259
+ else:
260
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,sequence_length,channel).reshape(-1,(self.id_length+1) * sequence_length,channel)
261
+
262
+ key = attn.to_k(encoder_hidden_states)
263
+ value = attn.to_v(encoder_hidden_states)
264
+
265
+ inner_dim = key.shape[-1]
266
+ head_dim = inner_dim // attn.heads
267
+
268
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
269
+
270
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
271
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
272
+
273
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
274
+ # TODO: add support for attn.scale when we move to Torch 2.1
275
+ hidden_states = F.scaled_dot_product_attention(
276
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
277
+ )
278
+
279
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
280
+ hidden_states = hidden_states.to(query.dtype)
281
+
282
+ # linear proj
283
+ hidden_states = attn.to_out[0](hidden_states)
284
+ # dropout
285
+ hidden_states = attn.to_out[1](hidden_states)
286
+
287
+ if input_ndim == 4:
288
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
289
+
290
+ if attn.residual_connection:
291
+ hidden_states = hidden_states + residual
292
+
293
+ hidden_states = hidden_states / attn.rescale_output_factor
294
+
295
+ return hidden_states
296
+
297
+ def set_attention_processor(unet,id_length,is_ipadapter = False):
298
+ global attn_procs
299
+ attn_procs = {}
300
+ for name in unet.attn_processors.keys():
301
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
302
+ if name.startswith("mid_block"):
303
+ hidden_size = unet.config.block_out_channels[-1]
304
+ elif name.startswith("up_blocks"):
305
+ block_id = int(name[len("up_blocks.")])
306
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
307
+ elif name.startswith("down_blocks"):
308
+ block_id = int(name[len("down_blocks.")])
309
+ hidden_size = unet.config.block_out_channels[block_id]
310
+ if cross_attention_dim is None:
311
+ if name.startswith("up_blocks") :
312
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length = id_length)
313
+ else:
314
+ attn_procs[name] = AttnProcessor()
315
+ else:
316
+ if is_ipadapter:
317
+ attn_procs[name] = IPAttnProcessor2_0(
318
+ hidden_size=hidden_size,
319
+ cross_attention_dim=cross_attention_dim,
320
+ scale=1,
321
+ num_tokens=4,
322
+ ).to(unet.device, dtype=torch.float16)
323
+ else:
324
+ attn_procs[name] = AttnProcessor()
325
+
326
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
327
+ #################################################
328
+ #################################################
329
+ canvas_html = "<div id='canvas-root' style='max-width:400px; margin: 0 auto'></div>"
330
+ load_js = """
331
+ async () => {
332
+ const url = "https://huggingface.co/datasets/radames/gradio-components/raw/main/sketch-canvas.js"
333
+ fetch(url)
334
+ .then(res => res.text())
335
+ .then(text => {
336
+ const script = document.createElement('script');
337
+ script.type = "module"
338
+ script.src = URL.createObjectURL(new Blob([text], { type: 'application/javascript' }));
339
+ document.head.appendChild(script);
340
+ });
341
+ }
342
+ """
343
+
344
+ get_js_colors = """
345
+ async (canvasData) => {
346
+ const canvasEl = document.getElementById("canvas-root");
347
+ return [canvasEl._data]
348
+ }
349
+ """
350
+
351
+ css = '''
352
+ #color-bg{display:flex;justify-content: center;align-items: center;}
353
+ .color-bg-item{width: 100%; height: 32px}
354
+ #main_button{width:100%}
355
+ <style>
356
+ '''
357
+
358
+
359
+ #################################################
360
+ title = r"""
361
+ <h1 align="center">StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</h1>
362
+ """
363
+
364
+ description = r"""
365
+ <b>Official 🤗 Gradio demo</b> for <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'><b>StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</b></a>.<br>
366
+ ❗️❗️❗️[<b>Important</b>] Personalization steps:<br>
367
+ 1️⃣ Enter a Textual Description for Character, if you add the Ref-Image, making sure to <b>follow the class word</b> you want to customize with the <b>trigger word</b>: `img`, such as: `man img` or `woman img` or `girl img`.<br>
368
+ 2️⃣ Enter the prompt array, each line corrsponds to one generated image.<br>
369
+ 3️⃣ Choose your preferred style template.<br>
370
+ 4️⃣ Click the <b>Submit</b> button to start customizing.
371
+ """
372
+
373
+ article = r"""
374
+
375
+ If StoryDiffusion is helpful, please help to ⭐ the <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'>Github Repo</a>. Thanks!
376
+ [![GitHub Stars](https://img.shields.io/github/stars/HVision-NKU/StoryDiffusion?style=social)](https://github.com/HVision-NKU/StoryDiffusion)
377
+ ---
378
+ 📝 **Citation**
379
+ <br>
380
+ If our work is useful for your research, please consider citing:
381
+
382
+ ```bibtex
383
+ @article{Zhou2024storydiffusion,
384
+ title={StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation},
385
+ author={Zhou, Yupeng and Zhou, Daquan and Cheng, Ming-Ming and Feng, Jiashi and Hou, Qibin},
386
+ year={2024}
387
+ }
388
+ ```
389
+ 📋 **License**
390
+ <br>
391
+ The Contents you create are under Apache-2.0 LICENSE. The Code are under Attribution-NonCommercial 4.0 International.
392
+
393
+ 📧 **Contact**
394
+ <br>
395
+ If you have any questions, please feel free to reach me out at <b>ypzhousdu@gmail.com</b>.
396
+ """
397
+ version = r"""
398
+ <h3 align="center">StoryDiffusion Version 0.01 (test version)</h3>
399
+
400
+ <h5 >1. Support image ref image. (Cartoon Ref image is not support now)</h5>
401
+ <h5 >2. Support Typesetting Style and Captioning.(By default, the prompt is used as the caption for each image. If you need to change the caption, add a # at the end of each line. Only the part after the # will be added as a caption to the image.)</h5>
402
+ <h5 >3. [NC]symbol (The [NC] symbol is used as a flag to indicate that no characters should be present in the generated scene images. If you want do that, prepend the "[NC]" at the beginning of the line. For example, to generate a scene of falling leaves without any character, write: "[NC] The leaves are falling.")</h5>
403
+ <h5 align="center">Tips: </h4>
404
+ """
405
+ #################################################
406
+ global attn_count, total_count, id_length, total_length,cur_step, cur_model_type
407
+ global write
408
+ global sa32, sa64
409
+ global height,width
410
+ attn_count = 0
411
+ total_count = 0
412
+ cur_step = 0
413
+ id_length = 4
414
+ total_length = 5
415
+ cur_model_type = ""
416
+ device="mps"
417
+ global attn_procs,unet
418
+ attn_procs = {}
419
+ ###
420
+ write = False
421
+ ###
422
+ sa32 = 0.5
423
+ sa64 = 0.5
424
+ height = 768
425
+ width = 768
426
+ ###
427
+ global pipe
428
+ global sd_model_path
429
+ pipe = None
430
+ sd_model_path = models_dict["RealVision"]#"SG161222/RealVisXL_V4.0"
431
+ ### LOAD Stable Diffusion Pipeline
432
+ pipe = StableDiffusionXLPipeline.from_pretrained(sd_model_path, torch_dtype=torch.float16, use_safetensors = True)
433
+ pipe = pipe.to(device)
434
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
435
+ # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
436
+ pipe.scheduler.set_timesteps(50)
437
+ unet = pipe.unet
438
+ ### Insert PairedAttention
439
+ for name in unet.attn_processors.keys():
440
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
441
+ if name.startswith("mid_block"):
442
+ hidden_size = unet.config.block_out_channels[-1]
443
+ elif name.startswith("up_blocks"):
444
+ block_id = int(name[len("up_blocks.")])
445
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
446
+ elif name.startswith("down_blocks"):
447
+ block_id = int(name[len("down_blocks.")])
448
+ hidden_size = unet.config.block_out_channels[block_id]
449
+ if cross_attention_dim is None and (name.startswith("up_blocks") ) :
450
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length = id_length)
451
+ total_count +=1
452
+ else:
453
+ attn_procs[name] = AttnProcessor()
454
+ print("successsfully load paired self-attention")
455
+ print(f"number of the processor : {total_count}")
456
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
457
+ global mask1024,mask4096
458
+ mask1024, mask4096 = cal_attn_mask_xl(total_length,id_length,sa32,sa64,height,width,device=device,dtype= torch.float16)
459
+
460
+ ######### Gradio Fuction #############
461
+
462
+ def swap_to_gallery(images):
463
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
464
+
465
+ def upload_example_to_gallery(images, prompt, style, negative_prompt):
466
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
467
+
468
+ def remove_back_to_files():
469
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
470
+
471
+ def remove_tips():
472
+ return gr.update(visible=False)
473
+
474
+ def apply_style_positive(style_name: str, positive: str):
475
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
476
+ return p.replace("{prompt}", positive)
477
+
478
+ def apply_style(style_name: str, positives: list, negative: str = ""):
479
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
480
+ return [p.replace("{prompt}", positive) for positive in positives], n + ' ' + negative
481
+
482
+ def change_visiale_by_model_type(_model_type):
483
+ if _model_type == "Only Using Textual Description":
484
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
485
+ elif _model_type == "Using Ref Images":
486
+ return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False)
487
+ else:
488
+ raise ValueError("Invalid model type",_model_type)
489
+
490
+
491
+ ######### Image Generation ##############
492
+ def process_generation(_sd_type,_model_type,_upload_images, _num_steps,style_name, _Ip_Adapter_Strength ,_style_strength_ratio, guidance_scale, seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt,prompt_array,G_height,G_width,_comic_type):
493
+ _model_type = "Photomaker" if _model_type == "Using Ref Images" else "original"
494
+ if _model_type == "Photomaker" and "img" not in general_prompt:
495
+ raise gr.Error("Please add the triger word \" img \" behind the class word you want to customize, such as: man img or woman img")
496
+ if _upload_images is None and _model_type != "original":
497
+ raise gr.Error(f"Cannot find any input face image!")
498
+ global sa32, sa64,id_length,total_length,attn_procs,unet,cur_model_type
499
+ global write
500
+ global cur_step,attn_count
501
+ global height,width
502
+ height = G_height
503
+ width = G_width
504
+ global pipe
505
+ global sd_model_path,models_dict
506
+ sd_model_path = models_dict[_sd_type]
507
+ use_safe_tensor = True
508
+ if cur_model_type != _sd_type+"-"+_model_type+""+str(id_length_):
509
+ if _sd_type == "Unstable":
510
+ use_safe_tensor = False
511
+ # apply the style template
512
+ ##### load pipe
513
+
514
+ if _model_type == "original":
515
+ pipe = StableDiffusionXLPipeline.from_pretrained(sd_model_path, torch_dtype=torch.float16, use_safetensors=use_safe_tensor)
516
+ pipe = pipe.to(device)
517
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
518
+ elif _model_type == "Photomaker":
519
+ pipe = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
520
+ sd_model_path, torch_dtype=torch.float16, use_safetensors=use_safe_tensor)
521
+ pipe = pipe.to(device)
522
+ pipe.load_photomaker_adapter(
523
+ os.path.dirname(photomaker_path),
524
+ subfolder="",
525
+ weight_name=os.path.basename(photomaker_path),
526
+ trigger_word="img" # define the trigger word
527
+ )
528
+ pipe.fuse_lora()
529
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
530
+ else:
531
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
532
+ ##### ########################
533
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
534
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
535
+ cur_model_type = _sd_type+"-"+_model_type+""+str(id_length_)
536
+ else:
537
+ unet = pipe.unet
538
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
539
+ if _model_type != "original":
540
+ input_id_images = []
541
+ for img in _upload_images:
542
+ print(img)
543
+ input_id_images.append(load_image(img))
544
+ prompts = prompt_array.splitlines()
545
+ start_merge_step = int(float(_style_strength_ratio) / 100 * _num_steps)
546
+ if start_merge_step > 30:
547
+ start_merge_step = 30
548
+ print(f"start_merge_step:{start_merge_step}")
549
+ generator = torch.Generator(device="mps").manual_seed(seed_)
550
+ sa32, sa64 = sa32_, sa64_
551
+ id_length = id_length_
552
+ clipped_prompts = prompts[:]
553
+ prompts = [general_prompt + "," + prompt if "[NC]" not in prompt else prompt.replace("[NC]","") for prompt in clipped_prompts]
554
+ prompts = [prompt.rpartition('#')[0] if "#" in prompt else prompt for prompt in prompts]
555
+ print(prompts)
556
+ id_prompts = prompts[:id_length]
557
+ real_prompts = prompts[id_length:]
558
+ #torch.cuda.empty_cache()
559
+ write = True
560
+ cur_step = 0
561
+
562
+ attn_count = 0
563
+ id_prompts, negative_prompt = apply_style(style_name, id_prompts, negative_prompt)
564
+ setup_seed(seed_)
565
+ total_results = []
566
+ if _model_type == "original":
567
+ id_images = pipe(id_prompts, num_inference_steps=_num_steps, guidance_scale=guidance_scale, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images
568
+ elif _model_type == "Photomaker":
569
+ id_images = pipe(id_prompts,input_id_images=input_id_images, num_inference_steps=_num_steps, guidance_scale=guidance_scale, start_merge_step = start_merge_step, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images
570
+ else:
571
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
572
+ total_results = id_images + total_results
573
+ yield total_results
574
+ real_images = []
575
+ write = False
576
+ for real_prompt in real_prompts:
577
+ setup_seed(seed_)
578
+ cur_step = 0
579
+ real_prompt = apply_style_positive(style_name, real_prompt)
580
+ if _model_type == "original":
581
+ real_images.append(pipe(real_prompt, num_inference_steps=_num_steps, guidance_scale=guidance_scale, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images[0])
582
+ elif _model_type == "Photomaker":
583
+ real_images.append(pipe(real_prompt, input_id_images=input_id_images, num_inference_steps=_num_steps, guidance_scale=guidance_scale, start_merge_step = start_merge_step, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images[0])
584
+ else:
585
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
586
+ total_results = [real_images[-1]] + total_results
587
+ yield total_results
588
+ if _comic_type != "No typesetting (default)":
589
+ captions= prompt_array.splitlines()
590
+ captions = [caption.replace("[NC]","") for caption in captions]
591
+ captions = [caption.split('#')[-1] if "#" in caption else caption for caption in captions]
592
+ from PIL import ImageFont
593
+ total_results = get_comic(id_images + real_images, _comic_type,captions= captions,font=ImageFont.truetype("./fonts/Inkfree.ttf", int(45))) + total_results
594
+ yield total_results
595
+
596
+
597
+
598
+ def array2string(arr):
599
+ stringtmp = ""
600
+ for i,part in enumerate(arr):
601
+ if i != len(arr)-1:
602
+ stringtmp += part +"\n"
603
+ else:
604
+ stringtmp += part
605
+
606
+ return stringtmp
607
+
608
+
609
+ #################################################
610
+ #################################################
611
+ ### define the interface
612
+ with gr.Blocks(css=css) as demo:
613
+ binary_matrixes = gr.State([])
614
+ color_layout = gr.State([])
615
+
616
+ # gr.Markdown(logo)
617
+ gr.Markdown(title)
618
+ gr.Markdown(description)
619
+
620
+ with gr.Row():
621
+ with gr.Group(elem_id="main-image"):
622
+
623
+ prompts = []
624
+ colors = []
625
+
626
+ with gr.Column(visible=True) as gen_prompt_vis:
627
+ sd_type = gr.Dropdown(choices=list(models_dict.keys()), value = "Unstable",label="sd_type", info="Select pretrained model")
628
+ model_type = gr.Radio(["Only Using Textual Description", "Using Ref Images"], label="model_type", value = "Only Using Textual Description", info="Control type of the Character")
629
+ with gr.Group(visible=False) as control_image_input:
630
+ files = gr.Files(
631
+ label="Drag (Select) 1 or more photos of your face",
632
+ file_types=["image"],
633
+ )
634
+ uploaded_files = gr.Gallery(label="Your images", visible=False, columns=5, rows=1, height=200)
635
+ with gr.Column(visible=False) as clear_button:
636
+ remove_and_reupload = gr.ClearButton(value="Remove and upload new ones", components=files, size="sm")
637
+ general_prompt = gr.Textbox(value='', label="(1) Textual Description for Character", interactive=True)
638
+ negative_prompt = gr.Textbox(value='', label="(2) Negative_prompt", interactive=True)
639
+ style = gr.Dropdown(label="Style template", choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME)
640
+ prompt_array = gr.Textbox(lines = 3,value='', label="(3) Comic Description (each line corresponds to a frame).", interactive=True)
641
+ with gr.Accordion("(4) Tune the hyperparameters", open=True):
642
+ sa32_ = gr.Slider(label=" (The degree of Paired Attention at 32 x 32 self-attention layers) ", minimum=0, maximum=1., value=0.5, step=0.1)
643
+ sa64_ = gr.Slider(label=" (The degree of Paired Attention at 64 x 64 self-attention layers) ", minimum=0, maximum=1., value=0.5, step=0.1)
644
+ id_length_ = gr.Slider(label= "Number of id images in total images" , minimum=2, maximum=4, value=2, step=1)
645
+ seed_ = gr.Slider(label="Seed", minimum=-1, maximum=MAX_SEED, value=0, step=1)
646
+ num_steps = gr.Slider(
647
+ label="Number of sample steps",
648
+ minimum=20,
649
+ maximum=100,
650
+ step=1,
651
+ value=50,
652
+ )
653
+ G_height = gr.Slider(
654
+ label="height",
655
+ minimum=256,
656
+ maximum=1024,
657
+ step=32,
658
+ value=768,
659
+ )
660
+ G_width = gr.Slider(
661
+ label="width",
662
+ minimum=256,
663
+ maximum=1024,
664
+ step=32,
665
+ value=768,
666
+ )
667
+ comic_type = gr.Radio(["No typesetting (default)", "Four Pannel", "Classic Comic Style"], value = "Classic Comic Style", label="Typesetting Style", info="Select the typesetting style ")
668
+ guidance_scale = gr.Slider(
669
+ label="Guidance scale",
670
+ minimum=0.1,
671
+ maximum=10.0,
672
+ step=0.1,
673
+ value=5,
674
+ )
675
+ style_strength_ratio = gr.Slider(
676
+ label="Style strength of Ref Image (%)",
677
+ minimum=15,
678
+ maximum=50,
679
+ step=1,
680
+ value=20,
681
+ visible=False
682
+ )
683
+ Ip_Adapter_Strength = gr.Slider(
684
+ label="Ip_Adapter_Strength",
685
+ minimum=0,
686
+ maximum=1,
687
+ step=0.1,
688
+ value=0.5,
689
+ visible=False
690
+ )
691
+ final_run_btn = gr.Button("Generate ! 😺")
692
+
693
+
694
+ with gr.Column():
695
+ out_image = gr.Gallery(label="Result", columns=2, height='auto')
696
+ generated_information = gr.Markdown(label="Generation Details", value="",visible=False)
697
+ gr.Markdown(version)
698
+ model_type.change(fn = change_visiale_by_model_type , inputs = model_type, outputs=[control_image_input,style_strength_ratio,Ip_Adapter_Strength])
699
+ files.upload(fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files])
700
+ remove_and_reupload.click(fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files])
701
+
702
+ final_run_btn.click(fn=set_text_unfinished, outputs = generated_information
703
+ ).then(process_generation, inputs=[sd_type,model_type,files, num_steps,style, Ip_Adapter_Strength,style_strength_ratio, guidance_scale, seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,G_height,G_width,comic_type], outputs=out_image
704
+ ).then(fn=set_text_finished,outputs = generated_information)
705
+
706
+
707
+ gr.Examples(
708
+ examples=[
709
+ [0,0.5,0.5,2,"a man, wearing black suit",
710
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
711
+ array2string(["at home, read new paper #at home, The newspaper says there is a treasure house in the forest.",
712
+ "on the road, near the forest",
713
+ "[NC] The car on the road, near the forest #He drives to the forest in search of treasure.",
714
+ "[NC]A tiger appeared in the forest, at night ",
715
+ "very frightened, open mouth, in the forest, at night",
716
+ "running very fast, in the forest, at night",
717
+ "[NC] A house in the forest, at night #Suddenly, he discovers the treasure house!",
718
+ "in the house filled with treasure, laughing, at night #He is overjoyed inside the house."
719
+ ]),
720
+ "Comic book","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
721
+ ],
722
+ [1,0.5,0.5,3,"a woman img, wearing a white T-shirt, blue loose hair",
723
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
724
+ array2string(["wake up in the bed",
725
+ "have breakfast",
726
+ "is on the road, go to company",
727
+ "work in the company",
728
+ "Take a walk next to the company at noon",
729
+ "lying in bed at night"]),
730
+ "Japanese Anime", "Using Ref Images",get_image_path_list('./examples/taylor'),768,768
731
+ ],
732
+ [0,0.5,0.5,3,"a man, wearing black jacket",
733
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
734
+ array2string(["wake up in the bed",
735
+ "have breakfast",
736
+ "is on the road, go to the company, close look",
737
+ "work in the company",
738
+ "laughing happily",
739
+ "lying in bed at night"
740
+ ]),
741
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
742
+ ],
743
+ [0,0.3,0.5,3,"a girl, wearing white shirt, black skirt, black tie, yellow hair",
744
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
745
+ array2string([
746
+ "at home #at home, began to go to drawing",
747
+ "sitting alone on a park bench.",
748
+ "reading a book on a park bench.",
749
+ "[NC]A squirrel approaches, peeking over the bench. ",
750
+ "look around in the park. # She looks around and enjoys the beauty of nature.",
751
+ "[NC]leaf falls from the tree, landing on the sketchbook.",
752
+ "picks up the leaf, examining its details closely.",
753
+ "[NC]The brown squirrel appear.",
754
+ "is very happy # She is very happy to see the squirrel again",
755
+ "[NC]The brown squirrel takes the cracker and scampers up a tree. # She gives the squirrel cracker"]),
756
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
757
+ ]
758
+ ],
759
+ inputs=[seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,style,model_type,files,G_height,G_width],
760
+ # outputs=[post_sketch, binary_matrixes, *color_row, *colors, *prompts, gen_prompt_vis, general_prompt, seed_],
761
+ # run_on_click=True,
762
+ label='😺 Examples 😺',
763
+ )
764
+ gr.Markdown(article)
765
+
766
+
767
+ demo.launch(server_name="0.0.0.0", share = False)
gradio_app_sdxl_specific_id_old_version.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from email.policy import default
2
+ import gradio as gr
3
+ import numpy as np
4
+ import torch
5
+ from huggingface_hub import hf_hub_download
6
+ import requests
7
+ import random
8
+ import os
9
+ import sys
10
+ import pickle
11
+ from PIL import Image
12
+ from tqdm.auto import tqdm
13
+ from datetime import datetime
14
+ from utils.gradio_utils import is_torch2_available
15
+ if is_torch2_available():
16
+ from utils.gradio_utils import \
17
+ AttnProcessor2_0 as AttnProcessor
18
+ else:
19
+ from utils.gradio_utils import AttnProcessor
20
+
21
+ import diffusers
22
+ from diffusers import StableDiffusionXLPipeline
23
+ from utils import PhotoMakerStableDiffusionXLPipeline
24
+ from diffusers import DDIMScheduler
25
+ import torch.nn.functional as F
26
+ from utils.gradio_utils import cal_attn_mask_xl
27
+ import copy
28
+ import os
29
+ from diffusers.utils import load_image
30
+ from utils.utils import get_comic
31
+ from utils.style_template import styles
32
+ image_encoder_path = "./data/models/ip_adapter/sdxl_models/image_encoder"
33
+ ip_ckpt = "./data/models/ip_adapter/sdxl_models/ip-adapter_sdxl_vit-h.bin"
34
+ os.environ["no_proxy"] = "localhost,127.0.0.1,::1"
35
+ STYLE_NAMES = list(styles.keys())
36
+ DEFAULT_STYLE_NAME = "Japanese Anime"
37
+ global models_dict
38
+ models_dict = {
39
+ # "Juggernaut": "RunDiffusion/Juggernaut-XL-v9",
40
+ "RealVision": "SG161222/RealVisXL_V4.0" ,
41
+ "SDXL": "stabilityai/stable-diffusion-xl-base-1.0" ,
42
+ "Unstable": "stablediffusionapi/sdxl-unstable-diffusers-y"
43
+ }
44
+ photomaker_path = hf_hub_download(repo_id="TencentARC/PhotoMaker", filename="photomaker-v1.bin", repo_type="model")
45
+ MAX_SEED = np.iinfo(np.int32).max
46
+ def setup_seed(seed):
47
+ torch.manual_seed(seed)
48
+ torch.cuda.manual_seed_all(seed)
49
+ np.random.seed(seed)
50
+ random.seed(seed)
51
+ torch.backends.cudnn.deterministic = True
52
+ def set_text_unfinished():
53
+ return gr.update(visible=True, value="<h3>(Not Finished) Generating ··· The intermediate results will be shown.</h3>")
54
+ def set_text_finished():
55
+ return gr.update(visible=True, value="<h3>Generation Finished</h3>")
56
+ #################################################
57
+ def get_image_path_list(folder_name):
58
+ image_basename_list = os.listdir(folder_name)
59
+ image_path_list = sorted([os.path.join(folder_name, basename) for basename in image_basename_list])
60
+ return image_path_list
61
+
62
+ #################################################
63
+ class SpatialAttnProcessor2_0(torch.nn.Module):
64
+ r"""
65
+ Attention processor for IP-Adapater for PyTorch 2.0.
66
+ Args:
67
+ hidden_size (`int`):
68
+ The hidden size of the attention layer.
69
+ cross_attention_dim (`int`):
70
+ The number of channels in the `encoder_hidden_states`.
71
+ text_context_len (`int`, defaults to 77):
72
+ The context length of the text features.
73
+ scale (`float`, defaults to 1.0):
74
+ the weight scale of image prompt.
75
+ """
76
+
77
+ def __init__(self, hidden_size = None, cross_attention_dim=None,id_length = 4,device = "cuda",dtype = torch.float16):
78
+ super().__init__()
79
+ if not hasattr(F, "scaled_dot_product_attention"):
80
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
81
+ self.device = device
82
+ self.dtype = dtype
83
+ self.hidden_size = hidden_size
84
+ self.cross_attention_dim = cross_attention_dim
85
+ self.total_length = id_length + 1
86
+ self.id_length = id_length
87
+ self.id_bank = {}
88
+
89
+ def __call__(
90
+ self,
91
+ attn,
92
+ hidden_states,
93
+ encoder_hidden_states=None,
94
+ attention_mask=None,
95
+ temb=None):
96
+ # un_cond_hidden_states, cond_hidden_states = hidden_states.chunk(2)
97
+ # un_cond_hidden_states = self.__call2__(attn, un_cond_hidden_states,encoder_hidden_states,attention_mask,temb)
98
+ # 生成一个0到1之间的随机数
99
+ global total_count,attn_count,cur_step,mask1024,mask4096
100
+ global sa32, sa64
101
+ global write
102
+ global height,width
103
+ if write:
104
+ # print(f"white:{cur_step}")
105
+ self.id_bank[cur_step] = [hidden_states[:self.id_length].clone(), hidden_states[self.id_length:].clone()]
106
+ else:
107
+ encoder_hidden_states = torch.cat((self.id_bank[cur_step][0].to(self.device),hidden_states[:1],self.id_bank[cur_step][1].to(self.device),hidden_states[1:]))
108
+ # 判断随机数是否大于0.5
109
+ if cur_step <1:
110
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
111
+ else: # 256 1024 4096
112
+ random_number = random.random()
113
+ if cur_step <20:
114
+ rand_num = 0.3
115
+ else:
116
+ rand_num = 0.1
117
+ # print(f"hidden state shape {hidden_states.shape[1]}")
118
+ if random_number > rand_num:
119
+ # print("mask shape",mask1024.shape,mask4096.shape)
120
+ if not write:
121
+ if hidden_states.shape[1] == (height//32) * (width//32):
122
+ attention_mask = mask1024[mask1024.shape[0] // self.total_length * self.id_length:]
123
+ else:
124
+ attention_mask = mask4096[mask4096.shape[0] // self.total_length * self.id_length:]
125
+ else:
126
+ # print(self.total_length,self.id_length,hidden_states.shape,(height//32) * (width//32))
127
+ if hidden_states.shape[1] == (height//32) * (width//32):
128
+ attention_mask = mask1024[:mask1024.shape[0] // self.total_length * self.id_length,:mask1024.shape[0] // self.total_length * self.id_length]
129
+ else:
130
+ attention_mask = mask4096[:mask4096.shape[0] // self.total_length * self.id_length,:mask4096.shape[0] // self.total_length * self.id_length]
131
+ # print(attention_mask.shape)
132
+ # print("before attention",hidden_states.shape,attention_mask.shape,encoder_hidden_states.shape if encoder_hidden_states is not None else "None")
133
+ hidden_states = self.__call1__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
134
+ else:
135
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
136
+ attn_count +=1
137
+ if attn_count == total_count:
138
+ attn_count = 0
139
+ cur_step += 1
140
+ mask1024,mask4096 = cal_attn_mask_xl(self.total_length,self.id_length,sa32,sa64,height,width, device=self.device, dtype= self.dtype)
141
+
142
+ return hidden_states
143
+ def __call1__(
144
+ self,
145
+ attn,
146
+ hidden_states,
147
+ encoder_hidden_states=None,
148
+ attention_mask=None,
149
+ temb=None,
150
+ ):
151
+ # print("hidden state shape",hidden_states.shape,self.id_length)
152
+ residual = hidden_states
153
+ # if encoder_hidden_states is not None:
154
+ # raise Exception("not implement")
155
+ if attn.spatial_norm is not None:
156
+ hidden_states = attn.spatial_norm(hidden_states, temb)
157
+ input_ndim = hidden_states.ndim
158
+
159
+ if input_ndim == 4:
160
+ total_batch_size, channel, height, width = hidden_states.shape
161
+ hidden_states = hidden_states.view(total_batch_size, channel, height * width).transpose(1, 2)
162
+ total_batch_size,nums_token,channel = hidden_states.shape
163
+ img_nums = total_batch_size//2
164
+ hidden_states = hidden_states.view(-1,img_nums,nums_token,channel).reshape(-1,img_nums * nums_token,channel)
165
+
166
+ batch_size, sequence_length, _ = hidden_states.shape
167
+
168
+ if attn.group_norm is not None:
169
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
170
+
171
+ query = attn.to_q(hidden_states)
172
+
173
+ if encoder_hidden_states is None:
174
+ encoder_hidden_states = hidden_states # B, N, C
175
+ else:
176
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,nums_token,channel).reshape(-1,(self.id_length+1) * nums_token,channel)
177
+
178
+ key = attn.to_k(encoder_hidden_states)
179
+ value = attn.to_v(encoder_hidden_states)
180
+
181
+
182
+ inner_dim = key.shape[-1]
183
+ head_dim = inner_dim // attn.heads
184
+
185
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
186
+
187
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
188
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
189
+ # print(key.shape,value.shape,query.shape,attention_mask.shape)
190
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
191
+ # TODO: add support for attn.scale when we move to Torch 2.1
192
+ #print(query.shape,key.shape,value.shape,attention_mask.shape)
193
+ hidden_states = F.scaled_dot_product_attention(
194
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
195
+ )
196
+
197
+ hidden_states = hidden_states.transpose(1, 2).reshape(total_batch_size, -1, attn.heads * head_dim)
198
+ hidden_states = hidden_states.to(query.dtype)
199
+
200
+
201
+
202
+ # linear proj
203
+ hidden_states = attn.to_out[0](hidden_states)
204
+ # dropout
205
+ hidden_states = attn.to_out[1](hidden_states)
206
+
207
+ # if input_ndim == 4:
208
+ # tile_hidden_states = tile_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
209
+
210
+ # if attn.residual_connection:
211
+ # tile_hidden_states = tile_hidden_states + residual
212
+
213
+ if input_ndim == 4:
214
+ hidden_states = hidden_states.transpose(-1, -2).reshape(total_batch_size, channel, height, width)
215
+ if attn.residual_connection:
216
+ hidden_states = hidden_states + residual
217
+ hidden_states = hidden_states / attn.rescale_output_factor
218
+ # print(hidden_states.shape)
219
+ return hidden_states
220
+ def __call2__(
221
+ self,
222
+ attn,
223
+ hidden_states,
224
+ encoder_hidden_states=None,
225
+ attention_mask=None,
226
+ temb=None):
227
+ residual = hidden_states
228
+
229
+ if attn.spatial_norm is not None:
230
+ hidden_states = attn.spatial_norm(hidden_states, temb)
231
+
232
+ input_ndim = hidden_states.ndim
233
+
234
+ if input_ndim == 4:
235
+ batch_size, channel, height, width = hidden_states.shape
236
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
237
+
238
+ batch_size, sequence_length, channel = (
239
+ hidden_states.shape
240
+ )
241
+ # print(hidden_states.shape)
242
+ if attention_mask is not None:
243
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
244
+ # scaled_dot_product_attention expects attention_mask shape to be
245
+ # (batch, heads, source_length, target_length)
246
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
247
+
248
+ if attn.group_norm is not None:
249
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
250
+
251
+ query = attn.to_q(hidden_states)
252
+
253
+ if encoder_hidden_states is None:
254
+ encoder_hidden_states = hidden_states # B, N, C
255
+ else:
256
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,sequence_length,channel).reshape(-1,(self.id_length+1) * sequence_length,channel)
257
+
258
+ key = attn.to_k(encoder_hidden_states)
259
+ value = attn.to_v(encoder_hidden_states)
260
+
261
+ inner_dim = key.shape[-1]
262
+ head_dim = inner_dim // attn.heads
263
+
264
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
265
+
266
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
267
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
268
+
269
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
270
+ # TODO: add support for attn.scale when we move to Torch 2.1
271
+ hidden_states = F.scaled_dot_product_attention(
272
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
273
+ )
274
+
275
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
276
+ hidden_states = hidden_states.to(query.dtype)
277
+
278
+ # linear proj
279
+ hidden_states = attn.to_out[0](hidden_states)
280
+ # dropout
281
+ hidden_states = attn.to_out[1](hidden_states)
282
+
283
+ if input_ndim == 4:
284
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
285
+
286
+ if attn.residual_connection:
287
+ hidden_states = hidden_states + residual
288
+
289
+ hidden_states = hidden_states / attn.rescale_output_factor
290
+
291
+ return hidden_states
292
+
293
+ def set_attention_processor(unet,id_length,is_ipadapter = False):
294
+ global attn_procs
295
+ attn_procs = {}
296
+ for name in unet.attn_processors.keys():
297
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
298
+ if name.startswith("mid_block"):
299
+ hidden_size = unet.config.block_out_channels[-1]
300
+ elif name.startswith("up_blocks"):
301
+ block_id = int(name[len("up_blocks.")])
302
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
303
+ elif name.startswith("down_blocks"):
304
+ block_id = int(name[len("down_blocks.")])
305
+ hidden_size = unet.config.block_out_channels[block_id]
306
+ if cross_attention_dim is None:
307
+ if name.startswith("up_blocks") :
308
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length = id_length)
309
+ else:
310
+ attn_procs[name] = AttnProcessor()
311
+ else:
312
+ if is_ipadapter:
313
+ attn_procs[name] = IPAttnProcessor2_0(
314
+ hidden_size=hidden_size,
315
+ cross_attention_dim=cross_attention_dim,
316
+ scale=1,
317
+ num_tokens=4,
318
+ ).to(unet.device, dtype=torch.float16)
319
+ else:
320
+ attn_procs[name] = AttnProcessor()
321
+
322
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
323
+ #################################################
324
+ #################################################
325
+ canvas_html = "<div id='canvas-root' style='max-width:400px; margin: 0 auto'></div>"
326
+ load_js = """
327
+ async () => {
328
+ const url = "https://huggingface.co/datasets/radames/gradio-components/raw/main/sketch-canvas.js"
329
+ fetch(url)
330
+ .then(res => res.text())
331
+ .then(text => {
332
+ const script = document.createElement('script');
333
+ script.type = "module"
334
+ script.src = URL.createObjectURL(new Blob([text], { type: 'application/javascript' }));
335
+ document.head.appendChild(script);
336
+ });
337
+ }
338
+ """
339
+
340
+ get_js_colors = """
341
+ async (canvasData) => {
342
+ const canvasEl = document.getElementById("canvas-root");
343
+ return [canvasEl._data]
344
+ }
345
+ """
346
+
347
+ css = '''
348
+ #color-bg{display:flex;justify-content: center;align-items: center;}
349
+ .color-bg-item{width: 100%; height: 32px}
350
+ #main_button{width:100%}
351
+ <style>
352
+ '''
353
+
354
+
355
+ #################################################
356
+ title = r"""
357
+ <h1 align="center">StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</h1>
358
+ """
359
+
360
+ description = r"""
361
+ <b>Official 🤗 Gradio demo</b> for <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'><b>StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</b></a>.<br>
362
+ ❗️❗️❗️[<b>Important</b>] Personalization steps:<br>
363
+ 1️⃣ Enter a Textual Description for Character, if you add the Ref-Image, making sure to <b>follow the class word</b> you want to customize with the <b>trigger word</b>: `img`, such as: `man img` or `woman img` or `girl img`.<br>
364
+ 2️⃣ Enter the prompt array, each line corrsponds to one generated image.<br>
365
+ 3️⃣ Choose your preferred style template.<br>
366
+ 4️⃣ Click the <b>Submit</b> button to start customizing.
367
+ """
368
+
369
+ article = r"""
370
+
371
+ If StoryDiffusion is helpful, please help to ⭐ the <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'>Github Repo</a>. Thanks!
372
+ [![GitHub Stars](https://img.shields.io/github/stars/HVision-NKU/StoryDiffusion?style=social)](https://github.com/HVision-NKU/StoryDiffusion)
373
+ ---
374
+ 📝 **Citation**
375
+ <br>
376
+ If our work is useful for your research, please consider citing:
377
+
378
+ ```bibtex
379
+ @article{Zhou2024storydiffusion,
380
+ title={StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation},
381
+ author={Zhou, Yupeng and Zhou, Daquan and Cheng, Ming-Ming and Feng, Jiashi and Hou, Qibin},
382
+ year={2024}
383
+ }
384
+ ```
385
+ 📋 **License**
386
+ <br>
387
+ The Contents you create are under Apache-2.0 LICENSE. The Code are under Attribution-NonCommercial 4.0 International.
388
+
389
+ 📧 **Contact**
390
+ <br>
391
+ If you have any questions, please feel free to reach me out at <b>ypzhousdu@gmail.com</b>.
392
+ """
393
+ version = r"""
394
+ <h3 align="center">StoryDiffusion Version 0.01 (test version)</h3>
395
+
396
+ <h5 >1. Support image ref image. (Cartoon Ref image is not support now)</h5>
397
+ <h5 >2. Support Typesetting Style and Captioning.(By default, the prompt is used as the caption for each image. If you need to change the caption, add a # at the end of each line. Only the part after the # will be added as a caption to the image.)</h5>
398
+ <h5 >3. [NC]symbol (The [NC] symbol is used as a flag to indicate that no characters should be present in the generated scene images. If you want do that, prepend the "[NC]" at the beginning of the line. For example, to generate a scene of falling leaves without any character, write: "[NC] The leaves are falling.")</h5>
399
+ <h5 align="center">Tips: </h4>
400
+ """
401
+ #################################################
402
+ global attn_count, total_count, id_length, total_length,cur_step, cur_model_type
403
+ global write
404
+ global sa32, sa64
405
+ global height,width
406
+ attn_count = 0
407
+ total_count = 0
408
+ cur_step = 0
409
+ id_length = 4
410
+ total_length = 5
411
+ cur_model_type = ""
412
+ device="cuda"
413
+ global attn_procs,unet
414
+ attn_procs = {}
415
+ ###
416
+ write = False
417
+ ###
418
+ sa32 = 0.5
419
+ sa64 = 0.5
420
+ height = 768
421
+ width = 768
422
+ ###
423
+ global pipe
424
+ global sd_model_path
425
+ pipe = None
426
+ sd_model_path = models_dict["RealVision"]#"SG161222/RealVisXL_V4.0"
427
+ ### LOAD Stable Diffusion Pipeline
428
+ pipe = StableDiffusionXLPipeline.from_pretrained(sd_model_path, torch_dtype=torch.float16, use_safetensors = True)
429
+ pipe = pipe.to(device)
430
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
431
+ # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
432
+ pipe.scheduler.set_timesteps(50)
433
+ unet = pipe.unet
434
+ ### Insert PairedAttention
435
+ for name in unet.attn_processors.keys():
436
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
437
+ if name.startswith("mid_block"):
438
+ hidden_size = unet.config.block_out_channels[-1]
439
+ elif name.startswith("up_blocks"):
440
+ block_id = int(name[len("up_blocks.")])
441
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
442
+ elif name.startswith("down_blocks"):
443
+ block_id = int(name[len("down_blocks.")])
444
+ hidden_size = unet.config.block_out_channels[block_id]
445
+ if cross_attention_dim is None and (name.startswith("up_blocks") ) :
446
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length = id_length)
447
+ total_count +=1
448
+ else:
449
+ attn_procs[name] = AttnProcessor()
450
+ print("successsfully load paired self-attention")
451
+ print(f"number of the processor : {total_count}")
452
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
453
+ global mask1024,mask4096
454
+ mask1024, mask4096 = cal_attn_mask_xl(total_length,id_length,sa32,sa64,height,width,device=device,dtype= torch.float16)
455
+
456
+ ######### Gradio Fuction #############
457
+
458
+ def swap_to_gallery(images):
459
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
460
+
461
+ def upload_example_to_gallery(images, prompt, style, negative_prompt):
462
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
463
+
464
+ def remove_back_to_files():
465
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
466
+
467
+ def remove_tips():
468
+ return gr.update(visible=False)
469
+
470
+ def apply_style_positive(style_name: str, positive: str):
471
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
472
+ return p.replace("{prompt}", positive)
473
+
474
+ def apply_style(style_name: str, positives: list, negative: str = ""):
475
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
476
+ return [p.replace("{prompt}", positive) for positive in positives], n + ' ' + negative
477
+
478
+ def change_visiale_by_model_type(_model_type):
479
+ if _model_type == "Only Using Textual Description":
480
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
481
+ elif _model_type == "Using Ref Images":
482
+ return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False)
483
+ else:
484
+ raise ValueError("Invalid model type",_model_type)
485
+
486
+
487
+ ######### Image Generation ##############
488
+ def process_generation(_sd_type,_model_type,_upload_images, _num_steps,style_name, _Ip_Adapter_Strength ,_style_strength_ratio, guidance_scale, seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt,prompt_array,G_height,G_width,_comic_type):
489
+ _model_type = "Photomaker" if _model_type == "Using Ref Images" else "original"
490
+ if _model_type == "Photomaker" and "img" not in general_prompt:
491
+ raise gr.Error("Please add the triger word \" img \" behind the class word you want to customize, such as: man img or woman img")
492
+ if _upload_images is None and _model_type != "original":
493
+ raise gr.Error(f"Cannot find any input face image!")
494
+ global sa32, sa64,id_length,total_length,attn_procs,unet,cur_model_type
495
+ global write
496
+ global cur_step,attn_count
497
+ global height,width
498
+ height = G_height
499
+ width = G_width
500
+ global pipe
501
+ global sd_model_path,models_dict
502
+ sd_model_path = models_dict[_sd_type]
503
+ use_safe_tensor = True
504
+ if cur_model_type != _sd_type+"-"+_model_type+""+str(id_length_):
505
+ if _sd_type == "Unstable":
506
+ use_safe_tensor = False
507
+ # apply the style template
508
+ ##### load pipe
509
+
510
+ if _model_type == "original":
511
+ pipe = StableDiffusionXLPipeline.from_pretrained(sd_model_path, torch_dtype=torch.float16, use_safetensors=use_safe_tensor)
512
+ pipe = pipe.to(device)
513
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
514
+ elif _model_type == "Photomaker":
515
+ pipe = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
516
+ sd_model_path, torch_dtype=torch.float16, use_safetensors=use_safe_tensor)
517
+ pipe = pipe.to(device)
518
+ pipe.load_photomaker_adapter(
519
+ os.path.dirname(photomaker_path),
520
+ subfolder="",
521
+ weight_name=os.path.basename(photomaker_path),
522
+ trigger_word="img" # define the trigger word
523
+ )
524
+ pipe.fuse_lora()
525
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
526
+ else:
527
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
528
+ ##### ########################
529
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
530
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
531
+ cur_model_type = _sd_type+"-"+_model_type+""+str(id_length_)
532
+ else:
533
+ unet = pipe.unet
534
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
535
+ if _model_type != "original":
536
+ input_id_images = []
537
+ for img in _upload_images:
538
+ print(img)
539
+ input_id_images.append(load_image(img))
540
+ prompts = prompt_array.splitlines()
541
+ start_merge_step = int(float(_style_strength_ratio) / 100 * _num_steps)
542
+ if start_merge_step > 30:
543
+ start_merge_step = 30
544
+ print(f"start_merge_step:{start_merge_step}")
545
+ generator = torch.Generator(device="cuda").manual_seed(seed_)
546
+ sa32, sa64 = sa32_, sa64_
547
+ id_length = id_length_
548
+ clipped_prompts = prompts[:]
549
+ nc_indexs = []
550
+ for ind,prompt in enumerate(clipped_prompts):
551
+ if "[NC]" in prompt:
552
+ nc_indexs.append(ind)
553
+ if ind < id_length:
554
+ raise gr.Error(f"The first {id_length} row is id prompts, cannot use [NC]!")
555
+ prompts = [general_prompt + "," + prompt if "[NC]" not in prompt else prompt.replace("[NC]","") for prompt in clipped_prompts]
556
+ prompts = [prompt.rpartition('#')[0] if "#" in prompt else prompt for prompt in prompts]
557
+ print(prompts)
558
+ id_prompts = prompts[:id_length]
559
+ real_prompts = prompts[id_length:]
560
+ torch.cuda.empty_cache()
561
+ write = True
562
+ cur_step = 0
563
+
564
+ attn_count = 0
565
+ id_prompts, negative_prompt = apply_style(style_name, id_prompts, negative_prompt)
566
+ setup_seed(seed_)
567
+ total_results = []
568
+ if _model_type == "original":
569
+ id_images = pipe(id_prompts, num_inference_steps=_num_steps, guidance_scale=guidance_scale, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images
570
+ elif _model_type == "Photomaker":
571
+ id_images = pipe(id_prompts,input_id_images=input_id_images, num_inference_steps=_num_steps, guidance_scale=guidance_scale, start_merge_step = start_merge_step, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images
572
+ else:
573
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
574
+ total_results = id_images + total_results
575
+ yield total_results
576
+ real_images = []
577
+ write = False
578
+ for ind,real_prompt in enumerate(real_prompts):
579
+ setup_seed(seed_)
580
+ cur_step = 0
581
+ real_prompt = apply_style_positive(style_name, real_prompt)
582
+ if _model_type == "original":
583
+ real_images.append(pipe(real_prompt, num_inference_steps=_num_steps, guidance_scale=guidance_scale, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images[0])
584
+ elif _model_type == "Photomaker":
585
+ real_images.append(pipe(real_prompt, input_id_images=input_id_images, num_inference_steps=_num_steps, guidance_scale=guidance_scale, start_merge_step = start_merge_step, height = height, width = width,negative_prompt = negative_prompt,generator = generator,nc_flag = True if ind+id_length in nc_indexs else False ).images[0])
586
+ else:
587
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
588
+ total_results = [real_images[-1]] + total_results
589
+ yield total_results
590
+ if _comic_type != "No typesetting (default)":
591
+ captions= prompt_array.splitlines()
592
+ captions = [caption.replace("[NC]","") for caption in captions]
593
+ captions = [caption.split('#')[-1] if "#" in caption else caption for caption in captions]
594
+ from PIL import ImageFont
595
+ total_results = get_comic(id_images + real_images, _comic_type,captions= captions,font=ImageFont.truetype("./fonts/Inkfree.ttf", int(45))) + total_results
596
+ yield total_results
597
+
598
+
599
+
600
+ def array2string(arr):
601
+ stringtmp = ""
602
+ for i,part in enumerate(arr):
603
+ if i != len(arr)-1:
604
+ stringtmp += part +"\n"
605
+ else:
606
+ stringtmp += part
607
+
608
+ return stringtmp
609
+
610
+
611
+ #################################################
612
+ #################################################
613
+ ### define the interface
614
+ with gr.Blocks(css=css) as demo:
615
+ binary_matrixes = gr.State([])
616
+ color_layout = gr.State([])
617
+
618
+ # gr.Markdown(logo)
619
+ gr.Markdown(title)
620
+ gr.Markdown(description)
621
+
622
+ with gr.Row():
623
+ with gr.Group(elem_id="main-image"):
624
+
625
+ prompts = []
626
+ colors = []
627
+
628
+ with gr.Column(visible=True) as gen_prompt_vis:
629
+ sd_type = gr.Dropdown(choices=list(models_dict.keys()), value = "Unstable",label="sd_type", info="Select pretrained model")
630
+ model_type = gr.Radio(["Only Using Textual Description", "Using Ref Images"], label="model_type", value = "Only Using Textual Description", info="Control type of the Character")
631
+ with gr.Group(visible=False) as control_image_input:
632
+ files = gr.Files(
633
+ label="Drag (Select) 1 or more photos of your face",
634
+ file_types=["image"],
635
+ )
636
+ uploaded_files = gr.Gallery(label="Your images", visible=False, columns=5, rows=1, height=200)
637
+ with gr.Column(visible=False) as clear_button:
638
+ remove_and_reupload = gr.ClearButton(value="Remove and upload new ones", components=files, size="sm")
639
+ general_prompt = gr.Textbox(value='', label="(1) Textual Description for Character", interactive=True)
640
+ negative_prompt = gr.Textbox(value='', label="(2) Negative_prompt", interactive=True)
641
+ style = gr.Dropdown(label="Style template", choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME)
642
+ prompt_array = gr.Textbox(lines = 3,value='', label="(3) Comic Description (each line corresponds to a frame).", interactive=True)
643
+ with gr.Accordion("(4) Tune the hyperparameters", open=True):
644
+ sa32_ = gr.Slider(label=" (The degree of Paired Attention at 32 x 32 self-attention layers) ", minimum=0, maximum=1., value=0.5, step=0.1)
645
+ sa64_ = gr.Slider(label=" (The degree of Paired Attention at 64 x 64 self-attention layers) ", minimum=0, maximum=1., value=0.5, step=0.1)
646
+ id_length_ = gr.Slider(label= "Number of id images in total images" , minimum=2, maximum=4, value=2, step=1)
647
+ seed_ = gr.Slider(label="Seed", minimum=-1, maximum=MAX_SEED, value=0, step=1)
648
+ num_steps = gr.Slider(
649
+ label="Number of sample steps",
650
+ minimum=20,
651
+ maximum=100,
652
+ step=1,
653
+ value=50,
654
+ )
655
+ G_height = gr.Slider(
656
+ label="height",
657
+ minimum=256,
658
+ maximum=1024,
659
+ step=32,
660
+ value=768,
661
+ )
662
+ G_width = gr.Slider(
663
+ label="width",
664
+ minimum=256,
665
+ maximum=1024,
666
+ step=32,
667
+ value=768,
668
+ )
669
+ comic_type = gr.Radio(["No typesetting (default)", "Four Pannel", "Classic Comic Style"], value = "Classic Comic Style", label="Typesetting Style", info="Select the typesetting style ")
670
+ guidance_scale = gr.Slider(
671
+ label="Guidance scale",
672
+ minimum=0.1,
673
+ maximum=10.0,
674
+ step=0.1,
675
+ value=5,
676
+ )
677
+ style_strength_ratio = gr.Slider(
678
+ label="Style strength of Ref Image (%)",
679
+ minimum=15,
680
+ maximum=50,
681
+ step=1,
682
+ value=20,
683
+ visible=False
684
+ )
685
+ Ip_Adapter_Strength = gr.Slider(
686
+ label="Ip_Adapter_Strength",
687
+ minimum=0,
688
+ maximum=1,
689
+ step=0.1,
690
+ value=0.5,
691
+ visible=False
692
+ )
693
+ final_run_btn = gr.Button("Generate ! 😺")
694
+
695
+
696
+ with gr.Column():
697
+ out_image = gr.Gallery(label="Result", columns=2, height='auto')
698
+ generated_information = gr.Markdown(label="Generation Details", value="",visible=False)
699
+ gr.Markdown(version)
700
+ model_type.change(fn = change_visiale_by_model_type , inputs = model_type, outputs=[control_image_input,style_strength_ratio,Ip_Adapter_Strength])
701
+ files.upload(fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files])
702
+ remove_and_reupload.click(fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files])
703
+
704
+ final_run_btn.click(fn=set_text_unfinished, outputs = generated_information
705
+ ).then(process_generation, inputs=[sd_type,model_type,files, num_steps,style, Ip_Adapter_Strength,style_strength_ratio, guidance_scale, seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,G_height,G_width,comic_type], outputs=out_image
706
+ ).then(fn=set_text_finished,outputs = generated_information)
707
+
708
+
709
+ gr.Examples(
710
+ examples=[
711
+ [0,0.5,0.5,2,"a man, wearing black suit",
712
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
713
+ array2string(["at home, read new paper #at home, The newspaper says there is a treasure house in the forest.",
714
+ "on the road, near the forest",
715
+ "[NC] The car on the road, near the forest #He drives to the forest in search of treasure.",
716
+ "[NC]A tiger appeared in the forest, at night ",
717
+ "very frightened, open mouth, in the forest, at night",
718
+ "running very fast, in the forest, at night",
719
+ "[NC] A house in the forest, at night #Suddenly, he discovers the treasure house!",
720
+ "in the house filled with treasure, laughing, at night #He is overjoyed inside the house."
721
+ ]),
722
+ "Comic book","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
723
+ ],
724
+ [0,0.5,0.5,2,"a man, wearing black suit",
725
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
726
+ array2string(["at home, read new paper #at home, The newspaper says there is a treasure house in the forest.",
727
+ "on the road, near the forest",
728
+ "[NC] The car on the road, near the forest #He drives to the forest in search of treasure.",
729
+ "[NC]A tiger appeared in the forest, at night ",
730
+ "very frightened, open mouth, in the forest, at night",
731
+ "running very fast, in the forest, at night",
732
+ "[NC] A house in the forest, at night #Suddenly, he discovers the treasure house!",
733
+ "in the house filled with treasure, laughing, at night #He is overjoyed inside the house."
734
+ ]),
735
+ "Comic book","Only Using Textual Description",get_image_path_list('./examples/Robert'),1024,1024
736
+ ],
737
+ [1,0.5,0.5,3,"a woman img, wearing a white T-shirt, blue loose hair",
738
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
739
+ array2string(["wake up in the bed",
740
+ "have breakfast",
741
+ "is on the road, go to company",
742
+ "work in the company",
743
+ "Take a walk next to the company at noon",
744
+ "lying in bed at night"]),
745
+ "Japanese Anime", "Using Ref Images",get_image_path_list('./examples/taylor'),768,768
746
+ ],
747
+ [0,0.5,0.5,3,"a man, wearing black jacket",
748
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
749
+ array2string(["wake up in the bed",
750
+ "have breakfast",
751
+ "is on the road, go to the company, close look",
752
+ "work in the company",
753
+ "laughing happily",
754
+ "lying in bed at night"
755
+ ]),
756
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
757
+ ],
758
+ [0,0.3,0.5,3,"a girl, wearing white shirt, black skirt, black tie, yellow hair",
759
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
760
+ array2string([
761
+ "at home #at home, began to go to drawing",
762
+ "sitting alone on a park bench.",
763
+ "reading a book on a park bench.",
764
+ "[NC]A squirrel approaches, peeking over the bench. ",
765
+ "look around in the park. # She looks around and enjoys the beauty of nature.",
766
+ "[NC]leaf falls from the tree, landing on the sketchbook.",
767
+ "picks up the leaf, examining its details closely.",
768
+ "[NC]The brown squirrel appear.",
769
+ "is very happy # She is very happy to see the squirrel again",
770
+ "[NC]The brown squirrel takes the cracker and scampers up a tree. # She gives the squirrel cracker"]),
771
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
772
+ ]
773
+ ],
774
+ inputs=[seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,style,model_type,files,G_height,G_width],
775
+ # outputs=[post_sketch, binary_matrixes, *color_row, *colors, *prompts, gen_prompt_vis, general_prompt, seed_],
776
+ # run_on_click=True,
777
+ label='😺 Examples 😺',
778
+ )
779
+ gr.Markdown(article)
780
+
781
+
782
+ demo.launch(server_name="0.0.0.0", share = False)
images/logo.png ADDED
images/pad_images.png ADDED
predict.py ADDED
@@ -0,0 +1,781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Prediction interface for Cog ⚙️
2
+ # https://cog.run/python
3
+
4
+ import os
5
+ import copy
6
+ import random
7
+ import subprocess
8
+ import numpy as np
9
+ import time
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from PIL import ImageFont
13
+ from cog import BasePredictor, Input, Path, BaseModel
14
+ from diffusers import StableDiffusionXLPipeline, DDIMScheduler
15
+ from diffusers.utils import load_image
16
+
17
+ from utils import PhotoMakerStableDiffusionXLPipeline
18
+ from utils.style_template import styles
19
+ from utils.gradio_utils import (
20
+ AttnProcessor2_0 as AttnProcessor,
21
+ ) # with torch2 installed
22
+ from utils.gradio_utils import cal_attn_mask_xl
23
+ from utils.utils import get_comic
24
+
25
+ MODEL_URL = "https://weights.replicate.delivery/default/HVision_NKU/StoryDiffusion.tar"
26
+ MODEL_CACHE = "model_weights"
27
+ STYLE_NAMES = list(styles.keys())
28
+ DEFAULT_STYLE_NAME = "Japanese Anime"
29
+
30
+ global total_count, attn_count, cur_step, mask1024, mask4096, attn_procs, unet
31
+ global sa32, sa64
32
+ global write
33
+ global height, width
34
+
35
+
36
+ """
37
+ # load and upload the weights to replicate.delivery for faster booting on Replicate
38
+ models_dict = {
39
+ "RealVision": "SG161222/RealVisXL_V4.0",
40
+ "Unstable": "stablediffusionapi/sdxl-unstable-diffusers-y",
41
+ }
42
+ # photomaker_path = hf_hub_download(repo_id="TencentARC/PhotoMaker", filename="photomaker-v1.bin", repo_type="model")
43
+ photomaker_path = f"{MODEL_CACHE}/PhotoMaker/photomaker-v1.bin"
44
+
45
+ pipe_unstable = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
46
+ models_dict["Unstable"],
47
+ torch_dtype=torch.float16,
48
+ use_safetensors=False,
49
+ )
50
+ pipe_unstable.save_pretrained(f"{MODEL_CACHE}/Unstable/stablediffusionapi/sdxl-unstable-diffusers-y")
51
+
52
+ pipe_realvision = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
53
+ models_dict["RealVision"], torch_dtype=torch.float16, use_safetensors=True
54
+ )
55
+ pipe_realvision.save_pretrained(f"{MODEL_CACHE}/RealVision/SG161222/RealVisXL_V4.0")
56
+ """
57
+
58
+
59
+ class ModelOutput(BaseModel):
60
+ comic: Path
61
+ individual_images: list[Path]
62
+
63
+
64
+ def download_weights(url, dest):
65
+ start = time.time()
66
+ print("downloading url: ", url)
67
+ print("downloading to: ", dest)
68
+ subprocess.check_call(["pget", "-x", url, dest], close_fds=False)
69
+ print("downloading took: ", time.time() - start)
70
+
71
+
72
+ def setup_seed(seed):
73
+ torch.manual_seed(seed)
74
+ torch.cuda.manual_seed_all(seed)
75
+ np.random.seed(seed)
76
+ random.seed(seed)
77
+ torch.backends.cudnn.deterministic = True
78
+
79
+
80
+ def apply_style_positive(style_name: str, positive: str):
81
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
82
+ return p.replace("{prompt}", positive)
83
+
84
+
85
+ def apply_style(style_name: str, positives: list, negative: str = ""):
86
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
87
+ return [
88
+ p.replace("{prompt}", positive) for positive in positives
89
+ ], n + " " + negative
90
+
91
+
92
+ def set_attention_processor(unet, id_length, is_ipadapter=False):
93
+ global total_count
94
+ total_count = 0
95
+ attn_procs = {}
96
+ for name in unet.attn_processors.keys():
97
+ cross_attention_dim = (
98
+ None
99
+ if name.endswith("attn1.processor")
100
+ else unet.config.cross_attention_dim
101
+ )
102
+ if name.startswith("mid_block"):
103
+ hidden_size = unet.config.block_out_channels[-1]
104
+ elif name.startswith("up_blocks"):
105
+ block_id = int(name[len("up_blocks.")])
106
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
107
+ elif name.startswith("down_blocks"):
108
+ block_id = int(name[len("down_blocks.")])
109
+ hidden_size = unet.config.block_out_channels[block_id]
110
+ if cross_attention_dim is None:
111
+ if name.startswith("up_blocks"):
112
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length=id_length)
113
+ total_count += 1
114
+ else:
115
+ attn_procs[name] = AttnProcessor()
116
+ else:
117
+ if is_ipadapter:
118
+ attn_procs[name] = IPAttnProcessor2_0(
119
+ hidden_size=hidden_size,
120
+ cross_attention_dim=cross_attention_dim,
121
+ scale=1,
122
+ num_tokens=4,
123
+ ).to(unet.device, dtype=torch.float16)
124
+ else:
125
+ attn_procs[name] = AttnProcessor()
126
+
127
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
128
+ print("Successfully load paired self-attention")
129
+ print(f"Number of the processor : {total_count}")
130
+
131
+
132
+ #################################################
133
+ ########Consistent Self-Attention################
134
+ #################################################
135
+ class SpatialAttnProcessor2_0(torch.nn.Module):
136
+ r"""
137
+ Attention processor for IP-Adapater for PyTorch 2.0.
138
+ Args:
139
+ hidden_size (`int`):
140
+ The hidden size of the attention layer.
141
+ cross_attention_dim (`int`):
142
+ The number of channels in the `encoder_hidden_states`.
143
+ text_context_len (`int`, defaults to 77):
144
+ The context length of the text features.
145
+ scale (`float`, defaults to 1.0):
146
+ the weight scale of image prompt.
147
+ """
148
+
149
+ def __init__(
150
+ self,
151
+ hidden_size=None,
152
+ cross_attention_dim=None,
153
+ id_length=4,
154
+ device="cuda",
155
+ dtype=torch.float16,
156
+ ):
157
+ super().__init__()
158
+ if not hasattr(F, "scaled_dot_product_attention"):
159
+ raise ImportError(
160
+ "AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
161
+ )
162
+ self.device = device
163
+ self.dtype = dtype
164
+ self.hidden_size = hidden_size
165
+ self.cross_attention_dim = cross_attention_dim
166
+ self.total_length = id_length + 1
167
+ self.id_length = id_length
168
+ self.id_bank = {}
169
+
170
+ def __call__(
171
+ self,
172
+ attn,
173
+ hidden_states,
174
+ encoder_hidden_states=None,
175
+ attention_mask=None,
176
+ temb=None,
177
+ ):
178
+ global total_count, attn_count, cur_step, mask1024, mask4096
179
+ global sa32, sa64
180
+ global write
181
+ global height, width
182
+ if write:
183
+ self.id_bank[cur_step] = [
184
+ hidden_states[: self.id_length],
185
+ hidden_states[self.id_length :],
186
+ ]
187
+ else:
188
+ encoder_hidden_states = torch.cat(
189
+ (
190
+ self.id_bank[cur_step][0].to(self.device),
191
+ hidden_states[:1],
192
+ self.id_bank[cur_step][1].to(self.device),
193
+ hidden_states[1:],
194
+ )
195
+ )
196
+ # skip in early step
197
+ if cur_step < 5:
198
+ hidden_states = self.__call2__(
199
+ attn, hidden_states, encoder_hidden_states, attention_mask, temb
200
+ )
201
+ else: # 256 1024 4096
202
+ random_number = random.random()
203
+ if cur_step < 20:
204
+ rand_num = 0.3
205
+ else:
206
+ rand_num = 0.1
207
+ if random_number > rand_num:
208
+ if not write:
209
+ if hidden_states.shape[1] == (height // 32) * (width // 32):
210
+ attention_mask = mask1024[
211
+ mask1024.shape[0] // self.total_length * self.id_length :
212
+ ]
213
+ else:
214
+ attention_mask = mask4096[
215
+ mask4096.shape[0] // self.total_length * self.id_length :
216
+ ]
217
+ else:
218
+ if hidden_states.shape[1] == (height // 32) * (width // 32):
219
+ attention_mask = mask1024[
220
+ : mask1024.shape[0] // self.total_length * self.id_length,
221
+ : mask1024.shape[0] // self.total_length * self.id_length,
222
+ ]
223
+ else:
224
+ attention_mask = mask4096[
225
+ : mask4096.shape[0] // self.total_length * self.id_length,
226
+ : mask4096.shape[0] // self.total_length * self.id_length,
227
+ ]
228
+ hidden_states = self.__call1__(
229
+ attn, hidden_states, encoder_hidden_states, attention_mask, temb
230
+ )
231
+ else:
232
+ hidden_states = self.__call2__(
233
+ attn, hidden_states, None, attention_mask, temb
234
+ )
235
+ attn_count += 1
236
+ if attn_count == total_count:
237
+ attn_count = 0
238
+ cur_step += 1
239
+ mask1024, mask4096 = cal_attn_mask_xl(
240
+ self.total_length,
241
+ self.id_length,
242
+ sa32,
243
+ sa64,
244
+ height,
245
+ width,
246
+ device=self.device,
247
+ dtype=self.dtype,
248
+ )
249
+
250
+ return hidden_states
251
+
252
+ def __call1__(
253
+ self,
254
+ attn,
255
+ hidden_states,
256
+ encoder_hidden_states=None,
257
+ attention_mask=None,
258
+ temb=None,
259
+ ):
260
+ residual = hidden_states
261
+ if attn.spatial_norm is not None:
262
+ hidden_states = attn.spatial_norm(hidden_states, temb)
263
+ input_ndim = hidden_states.ndim
264
+
265
+ if input_ndim == 4:
266
+ total_batch_size, channel, height, width = hidden_states.shape
267
+ hidden_states = hidden_states.view(
268
+ total_batch_size, channel, height * width
269
+ ).transpose(1, 2)
270
+ total_batch_size, nums_token, channel = hidden_states.shape
271
+ img_nums = total_batch_size // 2
272
+ hidden_states = hidden_states.view(-1, img_nums, nums_token, channel).reshape(
273
+ -1, img_nums * nums_token, channel
274
+ )
275
+
276
+ batch_size, sequence_length, _ = hidden_states.shape
277
+
278
+ if attn.group_norm is not None:
279
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(
280
+ 1, 2
281
+ )
282
+
283
+ query = attn.to_q(hidden_states)
284
+
285
+ if encoder_hidden_states is None:
286
+ encoder_hidden_states = hidden_states # B, N, C
287
+ else:
288
+ encoder_hidden_states = encoder_hidden_states.view(
289
+ -1, self.id_length + 1, nums_token, channel
290
+ ).reshape(-1, (self.id_length + 1) * nums_token, channel)
291
+
292
+ key = attn.to_k(encoder_hidden_states)
293
+ value = attn.to_v(encoder_hidden_states)
294
+
295
+ inner_dim = key.shape[-1]
296
+ head_dim = inner_dim // attn.heads
297
+
298
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
299
+
300
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
301
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
302
+ hidden_states = F.scaled_dot_product_attention(
303
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
304
+ )
305
+
306
+ hidden_states = hidden_states.transpose(1, 2).reshape(
307
+ total_batch_size, -1, attn.heads * head_dim
308
+ )
309
+ hidden_states = hidden_states.to(query.dtype)
310
+
311
+ # linear proj
312
+ hidden_states = attn.to_out[0](hidden_states)
313
+ # dropout
314
+ hidden_states = attn.to_out[1](hidden_states)
315
+
316
+ if input_ndim == 4:
317
+ hidden_states = hidden_states.transpose(-1, -2).reshape(
318
+ total_batch_size, channel, height, width
319
+ )
320
+ if attn.residual_connection:
321
+ hidden_states = hidden_states + residual
322
+ hidden_states = hidden_states / attn.rescale_output_factor
323
+ # print(hidden_states.shape)
324
+ return hidden_states
325
+
326
+ def __call2__(
327
+ self,
328
+ attn,
329
+ hidden_states,
330
+ encoder_hidden_states=None,
331
+ attention_mask=None,
332
+ temb=None,
333
+ ):
334
+ residual = hidden_states
335
+
336
+ if attn.spatial_norm is not None:
337
+ hidden_states = attn.spatial_norm(hidden_states, temb)
338
+
339
+ input_ndim = hidden_states.ndim
340
+
341
+ if input_ndim == 4:
342
+ batch_size, channel, height, width = hidden_states.shape
343
+ hidden_states = hidden_states.view(
344
+ batch_size, channel, height * width
345
+ ).transpose(1, 2)
346
+
347
+ batch_size, sequence_length, channel = hidden_states.shape
348
+ # print(hidden_states.shape)
349
+ if attention_mask is not None:
350
+ attention_mask = attn.prepare_attention_mask(
351
+ attention_mask, sequence_length, batch_size
352
+ )
353
+ # scaled_dot_product_attention expects attention_mask shape to be
354
+ # (batch, heads, source_length, target_length)
355
+ attention_mask = attention_mask.view(
356
+ batch_size, attn.heads, -1, attention_mask.shape[-1]
357
+ )
358
+
359
+ if attn.group_norm is not None:
360
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(
361
+ 1, 2
362
+ )
363
+
364
+ query = attn.to_q(hidden_states)
365
+
366
+ if encoder_hidden_states is None:
367
+ encoder_hidden_states = hidden_states # B, N, C
368
+ else:
369
+ encoder_hidden_states = encoder_hidden_states.view(
370
+ -1, self.id_length + 1, sequence_length, channel
371
+ ).reshape(-1, (self.id_length + 1) * sequence_length, channel)
372
+
373
+ key = attn.to_k(encoder_hidden_states)
374
+ value = attn.to_v(encoder_hidden_states)
375
+
376
+ inner_dim = key.shape[-1]
377
+ head_dim = inner_dim // attn.heads
378
+
379
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
380
+
381
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
382
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
383
+
384
+ hidden_states = F.scaled_dot_product_attention(
385
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
386
+ )
387
+
388
+ hidden_states = hidden_states.transpose(1, 2).reshape(
389
+ batch_size, -1, attn.heads * head_dim
390
+ )
391
+ hidden_states = hidden_states.to(query.dtype)
392
+
393
+ # linear proj
394
+ hidden_states = attn.to_out[0](hidden_states)
395
+ # dropout
396
+ hidden_states = attn.to_out[1](hidden_states)
397
+
398
+ if input_ndim == 4:
399
+ hidden_states = hidden_states.transpose(-1, -2).reshape(
400
+ batch_size, channel, height, width
401
+ )
402
+
403
+ if attn.residual_connection:
404
+ hidden_states = hidden_states + residual
405
+
406
+ hidden_states = hidden_states / attn.rescale_output_factor
407
+
408
+ return hidden_states
409
+
410
+
411
+ class Predictor(BasePredictor):
412
+ def setup(self) -> None:
413
+ """Load the model into memory to make running multiple predictions efficient"""
414
+
415
+ models_dict = {
416
+ "RealVision": "SG161222/RealVisXL_V4.0",
417
+ "Unstable": "stablediffusionapi/sdxl-unstable-diffusers-y",
418
+ }
419
+
420
+ if not os.path.exists(MODEL_CACHE):
421
+ download_weights(MODEL_URL, MODEL_CACHE)
422
+
423
+ photomaker_path = f"{MODEL_CACHE}/PhotoMaker/photomaker-v1.bin"
424
+
425
+ self.sdxl_pipe_unstable = StableDiffusionXLPipeline.from_pretrained(
426
+ f"{MODEL_CACHE}/Unstable/sdxl/stablediffusionapi/sdxl-unstable-diffusers-y",
427
+ torch_dtype=torch.float16,
428
+ )
429
+ self.sdxl_pipe_realvision = StableDiffusionXLPipeline.from_pretrained(
430
+ f"{MODEL_CACHE}/RealVision/sdxl/SG161222/RealVisXL_V4.0",
431
+ torch_dtype=torch.float16,
432
+ )
433
+
434
+ self.pipe_unstable = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
435
+ f"{MODEL_CACHE}/Unstable/stablediffusionapi/sdxl-unstable-diffusers-y",
436
+ torch_dtype=torch.float16,
437
+ use_safetensors=False,
438
+ )
439
+ self.pipe_unstable.load_photomaker_adapter(
440
+ os.path.dirname(photomaker_path),
441
+ subfolder="",
442
+ weight_name=os.path.basename(photomaker_path),
443
+ trigger_word="img", # define the trigger word
444
+ )
445
+
446
+ self.pipe_realvision = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
447
+ f"{MODEL_CACHE}/RealVision/SG161222/RealVisXL_V4.0",
448
+ torch_dtype=torch.float16,
449
+ use_safetensors=True,
450
+ )
451
+ self.pipe_realvision.load_photomaker_adapter(
452
+ os.path.dirname(photomaker_path),
453
+ subfolder="",
454
+ weight_name=os.path.basename(photomaker_path),
455
+ trigger_word="img", # define the trigger word
456
+ )
457
+ self.pipe_realvision.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
458
+ self.pipe_realvision.fuse_lora()
459
+
460
+ @torch.inference_mode()
461
+ def predict(
462
+ self,
463
+ sd_model: str = Input(
464
+ description="Choose a model",
465
+ choices=["Unstable", "RealVision"],
466
+ default="Unstable",
467
+ ),
468
+ ref_image: Path = Input(
469
+ description="Reference image for the character",
470
+ default=None,
471
+ ),
472
+ character_description: str = Input(
473
+ description="General description of the character. If ref_image above is provided, making sure to follow the class word you want to customize with the trigger word 'img', such as: 'man img' or 'woman img' or 'girl img'",
474
+ default="a man, wearing black suit",
475
+ ),
476
+ negative_prompt: str = Input(
477
+ description="Describe things you do not want to see in the output",
478
+ default="bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
479
+ ),
480
+ comic_description: str = Input(
481
+ description="Comic Description. Each frame is divided by a new line. Only the first 10 prompts are valid for demo speed! For comic_description NOT using ref_image: (1) Support Typesetting Style and Captioning. By default, the prompt is used as the caption for each image. If you need to change the caption, add a '#' at the end of each line. Only the part after the '#' will be added as a caption to the image. (2) The [NC] symbol is used as a flag to indicate that no characters should be present in the generated scene images. If you want do that, prepend the '[NC]' at the beginning of the line.",
482
+ default="at home, read new paper #at home, The newspaper says there is a treasure house in the forest.\non the road, near the forest\n[NC] The car on the road, near the forest #He drives to the forest in search of treasure.\n[NC]A tiger appeared in the forest, at night \nvery frightened, open mouth, in the forest, at night\nrunning very fast, in the forest, at night\n[NC] A house in the forest, at night #Suddenly, he discovers the treasure house!\nin the house filled with treasure, laughing, at night #He is overjoyed inside the house.",
483
+ ),
484
+ style_name: str = Input(
485
+ description="Style template",
486
+ choices=STYLE_NAMES,
487
+ default=DEFAULT_STYLE_NAME,
488
+ ),
489
+ comic_style: str = Input(
490
+ description="Select the comic style for the combined comic",
491
+ choices=["Four Pannel", "Classic Comic Style"],
492
+ default="Classic Comic Style",
493
+ ),
494
+ style_strength_ratio: int = Input(
495
+ description="Style strength of Ref Image (%), only used if ref_image is provided",
496
+ default=20,
497
+ ge=15,
498
+ le=50,
499
+ ),
500
+ image_width: int = Input(
501
+ description="Width of output image",
502
+ choices=[
503
+ 256,
504
+ 288,
505
+ 320,
506
+ 352,
507
+ 384,
508
+ 416,
509
+ 448,
510
+ 480,
511
+ 512,
512
+ 544,
513
+ 576,
514
+ 608,
515
+ 640,
516
+ 672,
517
+ 704,
518
+ 736,
519
+ 768,
520
+ 800,
521
+ 832,
522
+ 864,
523
+ 896,
524
+ 928,
525
+ 960,
526
+ 992,
527
+ 1024,
528
+ ],
529
+ default=768,
530
+ ),
531
+ image_height: int = Input(
532
+ description="Height of output image",
533
+ choices=[
534
+ 256,
535
+ 288,
536
+ 320,
537
+ 352,
538
+ 384,
539
+ 416,
540
+ 448,
541
+ 480,
542
+ 512,
543
+ 544,
544
+ 576,
545
+ 608,
546
+ 640,
547
+ 672,
548
+ 704,
549
+ 736,
550
+ 768,
551
+ 800,
552
+ 832,
553
+ 864,
554
+ 896,
555
+ 928,
556
+ 960,
557
+ 992,
558
+ 1024,
559
+ ],
560
+ default=768,
561
+ ),
562
+ num_steps: int = Input(
563
+ description="Number of sample steps", ge=20, le=50, default=25
564
+ ),
565
+ guidance_scale: float = Input(
566
+ description="Scale for classifier-free guidance", ge=0.1, le=10, default=5
567
+ ),
568
+ seed: int = Input(
569
+ description="Random seed. Leave blank to randomize the seed", default=None
570
+ ),
571
+ sa32_setting: float = Input(
572
+ description="The degree of Paired Attention at 32 x 32 self-attention layers",
573
+ default=0.5,
574
+ ge=0,
575
+ le=1.0,
576
+ ),
577
+ sa64_setting: float = Input(
578
+ description="The degree of Paired Attention at 64 x 64 self-attention layers",
579
+ default=0.5,
580
+ ge=0,
581
+ le=1.0,
582
+ ),
583
+ num_ids: int = Input(
584
+ description="Number of id images in total images. This should not exceed total number of line-separated prompts",
585
+ default=3,
586
+ ),
587
+ output_format: str = Input(
588
+ description="Format of the output images",
589
+ choices=["webp", "jpg", "png"],
590
+ default="webp",
591
+ ),
592
+ output_quality: int = Input(
593
+ description="Quality of the output images, from 0 to 100. 100 is best quality, 0 is lowest quality",
594
+ default=80,
595
+ ge=0,
596
+ le=100,
597
+ ),
598
+ ) -> ModelOutput:
599
+ """Run a single prediction on the model"""
600
+
601
+ global total_count, attn_count, cur_step, mask1024, mask4096, attn_procs, unet
602
+ global sa32, sa64
603
+ global write
604
+ global height, width
605
+
606
+ assert (
607
+ len(character_description.strip()) > 0
608
+ ), "Please provide the description of the character."
609
+
610
+ if ref_image is not None:
611
+ assert (
612
+ "img" in character_description
613
+ ), f"When using ref_image, please add the trigger word 'img' behind the class word you want to customize, such as: man img or woman img"
614
+ assert (
615
+ "[NC]" not in comic_description
616
+ ), "You should not use trigger word [NC] when ref_image is provided."
617
+
618
+ height = image_height
619
+ width = image_width
620
+ id_length = num_ids
621
+ sa32 = sa32_setting
622
+ sa64 = sa64_setting
623
+
624
+ clipped_prompts = comic_description.splitlines()[:10]
625
+ print(clipped_prompts)
626
+ prompts = [
627
+ (
628
+ character_description + "," + prompt
629
+ if "[NC]" not in prompt
630
+ else prompt.replace("[NC]", "")
631
+ )
632
+ for prompt in clipped_prompts
633
+ ]
634
+ print(prompts)
635
+ prompts = [
636
+ prompt.rpartition("#")[0].strip() if "#" in prompt else prompt.strip()
637
+ for prompt in prompts
638
+ ]
639
+ print(prompts)
640
+ assert id_length <= len(
641
+ prompts
642
+ ), "id_length should not exceed total number of line-separated prompts"
643
+
644
+ id_prompts = prompts[:id_length]
645
+ real_prompts = prompts[id_length:]
646
+
647
+ if seed is None:
648
+ seed = int.from_bytes(os.urandom(2), "big")
649
+ print(f"Using seed: {seed}")
650
+
651
+ device = "cuda:0"
652
+ setup_seed(seed)
653
+ generator = torch.Generator(device=device).manual_seed(seed)
654
+
655
+ torch.cuda.empty_cache()
656
+
657
+ model_type = "original" if ref_image is None else "Photomaker"
658
+
659
+ if model_type == "original":
660
+ pipe = (
661
+ self.sdxl_pipe_realvision
662
+ if style_name == "(No style)"
663
+ else self.sdxl_pipe_unstable
664
+ )
665
+ pipe = pipe.to(device)
666
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
667
+ else:
668
+ if sd_model != "RealVision" and style_name != "(No style)":
669
+ pipe = self.pipe_unstable.to(device)
670
+ else:
671
+ pipe = self.pipe_realvision.to(device)
672
+ pipe.id_encoder.to(device)
673
+
674
+ write = True
675
+ cur_step = 0
676
+ attn_count = 0
677
+
678
+ set_attention_processor(pipe.unet, id_length, is_ipadapter=False)
679
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
680
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
681
+ curmodel_type = sd_model + "-" + model_type + "" + str(id_length)
682
+
683
+ id_prompts, negative_prompt = apply_style(
684
+ style_name, id_prompts, negative_prompt
685
+ )
686
+
687
+ total_results = []
688
+ if model_type == "original":
689
+ id_images = pipe(
690
+ id_prompts,
691
+ num_inference_steps=num_steps,
692
+ guidance_scale=guidance_scale,
693
+ height=height,
694
+ width=width,
695
+ negative_prompt=negative_prompt,
696
+ generator=generator,
697
+ ).images
698
+ else:
699
+ input_id_images = [load_image(str(ref_image))]
700
+ start_merge_step = int(float(style_strength_ratio) / 100 * num_steps)
701
+ id_images = pipe(
702
+ id_prompts,
703
+ input_id_images=input_id_images,
704
+ num_inference_steps=num_steps,
705
+ guidance_scale=guidance_scale,
706
+ start_merge_step=start_merge_step,
707
+ height=height,
708
+ width=width,
709
+ negative_prompt=negative_prompt,
710
+ generator=generator,
711
+ ).images
712
+
713
+ total_results = id_images + total_results
714
+
715
+ real_images = []
716
+ write = False
717
+ for real_prompt in real_prompts:
718
+ cur_step = 0
719
+ real_prompt = apply_style_positive(style_name, real_prompt)
720
+ if model_type == "original":
721
+ real_images.append(
722
+ pipe(
723
+ real_prompt,
724
+ num_inference_steps=num_steps,
725
+ guidance_scale=guidance_scale,
726
+ height=height,
727
+ width=width,
728
+ negative_prompt=negative_prompt,
729
+ generator=generator,
730
+ ).images[0]
731
+ )
732
+ else:
733
+ real_images.append(
734
+ pipe(
735
+ real_prompt,
736
+ input_id_images=input_id_images,
737
+ num_inference_steps=num_steps,
738
+ guidance_scale=guidance_scale,
739
+ start_merge_step=start_merge_step,
740
+ height=height,
741
+ width=width,
742
+ negative_prompt=negative_prompt,
743
+ generator=generator,
744
+ ).images[0]
745
+ )
746
+
747
+ total_results = [real_images[-1]] + total_results
748
+
749
+ captions = clipped_prompts
750
+ captions = [caption.replace("[NC]", "") for caption in captions]
751
+ captions = [
752
+ caption.split("#")[-1].strip() if "#" in caption else caption.strip()
753
+ for caption in captions
754
+ ]
755
+
756
+ comic = get_comic(
757
+ id_images + real_images,
758
+ comic_style,
759
+ captions=captions,
760
+ font=ImageFont.truetype("./fonts/Inkfree.ttf", int(45)),
761
+ )
762
+
763
+ extension = output_format.lower()
764
+ extension = "jpeg" if extension == "jpg" else extension
765
+ comic_out = f"/tmp/comic.{extension}"
766
+ comic[0].save(comic_out)
767
+
768
+ save_params = {"format": extension.upper()}
769
+ if not output_format == "png":
770
+ save_params["quality"] = output_quality
771
+ save_params["optimize"] = True
772
+
773
+ output_paths = []
774
+ for index, sample in enumerate(total_results[::-1]):
775
+ output_filename = f"/tmp/out-{index}.{extension}"
776
+ sample.save(output_filename, **save_params)
777
+ output_paths.append(Path(output_filename))
778
+
779
+ del pipe
780
+
781
+ return ModelOutput(comic=Path(comic_out), individual_images=output_paths)
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio==4.22.0
2
+ xformers==0.0.20
3
+ torch==2.0.1
4
+ torchvision==0.15.2
5
+ diffusers==0.25.0
6
+ transformers==4.36.2
7
+ huggingface-hub==0.20.2
8
+ spaces==0.19.4
9
+ numpy
10
+ accelerate
11
+ safetensors
12
+ omegaconf
13
+ peft
14
+ httpx==0.27.0
15
+ safetensors==0.4.0
results_examples/image1.png ADDED

Git LFS Details

  • SHA256: 0fe3c748813c1503b369c8b84bf35331e316cb12aacc6503536d11d9a514088e
  • Pointer size: 132 Bytes
  • Size of remote file: 8.3 MB
update.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Update History
2
+
3
+ ### Update 2024-05-08
4
+
5
+ - Support [NC] in Ref Image Model (Photomaker work best in 1024x1024 but may cost a lot of GPU memory, I recommend you to use the res. as larger as possible)
6
+
7
+ <img src="results_examples/image1.png" height=100>
8
+
9
+ - Merge Push by @cryptowooser to support lastest pillow. But you may be updated pillow if you using the old version.
10
+
11
+
12
+
13
+ ### Todo
14
+
15
+ - Support add captions on all images for the classical commic Typesetting Style
16
+
17
+
18
+
19
+
20
+ ### Welcome to contribute
21
+
22
+ - Various layout styles.
utils/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .model import PhotoMakerIDEncoder
2
+ from .pipeline import PhotoMakerStableDiffusionXLPipeline
3
+
4
+ __all__ = [
5
+ "PhotoMakerIDEncoder",
6
+ "PhotoMakerStableDiffusionXLPipeline",
7
+ ]
utils/gradio_utils.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import random
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+
6
+
7
+ class SpatialAttnProcessor2_0(torch.nn.Module):
8
+ r"""
9
+ Attention processor for IP-Adapater for PyTorch 2.0.
10
+ Args:
11
+ hidden_size (`int`):
12
+ The hidden size of the attention layer.
13
+ cross_attention_dim (`int`):
14
+ The number of channels in the `encoder_hidden_states`.
15
+ text_context_len (`int`, defaults to 77):
16
+ The context length of the text features.
17
+ scale (`float`, defaults to 1.0):
18
+ the weight scale of image prompt.
19
+ """
20
+
21
+ def __init__(self, hidden_size = None, cross_attention_dim=None,id_length = 4,device = "cuda",dtype = torch.float16):
22
+ super().__init__()
23
+ if not hasattr(F, "scaled_dot_product_attention"):
24
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
25
+ self.device = device
26
+ self.dtype = dtype
27
+ self.hidden_size = hidden_size
28
+ self.cross_attention_dim = cross_attention_dim
29
+ self.total_length = id_length + 1
30
+ self.id_length = id_length
31
+ self.id_bank = {}
32
+
33
+ def __call__(
34
+ self,
35
+ attn,
36
+ hidden_states,
37
+ encoder_hidden_states=None,
38
+ attention_mask=None,
39
+ temb=None):
40
+ # un_cond_hidden_states, cond_hidden_states = hidden_states.chunk(2)
41
+ # un_cond_hidden_states = self.__call2__(attn, un_cond_hidden_states,encoder_hidden_states,attention_mask,temb)
42
+ # 生成一个0到1之间的随机数
43
+ global total_count,attn_count,cur_step,mask256,mask1024,mask4096
44
+ global sa16, sa32, sa64
45
+ global write
46
+ if write:
47
+ self.id_bank[cur_step] = [hidden_states[:self.id_length], hidden_states[self.id_length:]]
48
+ else:
49
+ encoder_hidden_states = torch.cat(self.id_bank[cur_step][0],hidden_states[:1],self.id_bank[cur_step][1],hidden_states[1:])
50
+ # 判断随机数是否大于0.5
51
+ if cur_step <5:
52
+ hidden_states = self.__call2__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
53
+ else: # 256 1024 4096
54
+ random_number = random.random()
55
+ if cur_step <20:
56
+ rand_num = 0.3
57
+ else:
58
+ rand_num = 0.1
59
+ if random_number > rand_num:
60
+ if not write:
61
+ if hidden_states.shape[1] == 32* 32:
62
+ attention_mask = mask1024[mask1024.shape[0] // self.total_length * self.id_length:]
63
+ elif hidden_states.shape[1] ==16*16:
64
+ attention_mask = mask256[mask256.shape[0] // self.total_length * self.id_length:]
65
+ else:
66
+ attention_mask = mask4096[mask4096.shape[0] // self.total_length * self.id_length:]
67
+ else:
68
+ if hidden_states.shape[1] == 32* 32:
69
+ attention_mask = mask1024[:mask1024.shape[0] // self.total_length * self.id_length]
70
+ elif hidden_states.shape[1] ==16*16:
71
+ attention_mask = mask256[:mask256.shape[0] // self.total_length * self.id_length]
72
+ else:
73
+ attention_mask = mask4096[:mask4096.shape[0] // self.total_length * self.id_length]
74
+ hidden_states = self.__call1__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
75
+ else:
76
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
77
+ attn_count +=1
78
+ if attn_count == total_count:
79
+ attn_count = 0
80
+ cur_step += 1
81
+ mask256,mask1024,mask4096 = cal_attn_mask(self.total_length,self.id_length,sa16,sa32,sa64, device=self.device, dtype= self.dtype)
82
+
83
+ return hidden_states
84
+ def __call1__(
85
+ self,
86
+ attn,
87
+ hidden_states,
88
+ encoder_hidden_states=None,
89
+ attention_mask=None,
90
+ temb=None,
91
+ ):
92
+ residual = hidden_states
93
+ if encoder_hidden_states is not None:
94
+ raise Exception("not implement")
95
+ if attn.spatial_norm is not None:
96
+ hidden_states = attn.spatial_norm(hidden_states, temb)
97
+ input_ndim = hidden_states.ndim
98
+
99
+ if input_ndim == 4:
100
+ total_batch_size, channel, height, width = hidden_states.shape
101
+ hidden_states = hidden_states.view(total_batch_size, channel, height * width).transpose(1, 2)
102
+ total_batch_size,nums_token,channel = hidden_states.shape
103
+ img_nums = total_batch_size//2
104
+ hidden_states = hidden_states.view(-1,img_nums,nums_token,channel).reshape(-1,img_nums * nums_token,channel)
105
+
106
+ batch_size, sequence_length, _ = hidden_states.shape
107
+
108
+ if attn.group_norm is not None:
109
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
110
+
111
+ query = attn.to_q(hidden_states)
112
+
113
+ if encoder_hidden_states is None:
114
+ encoder_hidden_states = hidden_states # B, N, C
115
+ else:
116
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,nums_token,channel).reshape(-1,(self.id_length+1) * nums_token,channel)
117
+
118
+ key = attn.to_k(encoder_hidden_states)
119
+ value = attn.to_v(encoder_hidden_states)
120
+
121
+
122
+ inner_dim = key.shape[-1]
123
+ head_dim = inner_dim // attn.heads
124
+
125
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
126
+
127
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
128
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
129
+
130
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
131
+ # TODO: add support for attn.scale when we move to Torch 2.1
132
+ hidden_states = F.scaled_dot_product_attention(
133
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
134
+ )
135
+
136
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
137
+ hidden_states = hidden_states.to(query.dtype)
138
+
139
+
140
+
141
+ # linear proj
142
+ hidden_states = attn.to_out[0](hidden_states)
143
+ # dropout
144
+ hidden_states = attn.to_out[1](hidden_states)
145
+
146
+ # if input_ndim == 4:
147
+ # tile_hidden_states = tile_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
148
+
149
+ # if attn.residual_connection:
150
+ # tile_hidden_states = tile_hidden_states + residual
151
+
152
+ if input_ndim == 4:
153
+ hidden_states = hidden_states.transpose(-1, -2).reshape(total_batch_size, channel, height, width)
154
+ if attn.residual_connection:
155
+ hidden_states = hidden_states + residual
156
+ hidden_states = hidden_states / attn.rescale_output_factor
157
+
158
+ return hidden_states
159
+ def __call2__(
160
+ self,
161
+ attn,
162
+ hidden_states,
163
+ encoder_hidden_states=None,
164
+ attention_mask=None,
165
+ temb=None):
166
+ residual = hidden_states
167
+
168
+ if attn.spatial_norm is not None:
169
+ hidden_states = attn.spatial_norm(hidden_states, temb)
170
+
171
+ input_ndim = hidden_states.ndim
172
+
173
+ if input_ndim == 4:
174
+ batch_size, channel, height, width = hidden_states.shape
175
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
176
+
177
+ batch_size, sequence_length, _ = (
178
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
179
+ )
180
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
181
+
182
+ if attn.group_norm is not None:
183
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
184
+
185
+ query = attn.to_q(hidden_states)
186
+
187
+ if encoder_hidden_states is None:
188
+ encoder_hidden_states = hidden_states
189
+ elif attn.norm_cross:
190
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
191
+
192
+ key = attn.to_k(encoder_hidden_states)
193
+ value = attn.to_v(encoder_hidden_states)
194
+
195
+ query = attn.head_to_batch_dim(query)
196
+ key = attn.head_to_batch_dim(key)
197
+ value = attn.head_to_batch_dim(value)
198
+
199
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
200
+ hidden_states = torch.bmm(attention_probs, value)
201
+ hidden_states = attn.batch_to_head_dim(hidden_states)
202
+
203
+ # linear proj
204
+ hidden_states = attn.to_out[0](hidden_states)
205
+ # dropout
206
+ hidden_states = attn.to_out[1](hidden_states)
207
+
208
+ if input_ndim == 4:
209
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
210
+
211
+ if attn.residual_connection:
212
+ hidden_states = hidden_states + residual
213
+
214
+ hidden_states = hidden_states / attn.rescale_output_factor
215
+
216
+ return hidden_states
217
+
218
+
219
+ def cal_attn_mask(total_length,id_length,sa16,sa32,sa64,device="cuda",dtype= torch.float16):
220
+ bool_matrix256 = torch.rand((1, total_length * 256),device = device,dtype = dtype) < sa16
221
+ bool_matrix1024 = torch.rand((1, total_length * 1024),device = device,dtype = dtype) < sa32
222
+ bool_matrix4096 = torch.rand((1, total_length * 4096),device = device,dtype = dtype) < sa64
223
+ bool_matrix256 = bool_matrix256.repeat(total_length,1)
224
+ bool_matrix1024 = bool_matrix1024.repeat(total_length,1)
225
+ bool_matrix4096 = bool_matrix4096.repeat(total_length,1)
226
+ for i in range(total_length):
227
+ bool_matrix256[i:i+1,id_length*256:] = False
228
+ bool_matrix1024[i:i+1,id_length*1024:] = False
229
+ bool_matrix4096[i:i+1,id_length*4096:] = False
230
+ bool_matrix256[i:i+1,i*256:(i+1)*256] = True
231
+ bool_matrix1024[i:i+1,i*1024:(i+1)*1024] = True
232
+ bool_matrix4096[i:i+1,i*4096:(i+1)*4096] = True
233
+ mask256 = bool_matrix256.unsqueeze(1).repeat(1,256,1).reshape(-1,total_length * 256)
234
+ mask1024 = bool_matrix1024.unsqueeze(1).repeat(1,1024,1).reshape(-1,total_length * 1024)
235
+ mask4096 = bool_matrix4096.unsqueeze(1).repeat(1,4096,1).reshape(-1,total_length * 4096)
236
+ return mask256,mask1024,mask4096
237
+
238
+ def cal_attn_mask_xl(total_length,id_length,sa32,sa64,height,width,device="cuda",dtype= torch.float16):
239
+ nums_1024 = (height // 32) * (width // 32)
240
+ nums_4096 = (height // 16) * (width // 16)
241
+ bool_matrix1024 = torch.rand((1, total_length * nums_1024),device = device,dtype = dtype) < sa32
242
+ bool_matrix4096 = torch.rand((1, total_length * nums_4096),device = device,dtype = dtype) < sa64
243
+ bool_matrix1024 = bool_matrix1024.repeat(total_length,1)
244
+ bool_matrix4096 = bool_matrix4096.repeat(total_length,1)
245
+ for i in range(total_length):
246
+ bool_matrix1024[i:i+1,id_length*nums_1024:] = False
247
+ bool_matrix4096[i:i+1,id_length*nums_4096:] = False
248
+ bool_matrix1024[i:i+1,i*nums_1024:(i+1)*nums_1024] = True
249
+ bool_matrix4096[i:i+1,i*nums_4096:(i+1)*nums_4096] = True
250
+ mask1024 = bool_matrix1024.unsqueeze(1).repeat(1,nums_1024,1).reshape(-1,total_length * nums_1024)
251
+ mask4096 = bool_matrix4096.unsqueeze(1).repeat(1,nums_4096,1).reshape(-1,total_length * nums_4096)
252
+ return mask1024,mask4096
253
+
254
+
255
+ def cal_attn_indice_xl_effcient_memory(total_length,id_length,sa32,sa64,height,width,device="cuda",dtype= torch.float16):
256
+ nums_1024 = (height // 32) * (width // 32)
257
+ nums_4096 = (height // 16) * (width // 16)
258
+ bool_matrix1024 = torch.rand((total_length,nums_1024),device = device,dtype = dtype) < sa32
259
+ bool_matrix4096 = torch.rand((total_length,nums_4096),device = device,dtype = dtype) < sa64
260
+ # 用nonzero()函数获取所有为True的值的索引
261
+ indices1024 = [torch.nonzero(bool_matrix1024[i], as_tuple=True)[0] for i in range(total_length)]
262
+ indices4096 = [torch.nonzero(bool_matrix4096[i], as_tuple=True)[0] for i in range(total_length)]
263
+
264
+ return indices1024,indices4096
265
+
266
+
267
+ class AttnProcessor(nn.Module):
268
+ r"""
269
+ Default processor for performing attention-related computations.
270
+ """
271
+ def __init__(
272
+ self,
273
+ hidden_size=None,
274
+ cross_attention_dim=None,
275
+ ):
276
+ super().__init__()
277
+
278
+ def __call__(
279
+ self,
280
+ attn,
281
+ hidden_states,
282
+ encoder_hidden_states=None,
283
+ attention_mask=None,
284
+ temb=None,
285
+ ):
286
+ residual = hidden_states
287
+
288
+ if attn.spatial_norm is not None:
289
+ hidden_states = attn.spatial_norm(hidden_states, temb)
290
+
291
+ input_ndim = hidden_states.ndim
292
+
293
+ if input_ndim == 4:
294
+ batch_size, channel, height, width = hidden_states.shape
295
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
296
+
297
+ batch_size, sequence_length, _ = (
298
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
299
+ )
300
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
301
+
302
+ if attn.group_norm is not None:
303
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
304
+
305
+ query = attn.to_q(hidden_states)
306
+
307
+ if encoder_hidden_states is None:
308
+ encoder_hidden_states = hidden_states
309
+ elif attn.norm_cross:
310
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
311
+
312
+ key = attn.to_k(encoder_hidden_states)
313
+ value = attn.to_v(encoder_hidden_states)
314
+
315
+ query = attn.head_to_batch_dim(query)
316
+ key = attn.head_to_batch_dim(key)
317
+ value = attn.head_to_batch_dim(value)
318
+
319
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
320
+ hidden_states = torch.bmm(attention_probs, value)
321
+ hidden_states = attn.batch_to_head_dim(hidden_states)
322
+
323
+ # linear proj
324
+ hidden_states = attn.to_out[0](hidden_states)
325
+ # dropout
326
+ hidden_states = attn.to_out[1](hidden_states)
327
+
328
+ if input_ndim == 4:
329
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
330
+
331
+ if attn.residual_connection:
332
+ hidden_states = hidden_states + residual
333
+
334
+ hidden_states = hidden_states / attn.rescale_output_factor
335
+
336
+ return hidden_states
337
+
338
+
339
+ class AttnProcessor2_0(torch.nn.Module):
340
+ r"""
341
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
342
+ """
343
+ def __init__(
344
+ self,
345
+ hidden_size=None,
346
+ cross_attention_dim=None,
347
+ ):
348
+ super().__init__()
349
+ if not hasattr(F, "scaled_dot_product_attention"):
350
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
351
+
352
+ def __call__(
353
+ self,
354
+ attn,
355
+ hidden_states,
356
+ encoder_hidden_states=None,
357
+ attention_mask=None,
358
+ temb=None,
359
+ ):
360
+ residual = hidden_states
361
+
362
+ if attn.spatial_norm is not None:
363
+ hidden_states = attn.spatial_norm(hidden_states, temb)
364
+
365
+ input_ndim = hidden_states.ndim
366
+
367
+ if input_ndim == 4:
368
+ batch_size, channel, height, width = hidden_states.shape
369
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
370
+
371
+ batch_size, sequence_length, _ = (
372
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
373
+ )
374
+
375
+ if attention_mask is not None:
376
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
377
+ # scaled_dot_product_attention expects attention_mask shape to be
378
+ # (batch, heads, source_length, target_length)
379
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
380
+
381
+ if attn.group_norm is not None:
382
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
383
+
384
+ query = attn.to_q(hidden_states)
385
+
386
+ if encoder_hidden_states is None:
387
+ encoder_hidden_states = hidden_states
388
+ elif attn.norm_cross:
389
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
390
+
391
+ key = attn.to_k(encoder_hidden_states)
392
+ value = attn.to_v(encoder_hidden_states)
393
+
394
+ inner_dim = key.shape[-1]
395
+ head_dim = inner_dim // attn.heads
396
+
397
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
398
+
399
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
400
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
401
+
402
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
403
+ # TODO: add support for attn.scale when we move to Torch 2.1
404
+ hidden_states = F.scaled_dot_product_attention(
405
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
406
+ )
407
+
408
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
409
+ hidden_states = hidden_states.to(query.dtype)
410
+
411
+ # linear proj
412
+ hidden_states = attn.to_out[0](hidden_states)
413
+ # dropout
414
+ hidden_states = attn.to_out[1](hidden_states)
415
+
416
+ if input_ndim == 4:
417
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
418
+
419
+ if attn.residual_connection:
420
+ hidden_states = hidden_states + residual
421
+
422
+ hidden_states = hidden_states / attn.rescale_output_factor
423
+
424
+ return hidden_states
425
+
426
+
427
+ def is_torch2_available():
428
+ return hasattr(F, "scaled_dot_product_attention")
utils/load_models_utils.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yaml
2
+ import torch
3
+ from diffusers import StableDiffusionXLPipeline
4
+ from utils import PhotoMakerStableDiffusionXLPipeline
5
+ import os
6
+
7
+ def get_models_dict():
8
+ # 打开并读取YAML文件
9
+ with open('config/models.yaml', 'r') as stream:
10
+ try:
11
+ # 解析YAML文件内容
12
+ data = yaml.safe_load(stream)
13
+
14
+ # 此时 'data' 是一个Python字典,里面包含了YAML文件的所有数据
15
+ print(data)
16
+ return data
17
+
18
+ except yaml.YAMLError as exc:
19
+ # 如果在解析过程中发生了错误,打印异常信息
20
+ print(exc)
21
+
22
+ def load_models(model_info,device,photomaker_path):
23
+ path = model_info["path"]
24
+ single_files = model_info["single_files"]
25
+ use_safetensors = model_info["use_safetensors"]
26
+ model_type = model_info["model_type"]
27
+
28
+ if model_type == "original":
29
+ if single_files:
30
+ pipe = StableDiffusionXLPipeline.from_single_file(
31
+ path,
32
+ torch_dtype=torch.float16
33
+ )
34
+ else:
35
+ pipe = StableDiffusionXLPipeline.from_pretrained(path, torch_dtype=torch.float16, use_safetensors=use_safetensors)
36
+ pipe = pipe.to(device)
37
+ elif model_type == "Photomaker":
38
+ if single_files:
39
+ print("loading from a single_files")
40
+ pipe = PhotoMakerStableDiffusionXLPipeline.from_single_file(
41
+ path,
42
+ torch_dtype=torch.float16
43
+ )
44
+ else:
45
+ pipe = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
46
+ path, torch_dtype=torch.float16, use_safetensors=use_safetensors)
47
+ pipe = pipe.to(device)
48
+ pipe.load_photomaker_adapter(
49
+ os.path.dirname(photomaker_path),
50
+ subfolder="",
51
+ weight_name=os.path.basename(photomaker_path),
52
+ trigger_word="img" # define the trigger word
53
+ )
54
+ pipe.fuse_lora()
55
+ else:
56
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {model_type}")
57
+ return pipe
utils/model.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Merge image encoder and fuse module to create an ID Encoder
2
+ # send multiple ID images, we can directly obtain the updated text encoder containing a stacked ID embedding
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from transformers.models.clip.modeling_clip import CLIPVisionModelWithProjection
7
+ from transformers.models.clip.configuration_clip import CLIPVisionConfig
8
+ from transformers import PretrainedConfig
9
+
10
+ VISION_CONFIG_DICT = {
11
+ "hidden_size": 1024,
12
+ "intermediate_size": 4096,
13
+ "num_attention_heads": 16,
14
+ "num_hidden_layers": 24,
15
+ "patch_size": 14,
16
+ "projection_dim": 768
17
+ }
18
+
19
+ class MLP(nn.Module):
20
+ def __init__(self, in_dim, out_dim, hidden_dim, use_residual=True):
21
+ super().__init__()
22
+ if use_residual:
23
+ assert in_dim == out_dim
24
+ self.layernorm = nn.LayerNorm(in_dim)
25
+ self.fc1 = nn.Linear(in_dim, hidden_dim)
26
+ self.fc2 = nn.Linear(hidden_dim, out_dim)
27
+ self.use_residual = use_residual
28
+ self.act_fn = nn.GELU()
29
+
30
+ def forward(self, x):
31
+ residual = x
32
+ x = self.layernorm(x)
33
+ x = self.fc1(x)
34
+ x = self.act_fn(x)
35
+ x = self.fc2(x)
36
+ if self.use_residual:
37
+ x = x + residual
38
+ return x
39
+
40
+
41
+ class FuseModule(nn.Module):
42
+ def __init__(self, embed_dim):
43
+ super().__init__()
44
+ self.mlp1 = MLP(embed_dim * 2, embed_dim, embed_dim, use_residual=False)
45
+ self.mlp2 = MLP(embed_dim, embed_dim, embed_dim, use_residual=True)
46
+ self.layer_norm = nn.LayerNorm(embed_dim)
47
+
48
+ def fuse_fn(self, prompt_embeds, id_embeds):
49
+ stacked_id_embeds = torch.cat([prompt_embeds, id_embeds], dim=-1)
50
+ stacked_id_embeds = self.mlp1(stacked_id_embeds) + prompt_embeds
51
+ stacked_id_embeds = self.mlp2(stacked_id_embeds)
52
+ stacked_id_embeds = self.layer_norm(stacked_id_embeds)
53
+ return stacked_id_embeds
54
+
55
+ def forward(
56
+ self,
57
+ prompt_embeds,
58
+ id_embeds,
59
+ class_tokens_mask,
60
+ ) -> torch.Tensor:
61
+ # id_embeds shape: [b, max_num_inputs, 1, 2048]
62
+ id_embeds = id_embeds.to(prompt_embeds.dtype)
63
+ num_inputs = class_tokens_mask.sum().unsqueeze(0) # TODO: check for training case
64
+ batch_size, max_num_inputs = id_embeds.shape[:2]
65
+ # seq_length: 77
66
+ seq_length = prompt_embeds.shape[1]
67
+ # flat_id_embeds shape: [b*max_num_inputs, 1, 2048]
68
+ flat_id_embeds = id_embeds.view(
69
+ -1, id_embeds.shape[-2], id_embeds.shape[-1]
70
+ )
71
+ # valid_id_mask [b*max_num_inputs]
72
+ valid_id_mask = (
73
+ torch.arange(max_num_inputs, device=flat_id_embeds.device)[None, :]
74
+ < num_inputs[:, None]
75
+ )
76
+ valid_id_embeds = flat_id_embeds[valid_id_mask.flatten()]
77
+
78
+ prompt_embeds = prompt_embeds.view(-1, prompt_embeds.shape[-1])
79
+ class_tokens_mask = class_tokens_mask.view(-1)
80
+ valid_id_embeds = valid_id_embeds.view(-1, valid_id_embeds.shape[-1])
81
+ # slice out the image token embeddings
82
+ image_token_embeds = prompt_embeds[class_tokens_mask]
83
+ stacked_id_embeds = self.fuse_fn(image_token_embeds, valid_id_embeds)
84
+ assert class_tokens_mask.sum() == stacked_id_embeds.shape[0], f"{class_tokens_mask.sum()} != {stacked_id_embeds.shape[0]}"
85
+ prompt_embeds.masked_scatter_(class_tokens_mask[:, None], stacked_id_embeds.to(prompt_embeds.dtype))
86
+ updated_prompt_embeds = prompt_embeds.view(batch_size, seq_length, -1)
87
+ return updated_prompt_embeds
88
+
89
+ class PhotoMakerIDEncoder(CLIPVisionModelWithProjection):
90
+ def __init__(self):
91
+ super().__init__(CLIPVisionConfig(**VISION_CONFIG_DICT))
92
+ self.visual_projection_2 = nn.Linear(1024, 1280, bias=False)
93
+ self.fuse_module = FuseModule(2048)
94
+
95
+ def forward(self, id_pixel_values, prompt_embeds, class_tokens_mask):
96
+ b, num_inputs, c, h, w = id_pixel_values.shape
97
+ id_pixel_values = id_pixel_values.view(b * num_inputs, c, h, w)
98
+
99
+ shared_id_embeds = self.vision_model(id_pixel_values)[1]
100
+ id_embeds = self.visual_projection(shared_id_embeds)
101
+ id_embeds_2 = self.visual_projection_2(shared_id_embeds)
102
+
103
+ id_embeds = id_embeds.view(b, num_inputs, 1, -1)
104
+ id_embeds_2 = id_embeds_2.view(b, num_inputs, 1, -1)
105
+
106
+ id_embeds = torch.cat((id_embeds, id_embeds_2), dim=-1)
107
+ updated_prompt_embeds = self.fuse_module(prompt_embeds, id_embeds, class_tokens_mask)
108
+
109
+ return updated_prompt_embeds
110
+
111
+
112
+ if __name__ == "__main__":
113
+ PhotoMakerIDEncoder()
utils/pipeline.py ADDED
@@ -0,0 +1,588 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Union, Tuple
2
+ from collections import OrderedDict
3
+ import os
4
+ import PIL
5
+ import numpy as np
6
+
7
+ import torch
8
+ from torchvision import transforms as T
9
+
10
+ from safetensors import safe_open
11
+ from huggingface_hub.utils import validate_hf_hub_args
12
+ from transformers import CLIPImageProcessor, CLIPTokenizer
13
+ from diffusers import StableDiffusionXLPipeline
14
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
15
+ from diffusers.utils import (
16
+ _get_model_file,
17
+ is_transformers_available,
18
+ logging,
19
+ )
20
+
21
+ from . import PhotoMakerIDEncoder
22
+
23
+ PipelineImageInput = Union[
24
+ PIL.Image.Image,
25
+ torch.FloatTensor,
26
+ List[PIL.Image.Image],
27
+ List[torch.FloatTensor],
28
+ ]
29
+
30
+
31
+ class PhotoMakerStableDiffusionXLPipeline(StableDiffusionXLPipeline):
32
+ @validate_hf_hub_args
33
+ def load_photomaker_adapter(
34
+ self,
35
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
36
+ weight_name: str,
37
+ subfolder: str = '',
38
+ trigger_word: str = 'img',
39
+ **kwargs,
40
+ ):
41
+ """
42
+ Parameters:
43
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
44
+ Can be either:
45
+
46
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
47
+ the Hub.
48
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
49
+ with [`ModelMixin.save_pretrained`].
50
+ - A [torch state
51
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
52
+
53
+ weight_name (`str`):
54
+ The weight name NOT the path to the weight.
55
+
56
+ subfolder (`str`, defaults to `""`):
57
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
58
+
59
+ trigger_word (`str`, *optional*, defaults to `"img"`):
60
+ The trigger word is used to identify the position of class word in the text prompt,
61
+ and it is recommended not to set it as a common word.
62
+ This trigger word must be placed after the class word when used, otherwise, it will affect the performance of the personalized generation.
63
+ """
64
+
65
+ # Load the main state dict first.
66
+ cache_dir = kwargs.pop("cache_dir", None)
67
+ force_download = kwargs.pop("force_download", False)
68
+ resume_download = kwargs.pop("resume_download", False)
69
+ proxies = kwargs.pop("proxies", None)
70
+ local_files_only = kwargs.pop("local_files_only", None)
71
+ token = kwargs.pop("token", None)
72
+ revision = kwargs.pop("revision", None)
73
+
74
+ user_agent = {
75
+ "file_type": "attn_procs_weights",
76
+ "framework": "pytorch",
77
+ }
78
+
79
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
80
+ model_file = _get_model_file(
81
+ pretrained_model_name_or_path_or_dict,
82
+ weights_name=weight_name,
83
+ cache_dir=cache_dir,
84
+ force_download=force_download,
85
+ resume_download=resume_download,
86
+ proxies=proxies,
87
+ local_files_only=local_files_only,
88
+ token=token,
89
+ revision=revision,
90
+ subfolder=subfolder,
91
+ user_agent=user_agent,
92
+ )
93
+ if weight_name.endswith(".safetensors"):
94
+ state_dict = {"id_encoder": {}, "lora_weights": {}}
95
+ with safe_open(model_file, framework="pt", device="cpu") as f:
96
+ for key in f.keys():
97
+ if key.startswith("id_encoder."):
98
+ state_dict["id_encoder"][key.replace("id_encoder.", "")] = f.get_tensor(key)
99
+ elif key.startswith("lora_weights."):
100
+ state_dict["lora_weights"][key.replace("lora_weights.", "")] = f.get_tensor(key)
101
+ else:
102
+ state_dict = torch.load(model_file, map_location="cpu")
103
+ else:
104
+ state_dict = pretrained_model_name_or_path_or_dict
105
+
106
+ keys = list(state_dict.keys())
107
+ if keys != ["id_encoder", "lora_weights"]:
108
+ raise ValueError("Required keys are (`id_encoder` and `lora_weights`) missing from the state dict.")
109
+
110
+ self.trigger_word = trigger_word
111
+ # load finetuned CLIP image encoder and fuse module here if it has not been registered to the pipeline yet
112
+ print(f"Loading PhotoMaker components [1] id_encoder from [{pretrained_model_name_or_path_or_dict}]...")
113
+ id_encoder = PhotoMakerIDEncoder()
114
+ id_encoder.load_state_dict(state_dict["id_encoder"], strict=True)
115
+ id_encoder = id_encoder.to(self.device, dtype=self.unet.dtype)
116
+ self.id_encoder = id_encoder
117
+ self.id_image_processor = CLIPImageProcessor()
118
+
119
+ # load lora into models
120
+ print(f"Loading PhotoMaker components [2] lora_weights from [{pretrained_model_name_or_path_or_dict}]")
121
+ self.load_lora_weights(state_dict["lora_weights"], adapter_name="photomaker")
122
+
123
+ # Add trigger word token
124
+ if self.tokenizer is not None:
125
+ self.tokenizer.add_tokens([self.trigger_word], special_tokens=True)
126
+
127
+ self.tokenizer_2.add_tokens([self.trigger_word], special_tokens=True)
128
+
129
+
130
+ def encode_prompt_with_trigger_word(
131
+ self,
132
+ prompt: str,
133
+ prompt_2: Optional[str] = None,
134
+ num_id_images: int = 1,
135
+ device: Optional[torch.device] = None,
136
+ prompt_embeds: Optional[torch.FloatTensor] = None,
137
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
138
+ class_tokens_mask: Optional[torch.LongTensor] = None,
139
+ nc_flag: bool = False,
140
+ ):
141
+ device = device or self._execution_device
142
+
143
+ if prompt is not None and isinstance(prompt, str):
144
+ batch_size = 1
145
+ elif prompt is not None and isinstance(prompt, list):
146
+ batch_size = len(prompt)
147
+ else:
148
+ batch_size = prompt_embeds.shape[0]
149
+
150
+ # Find the token id of the trigger word
151
+ image_token_id = self.tokenizer_2.convert_tokens_to_ids(self.trigger_word)
152
+
153
+ # Define tokenizers and text encoders
154
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
155
+ text_encoders = (
156
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
157
+ )
158
+
159
+ if prompt_embeds is None:
160
+ prompt_2 = prompt_2 or prompt
161
+ prompt_embeds_list = []
162
+ prompts = [prompt, prompt_2]
163
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
164
+ input_ids = tokenizer.encode(prompt) # TODO: batch encode
165
+ clean_index = 0
166
+ clean_input_ids = []
167
+ class_token_index = []
168
+ # Find out the corresponding class word token based on the newly added trigger word token
169
+ for i, token_id in enumerate(input_ids):
170
+ if token_id == image_token_id:
171
+ class_token_index.append(clean_index - 1)
172
+ else:
173
+ clean_input_ids.append(token_id)
174
+ clean_index += 1
175
+ if nc_flag:
176
+ return None, None, None
177
+ if len(class_token_index) > 1:
178
+ raise ValueError(
179
+ f"PhotoMaker currently does not support multiple trigger words in a single prompt.\
180
+ Trigger word: {self.trigger_word}, Prompt: {prompt}."
181
+ )
182
+ elif len(class_token_index) == 0 and not nc_flag:
183
+ raise ValueError(
184
+ f"PhotoMaker currently does not support multiple trigger words in a single prompt.\
185
+ Trigger word: {self.trigger_word}, Prompt: {prompt}."
186
+ )
187
+ class_token_index = class_token_index[0]
188
+
189
+ # Expand the class word token and corresponding mask
190
+ class_token = clean_input_ids[class_token_index]
191
+ clean_input_ids = clean_input_ids[:class_token_index] + [class_token] * num_id_images + \
192
+ clean_input_ids[class_token_index+1:]
193
+
194
+ # Truncation or padding
195
+ max_len = tokenizer.model_max_length
196
+ if len(clean_input_ids) > max_len:
197
+ clean_input_ids = clean_input_ids[:max_len]
198
+ else:
199
+ clean_input_ids = clean_input_ids + [tokenizer.pad_token_id] * (
200
+ max_len - len(clean_input_ids)
201
+ )
202
+
203
+ class_tokens_mask = [True if class_token_index <= i < class_token_index+num_id_images else False \
204
+ for i in range(len(clean_input_ids))]
205
+
206
+ clean_input_ids = torch.tensor(clean_input_ids, dtype=torch.long).unsqueeze(0)
207
+ class_tokens_mask = torch.tensor(class_tokens_mask, dtype=torch.bool).unsqueeze(0)
208
+
209
+ prompt_embeds = text_encoder(
210
+ clean_input_ids.to(device),
211
+ output_hidden_states=True,
212
+ )
213
+
214
+ # We are only ALWAYS interested in the pooled output of the final text encoder
215
+ pooled_prompt_embeds = prompt_embeds[0]
216
+ prompt_embeds = prompt_embeds.hidden_states[-2]
217
+ prompt_embeds_list.append(prompt_embeds)
218
+
219
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
220
+
221
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
222
+ class_tokens_mask = class_tokens_mask.to(device=device) # TODO: ignoring two-prompt case
223
+
224
+ return prompt_embeds, pooled_prompt_embeds, class_tokens_mask
225
+
226
+ @property
227
+ def interrupt(self):
228
+ return self._interrupt
229
+
230
+ @torch.no_grad()
231
+ def __call__(
232
+ self,
233
+ prompt: Union[str, List[str]] = None,
234
+ prompt_2: Optional[Union[str, List[str]]] = None,
235
+ height: Optional[int] = None,
236
+ width: Optional[int] = None,
237
+ num_inference_steps: int = 50,
238
+ denoising_end: Optional[float] = None,
239
+ guidance_scale: float = 5.0,
240
+ negative_prompt: Optional[Union[str, List[str]]] = None,
241
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
242
+ num_images_per_prompt: Optional[int] = 1,
243
+ eta: float = 0.0,
244
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
245
+ latents: Optional[torch.FloatTensor] = None,
246
+ prompt_embeds: Optional[torch.FloatTensor] = None,
247
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
248
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
249
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
250
+ output_type: Optional[str] = "pil",
251
+ return_dict: bool = True,
252
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
253
+ guidance_rescale: float = 0.0,
254
+ original_size: Optional[Tuple[int, int]] = None,
255
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
256
+ target_size: Optional[Tuple[int, int]] = None,
257
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
258
+ callback_steps: int = 1,
259
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
260
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
261
+ # Added parameters (for PhotoMaker)
262
+ input_id_images: PipelineImageInput = None,
263
+ start_merge_step: int = 0, # TODO: change to `style_strength_ratio` in the future
264
+ class_tokens_mask: Optional[torch.LongTensor] = None,
265
+ prompt_embeds_text_only: Optional[torch.FloatTensor] = None,
266
+ pooled_prompt_embeds_text_only: Optional[torch.FloatTensor] = None,
267
+ nc_flag = False,
268
+ ):
269
+ r"""
270
+ Function invoked when calling the pipeline for generation.
271
+ Only the parameters introduced by PhotoMaker are discussed here.
272
+ For explanations of the previous parameters in StableDiffusionXLPipeline, please refer to https://github.com/huggingface/diffusers/blob/v0.25.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py
273
+
274
+ Args:
275
+ input_id_images (`PipelineImageInput`, *optional*):
276
+ Input ID Image to work with PhotoMaker.
277
+ class_tokens_mask (`torch.LongTensor`, *optional*):
278
+ Pre-generated class token. When the `prompt_embeds` parameter is provided in advance, it is necessary to prepare the `class_tokens_mask` beforehand for marking out the position of class word.
279
+ prompt_embeds_text_only (`torch.FloatTensor`, *optional*):
280
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
281
+ provided, text embeddings will be generated from `prompt` input argument.
282
+ pooled_prompt_embeds_text_only (`torch.FloatTensor`, *optional*):
283
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
284
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
285
+
286
+ Returns:
287
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
288
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
289
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
290
+ """
291
+ # 0. Default height and width to unet
292
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
293
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
294
+
295
+ original_size = original_size or (height, width)
296
+ target_size = target_size or (height, width)
297
+
298
+ # 1. Check inputs. Raise error if not correct
299
+ self.check_inputs(
300
+ prompt,
301
+ prompt_2,
302
+ height,
303
+ width,
304
+ callback_steps,
305
+ negative_prompt,
306
+ negative_prompt_2,
307
+ prompt_embeds,
308
+ negative_prompt_embeds,
309
+ pooled_prompt_embeds,
310
+ negative_pooled_prompt_embeds,
311
+ callback_on_step_end_tensor_inputs,
312
+ )
313
+
314
+ self._interrupt = False
315
+
316
+ #
317
+ if prompt_embeds is not None and class_tokens_mask is None:
318
+ raise ValueError(
319
+ "If `prompt_embeds` are provided, `class_tokens_mask` also have to be passed. Make sure to generate `class_tokens_mask` from the same tokenizer that was used to generate `prompt_embeds`."
320
+ )
321
+ # check the input id images
322
+ if input_id_images is None:
323
+ raise ValueError(
324
+ "Provide `input_id_images`. Cannot leave `input_id_images` undefined for PhotoMaker pipeline."
325
+ )
326
+ if not isinstance(input_id_images, list):
327
+ input_id_images = [input_id_images]
328
+
329
+ # 2. Define call parameters
330
+ if prompt is not None and isinstance(prompt, str):
331
+ batch_size = 1
332
+ prompt = [prompt]
333
+ elif prompt is not None and isinstance(prompt, list):
334
+ batch_size = len(prompt)
335
+ else:
336
+ batch_size = prompt_embeds.shape[0]
337
+
338
+ device = self._execution_device
339
+
340
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
341
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
342
+ # corresponds to doing no classifier free guidance.
343
+ do_classifier_free_guidance = guidance_scale >= 1.0
344
+
345
+ assert do_classifier_free_guidance
346
+
347
+ # 3. Encode input prompt
348
+ num_id_images = len(input_id_images)
349
+ if isinstance(prompt, list):
350
+ prompt_arr = prompt
351
+ negative_prompt_embeds_arr = []
352
+ prompt_embeds_text_only_arr = []
353
+ prompt_embeds_arr = []
354
+ latents_arr = []
355
+ add_time_ids_arr = []
356
+ negative_pooled_prompt_embeds_arr = []
357
+ pooled_prompt_embeds_text_only_arr = []
358
+ pooled_prompt_embeds_arr = []
359
+ for prompt in prompt_arr:
360
+ (
361
+ prompt_embeds,
362
+ pooled_prompt_embeds,
363
+ class_tokens_mask,
364
+ ) = self.encode_prompt_with_trigger_word(
365
+ prompt=prompt,
366
+ prompt_2=prompt_2,
367
+ device=device,
368
+ num_id_images=num_id_images,
369
+ prompt_embeds=prompt_embeds,
370
+ pooled_prompt_embeds=pooled_prompt_embeds,
371
+ class_tokens_mask=class_tokens_mask,
372
+ nc_flag = nc_flag,
373
+ )
374
+
375
+ # 4. Encode input prompt without the trigger word for delayed conditioning
376
+ # encode, remove trigger word token, then decode
377
+ tokens_text_only = self.tokenizer.encode(prompt, add_special_tokens=False)
378
+ trigger_word_token = self.tokenizer.convert_tokens_to_ids(self.trigger_word)
379
+ if not nc_flag:
380
+ tokens_text_only.remove(trigger_word_token)
381
+ prompt_text_only = self.tokenizer.decode(tokens_text_only, add_special_tokens=False)
382
+ print(prompt_text_only)
383
+ (
384
+ prompt_embeds_text_only,
385
+ negative_prompt_embeds,
386
+ pooled_prompt_embeds_text_only, # TODO: replace the pooled_prompt_embeds with text only prompt
387
+ negative_pooled_prompt_embeds,
388
+ ) = self.encode_prompt(
389
+ prompt=prompt_text_only,
390
+ prompt_2=prompt_2,
391
+ device=device,
392
+ num_images_per_prompt=num_images_per_prompt,
393
+ do_classifier_free_guidance=True,
394
+ negative_prompt=negative_prompt,
395
+ negative_prompt_2=negative_prompt_2,
396
+ prompt_embeds=prompt_embeds_text_only,
397
+ negative_prompt_embeds=negative_prompt_embeds,
398
+ pooled_prompt_embeds=pooled_prompt_embeds_text_only,
399
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
400
+ )
401
+
402
+ # 5. Prepare the input ID images
403
+ dtype = next(self.id_encoder.parameters()).dtype
404
+ if not isinstance(input_id_images[0], torch.Tensor):
405
+ id_pixel_values = self.id_image_processor(input_id_images, return_tensors="pt").pixel_values
406
+
407
+ id_pixel_values = id_pixel_values.unsqueeze(0).to(device=device, dtype=dtype) # TODO: multiple prompts
408
+
409
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
410
+ if not nc_flag:
411
+ # 6. Get the update text embedding with the stacked ID embedding
412
+ prompt_embeds = self.id_encoder(id_pixel_values, prompt_embeds, class_tokens_mask)
413
+
414
+ bs_embed, seq_len, _ = prompt_embeds.shape
415
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
416
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
417
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
418
+ bs_embed * num_images_per_prompt, -1
419
+ )
420
+ pooled_prompt_embeds_arr.append(pooled_prompt_embeds)
421
+ pooled_prompt_embeds = None
422
+
423
+ negative_prompt_embeds_arr.append(negative_prompt_embeds)
424
+ negative_prompt_embeds = None
425
+ negative_pooled_prompt_embeds_arr.append(negative_pooled_prompt_embeds)
426
+ negative_pooled_prompt_embeds = None
427
+ prompt_embeds_text_only_arr.append(prompt_embeds_text_only)
428
+ prompt_embeds_text_only = None
429
+ prompt_embeds_arr.append(prompt_embeds)
430
+ prompt_embeds = None
431
+ pooled_prompt_embeds_text_only_arr.append(pooled_prompt_embeds_text_only)
432
+ pooled_prompt_embeds_text_only = None
433
+ # 7. Prepare timesteps
434
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
435
+ timesteps = self.scheduler.timesteps
436
+
437
+ negative_prompt_embeds = torch.cat(negative_prompt_embeds_arr ,dim =0)
438
+ print(negative_prompt_embeds.shape)
439
+ if not nc_flag:
440
+ prompt_embeds = torch.cat(prompt_embeds_arr ,dim = 0)
441
+ print(prompt_embeds.shape)
442
+ pooled_prompt_embeds = torch.cat(pooled_prompt_embeds_arr,dim = 0)
443
+ print(pooled_prompt_embeds.shape)
444
+
445
+ prompt_embeds_text_only = torch.cat(prompt_embeds_text_only_arr ,dim = 0)
446
+ print(prompt_embeds_text_only.shape)
447
+ pooled_prompt_embeds_text_only = torch.cat(pooled_prompt_embeds_text_only_arr ,dim = 0)
448
+ print(pooled_prompt_embeds_text_only.shape)
449
+
450
+ negative_pooled_prompt_embeds = torch.cat(negative_pooled_prompt_embeds_arr ,dim = 0)
451
+ print(negative_pooled_prompt_embeds.shape)
452
+ # 8. Prepare latent variables
453
+ num_channels_latents = self.unet.config.in_channels
454
+ latents = self.prepare_latents(
455
+ batch_size * num_images_per_prompt,
456
+ num_channels_latents,
457
+ height,
458
+ width,
459
+ prompt_embeds.dtype if not nc_flag else prompt_embeds_text_only.dtype,
460
+ device,
461
+ generator,
462
+ latents,
463
+ )
464
+
465
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
466
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
467
+
468
+ # 10. Prepare added time ids & embeddings
469
+ if self.text_encoder_2 is None:
470
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
471
+ else:
472
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
473
+
474
+ add_time_ids = self._get_add_time_ids(
475
+ original_size,
476
+ crops_coords_top_left,
477
+ target_size,
478
+ dtype=prompt_embeds.dtype if not nc_flag else prompt_embeds_text_only.dtype,
479
+ text_encoder_projection_dim=text_encoder_projection_dim,
480
+ )
481
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
482
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
483
+
484
+
485
+ print(latents.shape)
486
+ print(add_time_ids.shape)
487
+
488
+ # 11. Denoising loop
489
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
490
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
491
+ for i, t in enumerate(timesteps):
492
+ if self.interrupt:
493
+ continue
494
+
495
+ latent_model_input = (
496
+ torch.cat([latents] * 2) if do_classifier_free_guidance else latents
497
+ )
498
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
499
+
500
+ if i <= start_merge_step or nc_flag:
501
+ current_prompt_embeds = torch.cat(
502
+ [negative_prompt_embeds, prompt_embeds_text_only], dim=0
503
+ )
504
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds_text_only], dim=0)
505
+ else:
506
+ current_prompt_embeds = torch.cat(
507
+ [negative_prompt_embeds, prompt_embeds], dim=0
508
+ )
509
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
510
+ # predict the noise residual
511
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
512
+ # print(latent_model_input.shape)
513
+ # print(t)
514
+ # print(current_prompt_embeds.shape)
515
+ # print(add_text_embeds.shape)
516
+ # print(add_time_ids.shape)
517
+ #zeros_matrix =
518
+ #global_mask1024 = torch.cat([torch.randn(1, 1024, 1, 1, device=device) for random_number])
519
+ #global_mask4096 =
520
+ noise_pred = self.unet(
521
+ latent_model_input,
522
+ t,
523
+ encoder_hidden_states=current_prompt_embeds,
524
+ cross_attention_kwargs=cross_attention_kwargs,
525
+ added_cond_kwargs=added_cond_kwargs,
526
+ return_dict=False,
527
+ )[0]
528
+ # print(noise_pred.shape)
529
+ # perform guidance
530
+ if do_classifier_free_guidance:
531
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
532
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
533
+
534
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
535
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
536
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
537
+
538
+ # compute the previous noisy sample x_t -> x_t-1
539
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
540
+
541
+ if callback_on_step_end is not None:
542
+ callback_kwargs = {}
543
+ for k in callback_on_step_end_tensor_inputs:
544
+ callback_kwargs[k] = locals()[k]
545
+
546
+ ck_outputs = callback_on_step_end(self, i, t, callback_kwargs)
547
+
548
+ latents = callback_outputs.pop("latents", latents)
549
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
550
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
551
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
552
+ # negative_pooled_prompt_embeds = callback_outputs.pop(
553
+ # "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
554
+ # )
555
+ # add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
556
+ # negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
557
+
558
+ # call the callback, if provided
559
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
560
+ progress_bar.update()
561
+ if callback is not None and i % callback_steps == 0:
562
+ step_idx = i // getattr(self.scheduler, "order", 1)
563
+ callback(step_idx, t, latents)
564
+
565
+ # make sure the VAE is in float32 mode, as it overflows in float16
566
+ if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
567
+ self.upcast_vae()
568
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
569
+
570
+ if not output_type == "latent":
571
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
572
+ else:
573
+ image = latents
574
+ return StableDiffusionXLPipelineOutput(images=image)
575
+
576
+ # apply watermark if available
577
+ # if self.watermark is not None:
578
+ # image = self.watermark.apply_watermark(image)
579
+
580
+ image = self.image_processor.postprocess(image, output_type=output_type)
581
+
582
+ # Offload all models
583
+ self.maybe_free_model_hooks()
584
+
585
+ if not return_dict:
586
+ return (image,)
587
+
588
+ return StableDiffusionXLPipelineOutput(images=image)
utils/style_template.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ style_list = [
2
+ {
3
+ "name": "(No style)",
4
+ "prompt": "{prompt}",
5
+ "negative_prompt": "",
6
+ },
7
+ {
8
+ "name": "Japanese Anime",
9
+ "prompt": "anime artwork illustrating {prompt}. created by japanese anime studio. highly emotional. best quality, high resolution",
10
+ "negative_prompt": "low quality, low resolution"
11
+ },
12
+ {
13
+ "name": "Cinematic",
14
+ "prompt": "cinematic still {prompt} . emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
15
+ "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
16
+ },
17
+ {
18
+ "name": "Disney Charactor",
19
+ "prompt": "A Pixar animation character of {prompt} . pixar-style, studio anime, Disney, high-quality",
20
+ "negative_prompt": "lowres, bad anatomy, bad hands, text, bad eyes, bad arms, bad legs, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, blurry, grayscale, noisy, sloppy, messy, grainy, highly detailed, ultra textured, photo",
21
+ },
22
+ {
23
+ "name": "Photographic",
24
+ "prompt": "cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed",
25
+ "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
26
+ },
27
+ {
28
+ "name": "Comic book",
29
+ "prompt": "comic {prompt} . graphic illustration, comic art, graphic novel art, vibrant, highly detailed",
30
+ "negative_prompt": "photograph, deformed, glitch, noisy, realistic, stock photo",
31
+ },
32
+ {
33
+ "name": "Line art",
34
+ "prompt": "line art drawing {prompt} . professional, sleek, modern, minimalist, graphic, line art, vector graphics",
35
+ "negative_prompt": "anime, photorealistic, 35mm film, deformed, glitch, blurry, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, mutated, realism, realistic, impressionism, expressionism, oil, acrylic",
36
+ }
37
+ ]
38
+
39
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
utils/utils.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from email.mime import image
2
+ import torch
3
+ import base64
4
+ import gradio as gr
5
+ import numpy as np
6
+ from PIL import Image,ImageOps,ImageDraw, ImageFont
7
+ from io import BytesIO
8
+ import random
9
+ MAX_COLORS = 12
10
+ def get_random_bool():
11
+ return random.choice([True, False])
12
+
13
+ def add_white_border(input_image, border_width=10):
14
+ """
15
+ 为PIL图像添加指定宽度的白色边框。
16
+
17
+ :param input_image: PIL图像对象
18
+ :param border_width: 边框宽度(单位:像素)
19
+ :return: 带有白色边框的PIL图像对象
20
+ """
21
+ border_color = 'white' # 白色边框
22
+ # 添加边框
23
+ img_with_border = ImageOps.expand(input_image, border=border_width, fill=border_color)
24
+ return img_with_border
25
+
26
+ def process_mulline_text(draw, text, font, max_width):
27
+ """
28
+ Draw the text on an image with word wrapping.
29
+ """
30
+ lines = [] # Store the lines of text here
31
+ words = text.split()
32
+
33
+ # Start building lines of text, and wrap when necessary
34
+ current_line = ""
35
+ for word in words:
36
+ test_line = f"{current_line} {word}".strip()
37
+ # Check the width of the line with this word added
38
+ bbox = draw.textbbox((0, 0), test_line, font=font)
39
+ text_left, text_top, text_right, text_bottom = bbox
40
+
41
+ width, _ = (text_right - text_left, text_bottom - text_top)
42
+
43
+ if width <= max_width:
44
+ # If it fits, add this word to the current line
45
+ current_line = test_line
46
+ else:
47
+ # If not, store the line and start a new one
48
+ lines.append(current_line)
49
+ current_line = word
50
+ # Add the last line
51
+ lines.append(current_line)
52
+ return lines
53
+
54
+
55
+
56
+ def add_caption(image, text, position = "bottom-mid", font = None, text_color= 'black', bg_color = (255, 255, 255) , bg_opacity = 200):
57
+ if text == "":
58
+ return image
59
+ image = image.convert("RGBA")
60
+ draw = ImageDraw.Draw(image)
61
+ width, height = image.size
62
+ lines = process_mulline_text(draw,text,font,width)
63
+ text_positions = []
64
+ maxwidth = 0
65
+ for ind, line in enumerate(lines[::-1]):
66
+ bbox = draw.textbbox((0, 0), line, font=font)
67
+ text_left, text_top, text_right, text_bottom = bbox
68
+ text_width, text_height = (text_right - text_left, text_bottom - text_top)
69
+ if position == 'bottom-right':
70
+ text_position = (width - text_width - 10, height - (text_height + 20))
71
+ elif position == 'bottom-left':
72
+ text_position = (10, height - (text_height + 20))
73
+ elif position == 'bottom-mid':
74
+ text_position = ((width - text_width) // 2, height - (text_height + 20) ) # 居中文本
75
+ height = text_position[1]
76
+ maxwidth = max(maxwidth,text_width)
77
+ text_positions.append(text_position)
78
+ rectpos = (width - maxwidth) // 2
79
+ rectangle_position = [rectpos - 5, text_positions[-1][1] - 5, rectpos + maxwidth + 5, text_positions[0][1] + text_height + 5]
80
+ image_with_transparency = Image.new('RGBA', image.size)
81
+ draw_with_transparency = ImageDraw.Draw(image_with_transparency)
82
+ draw_with_transparency.rectangle(rectangle_position, fill=bg_color + (bg_opacity,))
83
+
84
+ image.paste(Image.alpha_composite(image.convert('RGBA'), image_with_transparency))
85
+ print(ind,text_position)
86
+ draw = ImageDraw.Draw(image)
87
+ for ind, line in enumerate(lines[::-1]):
88
+ text_position = text_positions[ind]
89
+ draw.text(text_position, line, fill=text_color, font=font)
90
+
91
+ return image.convert('RGB')
92
+
93
+ def get_comic(images,types = "4panel",captions = [],font = None,pad_image = None):
94
+ if pad_image == None:
95
+ pad_image = Image.open("./images/pad_images.png")
96
+
97
+ if types == "No typesetting (default)":
98
+ return images
99
+ elif types == "Four Pannel":
100
+ return get_comic_4panel(images,captions,font,pad_image)
101
+ else: # "Classic Comic Style"
102
+ return get_comic_classical(images,captions,font,pad_image)
103
+
104
+ def get_caption_group(images_groups,captions = []):
105
+ caption_groups = []
106
+ for i in range(len(images_groups)):
107
+ length = len(images_groups[i])
108
+ caption_groups.append(captions[:length])
109
+ captions = captions[length:]
110
+ if len(caption_groups[-1]) < len(images_groups[-1]):
111
+ caption_groups[-1] = caption_groups[-1] + [""] * (len(images_groups[-1]) - len(caption_groups[-1]))
112
+ return caption_groups
113
+
114
+ def get_comic_classical(images,captions = None,font = None,pad_image = None):
115
+ if pad_image == None:
116
+ raise ValueError("pad_image is None")
117
+ images = [add_white_border(image) for image in images]
118
+ pad_image = pad_image.resize(images[0].size, Image.LANCZOS)
119
+ images_groups = distribute_images2(images,pad_image)
120
+ print(images_groups)
121
+ if captions != None:
122
+ captions_groups = get_caption_group(images_groups,captions)
123
+ # print(images_groups)
124
+ row_images = []
125
+ for ind, img_group in enumerate(images_groups):
126
+ row_images.append(get_row_image2(img_group ,captions= captions_groups[ind] if captions != None else None,font = font))
127
+
128
+ return [combine_images_vertically_with_resize(row_images)]
129
+
130
+
131
+
132
+ def get_comic_4panel(images,captions = [],font = None,pad_image = None):
133
+ if pad_image == None:
134
+ raise ValueError("pad_image is None")
135
+ pad_image = pad_image.resize(images[0].size, Image.LANCZOS)
136
+ images = [add_white_border(image) for image in images]
137
+ assert len(captions) == len(images)
138
+ for i,caption in enumerate(captions):
139
+ images[i] = add_caption(images[i],caption,font = font)
140
+ images_nums = len(images)
141
+ pad_nums = int((4 - images_nums % 4) % 4)
142
+ images = images + [pad_image for _ in range(pad_nums)]
143
+ comics = []
144
+ assert len(images)%4 == 0
145
+ for i in range(len(images)//4):
146
+ comics.append(combine_images_vertically_with_resize([combine_images_horizontally(images[i*4:i*4+2]), combine_images_horizontally(images[i*4+2:i*4+4])]))
147
+
148
+ return comics
149
+
150
+ def get_row_image(images):
151
+ row_image_arr = []
152
+ if len(images)>3:
153
+ stack_img_nums = (len(images) - 2)//2
154
+ else:
155
+ stack_img_nums = 0
156
+ while(len(images)>0):
157
+ if stack_img_nums <=0:
158
+ row_image_arr.append(images[0])
159
+ images = images[1:]
160
+ elif len(images)>stack_img_nums*2:
161
+ if get_random_bool():
162
+ row_image_arr.append(concat_images_vertically_and_scale(images[:2]))
163
+ images = images[2:]
164
+ stack_img_nums -=1
165
+ else:
166
+ row_image_arr.append(images[0])
167
+ images = images[1:]
168
+ else:
169
+ row_image_arr.append(concat_images_vertically_and_scale(images[:2]))
170
+ images = images[2:]
171
+ stack_img_nums-=1
172
+ return combine_images_horizontally(row_image_arr)
173
+
174
+ def get_row_image2(images,captions = None, font = None):
175
+ row_image_arr = []
176
+ if len(images)== 6:
177
+ sequence_list = [1,1,2,2]
178
+ elif len(images)== 4:
179
+ sequence_list = [1,1,2]
180
+ else:
181
+ raise ValueError("images nums is not 4 or 6 found",len(images))
182
+ random.shuffle(sequence_list)
183
+ index = 0
184
+ for length in sequence_list:
185
+ if length == 1:
186
+ if captions != None:
187
+ images_tmp = add_caption(images[0],text = captions[index],font= font)
188
+ else:
189
+ images_tmp = images[0]
190
+ row_image_arr.append( images_tmp)
191
+ images = images[1:]
192
+ index +=1
193
+ elif length == 2:
194
+ row_image_arr.append(concat_images_vertically_and_scale(images[:2]))
195
+ images = images[2:]
196
+ index +=2
197
+
198
+ return combine_images_horizontally(row_image_arr)
199
+
200
+
201
+
202
+ def concat_images_vertically_and_scale(images,scale_factor=2):
203
+ # 加载所有图像
204
+ # 确保所有图像的宽度一致
205
+ widths = [img.width for img in images]
206
+ if not all(width == widths[0] for width in widths):
207
+ raise ValueError('All images must have the same width.')
208
+
209
+ # 计算总高度
210
+ total_height = sum(img.height for img in images)
211
+
212
+ # 创建新的图像,宽度与原图相同,高度为所有图像高度之和
213
+ max_width = max(widths)
214
+ concatenated_image = Image.new('RGB', (max_width, total_height))
215
+
216
+ # 竖直拼接图像
217
+ current_height = 0
218
+ for img in images:
219
+ concatenated_image.paste(img, (0, current_height))
220
+ current_height += img.height
221
+
222
+ # 缩放图像为1/n高度
223
+ new_height = concatenated_image.height // scale_factor
224
+ new_width = concatenated_image.width // scale_factor
225
+ resized_image = concatenated_image.resize((new_width, new_height), Image.LANCZOS)
226
+
227
+ return resized_image
228
+
229
+
230
+ def combine_images_horizontally(images):
231
+ # 读取所有图片并存入列表
232
+
233
+ # 获取每幅图像的宽度和高度
234
+ widths, heights = zip(*(i.size for i in images))
235
+
236
+ # 计算总宽度和最大高度
237
+ total_width = sum(widths)
238
+ max_height = max(heights)
239
+
240
+ # 创建新的空白图片,用于拼接
241
+ new_im = Image.new('RGB', (total_width, max_height))
242
+
243
+ # 将图片横向拼接
244
+ x_offset = 0
245
+ for im in images:
246
+ new_im.paste(im, (x_offset, 0))
247
+ x_offset += im.width
248
+
249
+ return new_im
250
+
251
+ def combine_images_vertically_with_resize(images):
252
+
253
+ # 获取所有图片的宽度和高度
254
+ widths, heights = zip(*(i.size for i in images))
255
+
256
+ # 确定新图片的宽度,即所有图片中最小的宽度
257
+ min_width = min(widths)
258
+
259
+ # 调整图片尺寸以保持宽度一致,长宽比不变
260
+ resized_images = []
261
+ for img in images:
262
+ # 计算新高度保持图片长宽比
263
+ new_height = int(min_width * img.height / img.width)
264
+ # 调整图片大小
265
+ resized_img = img.resize((min_width, new_height), Image.LANCZOS)
266
+ resized_images.append(resized_img)
267
+
268
+ # 计算所有调整尺寸后图片的总高度
269
+ total_height = sum(img.height for img in resized_images)
270
+
271
+ # 创建一个足够宽和高的新图片对象
272
+ new_im = Image.new('RGB', (min_width, total_height))
273
+
274
+ # 竖直拼接图片
275
+ y_offset = 0
276
+ for im in resized_images:
277
+ new_im.paste(im, (0, y_offset))
278
+ y_offset += im.height
279
+
280
+ return new_im
281
+
282
+ def distribute_images2(images, pad_image):
283
+ groups = []
284
+ remaining = len(images)
285
+ if len(images) <= 8:
286
+ group_sizes = [4]
287
+ else:
288
+ group_sizes = [4, 6]
289
+
290
+ size_index = 0
291
+ while remaining > 0:
292
+ size = group_sizes[size_index%len(group_sizes)]
293
+ if remaining < size and remaining < min(group_sizes):
294
+ size = min(group_sizes)
295
+ if remaining > size:
296
+ new_group = images[-remaining: -remaining + size]
297
+ else:
298
+ new_group = images[-remaining:]
299
+ groups.append(new_group)
300
+ size_index += 1
301
+ remaining -= size
302
+ print(remaining,groups)
303
+ groups[-1] = groups[-1] + [pad_image for _ in range(-remaining)]
304
+
305
+ return groups
306
+
307
+
308
+ def distribute_images(images, group_sizes=(4, 3, 2)):
309
+ groups = []
310
+ remaining = len(images)
311
+
312
+ while remaining > 0:
313
+ # 优先分配最大组(4张图片),再考虑3张,最后处理2张
314
+ for size in sorted(group_sizes, reverse=True):
315
+ # 如果剩下的图片数量大于等于当前组大小,或者为图片总数时(也就是第一次迭代)
316
+ # 开始创建新组
317
+ if remaining >= size or remaining == len(images):
318
+ if remaining > size:
319
+ new_group = images[-remaining: -remaining + size]
320
+ else:
321
+ new_group = images[-remaining:]
322
+ groups.append(new_group)
323
+ remaining -= size
324
+ break
325
+ # 如果剩下的图片少于最小的组大小(2张)并且已经有组了,就把剩下的图片加到最后一个组
326
+ elif remaining < min(group_sizes) and groups:
327
+ groups[-1].extend(images[-remaining:])
328
+ remaining = 0
329
+
330
+ return groups
331
+
332
+ def create_binary_matrix(img_arr, target_color):
333
+ mask = np.all(img_arr == target_color, axis=-1)
334
+ binary_matrix = mask.astype(int)
335
+ return binary_matrix
336
+
337
+ def preprocess_mask(mask_, h, w, device):
338
+ mask = np.array(mask_)
339
+ mask = mask.astype(np.float32)
340
+ mask = mask[None, None]
341
+ mask[mask < 0.5] = 0
342
+ mask[mask >= 0.5] = 1
343
+ mask = torch.from_numpy(mask).to(device)
344
+ mask = torch.nn.functional.interpolate(mask, size=(h, w), mode='nearest')
345
+ return mask
346
+
347
+ def process_sketch(canvas_data):
348
+ binary_matrixes = []
349
+ base64_img = canvas_data['image']
350
+ image_data = base64.b64decode(base64_img.split(',')[1])
351
+ image = Image.open(BytesIO(image_data)).convert("RGB")
352
+ im2arr = np.array(image)
353
+ colors = [tuple(map(int, rgb[4:-1].split(','))) for rgb in canvas_data['colors']]
354
+ colors_fixed = []
355
+
356
+ r, g, b = 255, 255, 255
357
+ binary_matrix = create_binary_matrix(im2arr, (r,g,b))
358
+ binary_matrixes.append(binary_matrix)
359
+ binary_matrix_ = np.repeat(np.expand_dims(binary_matrix, axis=(-1)), 3, axis=(-1))
360
+ colored_map = binary_matrix_*(r,g,b) + (1-binary_matrix_)*(50,50,50)
361
+ colors_fixed.append(gr.update(value=colored_map.astype(np.uint8)))
362
+
363
+ for color in colors:
364
+ r, g, b = color
365
+ if any(c != 255 for c in (r, g, b)):
366
+ binary_matrix = create_binary_matrix(im2arr, (r,g,b))
367
+ binary_matrixes.append(binary_matrix)
368
+ binary_matrix_ = np.repeat(np.expand_dims(binary_matrix, axis=(-1)), 3, axis=(-1))
369
+ colored_map = binary_matrix_*(r,g,b) + (1-binary_matrix_)*(50,50,50)
370
+ colors_fixed.append(gr.update(value=colored_map.astype(np.uint8)))
371
+
372
+ visibilities = []
373
+ colors = []
374
+ for n in range(MAX_COLORS):
375
+ visibilities.append(gr.update(visible=False))
376
+ colors.append(gr.update())
377
+ for n in range(len(colors_fixed)):
378
+ visibilities[n] = gr.update(visible=True)
379
+ colors[n] = colors_fixed[n]
380
+
381
+ return [gr.update(visible=True), binary_matrixes, *visibilities, *colors]
382
+
383
+ def process_prompts(binary_matrixes, *seg_prompts):
384
+ return [gr.update(visible=True), gr.update(value=' , '.join(seg_prompts[:len(binary_matrixes)]))]
385
+
386
+ def process_example(layout_path, all_prompts, seed_):
387
+
388
+ all_prompts = all_prompts.split('***')
389
+
390
+ binary_matrixes = []
391
+ colors_fixed = []
392
+
393
+ im2arr = np.array(Image.open(layout_path))[:,:,:3]
394
+ unique, counts = np.unique(np.reshape(im2arr,(-1,3)), axis=0, return_counts=True)
395
+ sorted_idx = np.argsort(-counts)
396
+
397
+ binary_matrix = create_binary_matrix(im2arr, (0,0,0))
398
+ binary_matrixes.append(binary_matrix)
399
+ binary_matrix_ = np.repeat(np.expand_dims(binary_matrix, axis=(-1)), 3, axis=(-1))
400
+ colored_map = binary_matrix_*(255,255,255) + (1-binary_matrix_)*(50,50,50)
401
+ colors_fixed.append(gr.update(value=colored_map.astype(np.uint8)))
402
+
403
+ for i in range(len(all_prompts)-1):
404
+ r, g, b = unique[sorted_idx[i]]
405
+ if any(c != 255 for c in (r, g, b)) and any(c != 0 for c in (r, g, b)):
406
+ binary_matrix = create_binary_matrix(im2arr, (r,g,b))
407
+ binary_matrixes.append(binary_matrix)
408
+ binary_matrix_ = np.repeat(np.expand_dims(binary_matrix, axis=(-1)), 3, axis=(-1))
409
+ colored_map = binary_matrix_*(r,g,b) + (1-binary_matrix_)*(50,50,50)
410
+ colors_fixed.append(gr.update(value=colored_map.astype(np.uint8)))
411
+
412
+ visibilities = []
413
+ colors = []
414
+ prompts = []
415
+ for n in range(MAX_COLORS):
416
+ visibilities.append(gr.update(visible=False))
417
+ colors.append(gr.update())
418
+ prompts.append(gr.update())
419
+
420
+ for n in range(len(colors_fixed)):
421
+ visibilities[n] = gr.update(visible=True)
422
+ colors[n] = colors_fixed[n]
423
+ prompts[n] = all_prompts[n+1]
424
+
425
+ return [gr.update(visible=True), binary_matrixes, *visibilities, *colors, *prompts,
426
+ gr.update(visible=True), gr.update(value=all_prompts[0]), int(seed_)]