jasoncharles commited on
Commit
a05c27e
1 Parent(s): 1f378bc

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,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/
94
+ results/
95
+ .vscode/settings.json
96
+ fonts/agency.ttf
97
+ fonts/calibri.ttf
98
+ data/
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: StoryDiffusion
3
- emoji: 🦀
4
- colorFrom: blue
5
- colorTo: green
6
- sdk: gradio
7
- sdk_version: 4.31.5
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: StoryDiffusion
3
+ app_file: app.py
4
+ sdk: gradio
5
+ sdk_version: 4.22.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
+
15
+ [[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) [![Run Comics Demo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/HVision-NKU/StoryDiffusion/blob/main/Comic_Generation.ipynb) <br>
16
+ </div>
17
+
18
+
19
+ ---
20
+
21
+ Official implementation of **[StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation]()**.
22
+
23
+ ### **Demo Video**
24
+
25
+ https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/d5b80f8f-09b0-48cd-8b10-daff46d422af
26
+
27
+
28
+ ### Update History
29
+
30
+ ***You can visit [here](update.md) to visit update history.***
31
+
32
+ ### 🌠 **Key Features:**
33
+ StoryDiffusion can create a magic story by generating consistent images and videos. Our work mainly has two parts:
34
+ 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.
35
+ 2. Motion predictor for long-range video generation, which predicts motion between Condition Images in a compressed image semantic space, achieving larger motion prediction.
36
+
37
+
38
+
39
+ ## 🔥 **Examples**
40
+
41
+
42
+ ### Comics generation
43
+
44
+
45
+ ![1](https://github.com/HVision-NKU/StoryDiffusion/assets/49511209/b3771cbc-b6ca-4e26-bdc5-d944daf9f266)
46
+
47
+
48
+
49
+ ### Image-to-Video generation (Results are HIGHLY compressed for speed)
50
+ 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.
51
+
52
+ Note: results are **highly compressed** for speed, you can visit [our website](https://storydiffusion.github.io/) for the high-quality version.
53
+ #### Two-stage Long Videos Generation (New Update)
54
+ Combining the two parts, we can generate very long and high-quality AIGC videos.
55
+ | Video1 | Video2 | Video3 |
56
+ | --- | --- | --- |
57
+ | <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> |
58
+
59
+
60
+ #### Long Video Results using Condition Images
61
+ Our Image-to-Video model can generate a video by providing a sequence of user-input condition images.
62
+ | Video1 | Video2 | Video3 |
63
+ | --- | --- | --- |
64
+ | <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> |
65
+
66
+ | Video4 | Video5 | Video6 |
67
+ | --- | --- | --- |
68
+ | <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> |
69
+
70
+
71
+
72
+
73
+ #### Short Videos
74
+
75
+ | Video1 | Video2 | Video3 |
76
+ | --- | --- | --- |
77
+ | <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> |
78
+
79
+
80
+
81
+ | Video4 | Video5 | Video6 |
82
+ | --- | --- | --- |
83
+ | <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> |
84
+
85
+
86
+
87
+
88
+ ## 🚩 **TODO/Updates**
89
+ - [x] Comic Results of StoryDiffusion.
90
+ - [x] Video Results of StoryDiffusion.
91
+ - [x] Source code of Comic Generation
92
+ - [x] Source code of gradio demo
93
+ - [ ] Source code of Video Generation Model
94
+ - [ ] Pretrained weight of Video Generation Model
95
+ ---
96
+
97
+ # 🔧 Dependencies and Installation
98
+
99
+ - Python >= 3.8 (Recommend to use [Anaconda](https://www.anaconda.com/download/#linux) or [Miniconda](https://docs.conda.io/en/latest/miniconda.html))
100
+ - [PyTorch >= 2.0.0](https://pytorch.org/)
101
+ ```bash
102
+ conda create --name storydiffusion python=3.10
103
+ conda activate storydiffusion
104
+ pip install -U pip
105
+
106
+ # Install requirements
107
+ pip install -r requirements.txt
108
+ ```
109
+ # How to use
110
+
111
+ Currently, we provide two ways for you to generate comics.
112
+
113
+ ## Use the jupyter notebook
114
+
115
+ You can open the `Comic_Generation.ipynb` and run the code.
116
+
117
+ ## Start a local gradio demo
118
+ Run the following command:
119
+
120
+
121
+ **(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.
122
+
123
+ ```python
124
+ python gradio_app_sdxl_specific_id_low_vram.py
125
+ ```
126
+
127
+
128
+ ## Contact
129
+ If you have any questions, you are very welcome to email [email protected] and [email protected]
130
+
131
+
132
+
133
+
134
+ # Disclaimer
135
+ 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.
136
+
137
+ # Related Resources
138
+ Following are some third-party implementations of StoryDiffusion.
139
+
140
+
141
+ ## API
142
+
143
+ - [runpod.io serverless worker](https://github.com/bes-dev/story-diffusion-runpod-serverless-worker) provided by [BeS](https://github.com/bes-dev).
144
+ - [Replicate worker](https://github.com/camenduru/StoryDiffusion-replicate) provided by [camenduru](https://github.com/camenduru).
145
+
146
+
147
+
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>[email protected]</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
examples/twoperson/1.jpeg ADDED
examples/twoperson/2.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,1346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from this import d
2
+ import gradio as gr
3
+ import numpy as np
4
+ import torch
5
+ import gc
6
+ import copy
7
+ import os
8
+ import random
9
+ import datetime
10
+ from PIL import ImageFont
11
+ from utils.gradio_utils import (
12
+ character_to_dict,
13
+ process_original_prompt,
14
+ get_ref_character,
15
+ cal_attn_mask_xl,
16
+ cal_attn_indice_xl_effcient_memory,
17
+ is_torch2_available,
18
+ )
19
+
20
+ if is_torch2_available():
21
+ from utils.gradio_utils import AttnProcessor2_0 as AttnProcessor
22
+ else:
23
+ from utils.gradio_utils import AttnProcessor
24
+ from huggingface_hub import hf_hub_download
25
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
26
+ StableDiffusionXLPipeline,
27
+ )
28
+ from diffusers.schedulers.scheduling_ddim import DDIMScheduler
29
+ import torch.nn.functional as F
30
+ from diffusers.utils.loading_utils import load_image
31
+ from utils.utils import get_comic
32
+ from utils.style_template import styles
33
+ from utils.load_models_utils import get_models_dict, load_models
34
+
35
+ STYLE_NAMES = list(styles.keys())
36
+ DEFAULT_STYLE_NAME = "Japanese Anime"
37
+ global models_dict
38
+
39
+ models_dict = get_models_dict()
40
+
41
+ # Automatically select the device
42
+ device = (
43
+ "cuda"
44
+ if torch.cuda.is_available()
45
+ else "mps" if torch.backends.mps.is_available() else "cpu"
46
+ )
47
+ print(f"@@device:{device}")
48
+
49
+
50
+ # check if the file exists locally at a specified path before downloading it.
51
+ # if the file doesn't exist, it uses `hf_hub_download` to download the file
52
+ # and optionally move it to a specific directory. If the file already
53
+ # exists, it simply uses the local path.
54
+ local_dir = "data/"
55
+ photomaker_local_path = f"{local_dir}photomaker-v1.bin"
56
+ if not os.path.exists(photomaker_local_path):
57
+ photomaker_path = hf_hub_download(
58
+ repo_id="TencentARC/PhotoMaker",
59
+ filename="photomaker-v1.bin",
60
+ repo_type="model",
61
+ local_dir=local_dir,
62
+ )
63
+ else:
64
+ photomaker_path = photomaker_local_path
65
+
66
+ MAX_SEED = np.iinfo(np.int32).max
67
+
68
+
69
+ def setup_seed(seed):
70
+ torch.manual_seed(seed)
71
+ if device == "cuda":
72
+ torch.cuda.manual_seed_all(seed)
73
+ np.random.seed(seed)
74
+ random.seed(seed)
75
+ torch.backends.cudnn.deterministic = True
76
+
77
+
78
+ def set_text_unfinished():
79
+ return gr.update(
80
+ visible=True,
81
+ value="<h3>(Not Finished) Generating ··· The intermediate results will be shown.</h3>",
82
+ )
83
+
84
+
85
+ def set_text_finished():
86
+ return gr.update(visible=True, value="<h3>Generation Finished</h3>")
87
+
88
+
89
+ #################################################
90
+ def get_image_path_list(folder_name):
91
+ image_basename_list = os.listdir(folder_name)
92
+ image_path_list = sorted(
93
+ [os.path.join(folder_name, basename) for basename in image_basename_list]
94
+ )
95
+ return image_path_list
96
+
97
+
98
+ #################################################
99
+ class SpatialAttnProcessor2_0(torch.nn.Module):
100
+ r"""
101
+ Attention processor for IP-Adapater for PyTorch 2.0.
102
+ Args:
103
+ hidden_size (`int`):
104
+ The hidden size of the attention layer.
105
+ cross_attention_dim (`int`):
106
+ The number of channels in the `encoder_hidden_states`.
107
+ text_context_len (`int`, defaults to 77):
108
+ The context length of the text features.
109
+ scale (`float`, defaults to 1.0):
110
+ the weight scale of image prompt.
111
+ """
112
+
113
+ def __init__(
114
+ self,
115
+ hidden_size=None,
116
+ cross_attention_dim=None,
117
+ id_length=4,
118
+ device=device,
119
+ dtype=torch.float16,
120
+ ):
121
+ super().__init__()
122
+ if not hasattr(F, "scaled_dot_product_attention"):
123
+ raise ImportError(
124
+ "AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
125
+ )
126
+ self.device = device
127
+ self.dtype = dtype
128
+ self.hidden_size = hidden_size
129
+ self.cross_attention_dim = cross_attention_dim
130
+ self.total_length = id_length + 1
131
+ self.id_length = id_length
132
+ self.id_bank = {}
133
+
134
+ def __call__(
135
+ self,
136
+ attn,
137
+ hidden_states,
138
+ encoder_hidden_states=None,
139
+ attention_mask=None,
140
+ temb=None,
141
+ ):
142
+ # un_cond_hidden_states, cond_hidden_states = hidden_states.chunk(2)
143
+ # un_cond_hidden_states = self.__call2__(attn, un_cond_hidden_states,encoder_hidden_states,attention_mask,temb)
144
+ # 生成一个0到1之间的随机数
145
+ global total_count, attn_count, cur_step, indices1024, indices4096
146
+ global sa32, sa64
147
+ global write
148
+ global height, width
149
+ global character_dict, character_index_dict, invert_character_index_dict, cur_character, ref_indexs_dict, ref_totals, cur_character
150
+ if attn_count == 0 and cur_step == 0:
151
+ indices1024, indices4096 = cal_attn_indice_xl_effcient_memory(
152
+ self.total_length,
153
+ self.id_length,
154
+ sa32,
155
+ sa64,
156
+ height,
157
+ width,
158
+ device=self.device,
159
+ dtype=self.dtype,
160
+ )
161
+ if write:
162
+ assert len(cur_character) == 1
163
+ if hidden_states.shape[1] == (height // 32) * (width // 32):
164
+ indices = indices1024
165
+ else:
166
+ indices = indices4096
167
+ # print(f"white:{cur_step}")
168
+ total_batch_size, nums_token, channel = hidden_states.shape
169
+ img_nums = total_batch_size // 2
170
+ hidden_states = hidden_states.reshape(-1, img_nums, nums_token, channel)
171
+ # print(img_nums,len(indices),hidden_states.shape,self.total_length)
172
+ if cur_character[0] not in self.id_bank:
173
+ self.id_bank[cur_character[0]] = {}
174
+ self.id_bank[cur_character[0]][cur_step] = [
175
+ hidden_states[:, img_ind, indices[img_ind], :]
176
+ .reshape(2, -1, channel)
177
+ .clone()
178
+ for img_ind in range(img_nums)
179
+ ]
180
+ hidden_states = hidden_states.reshape(-1, nums_token, channel)
181
+ # self.id_bank[cur_step] = [hidden_states[:self.id_length].clone(), hidden_states[self.id_length:].clone()]
182
+ else:
183
+ # encoder_hidden_states = torch.cat((self.id_bank[cur_step][0].to(self.device),self.id_bank[cur_step][1].to(self.device)))
184
+ # TODO: ADD Multipersion Control
185
+ encoder_arr = []
186
+ for character in cur_character:
187
+ encoder_arr = encoder_arr + [
188
+ tensor.to(self.device)
189
+ for tensor in self.id_bank[character][cur_step]
190
+ ]
191
+ # 判断随机数是否大于0.5
192
+ if cur_step < 1:
193
+ hidden_states = self.__call2__(
194
+ attn, hidden_states, None, attention_mask, temb
195
+ )
196
+ else: # 256 1024 4096
197
+ random_number = random.random()
198
+ if cur_step < 20:
199
+ rand_num = 0.3
200
+ else:
201
+ rand_num = 0.1
202
+ # print(f"hidden state shape {hidden_states.shape[1]}")
203
+ if random_number > rand_num:
204
+ if hidden_states.shape[1] == (height // 32) * (width // 32):
205
+ indices = indices1024
206
+ else:
207
+ indices = indices4096
208
+ # print("before attention",hidden_states.shape,attention_mask.shape,encoder_hidden_states.shape if encoder_hidden_states is not None else "None")
209
+ if write:
210
+ total_batch_size, nums_token, channel = hidden_states.shape
211
+ img_nums = total_batch_size // 2
212
+ hidden_states = hidden_states.reshape(
213
+ -1, img_nums, nums_token, channel
214
+ )
215
+ encoder_arr = [
216
+ hidden_states[:, img_ind, indices[img_ind], :].reshape(
217
+ 2, -1, channel
218
+ )
219
+ for img_ind in range(img_nums)
220
+ ]
221
+ for img_ind in range(img_nums):
222
+ # print(img_nums)
223
+ # assert img_nums != 1
224
+ img_ind_list = [i for i in range(img_nums)]
225
+ # print(img_ind_list,img_ind)
226
+ img_ind_list.remove(img_ind)
227
+ # print(img_ind,invert_character_index_dict[img_ind])
228
+ # print(character_index_dict[invert_character_index_dict[img_ind]])
229
+ # print(img_ind_list)
230
+ # print(img_ind,img_ind_list)
231
+ encoder_hidden_states_tmp = torch.cat(
232
+ [encoder_arr[img_ind] for img_ind in img_ind_list]
233
+ + [hidden_states[:, img_ind, :, :]],
234
+ dim=1,
235
+ )
236
+
237
+ hidden_states[:, img_ind, :, :] = self.__call2__(
238
+ attn,
239
+ hidden_states[:, img_ind, :, :],
240
+ encoder_hidden_states_tmp,
241
+ None,
242
+ temb,
243
+ )
244
+ else:
245
+ _, nums_token, channel = hidden_states.shape
246
+ # img_nums = total_batch_size // 2
247
+ # encoder_hidden_states = encoder_hidden_states.reshape(-1,img_nums,nums_token,channel)
248
+ hidden_states = hidden_states.reshape(2, -1, nums_token, channel)
249
+ # print(len(indices))
250
+ # encoder_arr = [encoder_hidden_states[:,img_ind,indices[img_ind],:].reshape(2,-1,channel) for img_ind in range(img_nums)]
251
+ encoder_hidden_states_tmp = torch.cat(
252
+ encoder_arr + [hidden_states[:, 0, :, :]], dim=1
253
+ )
254
+ # print(len(encoder_arr),encoder_hidden_states_tmp.shape)
255
+ hidden_states[:, 0, :, :] = self.__call2__(
256
+ attn,
257
+ hidden_states[:, 0, :, :],
258
+ encoder_hidden_states_tmp,
259
+ None,
260
+ temb,
261
+ )
262
+ hidden_states = hidden_states.reshape(-1, nums_token, channel)
263
+ else:
264
+ hidden_states = self.__call2__(
265
+ attn, hidden_states, None, attention_mask, temb
266
+ )
267
+ attn_count += 1
268
+ if attn_count == total_count:
269
+ attn_count = 0
270
+ cur_step += 1
271
+ indices1024, indices4096 = cal_attn_indice_xl_effcient_memory(
272
+ self.total_length,
273
+ self.id_length,
274
+ sa32,
275
+ sa64,
276
+ height,
277
+ width,
278
+ device=self.device,
279
+ dtype=self.dtype,
280
+ )
281
+
282
+ return hidden_states
283
+
284
+ def __call2__(
285
+ self,
286
+ attn,
287
+ hidden_states,
288
+ encoder_hidden_states=None,
289
+ attention_mask=None,
290
+ temb=None,
291
+ ):
292
+ residual = hidden_states
293
+
294
+ if attn.spatial_norm is not None:
295
+ hidden_states = attn.spatial_norm(hidden_states, temb)
296
+
297
+ input_ndim = hidden_states.ndim
298
+
299
+ if input_ndim == 4:
300
+ batch_size, channel, height, width = hidden_states.shape
301
+ hidden_states = hidden_states.view(
302
+ batch_size, channel, height * width
303
+ ).transpose(1, 2)
304
+
305
+ batch_size, sequence_length, channel = hidden_states.shape
306
+ # print(hidden_states.shape)
307
+ if attention_mask is not None:
308
+ attention_mask = attn.prepare_attention_mask(
309
+ attention_mask, sequence_length, batch_size
310
+ )
311
+ # scaled_dot_product_attention expects attention_mask shape to be
312
+ # (batch, heads, source_length, target_length)
313
+ attention_mask = attention_mask.view(
314
+ batch_size, attn.heads, -1, attention_mask.shape[-1]
315
+ )
316
+
317
+ if attn.group_norm is not None:
318
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(
319
+ 1, 2
320
+ )
321
+
322
+ query = attn.to_q(hidden_states)
323
+
324
+ if encoder_hidden_states is None:
325
+ encoder_hidden_states = hidden_states # B, N, C
326
+ # else:
327
+ # encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,sequence_length,channel).reshape(-1,(self.id_length+1) * sequence_length,channel)
328
+
329
+ key = attn.to_k(encoder_hidden_states)
330
+ value = attn.to_v(encoder_hidden_states)
331
+
332
+ inner_dim = key.shape[-1]
333
+ head_dim = inner_dim // attn.heads
334
+
335
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
336
+
337
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
338
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
339
+
340
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
341
+ # TODO: add support for attn.scale when we move to Torch 2.1
342
+ hidden_states = F.scaled_dot_product_attention(
343
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
344
+ )
345
+
346
+ hidden_states = hidden_states.transpose(1, 2).reshape(
347
+ batch_size, -1, attn.heads * head_dim
348
+ )
349
+ hidden_states = hidden_states.to(query.dtype)
350
+
351
+ # linear proj
352
+ hidden_states = attn.to_out[0](hidden_states)
353
+ # dropout
354
+ hidden_states = attn.to_out[1](hidden_states)
355
+
356
+ if input_ndim == 4:
357
+ hidden_states = hidden_states.transpose(-1, -2).reshape(
358
+ batch_size, channel, height, width
359
+ )
360
+
361
+ if attn.residual_connection:
362
+ hidden_states = hidden_states + residual
363
+
364
+ hidden_states = hidden_states / attn.rescale_output_factor
365
+
366
+ return hidden_states
367
+
368
+
369
+ def set_attention_processor(unet, id_length, is_ipadapter=False):
370
+ global attn_procs
371
+ attn_procs = {}
372
+ for name in unet.attn_processors.keys():
373
+ cross_attention_dim = (
374
+ None
375
+ if name.endswith("attn1.processor")
376
+ else unet.config.cross_attention_dim
377
+ )
378
+ if name.startswith("mid_block"):
379
+ hidden_size = unet.config.block_out_channels[-1]
380
+ elif name.startswith("up_blocks"):
381
+ block_id = int(name[len("up_blocks.")])
382
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
383
+ elif name.startswith("down_blocks"):
384
+ block_id = int(name[len("down_blocks.")])
385
+ hidden_size = unet.config.block_out_channels[block_id]
386
+ if cross_attention_dim is None:
387
+ if name.startswith("up_blocks"):
388
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length=id_length)
389
+ else:
390
+ attn_procs[name] = AttnProcessor()
391
+ else:
392
+ if is_ipadapter:
393
+ attn_procs[name] = IPAttnProcessor2_0(
394
+ hidden_size=hidden_size,
395
+ cross_attention_dim=cross_attention_dim,
396
+ scale=1,
397
+ num_tokens=4,
398
+ ).to(unet.device, dtype=torch.float16)
399
+ else:
400
+ attn_procs[name] = AttnProcessor()
401
+
402
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
403
+
404
+
405
+ #################################################
406
+ #################################################
407
+ canvas_html = "<div id='canvas-root' style='max-width:400px; margin: 0 auto'></div>"
408
+ load_js = """
409
+ async () => {
410
+ const url = "https://huggingface.co/datasets/radames/gradio-components/raw/main/sketch-canvas.js"
411
+ fetch(url)
412
+ .then(res => res.text())
413
+ .then(text => {
414
+ const script = document.createElement('script');
415
+ script.type = "module"
416
+ script.src = URL.createObjectURL(new Blob([text], { type: 'application/javascript' }));
417
+ document.head.appendChild(script);
418
+ });
419
+ }
420
+ """
421
+
422
+ get_js_colors = """
423
+ async (canvasData) => {
424
+ const canvasEl = document.getElementById("canvas-root");
425
+ return [canvasEl._data]
426
+ }
427
+ """
428
+
429
+ css = """
430
+ #color-bg{display:flex;justify-content: center;align-items: center;}
431
+ .color-bg-item{width: 100%; height: 32px}
432
+ #main_button{width:100%}
433
+ <style>
434
+ """
435
+
436
+
437
+ def save_single_character_weights(unet, character, description, filepath):
438
+ """
439
+ 保存 attention_processor 类中的 id_bank GPU Tensor 列表到指定文件中。
440
+ 参数:
441
+ - model: 包含 attention_processor 类实例的模型。
442
+ - filepath: 权重要保存到的文件路径。
443
+ """
444
+ weights_to_save = {}
445
+ weights_to_save["description"] = description
446
+ weights_to_save["character"] = character
447
+ for attn_name, attn_processor in unet.attn_processors.items():
448
+ if isinstance(attn_processor, SpatialAttnProcessor2_0):
449
+ # 将每个 Tensor 转到 CPU 并转为列表,以确保它可以被序列化
450
+ weights_to_save[attn_name] = {}
451
+ for step_key in attn_processor.id_bank[character].keys():
452
+ weights_to_save[attn_name][step_key] = [
453
+ tensor.cpu()
454
+ for tensor in attn_processor.id_bank[character][step_key]
455
+ ]
456
+ # 使用torch.save保存权重
457
+ torch.save(weights_to_save, filepath)
458
+
459
+
460
+ def load_single_character_weights(unet, filepath):
461
+ """
462
+ 从指定文件中加载权重到 attention_processor 类的 id_bank 中。
463
+ 参数:
464
+ - model: 包含 attention_processor 类实例的模型。
465
+ - filepath: 权重文件的路径。
466
+ """
467
+ # 使用torch.load来读取权重
468
+ weights_to_load = torch.load(filepath, map_location=torch.device("cpu"))
469
+ character = weights_to_load["character"]
470
+ description = weights_to_load["description"]
471
+ for attn_name, attn_processor in unet.attn_processors.items():
472
+ if isinstance(attn_processor, SpatialAttnProcessor2_0):
473
+ # 转移权重到GPU(如果GPU可用的话)并赋值给id_bank
474
+ attn_processor.id_bank[character] = {}
475
+ for step_key in weights_to_load[attn_name].keys():
476
+ attn_processor.id_bank[character][step_key] = [
477
+ tensor.to(unet.device)
478
+ for tensor in weights_to_load[attn_name][step_key]
479
+ ]
480
+
481
+
482
+ def save_results(unet, img_list):
483
+
484
+ timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
485
+ folder_name = f"results/{timestamp}"
486
+ weight_folder_name = f"{folder_name}/weights"
487
+ # 创建文件夹
488
+ if not os.path.exists(folder_name):
489
+ os.makedirs(folder_name)
490
+ os.makedirs(weight_folder_name)
491
+
492
+ for idx, img in enumerate(img_list):
493
+ file_path = os.path.join(folder_name, f"image_{idx}.png") # 图片文件名
494
+ img.save(file_path)
495
+ global character_dict
496
+ # for char in character_dict:
497
+ # description = character_dict[char]
498
+ # save_single_character_weights(unet,char,description,os.path.join(weight_folder_name, f'{char}.pt'))
499
+
500
+
501
+ #################################################
502
+ title = r"""
503
+ <h1 align="center">StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</h1>
504
+ """
505
+
506
+ description = r"""
507
+ <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>
508
+ ❗️❗️❗️[<b>Important</b>] Personalization steps:<br>
509
+ 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>
510
+ 2️⃣ Enter the prompt array, each line corrsponds to one generated image.<br>
511
+ 3️⃣ Choose your preferred style template.<br>
512
+ 4️⃣ Click the <b>Submit</b> button to start customizing.
513
+ """
514
+
515
+ article = r"""
516
+
517
+ If StoryDiffusion is helpful, please help to ⭐ the <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'>Github Repo</a>. Thanks!
518
+ [![GitHub Stars](https://img.shields.io/github/stars/HVision-NKU/StoryDiffusion?style=social)](https://github.com/HVision-NKU/StoryDiffusion)
519
+ ---
520
+ 📝 **Citation**
521
+ <br>
522
+ If our work is useful for your research, please consider citing:
523
+
524
+ ```bibtex
525
+ @article{Zhou2024storydiffusion,
526
+ title={StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation},
527
+ author={Zhou, Yupeng and Zhou, Daquan and Cheng, Ming-Ming and Feng, Jiashi and Hou, Qibin},
528
+ year={2024}
529
+ }
530
+ ```
531
+ 📋 **License**
532
+ <br>
533
+ Apache-2.0 LICENSE.
534
+
535
+ 📧 **Contact**
536
+ <br>
537
+ If you have any questions, please feel free to reach me out at <b>[email protected]</b>.
538
+ """
539
+ version = r"""
540
+ <h3 align="center">StoryDiffusion Version 0.02 (test version)</h3>
541
+
542
+ <h5 >1. Support image ref image. (Cartoon Ref image is not support now)</h5>
543
+ <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>
544
+ <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>
545
+ <h5 align="center">Tips: </h4>
546
+ """
547
+ #################################################
548
+ global attn_count, total_count, id_length, total_length, cur_step, cur_model_type
549
+ global write
550
+ global sa32, sa64
551
+ global height, width
552
+ attn_count = 0
553
+ total_count = 0
554
+ cur_step = 0
555
+ id_length = 4
556
+ total_length = 5
557
+ cur_model_type = ""
558
+ global attn_procs, unet
559
+ attn_procs = {}
560
+ ###
561
+ write = False
562
+ ###
563
+ sa32 = 0.5
564
+ sa64 = 0.5
565
+ height = 768
566
+ width = 768
567
+ ###
568
+ global pipe
569
+ global sd_model_path
570
+ pipe = None
571
+ sd_model_path = models_dict["Unstable"]["path"] # "SG161222/RealVisXL_V4.0"
572
+ single_files = models_dict["Unstable"]["single_files"]
573
+ ### LOAD Stable Diffusion Pipeline
574
+ if single_files:
575
+ pipe = StableDiffusionXLPipeline.from_single_file(
576
+ sd_model_path, torch_dtype=torch.float16
577
+ )
578
+ else:
579
+ pipe = StableDiffusionXLPipeline.from_pretrained(
580
+ sd_model_path, torch_dtype=torch.float16, use_safetensors=False
581
+ )
582
+ pipe = pipe.to(device)
583
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
584
+ # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
585
+ pipe.scheduler.set_timesteps(50)
586
+ pipe.enable_vae_slicing()
587
+ if device != "mps":
588
+ pipe.enable_model_cpu_offload()
589
+ unet = pipe.unet
590
+ cur_model_type = "Unstable" + "-" + "original"
591
+ ### Insert PairedAttention
592
+ for name in unet.attn_processors.keys():
593
+ cross_attention_dim = (
594
+ None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
595
+ )
596
+ if name.startswith("mid_block"):
597
+ hidden_size = unet.config.block_out_channels[-1]
598
+ elif name.startswith("up_blocks"):
599
+ block_id = int(name[len("up_blocks.")])
600
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
601
+ elif name.startswith("down_blocks"):
602
+ block_id = int(name[len("down_blocks.")])
603
+ hidden_size = unet.config.block_out_channels[block_id]
604
+ if cross_attention_dim is None and (name.startswith("up_blocks")):
605
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length=id_length)
606
+ total_count += 1
607
+ else:
608
+ attn_procs[name] = AttnProcessor()
609
+ print("successsfully load paired self-attention")
610
+ print(f"number of the processor : {total_count}")
611
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
612
+ global mask1024, mask4096
613
+ mask1024, mask4096 = cal_attn_mask_xl(
614
+ total_length,
615
+ id_length,
616
+ sa32,
617
+ sa64,
618
+ height,
619
+ width,
620
+ device=device,
621
+ dtype=torch.float16,
622
+ )
623
+
624
+ ######### Gradio Fuction #############
625
+
626
+
627
+ def swap_to_gallery(images):
628
+ return (
629
+ gr.update(value=images, visible=True),
630
+ gr.update(visible=True),
631
+ gr.update(visible=False),
632
+ )
633
+
634
+
635
+ def upload_example_to_gallery(images, prompt, style, negative_prompt):
636
+ return (
637
+ gr.update(value=images, visible=True),
638
+ gr.update(visible=True),
639
+ gr.update(visible=False),
640
+ )
641
+
642
+
643
+ def remove_back_to_files():
644
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
645
+
646
+
647
+ def remove_tips():
648
+ return gr.update(visible=False)
649
+
650
+
651
+ def apply_style_positive(style_name: str, positive: str):
652
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
653
+ return p.replace("{prompt}", positive)
654
+
655
+
656
+ def apply_style(style_name: str, positives: list, negative: str = ""):
657
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
658
+ return [
659
+ p.replace("{prompt}", positive) for positive in positives
660
+ ], n + " " + negative
661
+
662
+
663
+ def change_visiale_by_model_type(_model_type):
664
+ if _model_type == "Only Using Textual Description":
665
+ return (
666
+ gr.update(visible=False),
667
+ gr.update(visible=False),
668
+ gr.update(visible=False),
669
+ )
670
+ elif _model_type == "Using Ref Images":
671
+ return (
672
+ gr.update(visible=True),
673
+ gr.update(visible=True),
674
+ gr.update(visible=False),
675
+ )
676
+ else:
677
+ raise ValueError("Invalid model type", _model_type)
678
+
679
+
680
+ def load_character_files(character_files: str):
681
+ if character_files == "":
682
+ raise gr.Error("Please set a character file!")
683
+ character_files_arr = character_files.splitlines()
684
+ primarytext = []
685
+ for character_file_name in character_files_arr:
686
+ character_file = torch.load(
687
+ character_file_name, map_location=torch.device("cpu")
688
+ )
689
+ primarytext.append(character_file["character"] + character_file["description"])
690
+ return array2string(primarytext)
691
+
692
+
693
+ def load_character_files_on_running(unet, character_files: str):
694
+ if character_files == "":
695
+ return False
696
+ character_files_arr = character_files.splitlines()
697
+ for character_file in character_files_arr:
698
+ load_single_character_weights(unet, character_file)
699
+ return True
700
+
701
+
702
+ ######### Image Generation ##############
703
+ def process_generation(
704
+ _sd_type,
705
+ _model_type,
706
+ _upload_images,
707
+ _num_steps,
708
+ style_name,
709
+ _Ip_Adapter_Strength,
710
+ _style_strength_ratio,
711
+ guidance_scale,
712
+ seed_,
713
+ sa32_,
714
+ sa64_,
715
+ id_length_,
716
+ general_prompt,
717
+ negative_prompt,
718
+ prompt_array,
719
+ G_height,
720
+ G_width,
721
+ _comic_type,
722
+ font_choice,
723
+ _char_files,
724
+ ): # Corrected font_choice usage
725
+ if len(general_prompt.splitlines()) >= 3:
726
+ raise gr.Error(
727
+ "Support for more than three characters is temporarily unavailable due to VRAM limitations, but this issue will be resolved soon."
728
+ )
729
+ _model_type = "Photomaker" if _model_type == "Using Ref Images" else "original"
730
+ if _model_type == "Photomaker" and "img" not in general_prompt:
731
+ raise gr.Error(
732
+ 'Please add the triger word " img " behind the class word you want to customize, such as: man img or woman img'
733
+ )
734
+ if _upload_images is None and _model_type != "original":
735
+ raise gr.Error(f"Cannot find any input face image!")
736
+ global sa32, sa64, id_length, total_length, attn_procs, unet, cur_model_type
737
+ global write
738
+ global cur_step, attn_count
739
+ global height, width
740
+ height = G_height
741
+ width = G_width
742
+ global pipe
743
+ global sd_model_path, models_dict
744
+ sd_model_path = models_dict[_sd_type]
745
+ use_safe_tensor = True
746
+ for attn_processor in pipe.unet.attn_processors.values():
747
+ if isinstance(attn_processor, SpatialAttnProcessor2_0):
748
+ for values in attn_processor.id_bank.values():
749
+ del values
750
+ attn_processor.id_bank = {}
751
+ attn_processor.id_length = id_length
752
+ attn_processor.total_length = id_length + 1
753
+ gc.collect()
754
+ torch.cuda.empty_cache()
755
+ if cur_model_type != _sd_type + "-" + _model_type:
756
+ # apply the style template
757
+ ##### load pipe
758
+ del pipe
759
+ gc.collect()
760
+ if device == "cuda":
761
+ torch.cuda.empty_cache()
762
+ model_info = models_dict[_sd_type]
763
+ model_info["model_type"] = _model_type
764
+ pipe = load_models(model_info, device=device, photomaker_path=photomaker_path)
765
+ set_attention_processor(pipe.unet, id_length_, is_ipadapter=False)
766
+ ##### ########################
767
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
768
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
769
+ cur_model_type = _sd_type + "-" + _model_type
770
+ pipe.enable_vae_slicing()
771
+ if device != "mps":
772
+ pipe.enable_model_cpu_offload()
773
+ else:
774
+ unet = pipe.unet
775
+ # unet.set_attn_processor(copy.deepcopy(attn_procs))
776
+
777
+ load_chars = load_character_files_on_running(unet, character_files=_char_files)
778
+
779
+ prompts = prompt_array.splitlines()
780
+ global character_dict, character_index_dict, invert_character_index_dict, ref_indexs_dict, ref_totals
781
+ character_dict, character_list = character_to_dict(general_prompt)
782
+
783
+ start_merge_step = int(float(_style_strength_ratio) / 100 * _num_steps)
784
+ if start_merge_step > 30:
785
+ start_merge_step = 30
786
+ print(f"start_merge_step:{start_merge_step}")
787
+ generator = torch.Generator(device=device).manual_seed(seed_)
788
+ sa32, sa64 = sa32_, sa64_
789
+ id_length = id_length_
790
+ clipped_prompts = prompts[:]
791
+ nc_indexs = []
792
+ for ind, prompt in enumerate(clipped_prompts):
793
+ if "[NC]" in prompt:
794
+ nc_indexs.append(ind)
795
+ if ind < id_length:
796
+ raise gr.Error(
797
+ f"The first {id_length} row is id prompts, cannot use [NC]!"
798
+ )
799
+ prompts = [
800
+ prompt if "[NC]" not in prompt else prompt.replace("[NC]", "")
801
+ for prompt in clipped_prompts
802
+ ]
803
+
804
+ prompts = [
805
+ prompt.rpartition("#")[0] if "#" in prompt else prompt for prompt in prompts
806
+ ]
807
+ print(prompts)
808
+ # id_prompts = prompts[:id_length]
809
+ (
810
+ character_index_dict,
811
+ invert_character_index_dict,
812
+ replace_prompts,
813
+ ref_indexs_dict,
814
+ ref_totals,
815
+ ) = process_original_prompt(character_dict, prompts.copy(), id_length)
816
+ if _model_type != "original":
817
+ input_id_images_dict = {}
818
+ if len(_upload_images) != len(character_dict.keys()):
819
+ raise gr.Error(
820
+ f"You upload images({len(_upload_images)}) is not equal to the number of characters({len(character_dict.keys())})!"
821
+ )
822
+ for ind, img in enumerate(_upload_images):
823
+ input_id_images_dict[character_list[ind]] = [load_image(img)]
824
+ print(character_dict)
825
+ print(character_index_dict)
826
+ print(invert_character_index_dict)
827
+ # real_prompts = prompts[id_length:]
828
+ if device == "cuda":
829
+ torch.cuda.empty_cache()
830
+ write = True
831
+ cur_step = 0
832
+
833
+ attn_count = 0
834
+ # id_prompts, negative_prompt = apply_style(style_name, id_prompts, negative_prompt)
835
+ # print(id_prompts)
836
+ setup_seed(seed_)
837
+ total_results = []
838
+ id_images = []
839
+ results_dict = {}
840
+ global cur_character
841
+ if not load_chars:
842
+ for character_key in character_dict.keys():
843
+ cur_character = [character_key]
844
+ ref_indexs = ref_indexs_dict[character_key]
845
+ print(character_key, ref_indexs)
846
+ current_prompts = [replace_prompts[ref_ind] for ref_ind in ref_indexs]
847
+ print(current_prompts)
848
+ setup_seed(seed_)
849
+ generator = torch.Generator(device=device).manual_seed(seed_)
850
+ cur_step = 0
851
+ cur_positive_prompts, negative_prompt = apply_style(
852
+ style_name, current_prompts, negative_prompt
853
+ )
854
+ if _model_type == "original":
855
+ id_images = pipe(
856
+ cur_positive_prompts,
857
+ num_inference_steps=_num_steps,
858
+ guidance_scale=guidance_scale,
859
+ height=height,
860
+ width=width,
861
+ negative_prompt=negative_prompt,
862
+ generator=generator,
863
+ ).images
864
+ elif _model_type == "Photomaker":
865
+ id_images = pipe(
866
+ cur_positive_prompts,
867
+ input_id_images=input_id_images_dict[character_key],
868
+ num_inference_steps=_num_steps,
869
+ guidance_scale=guidance_scale,
870
+ start_merge_step=start_merge_step,
871
+ height=height,
872
+ width=width,
873
+ negative_prompt=negative_prompt,
874
+ generator=generator,
875
+ ).images
876
+ else:
877
+ raise NotImplementedError(
878
+ "You should choice between original and Photomaker!",
879
+ f"But you choice {_model_type}",
880
+ )
881
+
882
+ # total_results = id_images + total_results
883
+ # yield total_results
884
+ print(id_images)
885
+ for ind, img in enumerate(id_images):
886
+ print(ref_indexs[ind])
887
+ results_dict[ref_indexs[ind]] = img
888
+ # real_images = []
889
+ yield [results_dict[ind] for ind in results_dict.keys()]
890
+ write = False
891
+ if not load_chars:
892
+ real_prompts_inds = [
893
+ ind for ind in range(len(prompts)) if ind not in ref_totals
894
+ ]
895
+ else:
896
+ real_prompts_inds = [ind for ind in range(len(prompts))]
897
+ print(real_prompts_inds)
898
+
899
+ for real_prompts_ind in real_prompts_inds:
900
+ real_prompt = replace_prompts[real_prompts_ind]
901
+ cur_character = get_ref_character(prompts[real_prompts_ind], character_dict)
902
+ print(cur_character, real_prompt)
903
+ setup_seed(seed_)
904
+ if len(cur_character) > 1 and _model_type == "Photomaker":
905
+ raise gr.Error(
906
+ "Temporarily Not Support Multiple character in Ref Image Mode!"
907
+ )
908
+ generator = torch.Generator(device=device).manual_seed(seed_)
909
+ cur_step = 0
910
+ real_prompt = apply_style_positive(style_name, real_prompt)
911
+ if _model_type == "original":
912
+ results_dict[real_prompts_ind] = pipe(
913
+ real_prompt,
914
+ num_inference_steps=_num_steps,
915
+ guidance_scale=guidance_scale,
916
+ height=height,
917
+ width=width,
918
+ negative_prompt=negative_prompt,
919
+ generator=generator,
920
+ ).images[0]
921
+ elif _model_type == "Photomaker":
922
+ results_dict[real_prompts_ind] = pipe(
923
+ real_prompt,
924
+ input_id_images=(
925
+ input_id_images_dict[cur_character[0]]
926
+ if real_prompts_ind not in nc_indexs
927
+ else input_id_images_dict[character_list[0]]
928
+ ),
929
+ num_inference_steps=_num_steps,
930
+ guidance_scale=guidance_scale,
931
+ start_merge_step=start_merge_step,
932
+ height=height,
933
+ width=width,
934
+ negative_prompt=negative_prompt,
935
+ generator=generator,
936
+ nc_flag=True if real_prompts_ind in nc_indexs else False,
937
+ ).images[0]
938
+ else:
939
+ raise NotImplementedError(
940
+ "You should choice between original and Photomaker!",
941
+ f"But you choice {_model_type}",
942
+ )
943
+ yield [results_dict[ind] for ind in results_dict.keys()]
944
+ total_results = [results_dict[ind] for ind in range(len(prompts))]
945
+ if _comic_type != "No typesetting (default)":
946
+ captions = prompt_array.splitlines()
947
+ captions = [caption.replace("[NC]", "") for caption in captions]
948
+ captions = [
949
+ caption.split("#")[-1] if "#" in caption else caption
950
+ for caption in captions
951
+ ]
952
+ font_path = os.path.join("fonts", font_choice)
953
+ font = ImageFont.truetype(font_path, int(45))
954
+ total_results = (
955
+ get_comic(total_results, _comic_type, captions=captions, font=font)
956
+ + total_results
957
+ )
958
+ save_results(pipe.unet, total_results)
959
+
960
+ yield total_results
961
+
962
+
963
+ def array2string(arr):
964
+ stringtmp = ""
965
+ for i, part in enumerate(arr):
966
+ if i != len(arr) - 1:
967
+ stringtmp += part + "\n"
968
+ else:
969
+ stringtmp += part
970
+
971
+ return stringtmp
972
+
973
+
974
+ #################################################
975
+ #################################################
976
+ ### define the interface
977
+
978
+ with gr.Blocks(css=css) as demo:
979
+ binary_matrixes = gr.State([])
980
+ color_layout = gr.State([])
981
+
982
+ # gr.Markdown(logo)
983
+ gr.Markdown(title)
984
+ gr.Markdown(description)
985
+
986
+ with gr.Row():
987
+ with gr.Group(elem_id="main-image"):
988
+
989
+ prompts = []
990
+ colors = []
991
+
992
+ with gr.Column(visible=True) as gen_prompt_vis:
993
+ sd_type = gr.Dropdown(
994
+ choices=list(models_dict.keys()),
995
+ value="Unstable",
996
+ label="sd_type",
997
+ info="Select pretrained model",
998
+ )
999
+ model_type = gr.Radio(
1000
+ ["Only Using Textual Description", "Using Ref Images"],
1001
+ label="model_type",
1002
+ value="Only Using Textual Description",
1003
+ info="Control type of the Character",
1004
+ )
1005
+ with gr.Group(visible=False) as control_image_input:
1006
+ files = gr.Files(
1007
+ label="Drag (Select) 1 or more photos of your face",
1008
+ file_types=["image"],
1009
+ )
1010
+ uploaded_files = gr.Gallery(
1011
+ label="Your images",
1012
+ visible=False,
1013
+ columns=5,
1014
+ rows=1,
1015
+ height=200,
1016
+ )
1017
+ with gr.Column(visible=False) as clear_button:
1018
+ remove_and_reupload = gr.ClearButton(
1019
+ value="Remove and upload new ones",
1020
+ components=files,
1021
+ size="sm",
1022
+ )
1023
+ general_prompt = gr.Textbox(
1024
+ value="",
1025
+ lines=2,
1026
+ label="(1) Textual Description for Character",
1027
+ interactive=True,
1028
+ )
1029
+ negative_prompt = gr.Textbox(
1030
+ value="", label="(2) Negative_prompt", interactive=True
1031
+ )
1032
+ style = gr.Dropdown(
1033
+ label="Style template",
1034
+ choices=STYLE_NAMES,
1035
+ value=DEFAULT_STYLE_NAME,
1036
+ )
1037
+ prompt_array = gr.Textbox(
1038
+ lines=3,
1039
+ value="",
1040
+ label="(3) Comic Description (each line corresponds to a frame).",
1041
+ interactive=True,
1042
+ )
1043
+ char_path = gr.Textbox(
1044
+ lines=2,
1045
+ value="",
1046
+ visible=False,
1047
+ label="(Optional) Character files",
1048
+ interactive=True,
1049
+ )
1050
+ char_btn = gr.Button("Load Character files", visible=False)
1051
+ with gr.Accordion("(4) Tune the hyperparameters", open=True):
1052
+ font_choice = gr.Dropdown(
1053
+ label="Select Font",
1054
+ choices=[
1055
+ f for f in os.listdir("./fonts") if f.endswith(".ttf")
1056
+ ],
1057
+ value="Inkfree.ttf",
1058
+ info="Select font for the final slide.",
1059
+ interactive=True,
1060
+ )
1061
+ sa32_ = gr.Slider(
1062
+ label=" (The degree of Paired Attention at 32 x 32 self-attention layers) ",
1063
+ minimum=0,
1064
+ maximum=1.0,
1065
+ value=0.5,
1066
+ step=0.1,
1067
+ )
1068
+ sa64_ = gr.Slider(
1069
+ label=" (The degree of Paired Attention at 64 x 64 self-attention layers) ",
1070
+ minimum=0,
1071
+ maximum=1.0,
1072
+ value=0.5,
1073
+ step=0.1,
1074
+ )
1075
+ id_length_ = gr.Slider(
1076
+ label="Number of id images in total images",
1077
+ minimum=1,
1078
+ maximum=4,
1079
+ value=1,
1080
+ step=1,
1081
+ )
1082
+ with gr.Row():
1083
+ seed_ = gr.Slider(
1084
+ label="Seed", minimum=-1, maximum=MAX_SEED, value=0, step=1
1085
+ )
1086
+ randomize_seed_btn = gr.Button("🎲", size="sm")
1087
+ num_steps = gr.Slider(
1088
+ label="Number of sample steps",
1089
+ minimum=20,
1090
+ maximum=100,
1091
+ step=1,
1092
+ value=35,
1093
+ )
1094
+ G_height = gr.Slider(
1095
+ label="height",
1096
+ minimum=256,
1097
+ maximum=1024,
1098
+ step=32,
1099
+ value=768,
1100
+ )
1101
+ G_width = gr.Slider(
1102
+ label="width",
1103
+ minimum=256,
1104
+ maximum=1024,
1105
+ step=32,
1106
+ value=768,
1107
+ )
1108
+ comic_type = gr.Radio(
1109
+ [
1110
+ "No typesetting (default)",
1111
+ "Four Pannel",
1112
+ "Classic Comic Style",
1113
+ ],
1114
+ value="Classic Comic Style",
1115
+ label="Typesetting Style",
1116
+ info="Select the typesetting style ",
1117
+ )
1118
+ guidance_scale = gr.Slider(
1119
+ label="Guidance scale",
1120
+ minimum=0.1,
1121
+ maximum=10.0,
1122
+ step=0.1,
1123
+ value=5,
1124
+ )
1125
+ style_strength_ratio = gr.Slider(
1126
+ label="Style strength of Ref Image (%)",
1127
+ minimum=15,
1128
+ maximum=50,
1129
+ step=1,
1130
+ value=20,
1131
+ visible=False,
1132
+ )
1133
+ Ip_Adapter_Strength = gr.Slider(
1134
+ label="Ip_Adapter_Strength",
1135
+ minimum=0,
1136
+ maximum=1,
1137
+ step=0.1,
1138
+ value=0.5,
1139
+ visible=False,
1140
+ )
1141
+ final_run_btn = gr.Button("Generate ! 😺")
1142
+
1143
+ with gr.Column():
1144
+ out_image = gr.Gallery(label="Result", columns=2, height="auto")
1145
+ generated_information = gr.Markdown(
1146
+ label="Generation Details", value="", visible=False
1147
+ )
1148
+ gr.Markdown(version)
1149
+ model_type.change(
1150
+ fn=change_visiale_by_model_type,
1151
+ inputs=model_type,
1152
+ outputs=[control_image_input, style_strength_ratio, Ip_Adapter_Strength],
1153
+ )
1154
+ files.upload(
1155
+ fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files]
1156
+ )
1157
+ remove_and_reupload.click(
1158
+ fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files]
1159
+ )
1160
+ char_btn.click(fn=load_character_files, inputs=char_path, outputs=[general_prompt])
1161
+
1162
+ randomize_seed_btn.click(
1163
+ fn=lambda: random.randint(-1, MAX_SEED),
1164
+ inputs=[],
1165
+ outputs=seed_,
1166
+ )
1167
+
1168
+ final_run_btn.click(fn=set_text_unfinished, outputs=generated_information).then(
1169
+ process_generation,
1170
+ inputs=[
1171
+ sd_type,
1172
+ model_type,
1173
+ files,
1174
+ num_steps,
1175
+ style,
1176
+ Ip_Adapter_Strength,
1177
+ style_strength_ratio,
1178
+ guidance_scale,
1179
+ seed_,
1180
+ sa32_,
1181
+ sa64_,
1182
+ id_length_,
1183
+ general_prompt,
1184
+ negative_prompt,
1185
+ prompt_array,
1186
+ G_height,
1187
+ G_width,
1188
+ comic_type,
1189
+ font_choice,
1190
+ char_path,
1191
+ ],
1192
+ outputs=out_image,
1193
+ ).then(fn=set_text_finished, outputs=generated_information)
1194
+
1195
+ gr.Examples(
1196
+ examples=[
1197
+ [
1198
+ 0,
1199
+ 0.5,
1200
+ 0.5,
1201
+ 2,
1202
+ "[Bob] A man, wearing a black suit\n[Alice]a woman, wearing a white shirt",
1203
+ "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",
1204
+ array2string(
1205
+ [
1206
+ "[Bob] at home, read new paper #at home, The newspaper says there is a treasure house in the forest.",
1207
+ "[Bob] on the road, near the forest",
1208
+ "[Alice] is make a call at home # [Bob] invited [Alice] to join him on an adventure.",
1209
+ "[NC]A tiger appeared in the forest, at night ",
1210
+ "[NC] The car on the road, near the forest #They drives to the forest in search of treasure.",
1211
+ "[Bob] very frightened, open mouth, in the forest, at night",
1212
+ "[Alice] very frightened, open mouth, in the forest, at night",
1213
+ "[Bob] and [Alice] running very fast, in the forest, at night",
1214
+ "[NC] A house in the forest, at night #Suddenly, They discovers the treasure house!",
1215
+ "[Bob] and [Alice] in the house filled with treasure, laughing, at night #He is overjoyed inside the house.",
1216
+ ]
1217
+ ),
1218
+ "Comic book",
1219
+ "Only Using Textual Description",
1220
+ get_image_path_list("./examples/taylor"),
1221
+ 768,
1222
+ 768,
1223
+ ],
1224
+ [
1225
+ 0,
1226
+ 0.5,
1227
+ 0.5,
1228
+ 2,
1229
+ "[Bob] A man img, wearing a black suit\n[Alice]a woman img, wearing a white shirt",
1230
+ "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",
1231
+ array2string(
1232
+ [
1233
+ "[Bob] at home, read new paper #at home, The newspaper says there is a treasure house in the forest.",
1234
+ "[Bob] on the road, near the forest",
1235
+ "[Alice] is make a call at home # [Bob] invited [Alice] to join him on an adventure.",
1236
+ "[NC] The car on the road, near the forest #They drives to the forest in search of treasure.",
1237
+ "[NC]A tiger appeared in the forest, at night ",
1238
+ "[Bob] very frightened, open mouth, in the forest, at night",
1239
+ "[Alice] very frightened, open mouth, in the forest, at night",
1240
+ "[Bob] running very fast, in the forest, at night",
1241
+ "[NC] A house in the forest, at night #Suddenly, They discovers the treasure house!",
1242
+ "[Bob] in the house filled with treasure, laughing, at night #They are overjoyed inside the house.",
1243
+ ]
1244
+ ),
1245
+ "Comic book",
1246
+ "Using Ref Images",
1247
+ get_image_path_list("./examples/twoperson"),
1248
+ 1024,
1249
+ 1024,
1250
+ ],
1251
+ [
1252
+ 1,
1253
+ 0.5,
1254
+ 0.5,
1255
+ 3,
1256
+ "[Taylor]a woman img, wearing a white T-shirt, blue loose hair",
1257
+ "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",
1258
+ array2string(
1259
+ [
1260
+ "[Taylor]wake up in the bed",
1261
+ "[Taylor]have breakfast",
1262
+ "[Taylor]is on the road, go to company",
1263
+ "[Taylor]work in the company",
1264
+ "[Taylor]Take a walk next to the company at noon",
1265
+ "[Taylor]lying in bed at night",
1266
+ ]
1267
+ ),
1268
+ "Japanese Anime",
1269
+ "Using Ref Images",
1270
+ get_image_path_list("./examples/taylor"),
1271
+ 768,
1272
+ 768,
1273
+ ],
1274
+ [
1275
+ 0,
1276
+ 0.5,
1277
+ 0.5,
1278
+ 3,
1279
+ "[Bob]a man, wearing black jacket",
1280
+ "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",
1281
+ array2string(
1282
+ [
1283
+ "[Bob]wake up in the bed",
1284
+ "[Bob]have breakfast",
1285
+ "[Bob]is on the road, go to the company, close look",
1286
+ "[Bob]work in the company",
1287
+ "[Bob]laughing happily",
1288
+ "[Bob]lying in bed at night",
1289
+ ]
1290
+ ),
1291
+ "Japanese Anime",
1292
+ "Only Using Textual Description",
1293
+ get_image_path_list("./examples/taylor"),
1294
+ 768,
1295
+ 768,
1296
+ ],
1297
+ [
1298
+ 0,
1299
+ 0.3,
1300
+ 0.5,
1301
+ 3,
1302
+ "[Kitty]a girl, wearing white shirt, black skirt, black tie, yellow hair",
1303
+ "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",
1304
+ array2string(
1305
+ [
1306
+ "[Kitty]at home #at home, began to go to drawing",
1307
+ "[Kitty]sitting alone on a park bench.",
1308
+ "[Kitty]reading a book on a park bench.",
1309
+ "[NC]A squirrel approaches, peeking over the bench. ",
1310
+ "[Kitty]look around in the park. # She looks around and enjoys the beauty of nature.",
1311
+ "[NC]leaf falls from the tree, landing on the sketchbook.",
1312
+ "[Kitty]picks up the leaf, examining its details closely.",
1313
+ "[NC]The brown squirrel appear.",
1314
+ "[Kitty]is very happy # She is very happy to see the squirrel again",
1315
+ "[NC]The brown squirrel takes the cracker and scampers up a tree. # She gives the squirrel cracker",
1316
+ ]
1317
+ ),
1318
+ "Japanese Anime",
1319
+ "Only Using Textual Description",
1320
+ get_image_path_list("./examples/taylor"),
1321
+ 768,
1322
+ 768,
1323
+ ],
1324
+ ],
1325
+ inputs=[
1326
+ seed_,
1327
+ sa32_,
1328
+ sa64_,
1329
+ id_length_,
1330
+ general_prompt,
1331
+ negative_prompt,
1332
+ prompt_array,
1333
+ style,
1334
+ model_type,
1335
+ files,
1336
+ G_height,
1337
+ G_width,
1338
+ ],
1339
+ # outputs=[post_sketch, binary_matrixes, *color_row, *colors, *prompts, gen_prompt_vis, general_prompt, seed_],
1340
+ # run_on_click=True,
1341
+ label="😺 Examples 😺",
1342
+ )
1343
+ gr.Markdown(article)
1344
+
1345
+
1346
+ demo.launch(server_name="0.0.0.0", share=True)
images/logo.png ADDED
images/pad_images.png ADDED
oldversion/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>[email protected]</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)
oldversion/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>[email protected]</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)
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
storydiffusionpipeline.py ADDED
File without changes
update.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Update History
2
+
3
+ ### Update 2023-05-14
4
+
5
+ - Support Two persons,support for more characters will also be possible in the feature. In Pnhotomaker, currently, only one person can appear in a single image.
6
+ - Auto Save generated images in the ‘results’ folder.
7
+ - I have changed the way to fill in prompts; please refer to the example provided.
8
+
9
+ ### Update 2024-05-08
10
+
11
+ - 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)
12
+
13
+ <img src="results_examples/image1.png" height=100>
14
+
15
+ - Merge Push by @cryptowooser to support lastest pillow. But you may be updated pillow if you using the old version.
16
+
17
+
18
+
19
+ ### Todo
20
+
21
+ - Support add captions on all images for the classical commic Typesetting Style
22
+
23
+
24
+
25
+
26
+ ### Welcome to contribute
27
+
28
+ - 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,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from calendar import c
2
+ from operator import invert
3
+ from webbrowser import get
4
+ import torch
5
+ import random
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ import gradio as gr
9
+
10
+ class SpatialAttnProcessor2_0(torch.nn.Module):
11
+ r"""
12
+ Attention processor for IP-Adapater for PyTorch 2.0.
13
+ Args:
14
+ hidden_size (`int`):
15
+ The hidden size of the attention layer.
16
+ cross_attention_dim (`int`):
17
+ The number of channels in the `encoder_hidden_states`.
18
+ text_context_len (`int`, defaults to 77):
19
+ The context length of the text features.
20
+ scale (`float`, defaults to 1.0):
21
+ the weight scale of image prompt.
22
+ """
23
+
24
+ def __init__(self, hidden_size = None, cross_attention_dim=None,id_length = 4,device = "cuda",dtype = torch.float16):
25
+ super().__init__()
26
+ if not hasattr(F, "scaled_dot_product_attention"):
27
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
28
+ self.device = device
29
+ self.dtype = dtype
30
+ self.hidden_size = hidden_size
31
+ self.cross_attention_dim = cross_attention_dim
32
+ self.total_length = id_length + 1
33
+ self.id_length = id_length
34
+ self.id_bank = {}
35
+
36
+ def __call__(
37
+ self,
38
+ attn,
39
+ hidden_states,
40
+ encoder_hidden_states=None,
41
+ attention_mask=None,
42
+ temb=None):
43
+ # un_cond_hidden_states, cond_hidden_states = hidden_states.chunk(2)
44
+ # un_cond_hidden_states = self.__call2__(attn, un_cond_hidden_states,encoder_hidden_states,attention_mask,temb)
45
+ # 生成一个0到1之间的随机数
46
+ global total_count,attn_count,cur_step,mask256,mask1024,mask4096
47
+ global sa16, sa32, sa64
48
+ global write
49
+ if write:
50
+ self.id_bank[cur_step] = [hidden_states[:self.id_length], hidden_states[self.id_length:]]
51
+ else:
52
+ encoder_hidden_states = torch.cat(self.id_bank[cur_step][0],hidden_states[:1],self.id_bank[cur_step][1],hidden_states[1:])
53
+ # 判断随机数是否大于0.5
54
+ if cur_step <5:
55
+ hidden_states = self.__call2__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
56
+ else: # 256 1024 4096
57
+ random_number = random.random()
58
+ if cur_step <20:
59
+ rand_num = 0.3
60
+ else:
61
+ rand_num = 0.1
62
+ if random_number > rand_num:
63
+ if not write:
64
+ if hidden_states.shape[1] == 32* 32:
65
+ attention_mask = mask1024[mask1024.shape[0] // self.total_length * self.id_length:]
66
+ elif hidden_states.shape[1] ==16*16:
67
+ attention_mask = mask256[mask256.shape[0] // self.total_length * self.id_length:]
68
+ else:
69
+ attention_mask = mask4096[mask4096.shape[0] // self.total_length * self.id_length:]
70
+ else:
71
+ if hidden_states.shape[1] == 32* 32:
72
+ attention_mask = mask1024[:mask1024.shape[0] // self.total_length * self.id_length]
73
+ elif hidden_states.shape[1] ==16*16:
74
+ attention_mask = mask256[:mask256.shape[0] // self.total_length * self.id_length]
75
+ else:
76
+ attention_mask = mask4096[:mask4096.shape[0] // self.total_length * self.id_length]
77
+ hidden_states = self.__call1__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
78
+ else:
79
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
80
+ attn_count +=1
81
+ if attn_count == total_count:
82
+ attn_count = 0
83
+ cur_step += 1
84
+ mask256,mask1024,mask4096 = cal_attn_mask(self.total_length,self.id_length,sa16,sa32,sa64, device=self.device, dtype= self.dtype)
85
+
86
+ return hidden_states
87
+ def __call1__(
88
+ self,
89
+ attn,
90
+ hidden_states,
91
+ encoder_hidden_states=None,
92
+ attention_mask=None,
93
+ temb=None,
94
+ ):
95
+ residual = hidden_states
96
+ if encoder_hidden_states is not None:
97
+ raise Exception("not implement")
98
+ if attn.spatial_norm is not None:
99
+ hidden_states = attn.spatial_norm(hidden_states, temb)
100
+ input_ndim = hidden_states.ndim
101
+
102
+ if input_ndim == 4:
103
+ total_batch_size, channel, height, width = hidden_states.shape
104
+ hidden_states = hidden_states.view(total_batch_size, channel, height * width).transpose(1, 2)
105
+ total_batch_size,nums_token,channel = hidden_states.shape
106
+ img_nums = total_batch_size//2
107
+ hidden_states = hidden_states.view(-1,img_nums,nums_token,channel).reshape(-1,img_nums * nums_token,channel)
108
+
109
+ batch_size, sequence_length, _ = hidden_states.shape
110
+
111
+ if attn.group_norm is not None:
112
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
113
+
114
+ query = attn.to_q(hidden_states)
115
+
116
+ if encoder_hidden_states is None:
117
+ encoder_hidden_states = hidden_states # B, N, C
118
+ else:
119
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,nums_token,channel).reshape(-1,(self.id_length+1) * nums_token,channel)
120
+
121
+ key = attn.to_k(encoder_hidden_states)
122
+ value = attn.to_v(encoder_hidden_states)
123
+
124
+
125
+ inner_dim = key.shape[-1]
126
+ head_dim = inner_dim // attn.heads
127
+
128
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
129
+
130
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
131
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
132
+
133
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
134
+ # TODO: add support for attn.scale when we move to Torch 2.1
135
+ hidden_states = F.scaled_dot_product_attention(
136
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
137
+ )
138
+
139
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
140
+ hidden_states = hidden_states.to(query.dtype)
141
+
142
+
143
+
144
+ # linear proj
145
+ hidden_states = attn.to_out[0](hidden_states)
146
+ # dropout
147
+ hidden_states = attn.to_out[1](hidden_states)
148
+
149
+ # if input_ndim == 4:
150
+ # tile_hidden_states = tile_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
151
+
152
+ # if attn.residual_connection:
153
+ # tile_hidden_states = tile_hidden_states + residual
154
+
155
+ if input_ndim == 4:
156
+ hidden_states = hidden_states.transpose(-1, -2).reshape(total_batch_size, channel, height, width)
157
+ if attn.residual_connection:
158
+ hidden_states = hidden_states + residual
159
+ hidden_states = hidden_states / attn.rescale_output_factor
160
+
161
+ return hidden_states
162
+ def __call2__(
163
+ self,
164
+ attn,
165
+ hidden_states,
166
+ encoder_hidden_states=None,
167
+ attention_mask=None,
168
+ temb=None):
169
+ residual = hidden_states
170
+
171
+ if attn.spatial_norm is not None:
172
+ hidden_states = attn.spatial_norm(hidden_states, temb)
173
+
174
+ input_ndim = hidden_states.ndim
175
+
176
+ if input_ndim == 4:
177
+ batch_size, channel, height, width = hidden_states.shape
178
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
179
+
180
+ batch_size, sequence_length, _ = (
181
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
182
+ )
183
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
184
+
185
+ if attn.group_norm is not None:
186
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
187
+
188
+ query = attn.to_q(hidden_states)
189
+
190
+ if encoder_hidden_states is None:
191
+ encoder_hidden_states = hidden_states
192
+ elif attn.norm_cross:
193
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
194
+
195
+ key = attn.to_k(encoder_hidden_states)
196
+ value = attn.to_v(encoder_hidden_states)
197
+
198
+ query = attn.head_to_batch_dim(query)
199
+ key = attn.head_to_batch_dim(key)
200
+ value = attn.head_to_batch_dim(value)
201
+
202
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
203
+ hidden_states = torch.bmm(attention_probs, value)
204
+ hidden_states = attn.batch_to_head_dim(hidden_states)
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
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
213
+
214
+ if attn.residual_connection:
215
+ hidden_states = hidden_states + residual
216
+
217
+ hidden_states = hidden_states / attn.rescale_output_factor
218
+
219
+ return hidden_states
220
+
221
+
222
+ def cal_attn_mask(total_length,id_length,sa16,sa32,sa64,device="cuda",dtype= torch.float16):
223
+ bool_matrix256 = torch.rand((1, total_length * 256),device = device,dtype = dtype) < sa16
224
+ bool_matrix1024 = torch.rand((1, total_length * 1024),device = device,dtype = dtype) < sa32
225
+ bool_matrix4096 = torch.rand((1, total_length * 4096),device = device,dtype = dtype) < sa64
226
+ bool_matrix256 = bool_matrix256.repeat(total_length,1)
227
+ bool_matrix1024 = bool_matrix1024.repeat(total_length,1)
228
+ bool_matrix4096 = bool_matrix4096.repeat(total_length,1)
229
+ for i in range(total_length):
230
+ bool_matrix256[i:i+1,id_length*256:] = False
231
+ bool_matrix1024[i:i+1,id_length*1024:] = False
232
+ bool_matrix4096[i:i+1,id_length*4096:] = False
233
+ bool_matrix256[i:i+1,i*256:(i+1)*256] = True
234
+ bool_matrix1024[i:i+1,i*1024:(i+1)*1024] = True
235
+ bool_matrix4096[i:i+1,i*4096:(i+1)*4096] = True
236
+ mask256 = bool_matrix256.unsqueeze(1).repeat(1,256,1).reshape(-1,total_length * 256)
237
+ mask1024 = bool_matrix1024.unsqueeze(1).repeat(1,1024,1).reshape(-1,total_length * 1024)
238
+ mask4096 = bool_matrix4096.unsqueeze(1).repeat(1,4096,1).reshape(-1,total_length * 4096)
239
+ return mask256,mask1024,mask4096
240
+
241
+ def cal_attn_mask_xl(total_length,id_length,sa32,sa64,height,width,device="cuda",dtype= torch.float16):
242
+ nums_1024 = (height // 32) * (width // 32)
243
+ nums_4096 = (height // 16) * (width // 16)
244
+ bool_matrix1024 = torch.rand((1, total_length * nums_1024),device = device,dtype = dtype) < sa32
245
+ bool_matrix4096 = torch.rand((1, total_length * nums_4096),device = device,dtype = dtype) < sa64
246
+ bool_matrix1024 = bool_matrix1024.repeat(total_length,1)
247
+ bool_matrix4096 = bool_matrix4096.repeat(total_length,1)
248
+ for i in range(total_length):
249
+ bool_matrix1024[i:i+1,id_length*nums_1024:] = False
250
+ bool_matrix4096[i:i+1,id_length*nums_4096:] = False
251
+ bool_matrix1024[i:i+1,i*nums_1024:(i+1)*nums_1024] = True
252
+ bool_matrix4096[i:i+1,i*nums_4096:(i+1)*nums_4096] = True
253
+ mask1024 = bool_matrix1024.unsqueeze(1).repeat(1,nums_1024,1).reshape(-1,total_length * nums_1024)
254
+ mask4096 = bool_matrix4096.unsqueeze(1).repeat(1,nums_4096,1).reshape(-1,total_length * nums_4096)
255
+ return mask1024,mask4096
256
+
257
+
258
+ def cal_attn_indice_xl_effcient_memory(total_length,id_length,sa32,sa64,height,width,device="cuda",dtype= torch.float16):
259
+ nums_1024 = (height // 32) * (width // 32)
260
+ nums_4096 = (height // 16) * (width // 16)
261
+ bool_matrix1024 = torch.rand((total_length,nums_1024),device = device,dtype = dtype) < sa32
262
+ bool_matrix4096 = torch.rand((total_length,nums_4096),device = device,dtype = dtype) < sa64
263
+ # 用nonzero()函数获取所有为True的值的索引
264
+ indices1024 = [torch.nonzero(bool_matrix1024[i], as_tuple=True)[0] for i in range(total_length)]
265
+ indices4096 = [torch.nonzero(bool_matrix4096[i], as_tuple=True)[0] for i in range(total_length)]
266
+
267
+ return indices1024,indices4096
268
+
269
+
270
+ class AttnProcessor(nn.Module):
271
+ r"""
272
+ Default processor for performing attention-related computations.
273
+ """
274
+ def __init__(
275
+ self,
276
+ hidden_size=None,
277
+ cross_attention_dim=None,
278
+ ):
279
+ super().__init__()
280
+
281
+ def __call__(
282
+ self,
283
+ attn,
284
+ hidden_states,
285
+ encoder_hidden_states=None,
286
+ attention_mask=None,
287
+ temb=None,
288
+ ):
289
+ residual = hidden_states
290
+
291
+ if attn.spatial_norm is not None:
292
+ hidden_states = attn.spatial_norm(hidden_states, temb)
293
+
294
+ input_ndim = hidden_states.ndim
295
+
296
+ if input_ndim == 4:
297
+ batch_size, channel, height, width = hidden_states.shape
298
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
299
+
300
+ batch_size, sequence_length, _ = (
301
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
302
+ )
303
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
304
+
305
+ if attn.group_norm is not None:
306
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
307
+
308
+ query = attn.to_q(hidden_states)
309
+
310
+ if encoder_hidden_states is None:
311
+ encoder_hidden_states = hidden_states
312
+ elif attn.norm_cross:
313
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
314
+
315
+ key = attn.to_k(encoder_hidden_states)
316
+ value = attn.to_v(encoder_hidden_states)
317
+
318
+ query = attn.head_to_batch_dim(query)
319
+ key = attn.head_to_batch_dim(key)
320
+ value = attn.head_to_batch_dim(value)
321
+
322
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
323
+ hidden_states = torch.bmm(attention_probs, value)
324
+ hidden_states = attn.batch_to_head_dim(hidden_states)
325
+
326
+ # linear proj
327
+ hidden_states = attn.to_out[0](hidden_states)
328
+ # dropout
329
+ hidden_states = attn.to_out[1](hidden_states)
330
+
331
+ if input_ndim == 4:
332
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
333
+
334
+ if attn.residual_connection:
335
+ hidden_states = hidden_states + residual
336
+
337
+ hidden_states = hidden_states / attn.rescale_output_factor
338
+
339
+ return hidden_states
340
+
341
+
342
+ class AttnProcessor2_0(torch.nn.Module):
343
+ r"""
344
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
345
+ """
346
+ def __init__(
347
+ self,
348
+ hidden_size=None,
349
+ cross_attention_dim=None,
350
+ ):
351
+ super().__init__()
352
+ if not hasattr(F, "scaled_dot_product_attention"):
353
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
354
+
355
+ def __call__(
356
+ self,
357
+ attn,
358
+ hidden_states,
359
+ encoder_hidden_states=None,
360
+ attention_mask=None,
361
+ temb=None,
362
+ ):
363
+ residual = hidden_states
364
+
365
+ if attn.spatial_norm is not None:
366
+ hidden_states = attn.spatial_norm(hidden_states, temb)
367
+
368
+ input_ndim = hidden_states.ndim
369
+
370
+ if input_ndim == 4:
371
+ batch_size, channel, height, width = hidden_states.shape
372
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
373
+
374
+ batch_size, sequence_length, _ = (
375
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
376
+ )
377
+
378
+ if attention_mask is not None:
379
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
380
+ # scaled_dot_product_attention expects attention_mask shape to be
381
+ # (batch, heads, source_length, target_length)
382
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
383
+
384
+ if attn.group_norm is not None:
385
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
386
+
387
+ query = attn.to_q(hidden_states)
388
+
389
+ if encoder_hidden_states is None:
390
+ encoder_hidden_states = hidden_states
391
+ elif attn.norm_cross:
392
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
393
+
394
+ key = attn.to_k(encoder_hidden_states)
395
+ value = attn.to_v(encoder_hidden_states)
396
+
397
+ inner_dim = key.shape[-1]
398
+ head_dim = inner_dim // attn.heads
399
+
400
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
401
+
402
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
403
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
404
+
405
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
406
+ # TODO: add support for attn.scale when we move to Torch 2.1
407
+ hidden_states = F.scaled_dot_product_attention(
408
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
409
+ )
410
+
411
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
412
+ hidden_states = hidden_states.to(query.dtype)
413
+
414
+ # linear proj
415
+ hidden_states = attn.to_out[0](hidden_states)
416
+ # dropout
417
+ hidden_states = attn.to_out[1](hidden_states)
418
+
419
+ if input_ndim == 4:
420
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
421
+
422
+ if attn.residual_connection:
423
+ hidden_states = hidden_states + residual
424
+
425
+ hidden_states = hidden_states / attn.rescale_output_factor
426
+
427
+ return hidden_states
428
+
429
+
430
+ def is_torch2_available():
431
+ return hasattr(F, "scaled_dot_product_attention")
432
+
433
+
434
+ # 将列表转换为字典的函数
435
+ def character_to_dict(general_prompt):
436
+ character_dict = {}
437
+ generate_prompt_arr = general_prompt.splitlines()
438
+ character_index_dict = {}
439
+ invert_character_index_dict = {}
440
+ character_list = []
441
+ for ind,string in enumerate(generate_prompt_arr):
442
+ # 分割字符串寻找key和value
443
+ start = string.find('[')
444
+ end = string.find(']')
445
+ if start != -1 and end != -1:
446
+ key = string[start:end+1]
447
+ value = string[end+1:]
448
+ if "#" in value:
449
+ value = value.rpartition('#')[0]
450
+ if key in character_dict:
451
+ raise gr.Error("duplicate character descirption: " + key)
452
+ character_dict[key] = value
453
+ character_list.append(key)
454
+
455
+
456
+ return character_dict,character_list
457
+
458
+ def get_id_prompt_index(character_dict,id_prompts):
459
+ replace_id_prompts = []
460
+ character_index_dict = {}
461
+ invert_character_index_dict = {}
462
+ for ind,id_prompt in enumerate(id_prompts):
463
+ for key in character_dict.keys():
464
+ if key in id_prompt:
465
+ if key not in character_index_dict:
466
+ character_index_dict[key] = []
467
+ character_index_dict[key].append(ind)
468
+ invert_character_index_dict[ind] = key
469
+ replace_id_prompts.append(id_prompt.replace(key,character_dict[key]))
470
+
471
+ return character_index_dict,invert_character_index_dict,replace_id_prompts
472
+
473
+ def get_cur_id_list(real_prompt,character_dict,character_index_dict):
474
+ list_arr = []
475
+ for keys in character_index_dict.keys():
476
+ if keys in real_prompt:
477
+ list_arr = list_arr + character_index_dict[keys]
478
+ real_prompt = real_prompt.replace(keys,character_dict[keys])
479
+ return list_arr,real_prompt
480
+
481
+ def process_original_prompt(character_dict,prompts,id_length):
482
+ replace_prompts = []
483
+ character_index_dict = {}
484
+ invert_character_index_dict = {}
485
+ for ind,prompt in enumerate(prompts):
486
+ for key in character_dict.keys():
487
+ if key in prompt:
488
+ if key not in character_index_dict:
489
+ character_index_dict[key] = []
490
+ character_index_dict[key].append(ind)
491
+ if ind not in invert_character_index_dict:
492
+ invert_character_index_dict[ind] = []
493
+ invert_character_index_dict[ind].append(key)
494
+ cur_prompt = prompt
495
+ if ind in invert_character_index_dict:
496
+ for key in invert_character_index_dict[ind]:
497
+ cur_prompt = cur_prompt.replace(key,character_dict[key] + " ")
498
+ replace_prompts.append(cur_prompt)
499
+ ref_index_dict = {}
500
+ ref_totals = []
501
+ print(character_index_dict)
502
+ for character_key in character_index_dict.keys():
503
+ if character_key not in character_index_dict:
504
+ raise gr.Error("{} not have prompt description, please remove it".format(character_key))
505
+ index_list = character_index_dict[character_key]
506
+ index_list = [index for index in index_list if len(invert_character_index_dict[index]) == 1]
507
+ if len(index_list) < id_length:
508
+ raise gr.Error(f"{character_key} not have enough prompt description, need no less than {id_length}, but you give {len(index_list)}")
509
+ ref_index_dict[character_key] = index_list[:id_length]
510
+ ref_totals = ref_totals + index_list[:id_length]
511
+ return character_index_dict,invert_character_index_dict,replace_prompts,ref_index_dict,ref_totals
512
+
513
+
514
+ def get_ref_character(real_prompt,character_dict):
515
+ list_arr = []
516
+ for keys in character_dict.keys():
517
+ if keys in real_prompt:
518
+ list_arr = list_arr + [keys]
519
+ return list_arr
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,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, (Anime Style, Manga Style:1.3), Low detail, sketch, concept art, line art, webtoon, manhua, hand drawn, defined lines, simple shades, minimalistic, High contrast, Linear compositions, Scalable artwork, Digital art, High Contrast Shadows",
10
+ "negative_prompt": "lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
11
+ },
12
+ {
13
+ "name": "Digital/Oil Painting",
14
+ "prompt": "{prompt} . (Extremely Detailed Oil Painting:1.2), glow effects, godrays, Hand drawn, render, 8k, octane render, cinema 4d, blender, dark, atmospheric 4k ultra detailed, cinematic sensual, Sharp focus, humorous illustration, big depth of field",
15
+ "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
16
+ },
17
+ {
18
+ "name": "Pixar/Disney Character",
19
+ "prompt": "Create a Disney Pixar 3D style illustration on {prompt} . The scene is vibrant, motivational, filled with vivid colors and a sense of wonder.",
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} . Hyperrealistic, Hyperdetailed, detailed skin, matte skin, soft lighting, realistic, best quality, ultra realistic, 8k, golden ratio, Intricate, High Detail, film photography, soft focus",
25
+ "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
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, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
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, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
36
+ },
37
+ {
38
+ "name": "Black and White Film Noir",
39
+ "prompt": "{prompt} . (b&w, Monochromatic, Film Photography:1.3), film noir, analog style, soft lighting, subsurface scattering, realistic, heavy shadow, masterpiece, best quality, ultra realistic, 8k",
40
+ "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, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
41
+ },
42
+ {
43
+ "name": "Isometric Rooms",
44
+ "prompt": "Tiny cute isometric {prompt} . in a cutaway box, soft smooth lighting, soft colors, 100mm lens, 3d blender render",
45
+ "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, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
46
+ },
47
+ ]
48
+
49
+ 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_)]