facechain root directory upload
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- facechain/.gitattributes +1 -0
- facechain/.gitignore +134 -0
- facechain/LICENSE +201 -0
- facechain/README.md +296 -0
- facechain/README_ZH.md +297 -0
- facechain/app.py +1007 -0
- facechain/facechain/__init__.py +1 -0
- facechain/facechain/__pycache__/__init__.cpython-310.pyc +0 -0
- facechain/facechain/__pycache__/utils.cpython-310.pyc +0 -0
- facechain/facechain/constants.py +202 -0
- facechain/facechain/data_process/__init__.py +1 -0
- facechain/facechain/data_process/deepbooru.py +796 -0
- facechain/facechain/data_process/preprocessing.py +355 -0
- facechain/facechain/inference.py +530 -0
- facechain/facechain/inference_inpaint.py +890 -0
- facechain/facechain/merge_lora.py +75 -0
- facechain/facechain/train_text_to_image_lora.py +1161 -0
- facechain/facechain/utils.py +37 -0
- facechain/facechain_demo.ipynb +181 -0
- facechain/poses/man/pose1.png +3 -0
- facechain/poses/man/pose2.png +3 -0
- facechain/poses/man/pose3.png +3 -0
- facechain/poses/man/pose4.png +3 -0
- facechain/poses/woman/pose1.png +3 -0
- facechain/poses/woman/pose2.png +3 -0
- facechain/poses/woman/pose3.png +3 -0
- facechain/poses/woman/pose4.png +3 -0
- facechain/requirements.txt +22 -0
- facechain/resources/awesome-prompts-facechain.txt +14 -0
- facechain/resources/example1.jpg +3 -0
- facechain/resources/example2.jpg +3 -0
- facechain/resources/example3.jpg +3 -0
- facechain/resources/framework.jpg +3 -0
- facechain/resources/framework_eng.jpg +3 -0
- facechain/resources/git_cover.jpg +3 -0
- facechain/resources/git_cover_1.jpg +3 -0
- facechain/resources/git_cover_2.jpg +3 -0
- facechain/resources/git_cover_CH.jpg +3 -0
- facechain/resources/inpaint_template/1.jpg +3 -0
- facechain/resources/inpaint_template/2.jpg +3 -0
- facechain/resources/inpaint_template/3.jpg +3 -0
- facechain/resources/inpaint_template/4.jpg +3 -0
- facechain/resources/inpaint_template/5.jpg +3 -0
- facechain/resources/prompt_elf_lord_of_rings.jpg +3 -0
- facechain/resources/style_lora_xiapei.jpg +3 -0
- facechain/run_inference.py +72 -0
- facechain/style_image/Armor.jpg +3 -0
- facechain/style_image/Chinese_traditional_gorgeous_suit.jpg +3 -0
- facechain/style_image/Chinese_winter_hanfu.jpg +3 -0
- facechain/style_image/Cybernetics_punk.jpg +3 -0
facechain/.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
facechain/.gitignore
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Byte-compiled / optimized / DLL files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
test.py
|
| 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 |
+
*.egg-info/
|
| 24 |
+
.installed.cfg
|
| 25 |
+
*.egg
|
| 26 |
+
/package
|
| 27 |
+
/temp
|
| 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 |
+
.coverage
|
| 44 |
+
.coverage.*
|
| 45 |
+
.cache
|
| 46 |
+
nosetests.xml
|
| 47 |
+
coverage.xml
|
| 48 |
+
*.cover
|
| 49 |
+
.hypothesis/
|
| 50 |
+
.pytest_cache/
|
| 51 |
+
|
| 52 |
+
# Translations
|
| 53 |
+
*.mo
|
| 54 |
+
*.pot
|
| 55 |
+
|
| 56 |
+
# Django stuff:
|
| 57 |
+
*.log
|
| 58 |
+
local_settings.py
|
| 59 |
+
db.sqlite3
|
| 60 |
+
|
| 61 |
+
# Flask stuff:
|
| 62 |
+
instance/
|
| 63 |
+
.webassets-cache
|
| 64 |
+
|
| 65 |
+
# Scrapy stuff:
|
| 66 |
+
.scrapy
|
| 67 |
+
|
| 68 |
+
# Sphinx documentation
|
| 69 |
+
docs/_build/
|
| 70 |
+
|
| 71 |
+
# PyBuilder
|
| 72 |
+
target/
|
| 73 |
+
|
| 74 |
+
# Jupyter Notebook
|
| 75 |
+
.ipynb_checkpoints
|
| 76 |
+
|
| 77 |
+
# pyenv
|
| 78 |
+
.python-version
|
| 79 |
+
|
| 80 |
+
# celery beat schedule file
|
| 81 |
+
celerybeat-schedule
|
| 82 |
+
|
| 83 |
+
# SageMath parsed files
|
| 84 |
+
*.sage.py
|
| 85 |
+
|
| 86 |
+
# Environments
|
| 87 |
+
.env
|
| 88 |
+
.venv
|
| 89 |
+
env/
|
| 90 |
+
venv/
|
| 91 |
+
ENV/
|
| 92 |
+
env.bak/
|
| 93 |
+
venv.bak/
|
| 94 |
+
|
| 95 |
+
# Spyder project settings
|
| 96 |
+
.spyderproject
|
| 97 |
+
.spyproject
|
| 98 |
+
|
| 99 |
+
# Rope project settings
|
| 100 |
+
.ropeproject
|
| 101 |
+
|
| 102 |
+
# mkdocs documentation
|
| 103 |
+
/site
|
| 104 |
+
|
| 105 |
+
# mypy
|
| 106 |
+
.mypy_cache/
|
| 107 |
+
|
| 108 |
+
.vscode
|
| 109 |
+
.idea
|
| 110 |
+
|
| 111 |
+
# custom
|
| 112 |
+
*.pkl
|
| 113 |
+
*.pkl.json
|
| 114 |
+
*.log.json
|
| 115 |
+
*.whl
|
| 116 |
+
*.tar.gz
|
| 117 |
+
*.swp
|
| 118 |
+
*.log
|
| 119 |
+
*.tar.gz
|
| 120 |
+
source.sh
|
| 121 |
+
tensorboard.sh
|
| 122 |
+
.DS_Store
|
| 123 |
+
replace.sh
|
| 124 |
+
result.png
|
| 125 |
+
lora_result.png
|
| 126 |
+
result.jpg
|
| 127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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
facechain/README.md
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<p align="center">
|
| 2 |
+
<br>
|
| 3 |
+
<img src="https://modelscope.oss-cn-beijing.aliyuncs.com/modelscope.gif" width="400"/>
|
| 4 |
+
<br>
|
| 5 |
+
<h1>FaceChain</h1>
|
| 6 |
+
<p>
|
| 7 |
+
|
| 8 |
+
# Introduction
|
| 9 |
+
|
| 10 |
+
如果您熟悉中文,可以阅读[中文版本的README](./README_ZH.md)。
|
| 11 |
+
|
| 12 |
+
FaceChain is a deep-learning toolchain for generating your Digital-Twin. With a minimum of 1 portrait-photo, you can create a Digital-Twin of your own and start generating personal portraits in different settings (multiple styles now supported!). You may train your Digital-Twin model and generate photos via FaceChain's Python scripts, or via the familiar Gradio interface.
|
| 13 |
+
FaceChain is powered by [ModelScope](https://github.com/modelscope/modelscope).
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
<p align="center">
|
| 17 |
+
ModelScope Studio <a href="https://modelscope.cn/studios/CVstudio/cv_human_portrait/summary">🤖<a></a>  | HuggingFace Space <a href="https://huggingface.co/spaces/modelscope/FaceChain">🤗</a> 
|
| 18 |
+
</p>
|
| 19 |
+
<br>
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+

|
| 23 |
+

|
| 24 |
+

|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# News
|
| 28 |
+
- High performance inpainting for single & double person, Simplify User Interface. (September 09th, 2023 UTC)
|
| 29 |
+
- More Technology Details can be seen in [Paper](https://arxiv.org/abs/2308.14256). (August 30th, 2023 UTC)
|
| 30 |
+
- Add validate & ensemble for Lora training, and InpaintTab(hide in gradio for now). (August 28th, 2023 UTC)
|
| 31 |
+
- Add pose control module. (August 27th, 2023 UTC)
|
| 32 |
+
- Add robust face lora training module, enhance the performance of one pic training & style-lora blending. (August 27th, 2023 UTC)
|
| 33 |
+
- HuggingFace Space is available now! You can experience FaceChain directly with <a href="https://huggingface.co/spaces/modelscope/FaceChain">🤗</a> (August 25th, 2023 UTC)
|
| 34 |
+
- Add awesome prompts! Refer to: [awesome-prompts-facechain](resources/awesome-prompts-facechain.txt) (August 18th, 2023 UTC)
|
| 35 |
+
- Support a series of new style models in a plug-and-play fashion. (August 16th, 2023 UTC)
|
| 36 |
+
- Support customizable prompts. (August 16th, 2023 UTC)
|
| 37 |
+
- Colab notebook is available now! You can experience FaceChain directly with [](https://colab.research.google.com/github/modelscope/facechain/blob/main/facechain_demo.ipynb). (August 15th, 2023 UTC)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# To-Do List
|
| 41 |
+
- Support more style models (such as those on Civitai). --on-going, hot
|
| 42 |
+
- Support more beauty-retouch effects
|
| 43 |
+
- Support latest foundation models such as SDXL
|
| 44 |
+
- Support high resolution
|
| 45 |
+
- Support group photo scenario, e.g, multi-person
|
| 46 |
+
- Provide more funny apps
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# Citation
|
| 50 |
+
|
| 51 |
+
Please cite FaceChain in your publications if it helps your research
|
| 52 |
+
```
|
| 53 |
+
@article{liu2023facechain,
|
| 54 |
+
title={FaceChain: A Playground for Identity-Preserving Portrait Generation},
|
| 55 |
+
author={Liu, Yang and Yu, Cheng and Shang, Lei and Wu, Ziheng and
|
| 56 |
+
Wang, Xingjun and Zhao, Yuze and Zhu, Lin and Cheng, Chen and
|
| 57 |
+
Chen, Weitao and Xu, Chao and Xie, Haoyu and Yao, Yuan and
|
| 58 |
+
Zhou, Wenmeng and Chen Yingda and Xie, Xuansong and Sun, Baigui},
|
| 59 |
+
journal={arXiv preprint arXiv:2308.14256},
|
| 60 |
+
year={2023}
|
| 61 |
+
}
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# Installation
|
| 66 |
+
|
| 67 |
+
## Compatibility Verification
|
| 68 |
+
We have verified e2e execution on the following environment:
|
| 69 |
+
- python: py3.8, py3.10
|
| 70 |
+
- pytorch: torch2.0.0, torch2.0.1
|
| 71 |
+
- tensorflow: 2.8.0, tensorflow-cpu
|
| 72 |
+
- CUDA: 11.7
|
| 73 |
+
- CUDNN: 8+
|
| 74 |
+
- OS: Ubuntu 20.04, CentOS 7.9
|
| 75 |
+
- GPU: Nvidia-A10 24G
|
| 76 |
+
|
| 77 |
+
## Resource Requirement
|
| 78 |
+
- GPU: About 19G
|
| 79 |
+
- Disk: About 50GB
|
| 80 |
+
|
| 81 |
+
## Installation Guide
|
| 82 |
+
The following installation methods are supported:
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
### 1. ModelScope notebook【recommended】
|
| 86 |
+
|
| 87 |
+
The ModelScope Notebook offers a free-tier that allows ModelScope user to run the FaceChain application with minimum setup, refer to [ModelScope Notebook](https://modelscope.cn/my/mynotebook/preset)
|
| 88 |
+
|
| 89 |
+
```shell
|
| 90 |
+
# Step1: 我的notebook -> PAI-DSW -> GPU环境
|
| 91 |
+
|
| 92 |
+
# Step2: Entry the Notebook cell,clone FaceChain from github:
|
| 93 |
+
!GIT_LFS_SKIP_SMUDGE=1 git clone https://github.com/modelscope/facechain.git --depth 1
|
| 94 |
+
|
| 95 |
+
# Step3: Change the working directory to facechain:
|
| 96 |
+
import os
|
| 97 |
+
os.chdir('/mnt/workspace/facechain') # You may change to your own path
|
| 98 |
+
print(os.getcwd())
|
| 99 |
+
|
| 100 |
+
!pip3 install gradio
|
| 101 |
+
!pip3 install controlnet_aux==0.0.6
|
| 102 |
+
!pip3 install python-slugify
|
| 103 |
+
!python3 app.py
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# Step4: click "public URL" or "local URL", upload your images to
|
| 107 |
+
# train your own model and then generate your digital twin.
|
| 108 |
+
```
|
| 109 |
+
Alternatively, you may also purchase a [PAI-DSW](https://www.aliyun.com/activity/bigdata/pai/dsw) instance (using A10 resource), with the option of ModelScope image to run FaceChain following similar steps.
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
### 2. Docker
|
| 113 |
+
|
| 114 |
+
If you are familiar with using docker, we recommend to use this way:
|
| 115 |
+
|
| 116 |
+
```shell
|
| 117 |
+
# Step1: Prepare the environment with GPU on local or cloud, we recommend to use Alibaba Cloud ECS, refer to: https://www.aliyun.com/product/ecs
|
| 118 |
+
|
| 119 |
+
# Step2: Download the docker image (for installing docker engine, refer to https://docs.docker.com/engine/install/)
|
| 120 |
+
docker pull registry.cn-hangzhou.aliyuncs.com/modelscope-repo/modelscope:ubuntu20.04-cuda11.7.1-py38-torch2.0.1-tf1.15.5-1.8.0
|
| 121 |
+
|
| 122 |
+
# Step3: run the docker container
|
| 123 |
+
docker run -it --name facechain -p 7860:7860 --gpus all registry.cn-hangzhou.aliyuncs.com/modelscope-repo/modelscope:ubuntu20.04-cuda11.7.1-py38-torch2.0.1-tf1.15.5-1.8.0 /bin/bash
|
| 124 |
+
(Note: you may need to install the nvidia-container-runtime, refer to https://github.com/NVIDIA/nvidia-container-runtime)
|
| 125 |
+
|
| 126 |
+
# Step4: Install the gradio in the docker container:
|
| 127 |
+
pip3 install gradio
|
| 128 |
+
pip3 install controlnet_aux==0.0.6
|
| 129 |
+
pip3 install python-slugify
|
| 130 |
+
|
| 131 |
+
# Step5 clone facechain from github
|
| 132 |
+
GIT_LFS_SKIP_SMUDGE=1 git clone https://github.com/modelscope/facechain.git --depth 1
|
| 133 |
+
cd facechain
|
| 134 |
+
python3 app.py
|
| 135 |
+
# Note: FaceChain currently assume single-GPU, if your environment has multiple GPU, please use the following instead:
|
| 136 |
+
# CUDA_VISIBLE_DEVICES=0 python3 app.py
|
| 137 |
+
|
| 138 |
+
# Step6
|
| 139 |
+
Run the app server: click "public URL" --> in the form of: https://xxx.gradio.live
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
### 3. Conda Virtual Environment
|
| 143 |
+
|
| 144 |
+
Use the conda virtual environment, and refer to [Anaconda](https://docs.anaconda.com/anaconda/install/) to manage your dependencies. After installation, execute the following commands:
|
| 145 |
+
(Note: mmcv has strict environment requirements and might not be compatible in some cases. It's recommended to use Docker.)
|
| 146 |
+
|
| 147 |
+
```shell
|
| 148 |
+
conda create -n facechain python=3.8 # Verified environments: 3.8 and 3.10
|
| 149 |
+
conda activate facechain
|
| 150 |
+
|
| 151 |
+
GIT_LFS_SKIP_SMUDGE=1 git clone https://github.com/modelscope/facechain.git --depth 1
|
| 152 |
+
cd facechain
|
| 153 |
+
|
| 154 |
+
pip3 install -r requirements.txt
|
| 155 |
+
pip3 install -U openmim
|
| 156 |
+
mim install mmcv-full==1.7.0
|
| 157 |
+
|
| 158 |
+
# Navigate to the facechain directory and run:
|
| 159 |
+
python3 app.py
|
| 160 |
+
# Note: FaceChain currently assume single-GPU, if your environment has multiple GPU, please use the following instead:
|
| 161 |
+
# CUDA_VISIBLE_DEVICES=0 python3 app.py
|
| 162 |
+
|
| 163 |
+
# Finally, click on the URL generated in the log to access the web page.
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
**Note**: After the app service is successfully launched, go to the URL in the log, enter the "Image Customization" tab, click "Select Image to Upload", and choose at least one image with a face. Then, click "Start Training" to begin model training. After the training is completed, there will be corresponding displays in the log. Afterwards, switch to the "Image Experience" tab and click "Start Inference" to generate your own digital image.
|
| 167 |
+
|
| 168 |
+
*Note* For windows user, you should pay attention to following steps:
|
| 169 |
+
```shell
|
| 170 |
+
1. reinstall package pytorch and numpy compatible with tensorflow
|
| 171 |
+
2. install mmcv-full by pip: pip3 install mmcv-full
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
### 4. Colab notebook
|
| 176 |
+
|
| 177 |
+
| Colab | Info
|
| 178 |
+
| --- | --- |
|
| 179 |
+
[](https://colab.research.google.com/github/modelscope/facechain/blob/main/facechain_demo.ipynb) | FaceChain Installation on Colab
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# Script Execution
|
| 184 |
+
|
| 185 |
+
FaceChain supports direct training and inference in the python environment. Run the following command in the cloned folder to start training:
|
| 186 |
+
|
| 187 |
+
```shell
|
| 188 |
+
PYTHONPATH=. sh train_lora.sh "ly261666/cv_portrait_model" "v2.0" "film/film" "./imgs" "./processed" "./output"
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
Parameters description:
|
| 192 |
+
|
| 193 |
+
```text
|
| 194 |
+
ly261666/cv_portrait_model: The stable diffusion base model of the ModelScope model hub, which will be used for training, no need to be changed.
|
| 195 |
+
v2.0: The version number of this base model, no need to be changed
|
| 196 |
+
film/film: This base model may contains multiple subdirectories of different styles, currently we use film/film, no need to be changed
|
| 197 |
+
./imgs: This parameter needs to be replaced with the actual value. It means a local file directory that contains the original photos used for training and generation
|
| 198 |
+
./processed: The folder of the processed images after preprocessing, this parameter needs to be passed the same value in inference, no need to be changed
|
| 199 |
+
./output: The folder where the model weights stored after training, no need to be changed
|
| 200 |
+
```
|
| 201 |
+
|
| 202 |
+
Wait for 5-20 minutes to complete the training. Users can also adjust other training hyperparameters. The hyperparameters supported by training can be viewed in the file of `train_lora.sh`, or the complete hyperparameter list in `facechain/train_text_to_image_lora.py`.
|
| 203 |
+
|
| 204 |
+
When inferring, please edit the code in run_inference.py:
|
| 205 |
+
|
| 206 |
+
```python
|
| 207 |
+
# Use depth control, default False, only effective when using pose control
|
| 208 |
+
use_depth_control = False
|
| 209 |
+
# Use pose control, default False
|
| 210 |
+
use_pose_model = False
|
| 211 |
+
# The path of the image for pose control, only effective when using pose control
|
| 212 |
+
pose_image = 'poses/man/pose1.png'
|
| 213 |
+
# Fill in the folder of the images after preprocessing above, it should be the same as during training
|
| 214 |
+
processed_dir = './processed'
|
| 215 |
+
# The number of images to generate in inference
|
| 216 |
+
num_generate = 5
|
| 217 |
+
# The stable diffusion base model used in training, no need to be changed
|
| 218 |
+
base_model = 'ly261666/cv_portrait_model'
|
| 219 |
+
# The version number of this base model, no need to be changed
|
| 220 |
+
revision = 'v2.0'
|
| 221 |
+
# This base model may contains multiple subdirectories of different styles, currently we use film/film, no need to be changed
|
| 222 |
+
base_model_sub_dir = 'film/film'
|
| 223 |
+
# The folder where the model weights stored after training, it must be the same as during training
|
| 224 |
+
train_output_dir = './output'
|
| 225 |
+
# Specify a folder to save the generated images, this parameter can be modified as needed
|
| 226 |
+
output_dir = './generated'
|
| 227 |
+
# Use Chinese style model, default False
|
| 228 |
+
use_style = False
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
Then execute:
|
| 232 |
+
|
| 233 |
+
```shell
|
| 234 |
+
python run_inference.py
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
You can find the generated personal digital image photos in the `output_dir`.
|
| 238 |
+
|
| 239 |
+
# Algorithm Introduction
|
| 240 |
+
|
| 241 |
+
## Architectural Overview
|
| 242 |
+
|
| 243 |
+
The ability of the personal portrait generation evolves around the text-to-image capability of Stable Diffusion model. We consider the main factors that affect the generation effect of personal portraits: portrait style information and user character information. For this, we use the style LoRA model trained offline and the face LoRA model trained online to learn the above information. LoRA is a fine-tuning model with fewer trainable parameters. In Stable Diffusion, the information of the input image can be injected into the LoRA model by the way of text generation image training with a small amount of input image. Therefore, the ability of the personal portrait model is divided into training and inference stages. The training stage generates image and text label data for fine-tuning the Stable Diffusion model, and obtains the face LoRA model. The inference stage generates personal portrait images based on the face LoRA model and style LoRA model.
|
| 244 |
+
|
| 245 |
+

|
| 246 |
+
|
| 247 |
+
## Training
|
| 248 |
+
|
| 249 |
+
Input: User-uploaded images that contain clear face areas
|
| 250 |
+
|
| 251 |
+
Output: Face LoRA model
|
| 252 |
+
|
| 253 |
+
Description: First, we process the user-uploaded images using an image rotation model based on orientation judgment and a face refinement rotation method based on face detection and keypoint models, and obtain images containing forward faces. Next, we use a human body parsing model and a human portrait beautification model to obtain high-quality face training images. Afterwards, we use a face attribute model and a text annotation model, combined with tag post-processing methods, to generate fine-grained labels for training images. Finally, we use the above images and label data to fine-tune the Stable Diffusion model to obtain the face LoRA model.
|
| 254 |
+
|
| 255 |
+
## Inference
|
| 256 |
+
|
| 257 |
+
Input: User-uploaded images in the training phase, preset input prompt words for generating personal portraits
|
| 258 |
+
|
| 259 |
+
Output: Personal portrait image
|
| 260 |
+
|
| 261 |
+
Description: First, we fuse the weights of the face LoRA model and style LoRA model into the Stable Diffusion model. Next, we use the text generation image function of the Stable Diffusion model to preliminarily generate personal portrait images based on the preset input prompt words. Then we further improve the face details of the above portrait image using the face fusion model. The template face used for fusion is selected from the training images through the face quality evaluation model. Finally, we use the face recognition model to calculate the similarity between the generated portrait image and the template face, and use this to sort the portrait images, and output the personal portrait image that ranks first as the final output result.
|
| 262 |
+
|
| 263 |
+
## Model List
|
| 264 |
+
|
| 265 |
+
The models used in FaceChain:
|
| 266 |
+
|
| 267 |
+
[1] Face detection model DamoFD:https://modelscope.cn/models/damo/cv_ddsar_face-detection_iclr23-damofd
|
| 268 |
+
|
| 269 |
+
[2] Image rotating model, offered in the ModelScope studio
|
| 270 |
+
|
| 271 |
+
[3] Human parsing model M2FP:https://modelscope.cn/models/damo/cv_resnet101_image-multiple-human-parsing
|
| 272 |
+
|
| 273 |
+
[4] Skin retouching model ABPN:https://www.modelscope.cn/models/damo/cv_unet_skin_retouching_torch
|
| 274 |
+
|
| 275 |
+
[5] Face attribute recognition model FairFace:https://modelscope.cn/models/damo/cv_resnet34_face-attribute-recognition_fairface
|
| 276 |
+
|
| 277 |
+
[6] DeepDanbooru model:https://github.com/KichangKim/DeepDanbooru
|
| 278 |
+
|
| 279 |
+
[7] Face quality assessment FQA:https://modelscope.cn/models/damo/cv_manual_face-quality-assessment_fqa
|
| 280 |
+
|
| 281 |
+
[8] Face fusion model:https://www.modelscope.cn/models/damo/cv_unet_face_fusion_torch
|
| 282 |
+
|
| 283 |
+
[9] Face recognition model RTS:https://modelscope.cn/models/damo/cv_ir_face-recognition-ood_rts
|
| 284 |
+
|
| 285 |
+
# More Information
|
| 286 |
+
|
| 287 |
+
- [ModelScope library](https://github.com/modelscope/modelscope/)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
ModelScope Library provides the foundation for building the model-ecosystem of ModelScope, including the interface and implementation to integrate various models into ModelScope.
|
| 291 |
+
|
| 292 |
+
- [Contribute models to ModelScope](https://modelscope.cn/docs/ModelScope%E6%A8%A1%E5%9E%8B%E6%8E%A5%E5%85%A5%E6%B5%81%E7%A8%8B%E6%A6%82%E8%A7%88)
|
| 293 |
+
|
| 294 |
+
# License
|
| 295 |
+
|
| 296 |
+
This project is licensed under the [Apache License (Version 2.0)](https://github.com/modelscope/modelscope/blob/master/LICENSE).
|
facechain/README_ZH.md
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<p align="center">
|
| 2 |
+
<br>
|
| 3 |
+
<img src="https://modelscope.oss-cn-beijing.aliyuncs.com/modelscope.gif" width="400"/>
|
| 4 |
+
<br>
|
| 5 |
+
<h1>FaceChain</h1>
|
| 6 |
+
<p>
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# 介绍
|
| 11 |
+
|
| 12 |
+
FaceChain是一个可以用来打造个人数字形象的深度学习模型工具。用户仅需要提供最低一张照片即可获得独属于自己的个人形象数字替身。FaceChain支持在gradio的界面中使用模型训练和推理能力,也支持资深开发者使用python脚本进行训练推理;同时,我们也欢迎开发者对本Repo进行继续开发和贡献。
|
| 13 |
+
FaceChain的模型由[ModelScope](https://github.com/modelscope/modelscope)开源模型社区提供支持。
|
| 14 |
+
|
| 15 |
+
<p align="center">
|
| 16 |
+
ModelScope Studio <a href="https://modelscope.cn/studios/CVstudio/cv_human_portrait/summary">🤖<a></a>  | HuggingFace Space <a href="https://huggingface.co/spaces/modelscope/FaceChain">🤗</a> 
|
| 17 |
+
</p>
|
| 18 |
+
<br>
|
| 19 |
+
|
| 20 |
+

|
| 21 |
+

|
| 22 |
+

|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# News
|
| 26 |
+
- 高性能的(单人&双人)模版重绘功能,简化用户界面. (2023-09-09)
|
| 27 |
+
- 更多技术细节可以在 [论文](https://arxiv.org/abs/2308.14256) 里查看. (2023-08-30)
|
| 28 |
+
- 为Lora训练添加验证和根据face_id的融合,并添加InpaintTab(目前在Gradio界面上暂时默认隐藏). (2023-08-28)
|
| 29 |
+
- 增加姿势控制模块,可一键体验模版pose复刻. (2023-08-27)
|
| 30 |
+
- 增加鲁棒性人脸lora训练,提升单图训练&风格lora融合的效果. (2023-08-27)
|
| 31 |
+
- 支持在HuggingFace Space中体验FaceChain ! <a href="https://huggingface.co/spaces/modelscope/FaceChain">🤗</a> (2023-08-25)
|
| 32 |
+
- 新增高质量提示词模板,欢迎大家一起贡献! 参考 [awesome-prompts-facechain](resources/awesome-prompts-facechain.txt) (2023-08-18)
|
| 33 |
+
- 支持即插即用的风格LoRA模型! (2023-08-16)
|
| 34 |
+
- 新增个性化prompt模块! (2023-08-16)
|
| 35 |
+
- Colab notebook安装已支持,您可以直接打开链接体验FaceChain: [](https://colab.research.google.com/github/modelscope/facechain/blob/main/facechain_demo.ipynb) (2023-08-15)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# 待办事项
|
| 39 |
+
- 现成风格模型即插即用(以C站风格模型为例) --迭代中
|
| 40 |
+
- 增加更多美肤功能
|
| 41 |
+
- 适配更多的基模,例如SDXL
|
| 42 |
+
- 增加超分模块
|
| 43 |
+
- 支持多人保id照片生成
|
| 44 |
+
- 开发更多好玩的app
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# Citation
|
| 48 |
+
|
| 49 |
+
如果FaceChain对您的研究有所帮助,请在您的出版物中引用FaceChain
|
| 50 |
+
```
|
| 51 |
+
@article{liu2023facechain,
|
| 52 |
+
title={FaceChain: A Playground for Identity-Preserving Portrait Generation},
|
| 53 |
+
author={Liu, Yang and Yu, Cheng and Shang, Lei and Wu, Ziheng and
|
| 54 |
+
Wang, Xingjun and Zhao, Yuze and Zhu, Lin and Cheng, Chen and
|
| 55 |
+
Chen, Weitao and Xu, Chao and Xie, Haoyu and Yao, Yuan and
|
| 56 |
+
Zhou, Wenmeng and Chen Yingda and Xie, Xuansong and Sun, Baigui},
|
| 57 |
+
journal={arXiv preprint arXiv:2308.14256},
|
| 58 |
+
year={2023}
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
# 环境准备
|
| 62 |
+
|
| 63 |
+
## 兼容性验证
|
| 64 |
+
FaceChain是一个组合模型,使用了包括PyTorch和TensorFlow在内的机器学习框架,以下是已经验证过的主要环境依赖:
|
| 65 |
+
- python环境: py3.8, py3.10
|
| 66 |
+
- pytorch版本: torch2.0.0, torch2.0.1
|
| 67 |
+
- tensorflow版本: 2.8.0, tensorflow-cpu
|
| 68 |
+
- CUDA版本: 11.7
|
| 69 |
+
- CUDNN版本: 8+
|
| 70 |
+
- 操作系统版本: Ubuntu 20.04, CentOS 7.9
|
| 71 |
+
- GPU型号: Nvidia-A10 24G
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
## 资源要求
|
| 75 |
+
- GPU: 显存占用约19G
|
| 76 |
+
- 磁盘: 推荐预留50GB以上的存储空间
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
## 安装指南
|
| 80 |
+
支持以下几种安装方式,任选其一:
|
| 81 |
+
|
| 82 |
+
### 1. 使用ModelScope提供的notebook环境【推荐】
|
| 83 |
+
ModelScope(魔搭社区)提供给新用户初始的免费计算资源,参考[ModelScope Notebook](https://modelscope.cn/my/mynotebook/preset)
|
| 84 |
+
|
| 85 |
+
如果初始免费计算资源无法满足要求,您还可以从上述页面开通付费流程,以便创建一个准备就绪的ModelScope(GPU) DSW镜像实例。
|
| 86 |
+
|
| 87 |
+
Notebook环境使用简单,您只需要按以下步骤操作(注意:目前暂不提供永久存储,实例重启后数据会丢失):
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
```shell
|
| 91 |
+
# Step1: 我的notebook -> PAI-DSW -> GPU环境
|
| 92 |
+
|
| 93 |
+
# Step2: 进入Notebook cell,执行下述命令从github clone代码:
|
| 94 |
+
!GIT_LFS_SKIP_SMUDGE=1 git clone https://github.com/modelscope/facechain.git --depth 1
|
| 95 |
+
|
| 96 |
+
# Step3: 切换当前工作路径
|
| 97 |
+
import os
|
| 98 |
+
os.chdir('/mnt/workspace/facechain') # 注意替换成上述clone后的代码文件夹主路径
|
| 99 |
+
print(os.getcwd())
|
| 100 |
+
|
| 101 |
+
!pip3 install gradio
|
| 102 |
+
!pip3 install controlnet_aux==0.0.6
|
| 103 |
+
!pip3 install python-slugify
|
| 104 |
+
!python3 app.py
|
| 105 |
+
|
| 106 |
+
# Step4: 点击生成的URL即可访问web页面,上传照片开始训练和预测
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
除了ModelScope入口以外,您也可以前往[PAI-DSW](https://www.aliyun.com/activity/bigdata/pai/dsw) 直接购买带有ModelScope镜像的计算实例(推荐使用A10资源),这样同样可以使用如上的最简步骤运行起来。
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
### 2. docker镜像
|
| 114 |
+
|
| 115 |
+
如果您熟悉docker,可以使用我们提供的docker镜像,其包含了模型依赖的所有组件,无需复杂的环境安装:
|
| 116 |
+
```shell
|
| 117 |
+
# Step1: 机器资源
|
| 118 |
+
您可以使用本地或云端带有GPU资源的运行环境。
|
| 119 |
+
如需使用阿里云ECS,可访问: https://www.aliyun.com/product/ecs,推荐使用”镜像市场“中的CentOS 7.9 64位(预装NVIDIA GPU驱动)
|
| 120 |
+
|
| 121 |
+
# Step2: 将镜像下载到本地 (前提是已经安装了docker engine并启动服务,具体可参考: https://docs.docker.com/engine/install/)
|
| 122 |
+
docker pull registry.cn-hangzhou.aliyuncs.com/modelscope-repo/modelscope:ubuntu20.04-cuda11.7.1-py38-torch2.0.1-tf1.15.5-1.8.0
|
| 123 |
+
|
| 124 |
+
# Step3: 拉起镜像运行
|
| 125 |
+
docker run -it --name facechain -p 7860:7860 --gpus all registry.cn-hangzhou.aliyuncs.com/modelscope-repo/modelscope:ubuntu20.04-cuda11.7.1-py38-torch2.0.1-tf1.15.5-1.8.0 /bin/bash # 注意 your_xxx_image_id 替换成你的镜像id
|
| 126 |
+
# (注意: 如果提示无法使用宿主机GPU的错误,可能需要安装nvidia-container-runtime, 参考:https://github.com/NVIDIA/nvidia-container-runtime)
|
| 127 |
+
|
| 128 |
+
# Step4: 在容器中安装gradio
|
| 129 |
+
pip3 install gradio
|
| 130 |
+
pip3 install controlnet_aux==0.0.6
|
| 131 |
+
pip3 install python-slugify
|
| 132 |
+
|
| 133 |
+
# Step5: 获取facechain源代码
|
| 134 |
+
GIT_LFS_SKIP_SMUDGE=1 git clone https://github.com/modelscope/facechain.git --depth 1
|
| 135 |
+
cd facechain
|
| 136 |
+
python3 app.py
|
| 137 |
+
# Note: FaceChain目前支持单卡GPU,如果您的环境有多卡,请使用如下命令
|
| 138 |
+
# CUDA_VISIBLE_DEVICES=0 python3 app.py
|
| 139 |
+
|
| 140 |
+
# Step6: 点击 "public URL", 形式为 https://xxx.gradio.live
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
### 3. conda虚拟环境
|
| 145 |
+
|
| 146 |
+
使用conda虚拟环境,参考[Anaconda](https://docs.anaconda.com/anaconda/install/)来管理您的依赖,安装完成后,执行如下命令:
|
| 147 |
+
(提示: mmcv对环境要求较高,可能出现不适配的情况,推荐使用docker方式)
|
| 148 |
+
|
| 149 |
+
```shell
|
| 150 |
+
conda create -n facechain python=3.8 # 已验证环境:3.8 和 3.10
|
| 151 |
+
conda activate facechain
|
| 152 |
+
|
| 153 |
+
GIT_LFS_SKIP_SMUDGE=1 git clone https://github.com/modelscope/facechain.git --depth 1
|
| 154 |
+
cd facechain
|
| 155 |
+
|
| 156 |
+
pip3 install -r requirements.txt
|
| 157 |
+
pip3 install -U openmim
|
| 158 |
+
mim install mmcv-full==1.7.0
|
| 159 |
+
|
| 160 |
+
# 进入facechain文件夹,执行:
|
| 161 |
+
python3 app.py
|
| 162 |
+
# Note: FaceChain目前支持单卡GPU,如果您的环境有多卡,请使用如下命令
|
| 163 |
+
# CUDA_VISIBLE_DEVICES=0 python3 app.py
|
| 164 |
+
|
| 165 |
+
# 最后点击log中生成的URL即可访问页面。
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
备注:如果是Windows环境还需要注意以下步骤:
|
| 169 |
+
```shell
|
| 170 |
+
# 1. 重新安装pytorch、与tensorflow匹配的numpy
|
| 171 |
+
# 2. pip方式安装mmcv-full: pip3 install mmcv-full
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
### 4. colab运行
|
| 175 |
+
|
| 176 |
+
| Colab | Info
|
| 177 |
+
| --- | --- |
|
| 178 |
+
[](https://colab.research.google.com/github/modelscope/facechain/blob/main/facechain_demo.ipynb) | FaceChain Installation on Colab
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
备注:app服务成功启动后,在log中访问页面URL,进入”形象定制“tab页,点击“选择图片上传”,并最少选1张包含人脸的图片;点击“开始训练”即可训练模型。训练完成后日志中会有对应展示,之后切换到“形象体验”标签页点击“开始生成”即可生成属于自己的数字形象。
|
| 183 |
+
|
| 184 |
+
# 脚本运行
|
| 185 |
+
|
| 186 |
+
如果不想启动服务,而是直接在命令行进行开发调试等工作,FaceChain也支持在python环境中直接运行脚本进行训练和推理。在克隆后的文件夹中直接运行如下命令来进行训练:
|
| 187 |
+
|
| 188 |
+
```shell
|
| 189 |
+
PYTHONPATH=. sh train_lora.sh "ly261666/cv_portrait_model" "v2.0" "film/film" "./imgs" "./processed" "./output"
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
参数含义:
|
| 193 |
+
|
| 194 |
+
```text
|
| 195 |
+
ly261666/cv_portrait_model: ModelScope模型仓库的stable diffusion基模型,该模型会用于训练,可以不修改
|
| 196 |
+
v2.0: 该基模型的版本号,可以不修改
|
| 197 |
+
film/film: 该基模型包含了多个不同风格的子目录,其中使用了film/film目录中的风格模型,可以不修改
|
| 198 |
+
./imgs: 本参数需要用实际值替换,本参数是一个本地文件目录,包含了用来训练和生成的原始照片
|
| 199 |
+
./processed: 预处理之后的图片文件夹,这个参数需要在推理中被传入相同的值,可以不修改
|
| 200 |
+
./output: 训练生成保存模型weights的文件夹,可以不修改
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
等待5-20分钟即可训练完成。用户也可以调节其他训练超参数,训练支持的超参数可以查看`train_lora.sh`的配置,或者`facechain/train_text_to_image_lora.py`中的完整超参数列表。
|
| 204 |
+
|
| 205 |
+
进行推理时,请编辑run_inference.py中的代码:
|
| 206 |
+
|
| 207 |
+
```python
|
| 208 |
+
# 使用深度控制,默认False,仅在使用姿态控制时生效
|
| 209 |
+
use_depth_control = False
|
| 210 |
+
# 使用姿态控制,默认False
|
| 211 |
+
use_pose_model = False
|
| 212 |
+
# 姿态控制图片路径,仅在使用姿态控制时生效
|
| 213 |
+
pose_image = 'poses/man/pose1.png'
|
| 214 |
+
# 填入上述的预处理之后的图片文件夹,需要和训练时相同
|
| 215 |
+
processed_dir = './processed'
|
| 216 |
+
# 推理生成的图片数量
|
| 217 |
+
num_generate = 5
|
| 218 |
+
# 训练时使用的stable diffusion基模型,可以不修改
|
| 219 |
+
base_model = 'ly261666/cv_portrait_model'
|
| 220 |
+
# 该基模型的版本号,可以不修改
|
| 221 |
+
revision = 'v2.0'
|
| 222 |
+
# 该基模型包含了多个不同风格的子目录,其中使用了film/film目录中的风格模型,可以不修改
|
| 223 |
+
base_model_sub_dir = 'film/film'
|
| 224 |
+
# 训练生成保存模型weights的文件夹,需要保证和训练时相同
|
| 225 |
+
train_output_dir = './output'
|
| 226 |
+
# 指定一个保存生成的图片的文件夹,本参数可以根据需要修改
|
| 227 |
+
output_dir = './generated'
|
| 228 |
+
# 使用凤冠霞帔风格模型,默认False
|
| 229 |
+
use_style = False
|
| 230 |
+
```
|
| 231 |
+
|
| 232 |
+
之后执行:
|
| 233 |
+
|
| 234 |
+
```python
|
| 235 |
+
python run_inference.py
|
| 236 |
+
```
|
| 237 |
+
|
| 238 |
+
即可在`output_dir`中找到生成的个人数字形象照片。
|
| 239 |
+
|
| 240 |
+
# 算法介绍
|
| 241 |
+
|
| 242 |
+
## 基本原理
|
| 243 |
+
|
| 244 |
+
个人写真模型的能力来源于Stable Diffusion模型的文生图功能,输入一段文本或一系列提示词,输出对应的图像。我们考虑影响个人写真生成效果的主要因素:写真风格信息,以及用户人物信息。为此,我们分别使用线下训练的风格LoRA模型和线上训练的人脸LoRA模型以学习上述信息。LoRA是一种具有较少可训练参数的微调模型,在Stable Diffusion中,可以通过对少量输入图像进行文生图训练的方式将输入图像的信息注入到LoRA模型中。因此,个人写真模型的能力分为训练与推断两个阶段,训练阶段生成用于微调Stable Diffusion模型的图像与文本标签数据,得到人脸LoRA模型;推断阶段基于人脸LoRA模型和风格LoRA模型生成个人写真图像。
|
| 245 |
+
|
| 246 |
+

|
| 247 |
+
|
| 248 |
+
## 训练阶段
|
| 249 |
+
|
| 250 |
+
输入:用户上传的包含清晰人脸区域的图像
|
| 251 |
+
|
| 252 |
+
输出:人脸LoRA模型
|
| 253 |
+
|
| 254 |
+
描述:首先,我们分别使用基于朝向判断的图像旋转模型,以及基于人脸检测和关键点模型的人脸精细化旋转方法处理用户上传图像,得到包含正向人脸的图像;接下来,我们使用人体解析模型和人像美肤模型,以获得高质量的人脸训练图像;随后,我们使用人脸属性模型和文本标注模型,结合标签后处理方法,产生训练图像的精细化标签;最后,我们使用上述图像和标签数据微调Stable Diffusion模型得到人脸LoRA模型。
|
| 255 |
+
|
| 256 |
+
## 推断阶段
|
| 257 |
+
|
| 258 |
+
输入:训练阶段用户上传图像,预设的用于生成个人写真的输入提示词
|
| 259 |
+
|
| 260 |
+
输出:个人写真图像
|
| 261 |
+
|
| 262 |
+
描述:首先,我们将人脸LoRA模型和风格LoRA模型的权重融合到Stable Diffusion模型中;接下来,我们使用Stable Diffusion模型的文生图功能,基于预设的输入提示词初步生成个人写真图像;随后,我们使用人脸融合模型进一步改善上述写真图像的人脸细节,其中用于融合的模板人脸通过人脸质量评估模型在训练图像中挑选;最后,我们使用人脸识别模型计算生成的写真图像与模板人脸的相似度,以此对写真图像进行排序,并输出排名靠前的个人写真图像作为最终输出结果。
|
| 263 |
+
|
| 264 |
+
## 模型列表
|
| 265 |
+
|
| 266 |
+
附(流程图中模型链接)
|
| 267 |
+
|
| 268 |
+
[1] 人脸检测+关键点模型DamoFD:https://modelscope.cn/models/damo/cv_ddsar_face-detection_iclr23-damofd
|
| 269 |
+
|
| 270 |
+
[2] 图像旋转模型:创空间内置模型
|
| 271 |
+
|
| 272 |
+
[3] 人体解析模型M2FP:https://modelscope.cn/models/damo/cv_resnet101_image-multiple-human-parsing
|
| 273 |
+
|
| 274 |
+
[4] 人像美肤模型ABPN:https://www.modelscope.cn/models/damo/cv_unet_skin_retouching_torch
|
| 275 |
+
|
| 276 |
+
[5] 人脸属性模型FairFace:https://modelscope.cn/models/damo/cv_resnet34_face-attribute-recognition_fairface
|
| 277 |
+
|
| 278 |
+
[6] 文本标注模型Deepbooru:https://github.com/KichangKim/DeepDanbooru
|
| 279 |
+
|
| 280 |
+
[7] 模板脸筛选模型FQA:https://modelscope.cn/models/damo/cv_manual_face-quality-assessment_fqa
|
| 281 |
+
|
| 282 |
+
[8] 人脸融合模型:https://www.modelscope.cn/models/damo/cv_unet_face_fusion_torch
|
| 283 |
+
|
| 284 |
+
[9] 人脸识别模型RTS:https://modelscope.cn/models/damo/cv_ir_face-recognition-ood_rts
|
| 285 |
+
|
| 286 |
+
# 更多信息
|
| 287 |
+
|
| 288 |
+
- [ModelScope library](https://github.com/modelscope/modelscope/)
|
| 289 |
+
|
| 290 |
+
ModelScope Library是一个托管于github上的模型生态仓库,隶属于达摩院魔搭项目。
|
| 291 |
+
|
| 292 |
+
- [贡献模型到ModelScope](https://modelscope.cn/docs/ModelScope%E6%A8%A1%E5%9E%8B%E6%8E%A5%E5%85%A5%E6%B5%81%E7%A8%8B%E6%A6%82%E8%A7%88)
|
| 293 |
+
|
| 294 |
+
# License
|
| 295 |
+
|
| 296 |
+
This project is licensed under the [Apache License (Version 2.0)](https://github.com/modelscope/modelscope/blob/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
+
import enum
|
| 3 |
+
import os
|
| 4 |
+
import shutil
|
| 5 |
+
import slugify
|
| 6 |
+
import time
|
| 7 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 8 |
+
from torch import multiprocessing
|
| 9 |
+
import cv2
|
| 10 |
+
import gradio as gr
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
from glob import glob
|
| 14 |
+
import platform
|
| 15 |
+
import subprocess
|
| 16 |
+
from facechain.utils import snapshot_download
|
| 17 |
+
|
| 18 |
+
from facechain.inference import preprocess_pose, GenPortrait
|
| 19 |
+
from facechain.inference_inpaint import GenPortrait_inpaint
|
| 20 |
+
from facechain.train_text_to_image_lora import prepare_dataset, data_process_fn
|
| 21 |
+
from facechain.constants import neg_prompt, pos_prompt_with_cloth, pos_prompt_with_style, styles, \
|
| 22 |
+
pose_models, pose_examples, base_models
|
| 23 |
+
|
| 24 |
+
training_done_count = 0
|
| 25 |
+
inference_done_count = 0
|
| 26 |
+
|
| 27 |
+
class UploadTarget(enum.Enum):
|
| 28 |
+
PERSONAL_PROFILE = 'Personal Profile'
|
| 29 |
+
LORA_LIaBRARY = 'LoRA Library'
|
| 30 |
+
|
| 31 |
+
# utils
|
| 32 |
+
def concatenate_images(images):
|
| 33 |
+
heights = [img.shape[0] for img in images]
|
| 34 |
+
max_width = sum([img.shape[1] for img in images])
|
| 35 |
+
|
| 36 |
+
concatenated_image = np.zeros((max(heights), max_width, 3), dtype=np.uint8)
|
| 37 |
+
x_offset = 0
|
| 38 |
+
for img in images:
|
| 39 |
+
concatenated_image[0:img.shape[0], x_offset:x_offset + img.shape[1], :] = img
|
| 40 |
+
x_offset += img.shape[1]
|
| 41 |
+
return concatenated_image
|
| 42 |
+
|
| 43 |
+
def select_function(evt: gr.SelectData):
|
| 44 |
+
matched = list(filter(lambda item: evt.value == item['name'], styles))
|
| 45 |
+
style = matched[0]
|
| 46 |
+
return gr.Text.update(value=style['name'], visible=True)
|
| 47 |
+
|
| 48 |
+
def update_prompt(style_model):
|
| 49 |
+
matched = list(filter(lambda item: style_model == item['name'], styles))
|
| 50 |
+
style = matched[0]
|
| 51 |
+
pos_prompt = generate_pos_prompt(style['name'], style['add_prompt_style'])
|
| 52 |
+
multiplier_style = style['multiplier_style']
|
| 53 |
+
multiplier_human = style['multiplier_human']
|
| 54 |
+
return gr.Textbox.update(value=pos_prompt), \
|
| 55 |
+
gr.Slider.update(value=multiplier_style), \
|
| 56 |
+
gr.Slider.update(value=multiplier_human)
|
| 57 |
+
|
| 58 |
+
def update_pose_model(pose_image, pose_model):
|
| 59 |
+
if pose_image is None:
|
| 60 |
+
return gr.Radio.update(value=pose_models[0]['name']), gr.Image.update(visible=False)
|
| 61 |
+
else:
|
| 62 |
+
if pose_model == 0:
|
| 63 |
+
pose_model = 1
|
| 64 |
+
pose_res_img = preprocess_pose(pose_image)
|
| 65 |
+
return gr.Radio.update(value=pose_models[pose_model]['name']), gr.Image.update(value=pose_res_img, visible=True)
|
| 66 |
+
|
| 67 |
+
def update_optional_styles(base_model_index):
|
| 68 |
+
style_list = base_models[base_model_index]['style_list']
|
| 69 |
+
optional_styles = '\n'.join(style_list)
|
| 70 |
+
return gr.Textbox.update(value=optional_styles)
|
| 71 |
+
|
| 72 |
+
def train_lora_fn(base_model_path=None, revision=None, sub_path=None, output_img_dir=None, work_dir=None, photo_num=0):
|
| 73 |
+
torch.cuda.empty_cache()
|
| 74 |
+
|
| 75 |
+
lora_r = 4
|
| 76 |
+
lora_alpha = 32
|
| 77 |
+
max_train_steps = min(photo_num * 200, 800)
|
| 78 |
+
|
| 79 |
+
if platform.system() == 'Windows':
|
| 80 |
+
command = [
|
| 81 |
+
'accelerate', 'launch', 'facechain/train_text_to_image_lora.py',
|
| 82 |
+
f'--pretrained_model_name_or_path={base_model_path}',
|
| 83 |
+
f'--revision={revision}',
|
| 84 |
+
f'--sub_path={sub_path}',
|
| 85 |
+
f'--output_dataset_name={output_img_dir}',
|
| 86 |
+
'--caption_column=text',
|
| 87 |
+
'--resolution=512',
|
| 88 |
+
'--random_flip',
|
| 89 |
+
'--train_batch_size=1',
|
| 90 |
+
'--num_train_epochs=200',
|
| 91 |
+
'--checkpointing_steps=5000',
|
| 92 |
+
'--learning_rate=1.5e-04',
|
| 93 |
+
'--lr_scheduler=cosine',
|
| 94 |
+
'--lr_warmup_steps=0',
|
| 95 |
+
'--seed=42',
|
| 96 |
+
f'--output_dir={work_dir}',
|
| 97 |
+
f'--lora_r={lora_r}',
|
| 98 |
+
f'--lora_alpha={lora_alpha}',
|
| 99 |
+
'--lora_text_encoder_r=32',
|
| 100 |
+
'--lora_text_encoder_alpha=32',
|
| 101 |
+
'--resume_from_checkpoint="fromfacecommon"'
|
| 102 |
+
]
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
subprocess.run(command, check=True)
|
| 106 |
+
except subprocess.CalledProcessError as e:
|
| 107 |
+
print(f"Error executing the command: {e}")
|
| 108 |
+
else:
|
| 109 |
+
os.system(
|
| 110 |
+
f'PYTHONPATH=. accelerate launch facechain/train_text_to_image_lora.py '
|
| 111 |
+
f'--pretrained_model_name_or_path={base_model_path} '
|
| 112 |
+
f'--revision={revision} '
|
| 113 |
+
f'--sub_path={sub_path} '
|
| 114 |
+
f'--output_dataset_name={output_img_dir} '
|
| 115 |
+
f'--caption_column="text" '
|
| 116 |
+
f'--resolution=512 '
|
| 117 |
+
f'--random_flip '
|
| 118 |
+
f'--train_batch_size=1 '
|
| 119 |
+
f'--num_train_epochs=200 '
|
| 120 |
+
f'--checkpointing_steps=5000 '
|
| 121 |
+
f'--learning_rate=1.5e-04 '
|
| 122 |
+
f'--lr_scheduler="cosine" '
|
| 123 |
+
f'--lr_warmup_steps=0 '
|
| 124 |
+
f'--seed=42 '
|
| 125 |
+
f'--output_dir={work_dir} '
|
| 126 |
+
f'--lora_r={lora_r} '
|
| 127 |
+
f'--lora_alpha={lora_alpha} '
|
| 128 |
+
f'--lora_text_encoder_r=32 '
|
| 129 |
+
f'--lora_text_encoder_alpha=32 '
|
| 130 |
+
f'--resume_from_checkpoint="fromfacecommon"')
|
| 131 |
+
|
| 132 |
+
def generate_pos_prompt(style_model, prompt_cloth):
|
| 133 |
+
if style_model in base_models[0]['style_list'][:-1] or style_model is None:
|
| 134 |
+
pos_prompt = pos_prompt_with_cloth.format(prompt_cloth)
|
| 135 |
+
else:
|
| 136 |
+
matched = list(filter(lambda style: style_model == style['name'], styles))
|
| 137 |
+
if len(matched) == 0:
|
| 138 |
+
raise ValueError(f'styles not found: {style_model}')
|
| 139 |
+
matched = matched[0]
|
| 140 |
+
pos_prompt = pos_prompt_with_style.format(matched['add_prompt_style'])
|
| 141 |
+
return pos_prompt
|
| 142 |
+
|
| 143 |
+
def launch_pipeline(uuid,
|
| 144 |
+
pos_prompt,
|
| 145 |
+
neg_prompt=None,
|
| 146 |
+
base_model_index=None,
|
| 147 |
+
user_model=None,
|
| 148 |
+
num_images=1,
|
| 149 |
+
lora_choice=None,
|
| 150 |
+
style_model=None,
|
| 151 |
+
multiplier_style=0.25,
|
| 152 |
+
multiplier_human=0.85,
|
| 153 |
+
pose_model=None,
|
| 154 |
+
pose_image=None
|
| 155 |
+
):
|
| 156 |
+
if not uuid:
|
| 157 |
+
if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
|
| 158 |
+
return "请登陆后使用! (Please login first)"
|
| 159 |
+
else:
|
| 160 |
+
uuid = 'qw'
|
| 161 |
+
|
| 162 |
+
# Check base model
|
| 163 |
+
if base_model_index == None:
|
| 164 |
+
raise gr.Error('请选择基模型(Please select the base model)!')
|
| 165 |
+
|
| 166 |
+
# Check character LoRA
|
| 167 |
+
base_model_path = base_models[base_model_index]['model_id']
|
| 168 |
+
folder_path = f"/tmp/{uuid}/{base_model_path}"
|
| 169 |
+
folder_list = []
|
| 170 |
+
if os.path.exists(folder_path):
|
| 171 |
+
files = os.listdir(folder_path)
|
| 172 |
+
for file in files:
|
| 173 |
+
file_path = os.path.join(folder_path, file)
|
| 174 |
+
if os.path.isdir(folder_path):
|
| 175 |
+
file_lora_path = f"{file_path}/pytorch_lora_weights.bin"
|
| 176 |
+
if os.path.exists(file_lora_path):
|
| 177 |
+
folder_list.append(file)
|
| 178 |
+
if len(folder_list) == 0:
|
| 179 |
+
raise gr.Error('该基模型下没有人物LoRA,请先训练(There is no character LoRA under this base model, please train first)!')
|
| 180 |
+
|
| 181 |
+
# Check output model
|
| 182 |
+
if user_model == None:
|
| 183 |
+
raise gr.Error('请选择人物LoRA(Please select the character LoRA)!')
|
| 184 |
+
# Check lora choice
|
| 185 |
+
if lora_choice == None:
|
| 186 |
+
raise gr.Error('请选择LoRA模型(Please select the LoRA model)!')
|
| 187 |
+
# Check style model
|
| 188 |
+
if style_model == None and lora_choice == 'preset':
|
| 189 |
+
raise gr.Error('请选择风格模型(Please select the style model)!')
|
| 190 |
+
|
| 191 |
+
base_model = base_models[base_model_index]['model_id']
|
| 192 |
+
revision = base_models[base_model_index]['revision']
|
| 193 |
+
sub_path = base_models[base_model_index]['sub_path']
|
| 194 |
+
|
| 195 |
+
before_queue_size = 0
|
| 196 |
+
before_done_count = inference_done_count
|
| 197 |
+
matched = list(filter(lambda item: style_model == item['name'], styles))
|
| 198 |
+
style_model = matched[0]['name']
|
| 199 |
+
|
| 200 |
+
if lora_choice == 'preset':
|
| 201 |
+
if style_model in base_models[0]['style_list'][:-1]:
|
| 202 |
+
style_model_path = None
|
| 203 |
+
else:
|
| 204 |
+
matched = list(filter(lambda style: style_model == style['name'], styles))
|
| 205 |
+
if len(matched) == 0:
|
| 206 |
+
raise ValueError(f'styles not found: {style_model}')
|
| 207 |
+
matched = matched[0]
|
| 208 |
+
model_dir = snapshot_download(matched['model_id'], revision=matched['revision'])
|
| 209 |
+
style_model_path = os.path.join(model_dir, matched['bin_file'])
|
| 210 |
+
else:
|
| 211 |
+
print(f'uuid: {uuid}')
|
| 212 |
+
temp_lora_dir = f"/tmp/{uuid}/temp_lora"
|
| 213 |
+
file_name = lora_choice
|
| 214 |
+
print(lora_choice.split('.')[-1], os.path.join(temp_lora_dir, file_name))
|
| 215 |
+
if lora_choice.split('.')[-1] != 'safetensors' or not os.path.exists(os.path.join(temp_lora_dir, file_name)):
|
| 216 |
+
raise ValueError(f'Invalid lora file: {lora_file.name}')
|
| 217 |
+
style_model_path = os.path.join(temp_lora_dir, file_name)
|
| 218 |
+
|
| 219 |
+
if pose_image is None or pose_model == 0:
|
| 220 |
+
pose_model_path = None
|
| 221 |
+
use_depth_control = False
|
| 222 |
+
pose_image = None
|
| 223 |
+
else:
|
| 224 |
+
model_dir = snapshot_download('damo/face_chain_control_model', revision='v1.0.1')
|
| 225 |
+
pose_model_path = os.path.join(model_dir, 'model_controlnet/control_v11p_sd15_openpose')
|
| 226 |
+
if pose_model == 1:
|
| 227 |
+
use_depth_control = True
|
| 228 |
+
else:
|
| 229 |
+
use_depth_control = False
|
| 230 |
+
|
| 231 |
+
print("-------user_model: ", user_model)
|
| 232 |
+
if not uuid:
|
| 233 |
+
if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
|
| 234 |
+
return "请登陆后使用! (Please login first)"
|
| 235 |
+
else:
|
| 236 |
+
uuid = 'qw'
|
| 237 |
+
|
| 238 |
+
use_main_model = True
|
| 239 |
+
use_face_swap = True
|
| 240 |
+
use_post_process = True
|
| 241 |
+
use_stylization = False
|
| 242 |
+
|
| 243 |
+
instance_data_dir = os.path.join('/tmp', uuid, 'training_data', base_model, user_model)
|
| 244 |
+
lora_model_path = f'/tmp/{uuid}/{base_model}/{user_model}/ensemble'
|
| 245 |
+
if not os.path.exists(lora_model_path):
|
| 246 |
+
lora_model_path = f'/tmp/{uuid}/{base_model}/{user_model}/'
|
| 247 |
+
|
| 248 |
+
gen_portrait = GenPortrait(pose_model_path, pose_image, use_depth_control, pos_prompt, neg_prompt, style_model_path,
|
| 249 |
+
multiplier_style, multiplier_human, use_main_model,
|
| 250 |
+
use_face_swap, use_post_process,
|
| 251 |
+
use_stylization)
|
| 252 |
+
|
| 253 |
+
num_images = min(6, num_images)
|
| 254 |
+
|
| 255 |
+
with ProcessPoolExecutor(max_workers=5) as executor:
|
| 256 |
+
future = executor.submit(gen_portrait, instance_data_dir,
|
| 257 |
+
num_images, base_model, lora_model_path, sub_path, revision)
|
| 258 |
+
while not future.done():
|
| 259 |
+
is_processing = future.running()
|
| 260 |
+
if not is_processing:
|
| 261 |
+
cur_done_count = inference_done_count
|
| 262 |
+
to_wait = before_queue_size - (cur_done_count - before_done_count)
|
| 263 |
+
yield ["排队等待资源中, 前方还有{}个生成任务, 预计需要等待{}分钟...".format(to_wait, to_wait * 2.5),
|
| 264 |
+
None]
|
| 265 |
+
else:
|
| 266 |
+
yield ["生成中, 请耐心等待(Generating)...", None]
|
| 267 |
+
time.sleep(1)
|
| 268 |
+
|
| 269 |
+
outputs = future.result()
|
| 270 |
+
outputs_RGB = []
|
| 271 |
+
for out_tmp in outputs:
|
| 272 |
+
outputs_RGB.append(cv2.cvtColor(out_tmp, cv2.COLOR_BGR2RGB))
|
| 273 |
+
|
| 274 |
+
save_dir = os.path.join('/tmp', uuid, 'inference_result', base_model, user_model)
|
| 275 |
+
if lora_choice == 'preset':
|
| 276 |
+
save_dir = os.path.join(save_dir, 'style_' + style_model)
|
| 277 |
+
else:
|
| 278 |
+
save_dir = os.path.join(save_dir, 'lora_' + os.path.basename(lora_choice).split('.')[0])
|
| 279 |
+
|
| 280 |
+
if not os.path.exists(save_dir):
|
| 281 |
+
os.makedirs(save_dir)
|
| 282 |
+
# use single to save outputs
|
| 283 |
+
if not os.path.exists(os.path.join(save_dir, 'single')):
|
| 284 |
+
os.makedirs(os.path.join(save_dir, 'single'))
|
| 285 |
+
for img in outputs:
|
| 286 |
+
# count the number of images in the folder
|
| 287 |
+
num = len(os.listdir(os.path.join(save_dir, 'single')))
|
| 288 |
+
cv2.imwrite(os.path.join(save_dir, 'single', str(num) + '.png'), img)
|
| 289 |
+
|
| 290 |
+
if len(outputs) > 0:
|
| 291 |
+
result = concatenate_images(outputs)
|
| 292 |
+
if not os.path.exists(os.path.join(save_dir, 'concat')):
|
| 293 |
+
os.makedirs(os.path.join(save_dir, 'concat'))
|
| 294 |
+
num = len(os.listdir(os.path.join(save_dir, 'concat')))
|
| 295 |
+
image_path = os.path.join(save_dir, 'concat', str(num) + '.png')
|
| 296 |
+
cv2.imwrite(image_path, result)
|
| 297 |
+
|
| 298 |
+
yield ["生成完毕(Generation done)!", outputs_RGB]
|
| 299 |
+
else:
|
| 300 |
+
yield ["生成失败, 请重试(Generation failed, please retry)!", outputs_RGB]
|
| 301 |
+
|
| 302 |
+
def launch_pipeline_inpaint(uuid,
|
| 303 |
+
base_model_index=None,
|
| 304 |
+
user_model_A=None,
|
| 305 |
+
user_model_B=None,
|
| 306 |
+
num_faces=1,
|
| 307 |
+
template_image=None):
|
| 308 |
+
before_queue_size = 0
|
| 309 |
+
before_done_count = inference_done_count
|
| 310 |
+
|
| 311 |
+
if not uuid:
|
| 312 |
+
if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
|
| 313 |
+
return "请登陆后使用! (Please login first)"
|
| 314 |
+
else:
|
| 315 |
+
uuid = 'qw'
|
| 316 |
+
|
| 317 |
+
# Check base model
|
| 318 |
+
if base_model_index == None:
|
| 319 |
+
raise gr.Error('请选择基模型(Please select the base model)!')
|
| 320 |
+
|
| 321 |
+
# Check character LoRA
|
| 322 |
+
base_model_path = base_models[base_model_index]['model_id']
|
| 323 |
+
folder_path = f"/tmp/{uuid}/{base_model_path}"
|
| 324 |
+
folder_list = []
|
| 325 |
+
if os.path.exists(folder_path):
|
| 326 |
+
files = os.listdir(folder_path)
|
| 327 |
+
for file in files:
|
| 328 |
+
file_path = os.path.join(folder_path, file)
|
| 329 |
+
if os.path.isdir(folder_path):
|
| 330 |
+
file_lora_path = f"{file_path}/pytorch_lora_weights.bin"
|
| 331 |
+
if os.path.exists(file_lora_path):
|
| 332 |
+
folder_list.append(file)
|
| 333 |
+
if len(folder_list) == 0:
|
| 334 |
+
raise gr.Error('该基模型下没有人物LoRA,请先训练(There is no character LoRA under this base model, please train first)!')
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
# Check character LoRA
|
| 338 |
+
if num_faces == 1:
|
| 339 |
+
if user_model_A == None:
|
| 340 |
+
raise gr.Error('请至少选择一个人物LoRA(Please select at least one character LoRA)!')
|
| 341 |
+
else:
|
| 342 |
+
if user_model_A == None and user_model_B == None:
|
| 343 |
+
raise gr.Error('请至少选择一个人物LoRA(Please select at least one character LoRA)!')
|
| 344 |
+
|
| 345 |
+
if not uuid:
|
| 346 |
+
if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
|
| 347 |
+
return "请登陆后使用! (Please login first)"
|
| 348 |
+
else:
|
| 349 |
+
uuid = 'qw'
|
| 350 |
+
|
| 351 |
+
if isinstance(template_image, str):
|
| 352 |
+
if len(template_image) == 0:
|
| 353 |
+
raise gr.Error('请选择一张模板(Please select 1 template)')
|
| 354 |
+
|
| 355 |
+
base_model = base_models[base_model_index]['model_id']
|
| 356 |
+
revision = base_models[base_model_index]['revision']
|
| 357 |
+
sub_path = base_models[base_model_index]['sub_path']
|
| 358 |
+
multiplier_style = 0.05
|
| 359 |
+
multiplier_human = 0.95
|
| 360 |
+
strength = 0.65
|
| 361 |
+
output_img_size = 512
|
| 362 |
+
|
| 363 |
+
model_dir = snapshot_download('ly261666/cv_wanx_style_model', revision='v1.0.3')
|
| 364 |
+
style_model_path = os.path.join(model_dir, 'zjz_mj_jiyi_small_addtxt_frommajicreal.safetensors')
|
| 365 |
+
|
| 366 |
+
pos_prompt = 'raw photo, masterpiece, chinese, simple background, high-class pure color background, solo, medium shot, high detail face, photorealistic, best quality, wearing T-shirt'
|
| 367 |
+
neg_prompt = 'nsfw, paintings, sketches, (worst quality:2), (low quality:2) ' \
|
| 368 |
+
'lowers, normal quality, ((monochrome)), ((grayscale)), logo, word, character'
|
| 369 |
+
|
| 370 |
+
if user_model_A == '不重绘该人物(Do not inpaint this character)':
|
| 371 |
+
user_model_A = None
|
| 372 |
+
if user_model_B == '不重绘该人物(Do not inpaint this character)':
|
| 373 |
+
user_model_B = None
|
| 374 |
+
|
| 375 |
+
if user_model_A is not None:
|
| 376 |
+
instance_data_dir_A = os.path.join('/tmp', uuid, 'training_data', base_model, user_model_A)
|
| 377 |
+
lora_model_path_A = f'/tmp/{uuid}/{base_model}/{user_model_A}/'
|
| 378 |
+
else:
|
| 379 |
+
instance_data_dir_A = None
|
| 380 |
+
lora_model_path_A = None
|
| 381 |
+
if user_model_B is not None:
|
| 382 |
+
instance_data_dir_B = os.path.join('/tmp', uuid, 'training_data', base_model, user_model_B)
|
| 383 |
+
lora_model_path_B = f'/tmp/{uuid}/{base_model}/{user_model_B}/'
|
| 384 |
+
else:
|
| 385 |
+
instance_data_dir_B = None
|
| 386 |
+
lora_model_path_B = None
|
| 387 |
+
|
| 388 |
+
in_path = template_image
|
| 389 |
+
out_path = 'inpaint_rst'
|
| 390 |
+
|
| 391 |
+
use_main_model = True
|
| 392 |
+
use_face_swap = True
|
| 393 |
+
use_post_process = True
|
| 394 |
+
use_stylization = False
|
| 395 |
+
|
| 396 |
+
gen_portrait = GenPortrait_inpaint(in_path, strength, num_faces,
|
| 397 |
+
pos_prompt, neg_prompt, style_model_path,
|
| 398 |
+
multiplier_style, multiplier_human, use_main_model,
|
| 399 |
+
use_face_swap, use_post_process,
|
| 400 |
+
use_stylization)
|
| 401 |
+
|
| 402 |
+
with ProcessPoolExecutor(max_workers=5) as executor:
|
| 403 |
+
future = executor.submit(gen_portrait, instance_data_dir_A, instance_data_dir_B, base_model,\
|
| 404 |
+
lora_model_path_A, lora_model_path_B, sub_path=sub_path, revision=revision)
|
| 405 |
+
|
| 406 |
+
while not future.done():
|
| 407 |
+
is_processing = future.running()
|
| 408 |
+
if not is_processing:
|
| 409 |
+
cur_done_count = inference_done_count
|
| 410 |
+
to_wait = before_queue_size - (cur_done_count - before_done_count)
|
| 411 |
+
yield ["排队等待资源中,前方还有{}个生成任务, 预计需要等待{}分钟...".format(to_wait, to_wait * 2.5),
|
| 412 |
+
None]
|
| 413 |
+
else:
|
| 414 |
+
yield ["生成中, 请耐心等待(Generating)...", None]
|
| 415 |
+
time.sleep(1)
|
| 416 |
+
|
| 417 |
+
outputs = future.result()
|
| 418 |
+
outputs_RGB = []
|
| 419 |
+
for out_tmp in outputs:
|
| 420 |
+
outputs_RGB.append(cv2.cvtColor(out_tmp, cv2.COLOR_BGR2RGB))
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
for i, out_tmp in enumerate(outputs):
|
| 424 |
+
cv2.imwrite('{}_{}.png'.format(out_path, i), out_tmp)
|
| 425 |
+
|
| 426 |
+
if len(outputs) > 0:
|
| 427 |
+
yield ["生成完毕(Generation done)!", outputs_RGB]
|
| 428 |
+
else:
|
| 429 |
+
yield ["生成失败,请重试(Generation failed, please retry)!", outputs_RGB]
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
class Trainer:
|
| 433 |
+
def __init__(self):
|
| 434 |
+
pass
|
| 435 |
+
|
| 436 |
+
def run(
|
| 437 |
+
self,
|
| 438 |
+
uuid: str,
|
| 439 |
+
instance_images: list,
|
| 440 |
+
base_model_index: int,
|
| 441 |
+
output_model_name: str,
|
| 442 |
+
) -> str:
|
| 443 |
+
# Check Cuda
|
| 444 |
+
if not torch.cuda.is_available():
|
| 445 |
+
raise gr.Error('CUDA不可用(CUDA not available)')
|
| 446 |
+
|
| 447 |
+
# Check Instance Valid
|
| 448 |
+
if instance_images is None:
|
| 449 |
+
raise gr.Error('您需要上传训练图片(Please upload photos)!')
|
| 450 |
+
|
| 451 |
+
# Check output model name
|
| 452 |
+
if not output_model_name:
|
| 453 |
+
raise gr.Error('请指定人物lora的名称(Please specify the character LoRA name)!')
|
| 454 |
+
|
| 455 |
+
# Limit input Image
|
| 456 |
+
if len(instance_images) > 20:
|
| 457 |
+
raise gr.Error('请最多上传20张训练图片(20 images at most!)')
|
| 458 |
+
|
| 459 |
+
# Check UUID & Studio
|
| 460 |
+
if not uuid:
|
| 461 |
+
if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
|
| 462 |
+
return "请登陆后使用(Please login first)! "
|
| 463 |
+
else:
|
| 464 |
+
uuid = 'qw'
|
| 465 |
+
|
| 466 |
+
base_model_path = base_models[base_model_index]['model_id']
|
| 467 |
+
revision = base_models[base_model_index]['revision']
|
| 468 |
+
sub_path = base_models[base_model_index]['sub_path']
|
| 469 |
+
output_model_name = slugify.slugify(output_model_name)
|
| 470 |
+
|
| 471 |
+
# mv user upload data to target dir
|
| 472 |
+
instance_data_dir = os.path.join('/tmp', uuid, 'training_data', base_model_path, output_model_name)
|
| 473 |
+
print("--------uuid: ", uuid)
|
| 474 |
+
|
| 475 |
+
if not os.path.exists(f"/tmp/{uuid}"):
|
| 476 |
+
os.makedirs(f"/tmp/{uuid}")
|
| 477 |
+
work_dir = f"/tmp/{uuid}/{base_model_path}/{output_model_name}"
|
| 478 |
+
|
| 479 |
+
if os.path.exists(work_dir):
|
| 480 |
+
raise gr.Error("人物lora名称已存在。(This character lora name already exists.)")
|
| 481 |
+
|
| 482 |
+
print("----------work_dir: ", work_dir)
|
| 483 |
+
shutil.rmtree(work_dir, ignore_errors=True)
|
| 484 |
+
shutil.rmtree(instance_data_dir, ignore_errors=True)
|
| 485 |
+
|
| 486 |
+
prepare_dataset([img['name'] for img in instance_images], output_dataset_dir=instance_data_dir)
|
| 487 |
+
data_process_fn(instance_data_dir, True)
|
| 488 |
+
|
| 489 |
+
# train lora
|
| 490 |
+
print("instance_data_dir", instance_data_dir)
|
| 491 |
+
train_lora_fn(base_model_path=base_model_path,
|
| 492 |
+
revision=revision,
|
| 493 |
+
sub_path=sub_path,
|
| 494 |
+
output_img_dir=instance_data_dir,
|
| 495 |
+
work_dir=work_dir,
|
| 496 |
+
photo_num=len(instance_images))
|
| 497 |
+
|
| 498 |
+
message = '''<center><font size=4>训练已经完成!请切换至 [无限风格形象写真] 标签体验模型效果。</center>
|
| 499 |
+
|
| 500 |
+
<center><font size=4>(Training done, please switch to the Infinite Style Portrait tab to generate photos.)</center>'''
|
| 501 |
+
print(message)
|
| 502 |
+
return message
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def flash_model_list(uuid, base_model_index, lora_choice:gr.Dropdown):
|
| 506 |
+
|
| 507 |
+
base_model_path = base_models[base_model_index]['model_id']
|
| 508 |
+
style_list = base_models[base_model_index]['style_list']
|
| 509 |
+
|
| 510 |
+
sub_styles=[]
|
| 511 |
+
for style in style_list:
|
| 512 |
+
matched = list(filter(lambda item: style == item['name'], styles))
|
| 513 |
+
sub_styles.append(matched[0])
|
| 514 |
+
|
| 515 |
+
if not uuid:
|
| 516 |
+
if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
|
| 517 |
+
return "请登陆后使用! (Please login first)"
|
| 518 |
+
else:
|
| 519 |
+
uuid = 'qw'
|
| 520 |
+
|
| 521 |
+
folder_path = f"/tmp/{uuid}/{base_model_path}"
|
| 522 |
+
folder_list = []
|
| 523 |
+
lora_save_path = f"/tmp/{uuid}/temp_lora"
|
| 524 |
+
if not os.path.exists(lora_save_path):
|
| 525 |
+
lora_list = ['preset']
|
| 526 |
+
else:
|
| 527 |
+
lora_list = sorted(os.listdir(lora_save_path))
|
| 528 |
+
lora_list = ["preset"] + lora_list
|
| 529 |
+
|
| 530 |
+
if not os.path.exists(folder_path):
|
| 531 |
+
if lora_choice == 'preset':
|
| 532 |
+
return gr.Radio.update(choices=[]), \
|
| 533 |
+
gr.Gallery.update(value=[(item["img"], item["name"]) for item in sub_styles], visible=True), \
|
| 534 |
+
gr.Text.update(value=style_list[0], visible=True), \
|
| 535 |
+
gr.Dropdown.update(choices=lora_list, visible=True), gr.File.update(visible=True)
|
| 536 |
+
else:
|
| 537 |
+
return gr.Radio.update(choices=[]), \
|
| 538 |
+
gr.Gallery.update(visible=False), gr.Text.update(),\
|
| 539 |
+
gr.Dropdown.update(choices=lora_list, visible=True), gr.File.update(visible=True)
|
| 540 |
+
else:
|
| 541 |
+
files = os.listdir(folder_path)
|
| 542 |
+
for file in files:
|
| 543 |
+
file_path = os.path.join(folder_path, file)
|
| 544 |
+
if os.path.isdir(folder_path):
|
| 545 |
+
file_lora_path = f"{file_path}/pytorch_lora_weights.bin"
|
| 546 |
+
if os.path.exists(file_lora_path):
|
| 547 |
+
folder_list.append(file)
|
| 548 |
+
|
| 549 |
+
if lora_choice == 'preset':
|
| 550 |
+
return gr.Radio.update(choices=folder_list), \
|
| 551 |
+
gr.Gallery.update(value=[(item["img"], item["name"]) for item in sub_styles], visible=True), \
|
| 552 |
+
gr.Text.update(value=style_list[0], visible=True), \
|
| 553 |
+
gr.Dropdown.update(choices=lora_list, visible=True), gr.File.update(visible=True)
|
| 554 |
+
else:
|
| 555 |
+
return gr.Radio.update(choices=folder_list), \
|
| 556 |
+
gr.Gallery.update(visible=False), gr.Text.update(), \
|
| 557 |
+
gr.Dropdown.update(choices=lora_list, visible=True), gr.File.update(visible=True)
|
| 558 |
+
|
| 559 |
+
def update_output_model(uuid, base_model_index):
|
| 560 |
+
|
| 561 |
+
# Check base model
|
| 562 |
+
if base_model_index == None:
|
| 563 |
+
raise gr.Error('请选择基模型(Please select the base model)!')
|
| 564 |
+
|
| 565 |
+
base_model_path = base_models[base_model_index]['model_id']
|
| 566 |
+
style_list = base_models[base_model_index]['style_list']
|
| 567 |
+
|
| 568 |
+
if not uuid:
|
| 569 |
+
if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
|
| 570 |
+
return "请登陆后使用! (Please login first)"
|
| 571 |
+
else:
|
| 572 |
+
uuid = 'qw'
|
| 573 |
+
|
| 574 |
+
folder_path = f"/tmp/{uuid}/{base_model_path}"
|
| 575 |
+
folder_list = []
|
| 576 |
+
if not os.path.exists(folder_path):
|
| 577 |
+
return gr.Radio.update(choices=[]),gr.Dropdown.update(choices=style_list)
|
| 578 |
+
else:
|
| 579 |
+
files = os.listdir(folder_path)
|
| 580 |
+
for file in files:
|
| 581 |
+
file_path = os.path.join(folder_path, file)
|
| 582 |
+
if os.path.isdir(folder_path):
|
| 583 |
+
file_lora_path = f"{file_path}/pytorch_lora_weights.bin"
|
| 584 |
+
if os.path.exists(file_lora_path):
|
| 585 |
+
folder_list.append(file)
|
| 586 |
+
|
| 587 |
+
return gr.Radio.update(choices=folder_list)
|
| 588 |
+
|
| 589 |
+
def update_output_model_inpaint(uuid, base_model_index):
|
| 590 |
+
# Check base model
|
| 591 |
+
if base_model_index == None:
|
| 592 |
+
raise gr.Error('请选择基模型(Please select the base model)!')
|
| 593 |
+
|
| 594 |
+
base_model_path = base_models[base_model_index]['model_id']
|
| 595 |
+
style_list = base_models[base_model_index]['style_list']
|
| 596 |
+
|
| 597 |
+
if not uuid:
|
| 598 |
+
if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
|
| 599 |
+
return "请登陆后使用! (Please login first)"
|
| 600 |
+
else:
|
| 601 |
+
uuid = 'qw'
|
| 602 |
+
|
| 603 |
+
folder_path = f"/tmp/{uuid}/{base_model_path}"
|
| 604 |
+
folder_list = ['不重绘该人物(Do not inpaint this character)']
|
| 605 |
+
if not os.path.exists(folder_path):
|
| 606 |
+
return gr.Radio.update(choices=[]), gr.Dropdown.update(choices=style_list)
|
| 607 |
+
else:
|
| 608 |
+
files = os.listdir(folder_path)
|
| 609 |
+
for file in files:
|
| 610 |
+
file_path = os.path.join(folder_path, file)
|
| 611 |
+
if os.path.isdir(folder_path):
|
| 612 |
+
file_lora_path = f"{file_path}/pytorch_lora_weights.bin"
|
| 613 |
+
if os.path.exists(file_lora_path):
|
| 614 |
+
folder_list.append(file)
|
| 615 |
+
|
| 616 |
+
return gr.Radio.update(choices=folder_list, value=folder_list[0]), gr.Radio.update(choices=folder_list, value=folder_list[0])
|
| 617 |
+
|
| 618 |
+
def update_output_model_num(num_faces):
|
| 619 |
+
if num_faces == 1:
|
| 620 |
+
return gr.Radio.update(), gr.Radio.update(visible=False)
|
| 621 |
+
else:
|
| 622 |
+
return gr.Radio.update(), gr.Radio.update(visible=True)
|
| 623 |
+
|
| 624 |
+
def upload_file(files, current_files):
|
| 625 |
+
file_paths = [file_d['name'] for file_d in current_files] + [file.name for file in files]
|
| 626 |
+
return file_paths
|
| 627 |
+
|
| 628 |
+
def upload_lora_file(uuid, lora_file):
|
| 629 |
+
if not uuid:
|
| 630 |
+
if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
|
| 631 |
+
return "请登陆后使用! (Please login first)"
|
| 632 |
+
else:
|
| 633 |
+
uuid = 'qw'
|
| 634 |
+
print("uuid: ", uuid)
|
| 635 |
+
temp_lora_dir = f"/tmp/{uuid}/temp_lora"
|
| 636 |
+
if not os.path.exists(temp_lora_dir):
|
| 637 |
+
os.makedirs(temp_lora_dir)
|
| 638 |
+
shutil.copy(lora_file.name, temp_lora_dir)
|
| 639 |
+
filename = os.path.basename(lora_file.name)
|
| 640 |
+
newfilepath = os.path.join(temp_lora_dir, filename)
|
| 641 |
+
print("newfilepath: ", newfilepath)
|
| 642 |
+
|
| 643 |
+
lora_list = sorted(os.listdir(temp_lora_dir))
|
| 644 |
+
lora_list = ["preset"] + lora_list
|
| 645 |
+
|
| 646 |
+
return gr.Dropdown.update(choices=lora_list, value=filename)
|
| 647 |
+
|
| 648 |
+
def clear_lora_file(uuid, lora_file):
|
| 649 |
+
if not uuid:
|
| 650 |
+
if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
|
| 651 |
+
return "请登陆后使用! (Please login first)"
|
| 652 |
+
else:
|
| 653 |
+
uuid = 'qw'
|
| 654 |
+
|
| 655 |
+
return gr.Dropdown.update(value="preset")
|
| 656 |
+
|
| 657 |
+
def change_lora_choice(lora_choice, base_model_index):
|
| 658 |
+
style_list = base_models[base_model_index]['style_list']
|
| 659 |
+
sub_styles=[]
|
| 660 |
+
for style in style_list:
|
| 661 |
+
matched = list(filter(lambda item: style == item['name'], styles))
|
| 662 |
+
sub_styles.append(matched[0])
|
| 663 |
+
|
| 664 |
+
if lora_choice == 'preset':
|
| 665 |
+
return gr.Gallery.update(value=[(item["img"], item["name"]) for item in sub_styles], visible=True), \
|
| 666 |
+
gr.Text.update(value=style_list[0])
|
| 667 |
+
else:
|
| 668 |
+
return gr.Gallery.update(visible=False), gr.Text.update(visible=False)
|
| 669 |
+
|
| 670 |
+
def deal_history(uuid, base_model_index=None , user_model=None, lora_choice=None, style_model=None, deal_type="load"):
|
| 671 |
+
if not uuid:
|
| 672 |
+
if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
|
| 673 |
+
return "请登陆后使用! (Please login first)"
|
| 674 |
+
else:
|
| 675 |
+
uuid = 'qw'
|
| 676 |
+
|
| 677 |
+
if base_model_index is None:
|
| 678 |
+
raise gr.Error('请选择基模型(Please select the base model)!')
|
| 679 |
+
if user_model is None:
|
| 680 |
+
raise gr.Error('请选择人物lora(Please select the character lora)!')
|
| 681 |
+
if lora_choice is None:
|
| 682 |
+
raise gr.Error('请选择LoRa文件(Please select the LoRa file)!')
|
| 683 |
+
if style_model is None and lora_choice == 'preset':
|
| 684 |
+
raise gr.Error('请选择风格(Please select the style)!')
|
| 685 |
+
|
| 686 |
+
base_model = base_models[base_model_index]['model_id']
|
| 687 |
+
matched = list(filter(lambda item: style_model == item['name'], styles))
|
| 688 |
+
style_model = matched[0]['name']
|
| 689 |
+
|
| 690 |
+
save_dir = os.path.join('/tmp', uuid, 'inference_result', base_model, user_model)
|
| 691 |
+
if lora_choice == 'preset':
|
| 692 |
+
save_dir = os.path.join(save_dir, 'style_' + style_model)
|
| 693 |
+
else:
|
| 694 |
+
save_dir = os.path.join(save_dir, 'lora_' + os.path.basename(lora_choice).split('.')[0])
|
| 695 |
+
|
| 696 |
+
if not os.path.exists(save_dir):
|
| 697 |
+
return gr.Gallery.update(value=[], visible=True), gr.Gallery.update(value=[], visible=True)
|
| 698 |
+
|
| 699 |
+
if deal_type == "load":
|
| 700 |
+
single_dir = os.path.join(save_dir, 'single')
|
| 701 |
+
concat_dir = os.path.join(save_dir, 'concat')
|
| 702 |
+
single_imgs = []
|
| 703 |
+
concat_imgs = []
|
| 704 |
+
if os.path.exists(single_dir):
|
| 705 |
+
single_imgs = sorted(os.listdir(single_dir))
|
| 706 |
+
single_imgs = [os.path.join(single_dir, img) for img in single_imgs]
|
| 707 |
+
if os.path.exists(concat_dir):
|
| 708 |
+
concat_imgs = sorted(os.listdir(concat_dir))
|
| 709 |
+
concat_imgs = [os.path.join(concat_dir, img) for img in concat_imgs]
|
| 710 |
+
|
| 711 |
+
return gr.Gallery.update(value=single_imgs, visible=True), gr.Gallery.update(value=concat_imgs, visible=True)
|
| 712 |
+
elif deal_type == "delete":
|
| 713 |
+
shutil.rmtree(save_dir)
|
| 714 |
+
return gr.Gallery.update(value=[], visible=True), gr.Gallery.update(value=[], visible=True)
|
| 715 |
+
|
| 716 |
+
def train_input():
|
| 717 |
+
trainer = Trainer()
|
| 718 |
+
|
| 719 |
+
with gr.Blocks() as demo:
|
| 720 |
+
uuid = gr.Text(label="modelscope_uuid", visible=False)
|
| 721 |
+
with gr.Row():
|
| 722 |
+
with gr.Column():
|
| 723 |
+
with gr.Box():
|
| 724 |
+
gr.Markdown('模型选择(Model list)')
|
| 725 |
+
|
| 726 |
+
base_model_list = []
|
| 727 |
+
for base_model in base_models:
|
| 728 |
+
base_model_list.append(base_model['name'])
|
| 729 |
+
|
| 730 |
+
base_model_index = gr.Radio(label="基模型选择(Base model list)", choices=base_model_list, type="index",
|
| 731 |
+
value=base_model_list[0])
|
| 732 |
+
|
| 733 |
+
optional_style = '\n'.join(base_models[0]['style_list'])
|
| 734 |
+
|
| 735 |
+
optional_styles = gr.Textbox(label="该基模型支持的风格(Styles supported by this base model.)", max_lines=5,
|
| 736 |
+
value=optional_style, interactive=False)
|
| 737 |
+
|
| 738 |
+
output_model_name = gr.Textbox(label="人物lora名称(Character lora name)", value='person1', lines=1)
|
| 739 |
+
|
| 740 |
+
gr.Markdown('训练图片(Training photos)')
|
| 741 |
+
instance_images = gr.Gallery()
|
| 742 |
+
with gr.Row():
|
| 743 |
+
upload_button = gr.UploadButton("选择图片上传(Upload photos)", file_types=["image"],
|
| 744 |
+
file_count="multiple")
|
| 745 |
+
|
| 746 |
+
clear_button = gr.Button("清空图片(Clear photos)")
|
| 747 |
+
clear_button.click(fn=lambda: [], inputs=None, outputs=instance_images)
|
| 748 |
+
|
| 749 |
+
upload_button.upload(upload_file, inputs=[upload_button, instance_images], outputs=instance_images,
|
| 750 |
+
queue=False)
|
| 751 |
+
|
| 752 |
+
gr.Markdown('''
|
| 753 |
+
使用说明(Instructions):
|
| 754 |
+
''')
|
| 755 |
+
gr.Markdown('''
|
| 756 |
+
- Step 1. 上传计划训练的图片, 1~10张头肩照(注意: 请避免图片中出现多人脸、脸部遮挡等情况, 否则可能导致效果异常)
|
| 757 |
+
- Step 2. 点击 [开始训练] , 启动形象定制化训练, 每张图片约需1.5分钟, 请耐心等待~
|
| 758 |
+
- Step 3. 切换至 [形象写真] , 生成你的风格照片<br/><br/>
|
| 759 |
+
''')
|
| 760 |
+
gr.Markdown('''
|
| 761 |
+
- Step 1. Upload 1-10 headshot photos of yours (Note: avoid photos with multiple faces or face obstruction, which may lead to non-ideal result).
|
| 762 |
+
- Step 2. Click [Train] to start training for customizing your Digital-Twin, this may take up-to 1.5 mins per image.
|
| 763 |
+
- Step 3. Switch to [Portrait] Tab to generate stylized photos.
|
| 764 |
+
''')
|
| 765 |
+
|
| 766 |
+
run_button = gr.Button('开始训练(等待上传图片加载显示出来再点, 否则会报错)... '
|
| 767 |
+
'Start training (please wait until photo(s) fully uploaded, otherwise it may result in training failure)')
|
| 768 |
+
|
| 769 |
+
with gr.Box():
|
| 770 |
+
gr.Markdown('''
|
| 771 |
+
<center>请等待训练完成,请勿刷新或关闭页面。</center>
|
| 772 |
+
|
| 773 |
+
<center>(Please wait for the training to complete, do not refresh or close the page.)</center>
|
| 774 |
+
''')
|
| 775 |
+
output_message = gr.Markdown()
|
| 776 |
+
with gr.Box():
|
| 777 |
+
gr.Markdown('''
|
| 778 |
+
碰到抓狂的错误或者计算资源紧张的情况下,推荐直接在[NoteBook](https://modelscope.cn/my/mynotebook/preset)上进行体验。
|
| 779 |
+
|
| 780 |
+
(If you are experiencing prolonged waiting time, you may try on [ModelScope NoteBook](https://modelscope.cn/my/mynotebook/preset) to prepare your dedicated environment.)
|
| 781 |
+
|
| 782 |
+
安装方法请参考:https://github.com/modelscope/facechain .
|
| 783 |
+
|
| 784 |
+
(You may refer to: https://github.com/modelscope/facechain for installation instruction.)
|
| 785 |
+
''')
|
| 786 |
+
base_model_index.change(fn=update_optional_styles,
|
| 787 |
+
inputs=[base_model_index],
|
| 788 |
+
outputs=[optional_styles],
|
| 789 |
+
queue=False)
|
| 790 |
+
|
| 791 |
+
run_button.click(fn=trainer.run,
|
| 792 |
+
inputs=[
|
| 793 |
+
uuid,
|
| 794 |
+
instance_images,
|
| 795 |
+
base_model_index,
|
| 796 |
+
output_model_name,
|
| 797 |
+
],
|
| 798 |
+
outputs=[output_message])
|
| 799 |
+
|
| 800 |
+
return demo
|
| 801 |
+
|
| 802 |
+
def inference_input():
|
| 803 |
+
with gr.Blocks() as demo:
|
| 804 |
+
uuid = gr.Text(label="modelscope_uuid", visible=False)
|
| 805 |
+
|
| 806 |
+
with gr.Row():
|
| 807 |
+
with gr.Column():
|
| 808 |
+
base_model_list = []
|
| 809 |
+
for base_model in base_models:
|
| 810 |
+
base_model_list.append(base_model['name'])
|
| 811 |
+
|
| 812 |
+
base_model_index = gr.Radio(label="基模型选择(Base model list)", choices=base_model_list, type="index")
|
| 813 |
+
|
| 814 |
+
with gr.Row():
|
| 815 |
+
with gr.Column(scale=2):
|
| 816 |
+
user_model = gr.Radio(label="人物LoRA列表(Character LoRAs)", choices=[], type="value")
|
| 817 |
+
with gr.Column(scale=1):
|
| 818 |
+
update_button = gr.Button('刷新人物LoRA列表(Refresh character LoRAs)')
|
| 819 |
+
|
| 820 |
+
with gr.Box():
|
| 821 |
+
style_model = gr.Text(label='请选择一种风格(Select a style from the pics below):', interactive=False)
|
| 822 |
+
gallery = gr.Gallery(value=[(item["img"], item["name"]) for item in styles],
|
| 823 |
+
label="风格(Style)",
|
| 824 |
+
allow_preview=False,
|
| 825 |
+
columns=5,
|
| 826 |
+
elem_id="gallery",
|
| 827 |
+
show_share_button=False,
|
| 828 |
+
visible=False)
|
| 829 |
+
|
| 830 |
+
pmodels = []
|
| 831 |
+
for pmodel in pose_models:
|
| 832 |
+
pmodels.append(pmodel['name'])
|
| 833 |
+
|
| 834 |
+
with gr.Accordion("高级选项(Advanced Options)", open=False):
|
| 835 |
+
# upload one lora file and show the name or path of the file
|
| 836 |
+
with gr.Accordion("上传LoRA文件(Upload LoRA file)", open=False):
|
| 837 |
+
lora_choice = gr.Dropdown(choices=["preset"], type="value", value="preset", label="LoRA文件(LoRA file)", visible=False)
|
| 838 |
+
lora_file = gr.File(
|
| 839 |
+
value=None,
|
| 840 |
+
label="上传LoRA文件(Upload LoRA file)",
|
| 841 |
+
type="file",
|
| 842 |
+
file_types=[".safetensors"],
|
| 843 |
+
file_count="single",
|
| 844 |
+
visible=False,
|
| 845 |
+
)
|
| 846 |
+
|
| 847 |
+
pos_prompt = gr.Textbox(label="提示语(Prompt)", lines=3,
|
| 848 |
+
value=generate_pos_prompt(None, styles[0]['add_prompt_style']),
|
| 849 |
+
interactive=True)
|
| 850 |
+
neg_prompt = gr.Textbox(label="负向提示语(Negative Prompt)", lines=3,
|
| 851 |
+
value="",
|
| 852 |
+
interactive=True)
|
| 853 |
+
multiplier_style = gr.Slider(minimum=0, maximum=1, value=0.25,
|
| 854 |
+
step=0.05, label='风格权重(Multiplier style)')
|
| 855 |
+
multiplier_human = gr.Slider(minimum=0, maximum=1.2, value=0.95,
|
| 856 |
+
step=0.05, label='形象权重(Multiplier human)')
|
| 857 |
+
|
| 858 |
+
with gr.Accordion("姿态控制(Pose control)", open=False):
|
| 859 |
+
with gr.Row():
|
| 860 |
+
pose_image = gr.Image(source='upload', type='filepath', label='姿态图片(Pose image)', height=250)
|
| 861 |
+
pose_res_image = gr.Image(source='upload', interactive=False, label='姿态结果(Pose result)', visible=False, height=250)
|
| 862 |
+
gr.Examples(pose_examples['man'], inputs=[pose_image], label='男性姿态示例')
|
| 863 |
+
gr.Examples(pose_examples['woman'], inputs=[pose_image], label='女性姿态示例')
|
| 864 |
+
pose_model = gr.Radio(choices=pmodels, value=pose_models[0]['name'],
|
| 865 |
+
type="index", label="姿态控制模型(Pose control model)")
|
| 866 |
+
with gr.Box():
|
| 867 |
+
num_images = gr.Number(
|
| 868 |
+
label='生成图片数量(Number of photos)', value=6, precision=1, minimum=1, maximum=6)
|
| 869 |
+
gr.Markdown('''
|
| 870 |
+
注意:
|
| 871 |
+
- 最多支持生成6张图片!(You may generate a maximum of 6 photos at one time!)
|
| 872 |
+
- 可上传在定义LoRA文件使用, 否则默认使用风格模型的LoRA。(You may upload custome LoRA file, otherwise the LoRA file of the style model will be used by deault.)
|
| 873 |
+
- 使用自定义LoRA文件需手动输入prompt, 否则可能无法正常触发LoRA文件风格。(You shall provide prompt when using custom LoRA, otherwise desired LoRA style may not be triggered.)
|
| 874 |
+
''')
|
| 875 |
+
|
| 876 |
+
with gr.Row():
|
| 877 |
+
display_button = gr.Button('开始生成(Start!)')
|
| 878 |
+
with gr.Column():
|
| 879 |
+
history_button = gr.Button('查看历史(Show history)')
|
| 880 |
+
load_history_text = gr.Text("load", visible=False)
|
| 881 |
+
delete_history_button = gr.Button('删除历史(Delete history)')
|
| 882 |
+
delete_history_text = gr.Text("delete", visible=False)
|
| 883 |
+
|
| 884 |
+
with gr.Box():
|
| 885 |
+
infer_progress = gr.Textbox(label="生成进度(Progress)", value="当前无生成任务(No task)", interactive=False)
|
| 886 |
+
with gr.Box():
|
| 887 |
+
gr.Markdown('生成结果(Result)')
|
| 888 |
+
output_images = gr.Gallery(label='Output', show_label=False).style(columns=3, rows=2, height=600,
|
| 889 |
+
object_fit="contain")
|
| 890 |
+
|
| 891 |
+
with gr.Accordion(label="历史生成结果(History)", open=False):
|
| 892 |
+
with gr.Row():
|
| 893 |
+
single_history = gr.Gallery(label='单张图片(Single image history)')
|
| 894 |
+
batch_history = gr.Gallery(label='图片组(Batch image history)')
|
| 895 |
+
|
| 896 |
+
gallery.select(select_function, None, style_model, queue=False)
|
| 897 |
+
lora_choice.change(fn=change_lora_choice, inputs=[lora_choice, base_model_index], outputs=[gallery, style_model], queue=False)
|
| 898 |
+
|
| 899 |
+
lora_file.upload(fn=upload_lora_file, inputs=[uuid, lora_file], outputs=[lora_choice], queue=False)
|
| 900 |
+
lora_file.clear(fn=clear_lora_file, inputs=[uuid, lora_file], outputs=[lora_choice], queue=False)
|
| 901 |
+
|
| 902 |
+
style_model.change(update_prompt, style_model, [pos_prompt, multiplier_style, multiplier_human], queue=False)
|
| 903 |
+
pose_image.change(update_pose_model, [pose_image, pose_model], [pose_model, pose_res_image])
|
| 904 |
+
base_model_index.change(fn=flash_model_list,
|
| 905 |
+
inputs=[uuid, base_model_index, lora_choice],
|
| 906 |
+
outputs=[user_model, gallery, style_model, lora_choice, lora_file],
|
| 907 |
+
queue=False)
|
| 908 |
+
update_button.click(fn=update_output_model,
|
| 909 |
+
inputs=[uuid, base_model_index],
|
| 910 |
+
outputs=[user_model],
|
| 911 |
+
queue=False)
|
| 912 |
+
display_button.click(fn=launch_pipeline,
|
| 913 |
+
inputs=[uuid, pos_prompt, neg_prompt, base_model_index, user_model, num_images, lora_choice, style_model, multiplier_style, multiplier_human,
|
| 914 |
+
pose_model, pose_image],
|
| 915 |
+
outputs=[infer_progress, output_images])
|
| 916 |
+
history_button.click(fn=deal_history,
|
| 917 |
+
inputs=[uuid, base_model_index, user_model, lora_choice, style_model, load_history_text],
|
| 918 |
+
outputs=[single_history, batch_history])
|
| 919 |
+
delete_history_button.click(fn=deal_history,
|
| 920 |
+
inputs=[uuid, base_model_index, user_model, lora_choice, style_model, delete_history_text],
|
| 921 |
+
outputs=[single_history, batch_history])
|
| 922 |
+
|
| 923 |
+
return demo
|
| 924 |
+
|
| 925 |
+
def inference_inpaint():
|
| 926 |
+
preset_template = glob(os.path.join('resources/inpaint_template/*.jpg'))
|
| 927 |
+
with gr.Blocks() as demo:
|
| 928 |
+
uuid = gr.Text(label="modelscope_uuid", visible=False)
|
| 929 |
+
# Initialize the GUI
|
| 930 |
+
|
| 931 |
+
with gr.Row():
|
| 932 |
+
with gr.Column():
|
| 933 |
+
with gr.Box():
|
| 934 |
+
gr.Markdown('请选择或上传模板图片(Please select or upload a template image):')
|
| 935 |
+
template_image_list = [[i] for idx, i in enumerate(preset_template)]
|
| 936 |
+
print(template_image_list)
|
| 937 |
+
template_image = gr.Image(source='upload', type='filepath', label='模板图片(Template image)')
|
| 938 |
+
gr.Examples(template_image_list, inputs=[template_image], label='模板示例(Template examples)')
|
| 939 |
+
|
| 940 |
+
base_model_list = []
|
| 941 |
+
for base_model in base_models:
|
| 942 |
+
base_model_list.append(base_model['name'])
|
| 943 |
+
|
| 944 |
+
base_model_index = gr.Radio(
|
| 945 |
+
label="基模型选择(Base model list)",
|
| 946 |
+
choices=base_model_list,
|
| 947 |
+
type="index"
|
| 948 |
+
)
|
| 949 |
+
|
| 950 |
+
num_faces = gr.Number(minimum=1, maximum=2, value=1, precision=1, label='照片中的人脸数目(Number of Faces)')
|
| 951 |
+
with gr.Row():
|
| 952 |
+
with gr.Column(scale=2):
|
| 953 |
+
user_model_A = gr.Radio(label="第1个人物LoRA,按从左至右的顺序(1st Character LoRA,counting from left to right)", choices=[], type="value")
|
| 954 |
+
user_model_B = gr.Radio(label="第2个人物LoRA,按从左至右的顺序(2nd Character LoRA,counting from left to right)", choices=[], type="value", visible=False)
|
| 955 |
+
with gr.Column(scale=1):
|
| 956 |
+
update_button = gr.Button('刷新人物LoRA列表(Refresh character LoRAs)')
|
| 957 |
+
|
| 958 |
+
display_button = gr.Button('开始生成(Start Generation)')
|
| 959 |
+
with gr.Box():
|
| 960 |
+
infer_progress = gr.Textbox(
|
| 961 |
+
label="生成(Generation Progress)",
|
| 962 |
+
value="No task currently",
|
| 963 |
+
interactive=False
|
| 964 |
+
)
|
| 965 |
+
with gr.Box():
|
| 966 |
+
gr.Markdown('生成结果(Generated Results)')
|
| 967 |
+
output_images = gr.Gallery(
|
| 968 |
+
label='输出(Output)',
|
| 969 |
+
show_label=False
|
| 970 |
+
).style(columns=3, rows=2, height=600, object_fit="contain")
|
| 971 |
+
|
| 972 |
+
base_model_index.change(fn=update_output_model_inpaint,
|
| 973 |
+
inputs=[uuid, base_model_index],
|
| 974 |
+
outputs=[user_model_A, user_model_B],
|
| 975 |
+
queue=False)
|
| 976 |
+
|
| 977 |
+
update_button.click(fn=update_output_model_inpaint,
|
| 978 |
+
inputs=[uuid, base_model_index],
|
| 979 |
+
outputs=[user_model_A, user_model_B],
|
| 980 |
+
queue=False)
|
| 981 |
+
|
| 982 |
+
num_faces.change(fn=update_output_model_num,
|
| 983 |
+
inputs=[num_faces],
|
| 984 |
+
outputs=[user_model_A, user_model_B],
|
| 985 |
+
queue=False)
|
| 986 |
+
|
| 987 |
+
display_button.click(
|
| 988 |
+
fn=launch_pipeline_inpaint,
|
| 989 |
+
inputs=[uuid, base_model_index, user_model_A, user_model_B, num_faces, template_image],
|
| 990 |
+
outputs=[infer_progress, output_images]
|
| 991 |
+
)
|
| 992 |
+
|
| 993 |
+
return demo
|
| 994 |
+
|
| 995 |
+
with gr.Blocks(css='style.css') as demo:
|
| 996 |
+
gr.Markdown("# <center> \N{fire} FaceChain Potrait Generation ([Github star it here](https://github.com/modelscope/facechain/tree/main) \N{whale}, [Paper cite it here](https://arxiv.org/abs/2308.14256) \N{whale})</center>")
|
| 997 |
+
with gr.Tabs():
|
| 998 |
+
with gr.TabItem('\N{rocket}人物形象训练(Train Digital Twin)'):
|
| 999 |
+
train_input()
|
| 1000 |
+
with gr.TabItem('\N{party popper}无限风格形象写真(Infinite Style Portrait)'):
|
| 1001 |
+
inference_input()
|
| 1002 |
+
with gr.TabItem('\N{party popper}固定模板形象写真(Fixed Templates Portrait)'):
|
| 1003 |
+
inference_inpaint()
|
| 1004 |
+
|
| 1005 |
+
if __name__ == "__main__":
|
| 1006 |
+
multiprocessing.set_start_method('spawn')
|
| 1007 |
+
demo.queue(status_update_rate=1).launch(share=True)
|
facechain/facechain/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
facechain/facechain/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (140 Bytes). View file
|
|
|
facechain/facechain/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (1.5 kB). View file
|
|
|
facechain/facechain/constants.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
neg_prompt = 'nsfw, paintings, sketches, (worst quality:2), (low quality:2) ' \
|
| 2 |
+
'lowers, normal quality, ((monochrome)), ((grayscale)), logo, word, character'
|
| 3 |
+
pos_prompt_with_cloth = 'raw photo, masterpiece, chinese, {}, solo, medium shot, high detail face, looking straight into the camera with shoulders parallel to the frame, slim body, photorealistic, best quality'
|
| 4 |
+
pos_prompt_with_style = '{}, upper_body, raw photo, masterpiece, solo, medium shot, high detail face, slim body, photorealistic, best quality'
|
| 5 |
+
|
| 6 |
+
base_models = [
|
| 7 |
+
{'name': 'leosamsMoonfilm_filmGrain20',
|
| 8 |
+
'model_id': 'ly261666/cv_portrait_model',
|
| 9 |
+
'revision': 'v2.0',
|
| 10 |
+
'sub_path': "film/film",
|
| 11 |
+
'style_list': ['工作服(Working suit)', '盔甲风(Armor)','T恤衫(T-shirt)','汉服风(Hanfu)','女士晚礼服(Gown)','赛博朋克(Cybernetics punk)','凤冠霞帔(Chinese traditional gorgeous suit)']},
|
| 12 |
+
{'name': 'MajicmixRealistic_v6',
|
| 13 |
+
'model_id': 'YorickHe/majicmixRealistic_v6',
|
| 14 |
+
'revision': 'v1.0.0',
|
| 15 |
+
'sub_path': "realistic",
|
| 16 |
+
'style_list': ['冬季汉服(Chinese winter hanfu)', '校服风(School uniform)', '婚纱风(Wedding dress)', '夜景港风(Hong Kong night style)', '雨夜(Rainy night)', '模特风(Model style)', '机车风(Motorcycle race style)', '婚纱风-2(Wedding dress 2)','拍立得风(Polaroid style)', '仙女风(Fairy style)', '古风(traditional chinese style)', '壮族服装风(Zhuang style)', '欧式田野风(European fields)']},
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
styles = [
|
| 20 |
+
{'name': '工作服(Working suit)',
|
| 21 |
+
'img': './style_image/Working_suit.jpg',
|
| 22 |
+
'model_id': None,
|
| 23 |
+
'revision': None,
|
| 24 |
+
'bin_file': None,
|
| 25 |
+
'multiplier_style': 0.35,
|
| 26 |
+
'multiplier_human': 0.95,
|
| 27 |
+
'add_prompt_style': 'wearing high-class business/working suit, simple background, high-class pure color background'},
|
| 28 |
+
{'name': '盔甲风(Armor)',
|
| 29 |
+
'img': './style_image/Armor.jpg',
|
| 30 |
+
'model_id': None,
|
| 31 |
+
'revision': None,
|
| 32 |
+
'bin_file': None,
|
| 33 |
+
'multiplier_style': 0.35,
|
| 34 |
+
'multiplier_human': 0.95,
|
| 35 |
+
'add_prompt_style': 'wearing silver armor, simple background, high-class pure color background'},
|
| 36 |
+
{'name': 'T恤衫(T-shirt)',
|
| 37 |
+
'img': './style_image/T-shirt.jpg',
|
| 38 |
+
'model_id': None,
|
| 39 |
+
'revision': None,
|
| 40 |
+
'bin_file': None,
|
| 41 |
+
'multiplier_style': 0.35,
|
| 42 |
+
'multiplier_human': 0.95,
|
| 43 |
+
'add_prompt_style': 'wearing T-shirt, simple background, high-class pure color background'},
|
| 44 |
+
{'name': '汉服风(Hanfu)',
|
| 45 |
+
'img': './style_image/Hanfu.jpg',
|
| 46 |
+
'model_id': None,
|
| 47 |
+
'revision': None,
|
| 48 |
+
'bin_file': None,
|
| 49 |
+
'multiplier_style': 0.35,
|
| 50 |
+
'multiplier_human': 0.95,
|
| 51 |
+
'add_prompt_style': 'wearing beautiful traditional hanfu, upper_body, simple background, high-class pure color background'},
|
| 52 |
+
{'name': '女士晚礼服(Gown)',
|
| 53 |
+
'img': './style_image/Gown.jpg',
|
| 54 |
+
'model_id': None,
|
| 55 |
+
'revision': None,
|
| 56 |
+
'bin_file': None,
|
| 57 |
+
'multiplier_style': 0.35,
|
| 58 |
+
'multiplier_human': 0.95,
|
| 59 |
+
'add_prompt_style': 'wearing an elegant evening gown, simple background, high-class pure color background'},
|
| 60 |
+
{'name': '赛博朋克(Cybernetics punk)',
|
| 61 |
+
'img': './style_image/Cybernetics_punk.jpg',
|
| 62 |
+
'model_id': None,
|
| 63 |
+
'revision': None,
|
| 64 |
+
'bin_file': None,
|
| 65 |
+
'multiplier_style': 0.35,
|
| 66 |
+
'multiplier_human': 0.95,
|
| 67 |
+
'add_prompt_style': 'white hair, neon glowing glasses, cybernetics, punks, robotic, AI, NFT art, Fluorescent color, ustration'},
|
| 68 |
+
{'name': '凤冠霞帔(Chinese traditional gorgeous suit)',
|
| 69 |
+
'img': './style_image/Chinese_traditional_gorgeous_suit.jpg',
|
| 70 |
+
'model_id': 'ly261666/civitai_xiapei_lora',
|
| 71 |
+
'revision': 'v1.0.0',
|
| 72 |
+
'bin_file': 'xiapei.safetensors',
|
| 73 |
+
'multiplier_style': 0.35,
|
| 74 |
+
'multiplier_human': 0.95,
|
| 75 |
+
'add_prompt_style': 'red, hanfu, tiara, crown'},
|
| 76 |
+
{'name': '冬季汉服(Chinese winter hanfu)',
|
| 77 |
+
'img': './style_image/Chinese_winter_hanfu.jpg',
|
| 78 |
+
'model_id': 'YorickHe/Winter_hanfu_lora',
|
| 79 |
+
'revision': 'v1.0.0',
|
| 80 |
+
'bin_file': 'Winter_Hanfu.safetensors',
|
| 81 |
+
'multiplier_style': 0.3,
|
| 82 |
+
'multiplier_human': 0.95,
|
| 83 |
+
'add_prompt_style': 'red hanfu, winter hanfu, cloak, photography, warm light, sunlight, majestic snow scene, close-up, front view, soft falling snowflakes, jewelry, enchanted winter wonderland'},
|
| 84 |
+
{'name': '校服风(School uniform)',
|
| 85 |
+
'img': './style_image/School_uniform.jpg',
|
| 86 |
+
'model_id': 'YorickHe/JK_uniform_lora',
|
| 87 |
+
'revision': 'v1.0.0',
|
| 88 |
+
'bin_file': 'jk_uniform.safetensors',
|
| 89 |
+
'multiplier_style': 0.2,
|
| 90 |
+
'multiplier_human': 0.95,
|
| 91 |
+
'add_prompt_style': 'JK_style, white short-sleeved JK_shirt, dark blue JK_skirt, bow JK_tie, close-up, looking at viewer, sweet smile, night, Tokyo street, night city scape'},
|
| 92 |
+
{'name': '婚纱风(Wedding dress)',
|
| 93 |
+
'img': './style_image/Wedding_dress.jpg',
|
| 94 |
+
'model_id': 'YorickHe/outdoor_photo_lora',
|
| 95 |
+
'revision': 'v1.0.0',
|
| 96 |
+
'bin_file': 'outdoor_photo_v2.0.safetensors',
|
| 97 |
+
'multiplier_style': 0.3,
|
| 98 |
+
'multiplier_human': 0.95,
|
| 99 |
+
'add_prompt_style': 'white wedding dress, 1girl, summer, flower, happy atmosphere, sunlight, Waist Shot'},
|
| 100 |
+
{'name': '夜景港风(Hong Kong night style)',
|
| 101 |
+
'img': './style_image/Hong_Kong_night_style.jpg',
|
| 102 |
+
'model_id': 'YorickHe/polaroid_lora',
|
| 103 |
+
'revision': 'v1.0.0',
|
| 104 |
+
'bin_file': 'InstantPhotoX3.safetensors',
|
| 105 |
+
'multiplier_style': 0.35,
|
| 106 |
+
'multiplier_human': 0.95,
|
| 107 |
+
'add_prompt_style': '1girl, close-up, face shot, stylish outfit, fitted jeans, oversized jacket, fashionable accessories, cityscape backdrop, rooftop or high-rise balcony, dynamic composition, engaging pose, soft yet striking lighting, shallow depth of field, bokeh from city lights, naturally blurred background'},
|
| 108 |
+
{'name': '雨夜(Rainy night)',
|
| 109 |
+
'img': './style_image/Rainy_night.jpg',
|
| 110 |
+
'model_id': 'YorickHe/polaroid_lora',
|
| 111 |
+
'revision': 'v1.0.0',
|
| 112 |
+
'bin_file': 'InstantPhotoX3.safetensors',
|
| 113 |
+
'multiplier_style': 0.45,
|
| 114 |
+
'multiplier_human': 0.95,
|
| 115 |
+
'add_prompt_style': 'standing in the rain, wet, wet clothes, wet hair, face Shot, front view, close-up, cityscape, cold lighting, realistic, cinematic lighting, photon mapping, radiosity, physically-based rendering'},
|
| 116 |
+
{'name': '模特风(Model style)',
|
| 117 |
+
'img': './style_image/Model_style.jpg',
|
| 118 |
+
'model_id': 'YorickHe/polaroid_lora',
|
| 119 |
+
'revision': 'v1.0.0',
|
| 120 |
+
'bin_file': 'InstantPhotoX3.safetensors',
|
| 121 |
+
'multiplier_style': 0.3,
|
| 122 |
+
'multiplier_human': 0.95,
|
| 123 |
+
'add_prompt_style': '1girl, balenciaga, close-up, fashion, streets of new york, new york, modeling for Balenciaga, natural skin texture, dynamic pose, rouge, film grain'},
|
| 124 |
+
{'name': '机车风(Motorcycle race style)',
|
| 125 |
+
'img': './style_image/Motorcycle_race_style.jpg',
|
| 126 |
+
'model_id': 'YorickHe/polaroid_lora',
|
| 127 |
+
'revision': 'v1.0.0',
|
| 128 |
+
'bin_file': 'InstantPhotoX3.safetensors',
|
| 129 |
+
'multiplier_style': 0.4,
|
| 130 |
+
'multiplier_human': 0.95,
|
| 131 |
+
'add_prompt_style': '1girl, close-up, wearing racing clothes, motorbike clothes, modeling, playful, futuristic, city street background, at night, cool atmospheric, realistic'},
|
| 132 |
+
{'name': '婚纱风-2(Wedding dress 2)',
|
| 133 |
+
'img': './style_image/Wedding_dress_2.jpg',
|
| 134 |
+
'model_id': 'YorickHe/polaroid_lora',
|
| 135 |
+
'revision': 'v1.0.0',
|
| 136 |
+
'bin_file': 'InstantPhotoX3.safetensors',
|
| 137 |
+
'multiplier_style': 0.4,
|
| 138 |
+
'multiplier_human': 0.95,
|
| 139 |
+
'add_prompt_style': '1girl, close-up, wearing wedding dress, white, film grain, sunlight, sun flare, lens flare, field of white roses, high fashion, top model'},
|
| 140 |
+
{'name': '拍立得风(Polaroid style)',
|
| 141 |
+
'img': './style_image/Polaroid_style.jpg',
|
| 142 |
+
'model_id': 'YorickHe/polaroid_lora',
|
| 143 |
+
'revision': 'v1.0.0',
|
| 144 |
+
'bin_file': 'InstantPhotoX3.safetensors',
|
| 145 |
+
'multiplier_style': 0.4,
|
| 146 |
+
'multiplier_human': 0.95,
|
| 147 |
+
'add_prompt_style': '1girl, close-up, simple clothes, front view, looking straight into the camera, film grain, flash, enhanced flash, dark background, polaroid, instant photo, realistic face'},
|
| 148 |
+
{'name': '仙女风(Fairy style)',
|
| 149 |
+
'img': './style_image/Fairy_style.jpg',
|
| 150 |
+
'model_id': 'YorickHe/fairy_lora',
|
| 151 |
+
'revision': 'v1.0.0',
|
| 152 |
+
'bin_file': 'fairy.safetensors',
|
| 153 |
+
'multiplier_style': 0.25,
|
| 154 |
+
'multiplier_human': 0.95,
|
| 155 |
+
'add_prompt_style': 'a beautiful fairy standing in the middle of a flower field, petals, close-up, warm light, light green atmosphere, white atmosphere, in the style of celebrity photography, soft, romantic scenes, flowing fabrics, light white and light orange, high resolution'},
|
| 156 |
+
{'name': '古风(traditional chinese style)',
|
| 157 |
+
'img': './style_image/traditional_chinese_style.jpg',
|
| 158 |
+
'model_id': 'iotang/lora_testing',
|
| 159 |
+
'revision': 'v5',
|
| 160 |
+
'bin_file': 'MoXinV1.safetensors',
|
| 161 |
+
'multiplier_style': 0.3,
|
| 162 |
+
'multiplier_human': 0.95,
|
| 163 |
+
'add_prompt_style': '(ultra high res face, face ultra zoom, highres, best quality, ultra detailed, cinematic lighting, portrait, Chinese traditional ink painting:1.2), sfw, shuimobysim, song, anxiang, hanfu, Ultra HD, wuchangshuo, detailed background, looking at viewer, serenity, peace'},
|
| 164 |
+
{'name': '壮族服装风(Zhuang style)',
|
| 165 |
+
'img': './style_image/Zhuang_style.jpg',
|
| 166 |
+
'model_id': 'iotang/lora_testing',
|
| 167 |
+
'revision': 'v5',
|
| 168 |
+
'bin_file': 'zhuangnv.safetensors',
|
| 169 |
+
'multiplier_style': 0.7,
|
| 170 |
+
'multiplier_human': 0.95,
|
| 171 |
+
'add_prompt_style': '(masterpiece, ultra high res face, face ultra zoom, highres, best quality, ultra detailed, cinematic lighting, portrait:1.2), sfw, facing the camera with a smile, zhuangzunv, ornaments, jewelry, headwear, beautiful embroidery, floral print, marvelous design, ancient Chinese traditional clothing'},
|
| 172 |
+
{'name': '欧式田野风(European fields)',
|
| 173 |
+
'img': './style_image/European_fields.jpg',
|
| 174 |
+
'model_id': 'iotang/lora_testing',
|
| 175 |
+
'revision': 'v5',
|
| 176 |
+
'bin_file': 'edgEuropean_Vintage.safetensors',
|
| 177 |
+
'multiplier_style': 0.55,
|
| 178 |
+
'multiplier_human': 0.95,
|
| 179 |
+
'add_prompt_style': '(masterpiece, ultra high res face, face ultra zoom, highres, best quality, ultra detailed, detailed background, cinematic lighting, portrait:1.2), sfw, focused, edgEV, wearing edgEV_vintage dress, field, natural lighting, windy hair, gentle hair, clean'},
|
| 180 |
+
|
| 181 |
+
]
|
| 182 |
+
|
| 183 |
+
pose_models = [
|
| 184 |
+
{'name': '无姿态控制(No pose control)'},
|
| 185 |
+
{'name': 'pose-v1.1-with-depth'},
|
| 186 |
+
{'name': 'pose-v1.1'}
|
| 187 |
+
]
|
| 188 |
+
|
| 189 |
+
pose_examples = {
|
| 190 |
+
'man': [
|
| 191 |
+
['./poses/man/pose1.png'],
|
| 192 |
+
['./poses/man/pose2.png'],
|
| 193 |
+
['./poses/man/pose3.png'],
|
| 194 |
+
['./poses/man/pose4.png']
|
| 195 |
+
],
|
| 196 |
+
'woman': [
|
| 197 |
+
['./poses/woman/pose1.png'],
|
| 198 |
+
['./poses/woman/pose2.png'],
|
| 199 |
+
['./poses/woman/pose3.png'],
|
| 200 |
+
['./poses/woman/pose4.png'],
|
| 201 |
+
]
|
| 202 |
+
}
|
facechain/facechain/data_process/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
facechain/facechain/data_process/deepbooru.py
ADDED
|
@@ -0,0 +1,796 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
import numpy as np
|
| 8 |
+
|
| 9 |
+
re_special = re.compile(r'([\\()])')
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
from modelscope.hub.snapshot_download import snapshot_download
|
| 15 |
+
|
| 16 |
+
# see https://github.com/AUTOMATIC1111/TorchDeepDanbooru for more
|
| 17 |
+
LANCZOS = (Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class DeepDanbooruModel(nn.Module):
|
| 21 |
+
def __init__(self):
|
| 22 |
+
super(DeepDanbooruModel, self).__init__()
|
| 23 |
+
|
| 24 |
+
self.tags = []
|
| 25 |
+
|
| 26 |
+
self.n_Conv_0 = nn.Conv2d(kernel_size=(7, 7), in_channels=3, out_channels=64, stride=(2, 2))
|
| 27 |
+
self.n_MaxPool_0 = nn.MaxPool2d(kernel_size=(3, 3), stride=(2, 2))
|
| 28 |
+
self.n_Conv_1 = nn.Conv2d(kernel_size=(1, 1), in_channels=64, out_channels=256)
|
| 29 |
+
self.n_Conv_2 = nn.Conv2d(kernel_size=(1, 1), in_channels=64, out_channels=64)
|
| 30 |
+
self.n_Conv_3 = nn.Conv2d(kernel_size=(3, 3), in_channels=64, out_channels=64)
|
| 31 |
+
self.n_Conv_4 = nn.Conv2d(kernel_size=(1, 1), in_channels=64, out_channels=256)
|
| 32 |
+
self.n_Conv_5 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=64)
|
| 33 |
+
self.n_Conv_6 = nn.Conv2d(kernel_size=(3, 3), in_channels=64, out_channels=64)
|
| 34 |
+
self.n_Conv_7 = nn.Conv2d(kernel_size=(1, 1), in_channels=64, out_channels=256)
|
| 35 |
+
self.n_Conv_8 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=64)
|
| 36 |
+
self.n_Conv_9 = nn.Conv2d(kernel_size=(3, 3), in_channels=64, out_channels=64)
|
| 37 |
+
self.n_Conv_10 = nn.Conv2d(kernel_size=(1, 1), in_channels=64, out_channels=256)
|
| 38 |
+
self.n_Conv_11 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=512, stride=(2, 2))
|
| 39 |
+
self.n_Conv_12 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=128)
|
| 40 |
+
self.n_Conv_13 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128, stride=(2, 2))
|
| 41 |
+
self.n_Conv_14 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512)
|
| 42 |
+
self.n_Conv_15 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128)
|
| 43 |
+
self.n_Conv_16 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128)
|
| 44 |
+
self.n_Conv_17 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512)
|
| 45 |
+
self.n_Conv_18 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128)
|
| 46 |
+
self.n_Conv_19 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128)
|
| 47 |
+
self.n_Conv_20 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512)
|
| 48 |
+
self.n_Conv_21 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128)
|
| 49 |
+
self.n_Conv_22 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128)
|
| 50 |
+
self.n_Conv_23 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512)
|
| 51 |
+
self.n_Conv_24 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128)
|
| 52 |
+
self.n_Conv_25 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128)
|
| 53 |
+
self.n_Conv_26 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512)
|
| 54 |
+
self.n_Conv_27 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128)
|
| 55 |
+
self.n_Conv_28 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128)
|
| 56 |
+
self.n_Conv_29 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512)
|
| 57 |
+
self.n_Conv_30 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128)
|
| 58 |
+
self.n_Conv_31 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128)
|
| 59 |
+
self.n_Conv_32 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512)
|
| 60 |
+
self.n_Conv_33 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128)
|
| 61 |
+
self.n_Conv_34 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128)
|
| 62 |
+
self.n_Conv_35 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512)
|
| 63 |
+
self.n_Conv_36 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=1024, stride=(2, 2))
|
| 64 |
+
self.n_Conv_37 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=256)
|
| 65 |
+
self.n_Conv_38 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256, stride=(2, 2))
|
| 66 |
+
self.n_Conv_39 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 67 |
+
self.n_Conv_40 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 68 |
+
self.n_Conv_41 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 69 |
+
self.n_Conv_42 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 70 |
+
self.n_Conv_43 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 71 |
+
self.n_Conv_44 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 72 |
+
self.n_Conv_45 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 73 |
+
self.n_Conv_46 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 74 |
+
self.n_Conv_47 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 75 |
+
self.n_Conv_48 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 76 |
+
self.n_Conv_49 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 77 |
+
self.n_Conv_50 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 78 |
+
self.n_Conv_51 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 79 |
+
self.n_Conv_52 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 80 |
+
self.n_Conv_53 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 81 |
+
self.n_Conv_54 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 82 |
+
self.n_Conv_55 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 83 |
+
self.n_Conv_56 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 84 |
+
self.n_Conv_57 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 85 |
+
self.n_Conv_58 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 86 |
+
self.n_Conv_59 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 87 |
+
self.n_Conv_60 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 88 |
+
self.n_Conv_61 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 89 |
+
self.n_Conv_62 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 90 |
+
self.n_Conv_63 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 91 |
+
self.n_Conv_64 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 92 |
+
self.n_Conv_65 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 93 |
+
self.n_Conv_66 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 94 |
+
self.n_Conv_67 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 95 |
+
self.n_Conv_68 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 96 |
+
self.n_Conv_69 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 97 |
+
self.n_Conv_70 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 98 |
+
self.n_Conv_71 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 99 |
+
self.n_Conv_72 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 100 |
+
self.n_Conv_73 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 101 |
+
self.n_Conv_74 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 102 |
+
self.n_Conv_75 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 103 |
+
self.n_Conv_76 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 104 |
+
self.n_Conv_77 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 105 |
+
self.n_Conv_78 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 106 |
+
self.n_Conv_79 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 107 |
+
self.n_Conv_80 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 108 |
+
self.n_Conv_81 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 109 |
+
self.n_Conv_82 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 110 |
+
self.n_Conv_83 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 111 |
+
self.n_Conv_84 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 112 |
+
self.n_Conv_85 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 113 |
+
self.n_Conv_86 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 114 |
+
self.n_Conv_87 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 115 |
+
self.n_Conv_88 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 116 |
+
self.n_Conv_89 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 117 |
+
self.n_Conv_90 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 118 |
+
self.n_Conv_91 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 119 |
+
self.n_Conv_92 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 120 |
+
self.n_Conv_93 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 121 |
+
self.n_Conv_94 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 122 |
+
self.n_Conv_95 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 123 |
+
self.n_Conv_96 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 124 |
+
self.n_Conv_97 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 125 |
+
self.n_Conv_98 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256, stride=(2, 2))
|
| 126 |
+
self.n_Conv_99 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 127 |
+
self.n_Conv_100 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=1024, stride=(2, 2))
|
| 128 |
+
self.n_Conv_101 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 129 |
+
self.n_Conv_102 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 130 |
+
self.n_Conv_103 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 131 |
+
self.n_Conv_104 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 132 |
+
self.n_Conv_105 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 133 |
+
self.n_Conv_106 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 134 |
+
self.n_Conv_107 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 135 |
+
self.n_Conv_108 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 136 |
+
self.n_Conv_109 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 137 |
+
self.n_Conv_110 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 138 |
+
self.n_Conv_111 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 139 |
+
self.n_Conv_112 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 140 |
+
self.n_Conv_113 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 141 |
+
self.n_Conv_114 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 142 |
+
self.n_Conv_115 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 143 |
+
self.n_Conv_116 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 144 |
+
self.n_Conv_117 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 145 |
+
self.n_Conv_118 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 146 |
+
self.n_Conv_119 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 147 |
+
self.n_Conv_120 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 148 |
+
self.n_Conv_121 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 149 |
+
self.n_Conv_122 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 150 |
+
self.n_Conv_123 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 151 |
+
self.n_Conv_124 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 152 |
+
self.n_Conv_125 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 153 |
+
self.n_Conv_126 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 154 |
+
self.n_Conv_127 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 155 |
+
self.n_Conv_128 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 156 |
+
self.n_Conv_129 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 157 |
+
self.n_Conv_130 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 158 |
+
self.n_Conv_131 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 159 |
+
self.n_Conv_132 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 160 |
+
self.n_Conv_133 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 161 |
+
self.n_Conv_134 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 162 |
+
self.n_Conv_135 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 163 |
+
self.n_Conv_136 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 164 |
+
self.n_Conv_137 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 165 |
+
self.n_Conv_138 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 166 |
+
self.n_Conv_139 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 167 |
+
self.n_Conv_140 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 168 |
+
self.n_Conv_141 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 169 |
+
self.n_Conv_142 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 170 |
+
self.n_Conv_143 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 171 |
+
self.n_Conv_144 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 172 |
+
self.n_Conv_145 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 173 |
+
self.n_Conv_146 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 174 |
+
self.n_Conv_147 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 175 |
+
self.n_Conv_148 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 176 |
+
self.n_Conv_149 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 177 |
+
self.n_Conv_150 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 178 |
+
self.n_Conv_151 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 179 |
+
self.n_Conv_152 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 180 |
+
self.n_Conv_153 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 181 |
+
self.n_Conv_154 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 182 |
+
self.n_Conv_155 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256)
|
| 183 |
+
self.n_Conv_156 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256)
|
| 184 |
+
self.n_Conv_157 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024)
|
| 185 |
+
self.n_Conv_158 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=2048, stride=(2, 2))
|
| 186 |
+
self.n_Conv_159 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=512)
|
| 187 |
+
self.n_Conv_160 = nn.Conv2d(kernel_size=(3, 3), in_channels=512, out_channels=512, stride=(2, 2))
|
| 188 |
+
self.n_Conv_161 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=2048)
|
| 189 |
+
self.n_Conv_162 = nn.Conv2d(kernel_size=(1, 1), in_channels=2048, out_channels=512)
|
| 190 |
+
self.n_Conv_163 = nn.Conv2d(kernel_size=(3, 3), in_channels=512, out_channels=512)
|
| 191 |
+
self.n_Conv_164 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=2048)
|
| 192 |
+
self.n_Conv_165 = nn.Conv2d(kernel_size=(1, 1), in_channels=2048, out_channels=512)
|
| 193 |
+
self.n_Conv_166 = nn.Conv2d(kernel_size=(3, 3), in_channels=512, out_channels=512)
|
| 194 |
+
self.n_Conv_167 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=2048)
|
| 195 |
+
self.n_Conv_168 = nn.Conv2d(kernel_size=(1, 1), in_channels=2048, out_channels=4096, stride=(2, 2))
|
| 196 |
+
self.n_Conv_169 = nn.Conv2d(kernel_size=(1, 1), in_channels=2048, out_channels=1024)
|
| 197 |
+
self.n_Conv_170 = nn.Conv2d(kernel_size=(3, 3), in_channels=1024, out_channels=1024, stride=(2, 2))
|
| 198 |
+
self.n_Conv_171 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=4096)
|
| 199 |
+
self.n_Conv_172 = nn.Conv2d(kernel_size=(1, 1), in_channels=4096, out_channels=1024)
|
| 200 |
+
self.n_Conv_173 = nn.Conv2d(kernel_size=(3, 3), in_channels=1024, out_channels=1024)
|
| 201 |
+
self.n_Conv_174 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=4096)
|
| 202 |
+
self.n_Conv_175 = nn.Conv2d(kernel_size=(1, 1), in_channels=4096, out_channels=1024)
|
| 203 |
+
self.n_Conv_176 = nn.Conv2d(kernel_size=(3, 3), in_channels=1024, out_channels=1024)
|
| 204 |
+
self.n_Conv_177 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=4096)
|
| 205 |
+
self.n_Conv_178 = nn.Conv2d(kernel_size=(1, 1), in_channels=4096, out_channels=9176, bias=False)
|
| 206 |
+
|
| 207 |
+
def forward(self, *inputs):
|
| 208 |
+
t_358, = inputs
|
| 209 |
+
t_359 = t_358.permute(*[0, 3, 1, 2])
|
| 210 |
+
t_359_padded = F.pad(t_359, [2, 3, 2, 3], value=0)
|
| 211 |
+
# t_360 = self.n_Conv_0(t_359_padded.to(self.n_Conv_0.bias.dtype) if devices.unet_needs_upcast else t_359_padded)
|
| 212 |
+
t_360 = self.n_Conv_0(t_359_padded.to(self.n_Conv_0.bias.dtype))
|
| 213 |
+
t_361 = F.relu(t_360)
|
| 214 |
+
t_361 = F.pad(t_361, [0, 1, 0, 1], value=float('-inf'))
|
| 215 |
+
t_362 = self.n_MaxPool_0(t_361)
|
| 216 |
+
t_363 = self.n_Conv_1(t_362)
|
| 217 |
+
t_364 = self.n_Conv_2(t_362)
|
| 218 |
+
t_365 = F.relu(t_364)
|
| 219 |
+
t_365_padded = F.pad(t_365, [1, 1, 1, 1], value=0)
|
| 220 |
+
t_366 = self.n_Conv_3(t_365_padded)
|
| 221 |
+
t_367 = F.relu(t_366)
|
| 222 |
+
t_368 = self.n_Conv_4(t_367)
|
| 223 |
+
t_369 = torch.add(t_368, t_363)
|
| 224 |
+
t_370 = F.relu(t_369)
|
| 225 |
+
t_371 = self.n_Conv_5(t_370)
|
| 226 |
+
t_372 = F.relu(t_371)
|
| 227 |
+
t_372_padded = F.pad(t_372, [1, 1, 1, 1], value=0)
|
| 228 |
+
t_373 = self.n_Conv_6(t_372_padded)
|
| 229 |
+
t_374 = F.relu(t_373)
|
| 230 |
+
t_375 = self.n_Conv_7(t_374)
|
| 231 |
+
t_376 = torch.add(t_375, t_370)
|
| 232 |
+
t_377 = F.relu(t_376)
|
| 233 |
+
t_378 = self.n_Conv_8(t_377)
|
| 234 |
+
t_379 = F.relu(t_378)
|
| 235 |
+
t_379_padded = F.pad(t_379, [1, 1, 1, 1], value=0)
|
| 236 |
+
t_380 = self.n_Conv_9(t_379_padded)
|
| 237 |
+
t_381 = F.relu(t_380)
|
| 238 |
+
t_382 = self.n_Conv_10(t_381)
|
| 239 |
+
t_383 = torch.add(t_382, t_377)
|
| 240 |
+
t_384 = F.relu(t_383)
|
| 241 |
+
t_385 = self.n_Conv_11(t_384)
|
| 242 |
+
t_386 = self.n_Conv_12(t_384)
|
| 243 |
+
t_387 = F.relu(t_386)
|
| 244 |
+
t_387_padded = F.pad(t_387, [0, 1, 0, 1], value=0)
|
| 245 |
+
t_388 = self.n_Conv_13(t_387_padded)
|
| 246 |
+
t_389 = F.relu(t_388)
|
| 247 |
+
t_390 = self.n_Conv_14(t_389)
|
| 248 |
+
t_391 = torch.add(t_390, t_385)
|
| 249 |
+
t_392 = F.relu(t_391)
|
| 250 |
+
t_393 = self.n_Conv_15(t_392)
|
| 251 |
+
t_394 = F.relu(t_393)
|
| 252 |
+
t_394_padded = F.pad(t_394, [1, 1, 1, 1], value=0)
|
| 253 |
+
t_395 = self.n_Conv_16(t_394_padded)
|
| 254 |
+
t_396 = F.relu(t_395)
|
| 255 |
+
t_397 = self.n_Conv_17(t_396)
|
| 256 |
+
t_398 = torch.add(t_397, t_392)
|
| 257 |
+
t_399 = F.relu(t_398)
|
| 258 |
+
t_400 = self.n_Conv_18(t_399)
|
| 259 |
+
t_401 = F.relu(t_400)
|
| 260 |
+
t_401_padded = F.pad(t_401, [1, 1, 1, 1], value=0)
|
| 261 |
+
t_402 = self.n_Conv_19(t_401_padded)
|
| 262 |
+
t_403 = F.relu(t_402)
|
| 263 |
+
t_404 = self.n_Conv_20(t_403)
|
| 264 |
+
t_405 = torch.add(t_404, t_399)
|
| 265 |
+
t_406 = F.relu(t_405)
|
| 266 |
+
t_407 = self.n_Conv_21(t_406)
|
| 267 |
+
t_408 = F.relu(t_407)
|
| 268 |
+
t_408_padded = F.pad(t_408, [1, 1, 1, 1], value=0)
|
| 269 |
+
t_409 = self.n_Conv_22(t_408_padded)
|
| 270 |
+
t_410 = F.relu(t_409)
|
| 271 |
+
t_411 = self.n_Conv_23(t_410)
|
| 272 |
+
t_412 = torch.add(t_411, t_406)
|
| 273 |
+
t_413 = F.relu(t_412)
|
| 274 |
+
t_414 = self.n_Conv_24(t_413)
|
| 275 |
+
t_415 = F.relu(t_414)
|
| 276 |
+
t_415_padded = F.pad(t_415, [1, 1, 1, 1], value=0)
|
| 277 |
+
t_416 = self.n_Conv_25(t_415_padded)
|
| 278 |
+
t_417 = F.relu(t_416)
|
| 279 |
+
t_418 = self.n_Conv_26(t_417)
|
| 280 |
+
t_419 = torch.add(t_418, t_413)
|
| 281 |
+
t_420 = F.relu(t_419)
|
| 282 |
+
t_421 = self.n_Conv_27(t_420)
|
| 283 |
+
t_422 = F.relu(t_421)
|
| 284 |
+
t_422_padded = F.pad(t_422, [1, 1, 1, 1], value=0)
|
| 285 |
+
t_423 = self.n_Conv_28(t_422_padded)
|
| 286 |
+
t_424 = F.relu(t_423)
|
| 287 |
+
t_425 = self.n_Conv_29(t_424)
|
| 288 |
+
t_426 = torch.add(t_425, t_420)
|
| 289 |
+
t_427 = F.relu(t_426)
|
| 290 |
+
t_428 = self.n_Conv_30(t_427)
|
| 291 |
+
t_429 = F.relu(t_428)
|
| 292 |
+
t_429_padded = F.pad(t_429, [1, 1, 1, 1], value=0)
|
| 293 |
+
t_430 = self.n_Conv_31(t_429_padded)
|
| 294 |
+
t_431 = F.relu(t_430)
|
| 295 |
+
t_432 = self.n_Conv_32(t_431)
|
| 296 |
+
t_433 = torch.add(t_432, t_427)
|
| 297 |
+
t_434 = F.relu(t_433)
|
| 298 |
+
t_435 = self.n_Conv_33(t_434)
|
| 299 |
+
t_436 = F.relu(t_435)
|
| 300 |
+
t_436_padded = F.pad(t_436, [1, 1, 1, 1], value=0)
|
| 301 |
+
t_437 = self.n_Conv_34(t_436_padded)
|
| 302 |
+
t_438 = F.relu(t_437)
|
| 303 |
+
t_439 = self.n_Conv_35(t_438)
|
| 304 |
+
t_440 = torch.add(t_439, t_434)
|
| 305 |
+
t_441 = F.relu(t_440)
|
| 306 |
+
t_442 = self.n_Conv_36(t_441)
|
| 307 |
+
t_443 = self.n_Conv_37(t_441)
|
| 308 |
+
t_444 = F.relu(t_443)
|
| 309 |
+
t_444_padded = F.pad(t_444, [0, 1, 0, 1], value=0)
|
| 310 |
+
t_445 = self.n_Conv_38(t_444_padded)
|
| 311 |
+
t_446 = F.relu(t_445)
|
| 312 |
+
t_447 = self.n_Conv_39(t_446)
|
| 313 |
+
t_448 = torch.add(t_447, t_442)
|
| 314 |
+
t_449 = F.relu(t_448)
|
| 315 |
+
t_450 = self.n_Conv_40(t_449)
|
| 316 |
+
t_451 = F.relu(t_450)
|
| 317 |
+
t_451_padded = F.pad(t_451, [1, 1, 1, 1], value=0)
|
| 318 |
+
t_452 = self.n_Conv_41(t_451_padded)
|
| 319 |
+
t_453 = F.relu(t_452)
|
| 320 |
+
t_454 = self.n_Conv_42(t_453)
|
| 321 |
+
t_455 = torch.add(t_454, t_449)
|
| 322 |
+
t_456 = F.relu(t_455)
|
| 323 |
+
t_457 = self.n_Conv_43(t_456)
|
| 324 |
+
t_458 = F.relu(t_457)
|
| 325 |
+
t_458_padded = F.pad(t_458, [1, 1, 1, 1], value=0)
|
| 326 |
+
t_459 = self.n_Conv_44(t_458_padded)
|
| 327 |
+
t_460 = F.relu(t_459)
|
| 328 |
+
t_461 = self.n_Conv_45(t_460)
|
| 329 |
+
t_462 = torch.add(t_461, t_456)
|
| 330 |
+
t_463 = F.relu(t_462)
|
| 331 |
+
t_464 = self.n_Conv_46(t_463)
|
| 332 |
+
t_465 = F.relu(t_464)
|
| 333 |
+
t_465_padded = F.pad(t_465, [1, 1, 1, 1], value=0)
|
| 334 |
+
t_466 = self.n_Conv_47(t_465_padded)
|
| 335 |
+
t_467 = F.relu(t_466)
|
| 336 |
+
t_468 = self.n_Conv_48(t_467)
|
| 337 |
+
t_469 = torch.add(t_468, t_463)
|
| 338 |
+
t_470 = F.relu(t_469)
|
| 339 |
+
t_471 = self.n_Conv_49(t_470)
|
| 340 |
+
t_472 = F.relu(t_471)
|
| 341 |
+
t_472_padded = F.pad(t_472, [1, 1, 1, 1], value=0)
|
| 342 |
+
t_473 = self.n_Conv_50(t_472_padded)
|
| 343 |
+
t_474 = F.relu(t_473)
|
| 344 |
+
t_475 = self.n_Conv_51(t_474)
|
| 345 |
+
t_476 = torch.add(t_475, t_470)
|
| 346 |
+
t_477 = F.relu(t_476)
|
| 347 |
+
t_478 = self.n_Conv_52(t_477)
|
| 348 |
+
t_479 = F.relu(t_478)
|
| 349 |
+
t_479_padded = F.pad(t_479, [1, 1, 1, 1], value=0)
|
| 350 |
+
t_480 = self.n_Conv_53(t_479_padded)
|
| 351 |
+
t_481 = F.relu(t_480)
|
| 352 |
+
t_482 = self.n_Conv_54(t_481)
|
| 353 |
+
t_483 = torch.add(t_482, t_477)
|
| 354 |
+
t_484 = F.relu(t_483)
|
| 355 |
+
t_485 = self.n_Conv_55(t_484)
|
| 356 |
+
t_486 = F.relu(t_485)
|
| 357 |
+
t_486_padded = F.pad(t_486, [1, 1, 1, 1], value=0)
|
| 358 |
+
t_487 = self.n_Conv_56(t_486_padded)
|
| 359 |
+
t_488 = F.relu(t_487)
|
| 360 |
+
t_489 = self.n_Conv_57(t_488)
|
| 361 |
+
t_490 = torch.add(t_489, t_484)
|
| 362 |
+
t_491 = F.relu(t_490)
|
| 363 |
+
t_492 = self.n_Conv_58(t_491)
|
| 364 |
+
t_493 = F.relu(t_492)
|
| 365 |
+
t_493_padded = F.pad(t_493, [1, 1, 1, 1], value=0)
|
| 366 |
+
t_494 = self.n_Conv_59(t_493_padded)
|
| 367 |
+
t_495 = F.relu(t_494)
|
| 368 |
+
t_496 = self.n_Conv_60(t_495)
|
| 369 |
+
t_497 = torch.add(t_496, t_491)
|
| 370 |
+
t_498 = F.relu(t_497)
|
| 371 |
+
t_499 = self.n_Conv_61(t_498)
|
| 372 |
+
t_500 = F.relu(t_499)
|
| 373 |
+
t_500_padded = F.pad(t_500, [1, 1, 1, 1], value=0)
|
| 374 |
+
t_501 = self.n_Conv_62(t_500_padded)
|
| 375 |
+
t_502 = F.relu(t_501)
|
| 376 |
+
t_503 = self.n_Conv_63(t_502)
|
| 377 |
+
t_504 = torch.add(t_503, t_498)
|
| 378 |
+
t_505 = F.relu(t_504)
|
| 379 |
+
t_506 = self.n_Conv_64(t_505)
|
| 380 |
+
t_507 = F.relu(t_506)
|
| 381 |
+
t_507_padded = F.pad(t_507, [1, 1, 1, 1], value=0)
|
| 382 |
+
t_508 = self.n_Conv_65(t_507_padded)
|
| 383 |
+
t_509 = F.relu(t_508)
|
| 384 |
+
t_510 = self.n_Conv_66(t_509)
|
| 385 |
+
t_511 = torch.add(t_510, t_505)
|
| 386 |
+
t_512 = F.relu(t_511)
|
| 387 |
+
t_513 = self.n_Conv_67(t_512)
|
| 388 |
+
t_514 = F.relu(t_513)
|
| 389 |
+
t_514_padded = F.pad(t_514, [1, 1, 1, 1], value=0)
|
| 390 |
+
t_515 = self.n_Conv_68(t_514_padded)
|
| 391 |
+
t_516 = F.relu(t_515)
|
| 392 |
+
t_517 = self.n_Conv_69(t_516)
|
| 393 |
+
t_518 = torch.add(t_517, t_512)
|
| 394 |
+
t_519 = F.relu(t_518)
|
| 395 |
+
t_520 = self.n_Conv_70(t_519)
|
| 396 |
+
t_521 = F.relu(t_520)
|
| 397 |
+
t_521_padded = F.pad(t_521, [1, 1, 1, 1], value=0)
|
| 398 |
+
t_522 = self.n_Conv_71(t_521_padded)
|
| 399 |
+
t_523 = F.relu(t_522)
|
| 400 |
+
t_524 = self.n_Conv_72(t_523)
|
| 401 |
+
t_525 = torch.add(t_524, t_519)
|
| 402 |
+
t_526 = F.relu(t_525)
|
| 403 |
+
t_527 = self.n_Conv_73(t_526)
|
| 404 |
+
t_528 = F.relu(t_527)
|
| 405 |
+
t_528_padded = F.pad(t_528, [1, 1, 1, 1], value=0)
|
| 406 |
+
t_529 = self.n_Conv_74(t_528_padded)
|
| 407 |
+
t_530 = F.relu(t_529)
|
| 408 |
+
t_531 = self.n_Conv_75(t_530)
|
| 409 |
+
t_532 = torch.add(t_531, t_526)
|
| 410 |
+
t_533 = F.relu(t_532)
|
| 411 |
+
t_534 = self.n_Conv_76(t_533)
|
| 412 |
+
t_535 = F.relu(t_534)
|
| 413 |
+
t_535_padded = F.pad(t_535, [1, 1, 1, 1], value=0)
|
| 414 |
+
t_536 = self.n_Conv_77(t_535_padded)
|
| 415 |
+
t_537 = F.relu(t_536)
|
| 416 |
+
t_538 = self.n_Conv_78(t_537)
|
| 417 |
+
t_539 = torch.add(t_538, t_533)
|
| 418 |
+
t_540 = F.relu(t_539)
|
| 419 |
+
t_541 = self.n_Conv_79(t_540)
|
| 420 |
+
t_542 = F.relu(t_541)
|
| 421 |
+
t_542_padded = F.pad(t_542, [1, 1, 1, 1], value=0)
|
| 422 |
+
t_543 = self.n_Conv_80(t_542_padded)
|
| 423 |
+
t_544 = F.relu(t_543)
|
| 424 |
+
t_545 = self.n_Conv_81(t_544)
|
| 425 |
+
t_546 = torch.add(t_545, t_540)
|
| 426 |
+
t_547 = F.relu(t_546)
|
| 427 |
+
t_548 = self.n_Conv_82(t_547)
|
| 428 |
+
t_549 = F.relu(t_548)
|
| 429 |
+
t_549_padded = F.pad(t_549, [1, 1, 1, 1], value=0)
|
| 430 |
+
t_550 = self.n_Conv_83(t_549_padded)
|
| 431 |
+
t_551 = F.relu(t_550)
|
| 432 |
+
t_552 = self.n_Conv_84(t_551)
|
| 433 |
+
t_553 = torch.add(t_552, t_547)
|
| 434 |
+
t_554 = F.relu(t_553)
|
| 435 |
+
t_555 = self.n_Conv_85(t_554)
|
| 436 |
+
t_556 = F.relu(t_555)
|
| 437 |
+
t_556_padded = F.pad(t_556, [1, 1, 1, 1], value=0)
|
| 438 |
+
t_557 = self.n_Conv_86(t_556_padded)
|
| 439 |
+
t_558 = F.relu(t_557)
|
| 440 |
+
t_559 = self.n_Conv_87(t_558)
|
| 441 |
+
t_560 = torch.add(t_559, t_554)
|
| 442 |
+
t_561 = F.relu(t_560)
|
| 443 |
+
t_562 = self.n_Conv_88(t_561)
|
| 444 |
+
t_563 = F.relu(t_562)
|
| 445 |
+
t_563_padded = F.pad(t_563, [1, 1, 1, 1], value=0)
|
| 446 |
+
t_564 = self.n_Conv_89(t_563_padded)
|
| 447 |
+
t_565 = F.relu(t_564)
|
| 448 |
+
t_566 = self.n_Conv_90(t_565)
|
| 449 |
+
t_567 = torch.add(t_566, t_561)
|
| 450 |
+
t_568 = F.relu(t_567)
|
| 451 |
+
t_569 = self.n_Conv_91(t_568)
|
| 452 |
+
t_570 = F.relu(t_569)
|
| 453 |
+
t_570_padded = F.pad(t_570, [1, 1, 1, 1], value=0)
|
| 454 |
+
t_571 = self.n_Conv_92(t_570_padded)
|
| 455 |
+
t_572 = F.relu(t_571)
|
| 456 |
+
t_573 = self.n_Conv_93(t_572)
|
| 457 |
+
t_574 = torch.add(t_573, t_568)
|
| 458 |
+
t_575 = F.relu(t_574)
|
| 459 |
+
t_576 = self.n_Conv_94(t_575)
|
| 460 |
+
t_577 = F.relu(t_576)
|
| 461 |
+
t_577_padded = F.pad(t_577, [1, 1, 1, 1], value=0)
|
| 462 |
+
t_578 = self.n_Conv_95(t_577_padded)
|
| 463 |
+
t_579 = F.relu(t_578)
|
| 464 |
+
t_580 = self.n_Conv_96(t_579)
|
| 465 |
+
t_581 = torch.add(t_580, t_575)
|
| 466 |
+
t_582 = F.relu(t_581)
|
| 467 |
+
t_583 = self.n_Conv_97(t_582)
|
| 468 |
+
t_584 = F.relu(t_583)
|
| 469 |
+
t_584_padded = F.pad(t_584, [0, 1, 0, 1], value=0)
|
| 470 |
+
t_585 = self.n_Conv_98(t_584_padded)
|
| 471 |
+
t_586 = F.relu(t_585)
|
| 472 |
+
t_587 = self.n_Conv_99(t_586)
|
| 473 |
+
t_588 = self.n_Conv_100(t_582)
|
| 474 |
+
t_589 = torch.add(t_587, t_588)
|
| 475 |
+
t_590 = F.relu(t_589)
|
| 476 |
+
t_591 = self.n_Conv_101(t_590)
|
| 477 |
+
t_592 = F.relu(t_591)
|
| 478 |
+
t_592_padded = F.pad(t_592, [1, 1, 1, 1], value=0)
|
| 479 |
+
t_593 = self.n_Conv_102(t_592_padded)
|
| 480 |
+
t_594 = F.relu(t_593)
|
| 481 |
+
t_595 = self.n_Conv_103(t_594)
|
| 482 |
+
t_596 = torch.add(t_595, t_590)
|
| 483 |
+
t_597 = F.relu(t_596)
|
| 484 |
+
t_598 = self.n_Conv_104(t_597)
|
| 485 |
+
t_599 = F.relu(t_598)
|
| 486 |
+
t_599_padded = F.pad(t_599, [1, 1, 1, 1], value=0)
|
| 487 |
+
t_600 = self.n_Conv_105(t_599_padded)
|
| 488 |
+
t_601 = F.relu(t_600)
|
| 489 |
+
t_602 = self.n_Conv_106(t_601)
|
| 490 |
+
t_603 = torch.add(t_602, t_597)
|
| 491 |
+
t_604 = F.relu(t_603)
|
| 492 |
+
t_605 = self.n_Conv_107(t_604)
|
| 493 |
+
t_606 = F.relu(t_605)
|
| 494 |
+
t_606_padded = F.pad(t_606, [1, 1, 1, 1], value=0)
|
| 495 |
+
t_607 = self.n_Conv_108(t_606_padded)
|
| 496 |
+
t_608 = F.relu(t_607)
|
| 497 |
+
t_609 = self.n_Conv_109(t_608)
|
| 498 |
+
t_610 = torch.add(t_609, t_604)
|
| 499 |
+
t_611 = F.relu(t_610)
|
| 500 |
+
t_612 = self.n_Conv_110(t_611)
|
| 501 |
+
t_613 = F.relu(t_612)
|
| 502 |
+
t_613_padded = F.pad(t_613, [1, 1, 1, 1], value=0)
|
| 503 |
+
t_614 = self.n_Conv_111(t_613_padded)
|
| 504 |
+
t_615 = F.relu(t_614)
|
| 505 |
+
t_616 = self.n_Conv_112(t_615)
|
| 506 |
+
t_617 = torch.add(t_616, t_611)
|
| 507 |
+
t_618 = F.relu(t_617)
|
| 508 |
+
t_619 = self.n_Conv_113(t_618)
|
| 509 |
+
t_620 = F.relu(t_619)
|
| 510 |
+
t_620_padded = F.pad(t_620, [1, 1, 1, 1], value=0)
|
| 511 |
+
t_621 = self.n_Conv_114(t_620_padded)
|
| 512 |
+
t_622 = F.relu(t_621)
|
| 513 |
+
t_623 = self.n_Conv_115(t_622)
|
| 514 |
+
t_624 = torch.add(t_623, t_618)
|
| 515 |
+
t_625 = F.relu(t_624)
|
| 516 |
+
t_626 = self.n_Conv_116(t_625)
|
| 517 |
+
t_627 = F.relu(t_626)
|
| 518 |
+
t_627_padded = F.pad(t_627, [1, 1, 1, 1], value=0)
|
| 519 |
+
t_628 = self.n_Conv_117(t_627_padded)
|
| 520 |
+
t_629 = F.relu(t_628)
|
| 521 |
+
t_630 = self.n_Conv_118(t_629)
|
| 522 |
+
t_631 = torch.add(t_630, t_625)
|
| 523 |
+
t_632 = F.relu(t_631)
|
| 524 |
+
t_633 = self.n_Conv_119(t_632)
|
| 525 |
+
t_634 = F.relu(t_633)
|
| 526 |
+
t_634_padded = F.pad(t_634, [1, 1, 1, 1], value=0)
|
| 527 |
+
t_635 = self.n_Conv_120(t_634_padded)
|
| 528 |
+
t_636 = F.relu(t_635)
|
| 529 |
+
t_637 = self.n_Conv_121(t_636)
|
| 530 |
+
t_638 = torch.add(t_637, t_632)
|
| 531 |
+
t_639 = F.relu(t_638)
|
| 532 |
+
t_640 = self.n_Conv_122(t_639)
|
| 533 |
+
t_641 = F.relu(t_640)
|
| 534 |
+
t_641_padded = F.pad(t_641, [1, 1, 1, 1], value=0)
|
| 535 |
+
t_642 = self.n_Conv_123(t_641_padded)
|
| 536 |
+
t_643 = F.relu(t_642)
|
| 537 |
+
t_644 = self.n_Conv_124(t_643)
|
| 538 |
+
t_645 = torch.add(t_644, t_639)
|
| 539 |
+
t_646 = F.relu(t_645)
|
| 540 |
+
t_647 = self.n_Conv_125(t_646)
|
| 541 |
+
t_648 = F.relu(t_647)
|
| 542 |
+
t_648_padded = F.pad(t_648, [1, 1, 1, 1], value=0)
|
| 543 |
+
t_649 = self.n_Conv_126(t_648_padded)
|
| 544 |
+
t_650 = F.relu(t_649)
|
| 545 |
+
t_651 = self.n_Conv_127(t_650)
|
| 546 |
+
t_652 = torch.add(t_651, t_646)
|
| 547 |
+
t_653 = F.relu(t_652)
|
| 548 |
+
t_654 = self.n_Conv_128(t_653)
|
| 549 |
+
t_655 = F.relu(t_654)
|
| 550 |
+
t_655_padded = F.pad(t_655, [1, 1, 1, 1], value=0)
|
| 551 |
+
t_656 = self.n_Conv_129(t_655_padded)
|
| 552 |
+
t_657 = F.relu(t_656)
|
| 553 |
+
t_658 = self.n_Conv_130(t_657)
|
| 554 |
+
t_659 = torch.add(t_658, t_653)
|
| 555 |
+
t_660 = F.relu(t_659)
|
| 556 |
+
t_661 = self.n_Conv_131(t_660)
|
| 557 |
+
t_662 = F.relu(t_661)
|
| 558 |
+
t_662_padded = F.pad(t_662, [1, 1, 1, 1], value=0)
|
| 559 |
+
t_663 = self.n_Conv_132(t_662_padded)
|
| 560 |
+
t_664 = F.relu(t_663)
|
| 561 |
+
t_665 = self.n_Conv_133(t_664)
|
| 562 |
+
t_666 = torch.add(t_665, t_660)
|
| 563 |
+
t_667 = F.relu(t_666)
|
| 564 |
+
t_668 = self.n_Conv_134(t_667)
|
| 565 |
+
t_669 = F.relu(t_668)
|
| 566 |
+
t_669_padded = F.pad(t_669, [1, 1, 1, 1], value=0)
|
| 567 |
+
t_670 = self.n_Conv_135(t_669_padded)
|
| 568 |
+
t_671 = F.relu(t_670)
|
| 569 |
+
t_672 = self.n_Conv_136(t_671)
|
| 570 |
+
t_673 = torch.add(t_672, t_667)
|
| 571 |
+
t_674 = F.relu(t_673)
|
| 572 |
+
t_675 = self.n_Conv_137(t_674)
|
| 573 |
+
t_676 = F.relu(t_675)
|
| 574 |
+
t_676_padded = F.pad(t_676, [1, 1, 1, 1], value=0)
|
| 575 |
+
t_677 = self.n_Conv_138(t_676_padded)
|
| 576 |
+
t_678 = F.relu(t_677)
|
| 577 |
+
t_679 = self.n_Conv_139(t_678)
|
| 578 |
+
t_680 = torch.add(t_679, t_674)
|
| 579 |
+
t_681 = F.relu(t_680)
|
| 580 |
+
t_682 = self.n_Conv_140(t_681)
|
| 581 |
+
t_683 = F.relu(t_682)
|
| 582 |
+
t_683_padded = F.pad(t_683, [1, 1, 1, 1], value=0)
|
| 583 |
+
t_684 = self.n_Conv_141(t_683_padded)
|
| 584 |
+
t_685 = F.relu(t_684)
|
| 585 |
+
t_686 = self.n_Conv_142(t_685)
|
| 586 |
+
t_687 = torch.add(t_686, t_681)
|
| 587 |
+
t_688 = F.relu(t_687)
|
| 588 |
+
t_689 = self.n_Conv_143(t_688)
|
| 589 |
+
t_690 = F.relu(t_689)
|
| 590 |
+
t_690_padded = F.pad(t_690, [1, 1, 1, 1], value=0)
|
| 591 |
+
t_691 = self.n_Conv_144(t_690_padded)
|
| 592 |
+
t_692 = F.relu(t_691)
|
| 593 |
+
t_693 = self.n_Conv_145(t_692)
|
| 594 |
+
t_694 = torch.add(t_693, t_688)
|
| 595 |
+
t_695 = F.relu(t_694)
|
| 596 |
+
t_696 = self.n_Conv_146(t_695)
|
| 597 |
+
t_697 = F.relu(t_696)
|
| 598 |
+
t_697_padded = F.pad(t_697, [1, 1, 1, 1], value=0)
|
| 599 |
+
t_698 = self.n_Conv_147(t_697_padded)
|
| 600 |
+
t_699 = F.relu(t_698)
|
| 601 |
+
t_700 = self.n_Conv_148(t_699)
|
| 602 |
+
t_701 = torch.add(t_700, t_695)
|
| 603 |
+
t_702 = F.relu(t_701)
|
| 604 |
+
t_703 = self.n_Conv_149(t_702)
|
| 605 |
+
t_704 = F.relu(t_703)
|
| 606 |
+
t_704_padded = F.pad(t_704, [1, 1, 1, 1], value=0)
|
| 607 |
+
t_705 = self.n_Conv_150(t_704_padded)
|
| 608 |
+
t_706 = F.relu(t_705)
|
| 609 |
+
t_707 = self.n_Conv_151(t_706)
|
| 610 |
+
t_708 = torch.add(t_707, t_702)
|
| 611 |
+
t_709 = F.relu(t_708)
|
| 612 |
+
t_710 = self.n_Conv_152(t_709)
|
| 613 |
+
t_711 = F.relu(t_710)
|
| 614 |
+
t_711_padded = F.pad(t_711, [1, 1, 1, 1], value=0)
|
| 615 |
+
t_712 = self.n_Conv_153(t_711_padded)
|
| 616 |
+
t_713 = F.relu(t_712)
|
| 617 |
+
t_714 = self.n_Conv_154(t_713)
|
| 618 |
+
t_715 = torch.add(t_714, t_709)
|
| 619 |
+
t_716 = F.relu(t_715)
|
| 620 |
+
t_717 = self.n_Conv_155(t_716)
|
| 621 |
+
t_718 = F.relu(t_717)
|
| 622 |
+
t_718_padded = F.pad(t_718, [1, 1, 1, 1], value=0)
|
| 623 |
+
t_719 = self.n_Conv_156(t_718_padded)
|
| 624 |
+
t_720 = F.relu(t_719)
|
| 625 |
+
t_721 = self.n_Conv_157(t_720)
|
| 626 |
+
t_722 = torch.add(t_721, t_716)
|
| 627 |
+
t_723 = F.relu(t_722)
|
| 628 |
+
t_724 = self.n_Conv_158(t_723)
|
| 629 |
+
t_725 = self.n_Conv_159(t_723)
|
| 630 |
+
t_726 = F.relu(t_725)
|
| 631 |
+
t_726_padded = F.pad(t_726, [0, 1, 0, 1], value=0)
|
| 632 |
+
t_727 = self.n_Conv_160(t_726_padded)
|
| 633 |
+
t_728 = F.relu(t_727)
|
| 634 |
+
t_729 = self.n_Conv_161(t_728)
|
| 635 |
+
t_730 = torch.add(t_729, t_724)
|
| 636 |
+
t_731 = F.relu(t_730)
|
| 637 |
+
t_732 = self.n_Conv_162(t_731)
|
| 638 |
+
t_733 = F.relu(t_732)
|
| 639 |
+
t_733_padded = F.pad(t_733, [1, 1, 1, 1], value=0)
|
| 640 |
+
t_734 = self.n_Conv_163(t_733_padded)
|
| 641 |
+
t_735 = F.relu(t_734)
|
| 642 |
+
t_736 = self.n_Conv_164(t_735)
|
| 643 |
+
t_737 = torch.add(t_736, t_731)
|
| 644 |
+
t_738 = F.relu(t_737)
|
| 645 |
+
t_739 = self.n_Conv_165(t_738)
|
| 646 |
+
t_740 = F.relu(t_739)
|
| 647 |
+
t_740_padded = F.pad(t_740, [1, 1, 1, 1], value=0)
|
| 648 |
+
t_741 = self.n_Conv_166(t_740_padded)
|
| 649 |
+
t_742 = F.relu(t_741)
|
| 650 |
+
t_743 = self.n_Conv_167(t_742)
|
| 651 |
+
t_744 = torch.add(t_743, t_738)
|
| 652 |
+
t_745 = F.relu(t_744)
|
| 653 |
+
t_746 = self.n_Conv_168(t_745)
|
| 654 |
+
t_747 = self.n_Conv_169(t_745)
|
| 655 |
+
t_748 = F.relu(t_747)
|
| 656 |
+
t_748_padded = F.pad(t_748, [0, 1, 0, 1], value=0)
|
| 657 |
+
t_749 = self.n_Conv_170(t_748_padded)
|
| 658 |
+
t_750 = F.relu(t_749)
|
| 659 |
+
t_751 = self.n_Conv_171(t_750)
|
| 660 |
+
t_752 = torch.add(t_751, t_746)
|
| 661 |
+
t_753 = F.relu(t_752)
|
| 662 |
+
t_754 = self.n_Conv_172(t_753)
|
| 663 |
+
t_755 = F.relu(t_754)
|
| 664 |
+
t_755_padded = F.pad(t_755, [1, 1, 1, 1], value=0)
|
| 665 |
+
t_756 = self.n_Conv_173(t_755_padded)
|
| 666 |
+
t_757 = F.relu(t_756)
|
| 667 |
+
t_758 = self.n_Conv_174(t_757)
|
| 668 |
+
t_759 = torch.add(t_758, t_753)
|
| 669 |
+
t_760 = F.relu(t_759)
|
| 670 |
+
t_761 = self.n_Conv_175(t_760)
|
| 671 |
+
t_762 = F.relu(t_761)
|
| 672 |
+
t_762_padded = F.pad(t_762, [1, 1, 1, 1], value=0)
|
| 673 |
+
t_763 = self.n_Conv_176(t_762_padded)
|
| 674 |
+
t_764 = F.relu(t_763)
|
| 675 |
+
t_765 = self.n_Conv_177(t_764)
|
| 676 |
+
t_766 = torch.add(t_765, t_760)
|
| 677 |
+
t_767 = F.relu(t_766)
|
| 678 |
+
t_768 = self.n_Conv_178(t_767)
|
| 679 |
+
t_769 = F.avg_pool2d(t_768, kernel_size=t_768.shape[-2:])
|
| 680 |
+
t_770 = torch.squeeze(t_769, 3)
|
| 681 |
+
t_770 = torch.squeeze(t_770, 2)
|
| 682 |
+
t_771 = torch.sigmoid(t_770)
|
| 683 |
+
return t_771
|
| 684 |
+
|
| 685 |
+
def load_state_dict(self, state_dict, **kwargs):
|
| 686 |
+
self.tags = state_dict.get('tags', [])
|
| 687 |
+
|
| 688 |
+
super(DeepDanbooruModel, self).load_state_dict({k: v for k, v in state_dict.items() if k != 'tags'})
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def resize_image(im, width, height):
|
| 692 |
+
ratio = width / height
|
| 693 |
+
src_ratio = im.width / im.height
|
| 694 |
+
|
| 695 |
+
src_w = width if ratio < src_ratio else im.width * height // im.height
|
| 696 |
+
src_h = height if ratio >= src_ratio else im.height * width // im.width
|
| 697 |
+
|
| 698 |
+
resized = im.resize((src_w, src_h), resample=LANCZOS)
|
| 699 |
+
res = Image.new("RGB", (width, height))
|
| 700 |
+
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
|
| 701 |
+
|
| 702 |
+
if ratio < src_ratio:
|
| 703 |
+
fill_height = height // 2 - src_h // 2
|
| 704 |
+
res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
|
| 705 |
+
res.paste(resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)),
|
| 706 |
+
box=(0, fill_height + src_h))
|
| 707 |
+
elif ratio > src_ratio:
|
| 708 |
+
fill_width = width // 2 - src_w // 2
|
| 709 |
+
res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
|
| 710 |
+
res.paste(resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)),
|
| 711 |
+
box=(fill_width + src_w, 0))
|
| 712 |
+
|
| 713 |
+
return res
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
class DeepDanbooru:
|
| 717 |
+
def __init__(self):
|
| 718 |
+
self.model = DeepDanbooruModel()
|
| 719 |
+
|
| 720 |
+
foundation_model_id = 'ly261666/cv_portrait_model'
|
| 721 |
+
snapshot_path = snapshot_download(foundation_model_id, revision='v4.0')
|
| 722 |
+
pretrain_model_path = os.path.join(snapshot_path, 'model-resnet_custom_v3.pt')
|
| 723 |
+
|
| 724 |
+
self.model.load_state_dict(torch.load(pretrain_model_path, map_location="cpu"))
|
| 725 |
+
self.model.eval()
|
| 726 |
+
self.model.to(torch.float16)
|
| 727 |
+
|
| 728 |
+
def start(self):
|
| 729 |
+
self.model.cuda()
|
| 730 |
+
|
| 731 |
+
def stop(self):
|
| 732 |
+
self.model.cpu()
|
| 733 |
+
torch.cuda.empty_cache()
|
| 734 |
+
torch.cuda.ipc_collect()
|
| 735 |
+
|
| 736 |
+
def tag(self, pil_image):
|
| 737 |
+
threshold = 0.5
|
| 738 |
+
use_spaces = False
|
| 739 |
+
use_escape = True
|
| 740 |
+
alpha_sort = True
|
| 741 |
+
include_ranks = False
|
| 742 |
+
|
| 743 |
+
pic = resize_image(pil_image.convert("RGB"), 512, 512)
|
| 744 |
+
a = np.expand_dims(np.array(pic, dtype=np.float32), 0) / 255
|
| 745 |
+
|
| 746 |
+
with torch.no_grad(), torch.autocast("cuda"):
|
| 747 |
+
x = torch.from_numpy(a).cuda()
|
| 748 |
+
y = self.model(x)[0].detach().cpu().numpy()
|
| 749 |
+
|
| 750 |
+
probability_dict = {}
|
| 751 |
+
|
| 752 |
+
for tag, probability in zip(self.model.tags, y):
|
| 753 |
+
if probability < threshold:
|
| 754 |
+
continue
|
| 755 |
+
|
| 756 |
+
if tag.startswith("rating:"):
|
| 757 |
+
continue
|
| 758 |
+
|
| 759 |
+
probability_dict[tag] = probability
|
| 760 |
+
|
| 761 |
+
if alpha_sort:
|
| 762 |
+
tags = sorted(probability_dict)
|
| 763 |
+
else:
|
| 764 |
+
tags = [tag for tag, _ in sorted(probability_dict.items(), key=lambda x: -x[1])]
|
| 765 |
+
|
| 766 |
+
res = []
|
| 767 |
+
|
| 768 |
+
for tag in [x for x in tags]:
|
| 769 |
+
probability = probability_dict[tag]
|
| 770 |
+
tag_outformat = tag
|
| 771 |
+
if use_spaces:
|
| 772 |
+
tag_outformat = tag_outformat.replace('_', ' ')
|
| 773 |
+
if use_escape:
|
| 774 |
+
tag_outformat = re.sub(re_special, r'\\\1', tag_outformat)
|
| 775 |
+
if include_ranks:
|
| 776 |
+
tag_outformat = f"({tag_outformat}:{probability:.3f})"
|
| 777 |
+
|
| 778 |
+
res.append(tag_outformat)
|
| 779 |
+
|
| 780 |
+
return ", ".join(res)
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
'''
|
| 784 |
+
model = DeepDanbooru()
|
| 785 |
+
impath = 'lyf'
|
| 786 |
+
imlist = os.listdir(impath)
|
| 787 |
+
result_list = []
|
| 788 |
+
for im in imlist:
|
| 789 |
+
if im[-4:]=='.png':
|
| 790 |
+
print(im)
|
| 791 |
+
img = Image.open(os.path.join(impath, im))
|
| 792 |
+
result = model.tag(img)
|
| 793 |
+
print(result)
|
| 794 |
+
result_list.append(result)
|
| 795 |
+
model.stop()
|
| 796 |
+
'''
|
facechain/facechain/data_process/preprocessing.py
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
|
| 8 |
+
import cv2
|
| 9 |
+
import numpy as np
|
| 10 |
+
from modelscope.outputs import OutputKeys
|
| 11 |
+
from modelscope.pipelines import pipeline
|
| 12 |
+
from modelscope.utils.constant import Tasks
|
| 13 |
+
from PIL import Image
|
| 14 |
+
from tqdm import tqdm
|
| 15 |
+
|
| 16 |
+
from .deepbooru import DeepDanbooru
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def crop_and_resize(im, bbox):
|
| 21 |
+
h, w, _ = im.shape
|
| 22 |
+
thre = 0.35/1.15
|
| 23 |
+
maxf = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
|
| 24 |
+
cx = (bbox[2] + bbox[0]) / 2
|
| 25 |
+
cy = (bbox[3] + bbox[1]) / 2
|
| 26 |
+
lenp = int(maxf / thre)
|
| 27 |
+
yc = 0.5/1.15
|
| 28 |
+
xc = 0.5
|
| 29 |
+
xmin = int(cx - xc * lenp)
|
| 30 |
+
xmax = xmin + lenp
|
| 31 |
+
ymin = int(cy - yc * lenp)
|
| 32 |
+
ymax = ymin + lenp
|
| 33 |
+
x1 = 0
|
| 34 |
+
x2 = lenp
|
| 35 |
+
y1 = 0
|
| 36 |
+
y2 = lenp
|
| 37 |
+
if xmin < 0:
|
| 38 |
+
x1 = -xmin
|
| 39 |
+
xmin = 0
|
| 40 |
+
if xmax > w:
|
| 41 |
+
x2 = w - (xmax - lenp)
|
| 42 |
+
xmax = w
|
| 43 |
+
if ymin < 0:
|
| 44 |
+
y1 = -ymin
|
| 45 |
+
ymin = 0
|
| 46 |
+
if ymax > h:
|
| 47 |
+
y2 = h - (ymax - lenp)
|
| 48 |
+
ymax = h
|
| 49 |
+
imc = (np.ones((lenp, lenp, 3)) * 255).astype(np.uint8)
|
| 50 |
+
imc[y1:y2, x1:x2, :] = im[ymin:ymax, xmin:xmax, :]
|
| 51 |
+
imr = cv2.resize(imc, (512, 512))
|
| 52 |
+
return imr
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def pad_to_square(im):
|
| 56 |
+
h, w, _ = im.shape
|
| 57 |
+
ns = int(max(h, w) * 1.5)
|
| 58 |
+
im = cv2.copyMakeBorder(im, int((ns - h) / 2), (ns - h) - int((ns - h) / 2), int((ns - w) / 2),
|
| 59 |
+
(ns - w) - int((ns - w) / 2), cv2.BORDER_CONSTANT, 255)
|
| 60 |
+
return im
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def post_process_naive(result_list, score_gender, score_age):
|
| 64 |
+
# determine trigger word
|
| 65 |
+
gender = np.argmax(score_gender)
|
| 66 |
+
age = np.argmax(score_age)
|
| 67 |
+
if age < 2:
|
| 68 |
+
if gender == 0:
|
| 69 |
+
tag_a_g = ['a boy', 'children']
|
| 70 |
+
else:
|
| 71 |
+
tag_a_g = ['a girl', 'children']
|
| 72 |
+
elif age > 4:
|
| 73 |
+
if gender == 0:
|
| 74 |
+
tag_a_g = ['a mature man']
|
| 75 |
+
else:
|
| 76 |
+
tag_a_g = ['a mature woman']
|
| 77 |
+
else:
|
| 78 |
+
if gender == 0:
|
| 79 |
+
tag_a_g = ['a handsome man']
|
| 80 |
+
else:
|
| 81 |
+
tag_a_g = ['a beautiful woman']
|
| 82 |
+
num_images = len(result_list)
|
| 83 |
+
cnt_girl = 0
|
| 84 |
+
cnt_boy = 0
|
| 85 |
+
result_list_new = []
|
| 86 |
+
for result in result_list:
|
| 87 |
+
result_new = []
|
| 88 |
+
result_new.extend(tag_a_g)
|
| 89 |
+
## don't include other infos for lora training
|
| 90 |
+
#for tag in result:
|
| 91 |
+
# if tag == '1girl' or tag == '1boy':
|
| 92 |
+
# continue
|
| 93 |
+
# if tag[-4:] == '_man':
|
| 94 |
+
# continue
|
| 95 |
+
# if tag[-6:] == '_woman':
|
| 96 |
+
# continue
|
| 97 |
+
# if tag[-5:] == '_male':
|
| 98 |
+
# continue
|
| 99 |
+
# elif tag[-7:] == '_female':
|
| 100 |
+
# continue
|
| 101 |
+
# elif (
|
| 102 |
+
# tag == 'ears' or tag == 'head' or tag == 'face' or tag == 'lips' or tag == 'mouth' or tag == '3d' or tag == 'asian' or tag == 'teeth'):
|
| 103 |
+
# continue
|
| 104 |
+
# elif ('eye' in tag and not 'eyewear' in tag):
|
| 105 |
+
# continue
|
| 106 |
+
# elif ('nose' in tag or 'body' in tag):
|
| 107 |
+
# continue
|
| 108 |
+
# elif tag[-5:] == '_lips':
|
| 109 |
+
# continue
|
| 110 |
+
# else:
|
| 111 |
+
# result_new.append(tag)
|
| 112 |
+
# # import pdb;pdb.set_trace()
|
| 113 |
+
## result_new.append('slim body')
|
| 114 |
+
result_list_new.append(result_new)
|
| 115 |
+
|
| 116 |
+
return result_list_new
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def transformation_from_points(points1, points2):
|
| 120 |
+
points1 = points1.astype(np.float64)
|
| 121 |
+
points2 = points2.astype(np.float64)
|
| 122 |
+
c1 = np.mean(points1, axis=0)
|
| 123 |
+
c2 = np.mean(points2, axis=0)
|
| 124 |
+
points1 -= c1
|
| 125 |
+
points2 -= c2
|
| 126 |
+
s1 = np.std(points1)
|
| 127 |
+
s2 = np.std(points2)
|
| 128 |
+
if s1 < 1.0e-4:
|
| 129 |
+
s1 = 1.0e-4
|
| 130 |
+
points1 /= s1
|
| 131 |
+
points2 /= s2
|
| 132 |
+
U, S, Vt = np.linalg.svd(points1.T * points2)
|
| 133 |
+
R = (U * Vt).T
|
| 134 |
+
return np.vstack([np.hstack(((s2 / s1) * R, c2.T - (s2 / s1) * R * c1.T)), np.matrix([0., 0., 1.])])
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def rotate(im, keypoints):
|
| 138 |
+
h, w, _ = im.shape
|
| 139 |
+
points_array = np.zeros((5, 2))
|
| 140 |
+
dst_mean_face_size = 160
|
| 141 |
+
dst_mean_face = np.asarray([0.31074522411511746, 0.2798131190011913,
|
| 142 |
+
0.6892073313037804, 0.2797830232679366,
|
| 143 |
+
0.49997367716346774, 0.5099309118810921,
|
| 144 |
+
0.35811903020866753, 0.7233174007629063,
|
| 145 |
+
0.6418878095835022, 0.7232890570786875])
|
| 146 |
+
dst_mean_face = np.reshape(dst_mean_face, (5, 2)) * dst_mean_face_size
|
| 147 |
+
|
| 148 |
+
for k in range(5):
|
| 149 |
+
points_array[k, 0] = keypoints[2 * k]
|
| 150 |
+
points_array[k, 1] = keypoints[2 * k + 1]
|
| 151 |
+
|
| 152 |
+
pts1 = np.float64(np.matrix([[point[0], point[1]] for point in points_array]))
|
| 153 |
+
pts2 = np.float64(np.matrix([[point[0], point[1]] for point in dst_mean_face]))
|
| 154 |
+
trans_mat = transformation_from_points(pts1, pts2)
|
| 155 |
+
if trans_mat[1, 1] > 1.0e-4:
|
| 156 |
+
angle = math.atan(trans_mat[1, 0] / trans_mat[1, 1])
|
| 157 |
+
else:
|
| 158 |
+
angle = math.atan(trans_mat[0, 1] / trans_mat[0, 2])
|
| 159 |
+
im = pad_to_square(im)
|
| 160 |
+
ns = int(1.5 * max(h, w))
|
| 161 |
+
M = cv2.getRotationMatrix2D((ns / 2, ns / 2), angle=-angle / np.pi * 180, scale=1.0)
|
| 162 |
+
im = cv2.warpAffine(im, M=M, dsize=(ns, ns))
|
| 163 |
+
return im
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def get_mask_head(result):
|
| 167 |
+
masks = result['masks']
|
| 168 |
+
scores = result['scores']
|
| 169 |
+
labels = result['labels']
|
| 170 |
+
mask_hair = np.zeros((512, 512))
|
| 171 |
+
mask_face = np.zeros((512, 512))
|
| 172 |
+
mask_human = np.zeros((512, 512))
|
| 173 |
+
for i in range(len(labels)):
|
| 174 |
+
if scores[i] > 0.8:
|
| 175 |
+
if labels[i] == 'Face':
|
| 176 |
+
if np.sum(masks[i]) > np.sum(mask_face):
|
| 177 |
+
mask_face = masks[i]
|
| 178 |
+
elif labels[i] == 'Human':
|
| 179 |
+
if np.sum(masks[i]) > np.sum(mask_human):
|
| 180 |
+
mask_human = masks[i]
|
| 181 |
+
elif labels[i] == 'Hair':
|
| 182 |
+
if np.sum(masks[i]) > np.sum(mask_hair):
|
| 183 |
+
mask_hair = masks[i]
|
| 184 |
+
mask_head = np.clip(mask_hair + mask_face, 0, 1)
|
| 185 |
+
ksize = max(int(np.sqrt(np.sum(mask_face)) / 20), 1)
|
| 186 |
+
kernel = np.ones((ksize, ksize))
|
| 187 |
+
mask_head = cv2.dilate(mask_head, kernel, iterations=1) * mask_human
|
| 188 |
+
_, mask_head = cv2.threshold((mask_head * 255).astype(np.uint8), 127, 255, cv2.THRESH_BINARY)
|
| 189 |
+
contours, hierarchy = cv2.findContours(mask_head, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
|
| 190 |
+
area = []
|
| 191 |
+
for j in range(len(contours)):
|
| 192 |
+
area.append(cv2.contourArea(contours[j]))
|
| 193 |
+
max_idx = np.argmax(area)
|
| 194 |
+
mask_head = np.zeros((512, 512)).astype(np.uint8)
|
| 195 |
+
cv2.fillPoly(mask_head, [contours[max_idx]], 255)
|
| 196 |
+
mask_head = mask_head.astype(np.float32) / 255
|
| 197 |
+
mask_head = np.clip(mask_head + mask_face, 0, 1)
|
| 198 |
+
mask_head = np.expand_dims(mask_head, 2)
|
| 199 |
+
return mask_head
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class Blipv2():
|
| 203 |
+
def __init__(self):
|
| 204 |
+
self.model = DeepDanbooru()
|
| 205 |
+
self.skin_retouching = pipeline('skin-retouching-torch', model='damo/cv_unet_skin_retouching_torch', model_revision='v1.0.1')
|
| 206 |
+
self.face_detection = pipeline(task=Tasks.face_detection, model='damo/cv_ddsar_face-detection_iclr23-damofd', model_revision='v1.1')
|
| 207 |
+
# self.mog_face_detection_func = pipeline(Tasks.face_detection, 'damo/cv_resnet101_face-detection_cvpr22papermogface')
|
| 208 |
+
self.segmentation_pipeline = pipeline(Tasks.image_segmentation,
|
| 209 |
+
'damo/cv_resnet101_image-multiple-human-parsing', model_revision='v1.0.1')
|
| 210 |
+
self.fair_face_attribute_func = pipeline(Tasks.face_attribute_recognition,
|
| 211 |
+
'damo/cv_resnet34_face-attribute-recognition_fairface', model_revision='v2.0.2')
|
| 212 |
+
self.facial_landmark_confidence_func = pipeline(Tasks.face_2d_keypoints,
|
| 213 |
+
'damo/cv_manual_facial-landmark-confidence_flcm', model_revision='v2.5')
|
| 214 |
+
|
| 215 |
+
def __call__(self, imdir):
|
| 216 |
+
self.model.start()
|
| 217 |
+
savedir = str(imdir) + '_labeled'
|
| 218 |
+
shutil.rmtree(savedir, ignore_errors=True)
|
| 219 |
+
os.makedirs(savedir, exist_ok=True)
|
| 220 |
+
|
| 221 |
+
imlist = os.listdir(imdir)
|
| 222 |
+
result_list = []
|
| 223 |
+
imgs_list = []
|
| 224 |
+
|
| 225 |
+
cnt = 0
|
| 226 |
+
tmp_path = os.path.join(savedir, 'tmp.png')
|
| 227 |
+
for imname in imlist:
|
| 228 |
+
try:
|
| 229 |
+
# if 1:
|
| 230 |
+
if imname.startswith('.'):
|
| 231 |
+
continue
|
| 232 |
+
img_path = os.path.join(imdir, imname)
|
| 233 |
+
im = cv2.imread(img_path)
|
| 234 |
+
h, w, _ = im.shape
|
| 235 |
+
max_size = max(w, h)
|
| 236 |
+
ratio = 1024 / max_size
|
| 237 |
+
new_w = round(w * ratio)
|
| 238 |
+
new_h = round(h * ratio)
|
| 239 |
+
imt = cv2.resize(im, (new_w, new_h))
|
| 240 |
+
cv2.imwrite(tmp_path, imt)
|
| 241 |
+
result_det = self.face_detection(tmp_path)
|
| 242 |
+
bboxes = result_det['boxes']
|
| 243 |
+
if len(bboxes) > 1:
|
| 244 |
+
areas = []
|
| 245 |
+
for i in range(len(bboxes)):
|
| 246 |
+
bbox = bboxes[i]
|
| 247 |
+
areas.append((bbox[2] - bbox[0]) * (bbox[3] - bbox[1]))
|
| 248 |
+
areas = np.array(areas)
|
| 249 |
+
areas_new = np.sort(areas)[::-1]
|
| 250 |
+
idxs = np.argsort(areas)[::-1]
|
| 251 |
+
if areas_new[0] < 4 * areas_new[1]:
|
| 252 |
+
print('Detecting multiple faces, do not use image {}.'.format(imname))
|
| 253 |
+
continue
|
| 254 |
+
else:
|
| 255 |
+
keypoints = result_det['keypoints'][idxs[0]]
|
| 256 |
+
elif len(bboxes) == 0:
|
| 257 |
+
print('Detecting no face, do not use image {}.'.format(imname))
|
| 258 |
+
continue
|
| 259 |
+
else:
|
| 260 |
+
keypoints = result_det['keypoints'][0]
|
| 261 |
+
|
| 262 |
+
im = rotate(im, keypoints)
|
| 263 |
+
ns = im.shape[0]
|
| 264 |
+
imt = cv2.resize(im, (1024, 1024))
|
| 265 |
+
cv2.imwrite(tmp_path, imt)
|
| 266 |
+
result_det = self.face_detection(tmp_path)
|
| 267 |
+
bboxes = result_det['boxes']
|
| 268 |
+
|
| 269 |
+
if len(bboxes) > 1:
|
| 270 |
+
areas = []
|
| 271 |
+
for i in range(len(bboxes)):
|
| 272 |
+
bbox = bboxes[i]
|
| 273 |
+
areas.append((bbox[2] - bbox[0]) * (bbox[3] - bbox[1]))
|
| 274 |
+
areas = np.array(areas)
|
| 275 |
+
areas_new = np.sort(areas)[::-1]
|
| 276 |
+
idxs = np.argsort(areas)[::-1]
|
| 277 |
+
if areas_new[0] < 4 * areas_new[1]:
|
| 278 |
+
print('Detecting multiple faces after rotation, do not use image {}.'.format(imname))
|
| 279 |
+
continue
|
| 280 |
+
else:
|
| 281 |
+
bbox = bboxes[idxs[0]]
|
| 282 |
+
elif len(bboxes) == 0:
|
| 283 |
+
print('Detecting no face after rotation, do not use this image {}'.format(imname))
|
| 284 |
+
continue
|
| 285 |
+
else:
|
| 286 |
+
bbox = bboxes[0]
|
| 287 |
+
|
| 288 |
+
for idx in range(4):
|
| 289 |
+
bbox[idx] = bbox[idx] * ns / 1024
|
| 290 |
+
imr = crop_and_resize(im, bbox)
|
| 291 |
+
cv2.imwrite(tmp_path, imr)
|
| 292 |
+
|
| 293 |
+
result = self.skin_retouching(tmp_path)
|
| 294 |
+
if (result is None or (result[OutputKeys.OUTPUT_IMG] is None)):
|
| 295 |
+
print('Cannot do skin retouching, do not use this image.')
|
| 296 |
+
continue
|
| 297 |
+
cv2.imwrite(tmp_path, result[OutputKeys.OUTPUT_IMG])
|
| 298 |
+
|
| 299 |
+
result = self.segmentation_pipeline(tmp_path)
|
| 300 |
+
mask_head = get_mask_head(result)
|
| 301 |
+
im = cv2.imread(tmp_path)
|
| 302 |
+
im = im * mask_head + 255 * (1 - mask_head)
|
| 303 |
+
# print(im.shape)
|
| 304 |
+
|
| 305 |
+
raw_result = self.facial_landmark_confidence_func(im)
|
| 306 |
+
if raw_result is None:
|
| 307 |
+
print('landmark quality fail...')
|
| 308 |
+
continue
|
| 309 |
+
|
| 310 |
+
print(imname, raw_result['scores'][0])
|
| 311 |
+
if float(raw_result['scores'][0]) < (1 - 0.145):
|
| 312 |
+
print('landmark quality fail...')
|
| 313 |
+
continue
|
| 314 |
+
|
| 315 |
+
cv2.imwrite(os.path.join(savedir, '{}.png'.format(cnt)), im)
|
| 316 |
+
imgs_list.append('{}.png'.format(cnt))
|
| 317 |
+
img = Image.open(os.path.join(savedir, '{}.png'.format(cnt)))
|
| 318 |
+
result = self.model.tag(img)
|
| 319 |
+
print(result)
|
| 320 |
+
attribute_result = self.fair_face_attribute_func(tmp_path)
|
| 321 |
+
if cnt == 0:
|
| 322 |
+
score_gender = np.array(attribute_result['scores'][0])
|
| 323 |
+
score_age = np.array(attribute_result['scores'][1])
|
| 324 |
+
else:
|
| 325 |
+
score_gender += np.array(attribute_result['scores'][0])
|
| 326 |
+
score_age += np.array(attribute_result['scores'][1])
|
| 327 |
+
|
| 328 |
+
result_list.append(result.split(', '))
|
| 329 |
+
cnt += 1
|
| 330 |
+
except Exception as e:
|
| 331 |
+
print('cathed for image process of ' + imname)
|
| 332 |
+
print(f'Error: {e}')
|
| 333 |
+
|
| 334 |
+
print(result_list)
|
| 335 |
+
if len(result_list) == 0:
|
| 336 |
+
print('Error: result is empty.')
|
| 337 |
+
exit()
|
| 338 |
+
# return os.path.join(savedir, "metadata.jsonl")
|
| 339 |
+
|
| 340 |
+
result_list = post_process_naive(result_list, score_gender, score_age)
|
| 341 |
+
self.model.stop()
|
| 342 |
+
try:
|
| 343 |
+
os.remove(tmp_path)
|
| 344 |
+
except OSError as e:
|
| 345 |
+
print(f"Failed to remove path {tmp_path}: {e}")
|
| 346 |
+
|
| 347 |
+
out_json_name = os.path.join(savedir, "metadata.jsonl")
|
| 348 |
+
fo = open(out_json_name, 'w')
|
| 349 |
+
for i in range(len(result_list)):
|
| 350 |
+
generated_text = ", ".join(result_list[i])
|
| 351 |
+
print(imgs_list[i], generated_text)
|
| 352 |
+
info_dict = {"file_name": imgs_list[i], "text": "<fcsks>, " + generated_text}
|
| 353 |
+
fo.write(json.dumps(info_dict) + '\n')
|
| 354 |
+
fo.close()
|
| 355 |
+
return out_json_name
|
facechain/facechain/inference.py
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
import cv2
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from controlnet_aux import OpenposeDetector
|
| 10 |
+
from diffusers import StableDiffusionPipeline, StableDiffusionControlNetPipeline, ControlNetModel, \
|
| 11 |
+
UniPCMultistepScheduler
|
| 12 |
+
from facechain.utils import snapshot_download
|
| 13 |
+
from modelscope.outputs import OutputKeys
|
| 14 |
+
from modelscope.pipelines import pipeline
|
| 15 |
+
from modelscope.utils.constant import Tasks
|
| 16 |
+
from torch import multiprocessing
|
| 17 |
+
from transformers import pipeline as tpipeline
|
| 18 |
+
|
| 19 |
+
from facechain.data_process.preprocessing import Blipv2
|
| 20 |
+
from facechain.merge_lora import merge_lora
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _data_process_fn_process(input_img_dir):
|
| 24 |
+
Blipv2()(input_img_dir)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def data_process_fn(input_img_dir, use_data_process):
|
| 28 |
+
## TODO add face quality filter
|
| 29 |
+
if use_data_process:
|
| 30 |
+
## TODO
|
| 31 |
+
|
| 32 |
+
_process = multiprocessing.Process(target=_data_process_fn_process, args=(input_img_dir,))
|
| 33 |
+
_process.start()
|
| 34 |
+
_process.join()
|
| 35 |
+
|
| 36 |
+
return os.path.join(str(input_img_dir) + '_labeled', "metadata.jsonl")
|
| 37 |
+
|
| 38 |
+
def txt2img(pipe, pos_prompt, neg_prompt, num_images=10):
|
| 39 |
+
batch_size = 5
|
| 40 |
+
images_out = []
|
| 41 |
+
for i in range(int(num_images / batch_size)):
|
| 42 |
+
images_style = pipe(prompt=pos_prompt, height=512, width=512, guidance_scale=7, negative_prompt=neg_prompt,
|
| 43 |
+
num_inference_steps=40, num_images_per_prompt=batch_size).images
|
| 44 |
+
images_out.extend(images_style)
|
| 45 |
+
return images_out
|
| 46 |
+
|
| 47 |
+
def img_pad(pil_file, fixed_height=512, fixed_width=512):
|
| 48 |
+
w, h = pil_file.size
|
| 49 |
+
|
| 50 |
+
if h / float(fixed_height) >= w / float(fixed_width):
|
| 51 |
+
factor = h / float(fixed_height)
|
| 52 |
+
new_w = int(w / factor)
|
| 53 |
+
pil_file.thumbnail(size=(new_w, fixed_height))
|
| 54 |
+
pad_w = int((fixed_width - new_w) / 2)
|
| 55 |
+
pad_w1 = (fixed_width - new_w) - pad_w
|
| 56 |
+
array_file = np.array(pil_file)
|
| 57 |
+
array_file = np.pad(array_file, ((0, 0), (pad_w, pad_w1), (0, 0)), 'constant')
|
| 58 |
+
else:
|
| 59 |
+
factor = w / float(fixed_width)
|
| 60 |
+
new_h = int(h / factor)
|
| 61 |
+
pil_file.thumbnail(size=(fixed_width, new_h))
|
| 62 |
+
pad_h = fixed_height - new_h
|
| 63 |
+
pad_h1 = 0
|
| 64 |
+
array_file = np.array(pil_file)
|
| 65 |
+
array_file = np.pad(array_file, ((pad_h, pad_h1), (0, 0), (0, 0)), 'constant')
|
| 66 |
+
|
| 67 |
+
output_file = Image.fromarray(array_file)
|
| 68 |
+
return output_file
|
| 69 |
+
|
| 70 |
+
def preprocess_pose(origin_img) -> Image:
|
| 71 |
+
img = Image.open(origin_img)
|
| 72 |
+
img = img_pad(img)
|
| 73 |
+
model_dir = snapshot_download('damo/face_chain_control_model',revision='v1.0.1')
|
| 74 |
+
openpose = OpenposeDetector.from_pretrained(os.path.join(model_dir, 'model_controlnet/ControlNet'))
|
| 75 |
+
result = openpose(img, include_hand=True, output_type='np')
|
| 76 |
+
# resize to original size
|
| 77 |
+
h, w = img.size
|
| 78 |
+
result = cv2.resize(result, (w, h))
|
| 79 |
+
return result
|
| 80 |
+
|
| 81 |
+
def txt2img_pose(pipe, pose_im, pos_prompt, neg_prompt, num_images=10):
|
| 82 |
+
batch_size = 2
|
| 83 |
+
images_out = []
|
| 84 |
+
for i in range(int(num_images / batch_size)):
|
| 85 |
+
images_style = pipe(prompt=pos_prompt, image=pose_im, height=512, width=512, guidance_scale=7, negative_prompt=neg_prompt,
|
| 86 |
+
num_inference_steps=40, num_images_per_prompt=batch_size).images
|
| 87 |
+
images_out.extend(images_style)
|
| 88 |
+
return images_out
|
| 89 |
+
|
| 90 |
+
def txt2img_multi(pipe, images, pos_prompt, neg_prompt, num_images=10):
|
| 91 |
+
batch_size = 2
|
| 92 |
+
images_out = []
|
| 93 |
+
for i in range(int(num_images / batch_size)):
|
| 94 |
+
images_style = pipe(pos_prompt, images, height=512, width=512, guidance_scale=7, negative_prompt=neg_prompt, controlnet_conditioning_scale=[1.0, 0.5],
|
| 95 |
+
num_inference_steps=40, num_images_per_prompt=batch_size).images
|
| 96 |
+
images_out.extend(images_style)
|
| 97 |
+
return images_out
|
| 98 |
+
|
| 99 |
+
def get_mask(result):
|
| 100 |
+
masks = result['masks']
|
| 101 |
+
scores = result['scores']
|
| 102 |
+
labels = result['labels']
|
| 103 |
+
h, w = masks[0].shape
|
| 104 |
+
mask_hair = np.zeros((h, w))
|
| 105 |
+
mask_face = np.zeros((h, w))
|
| 106 |
+
mask_human = np.zeros((h, w))
|
| 107 |
+
for i in range(len(labels)):
|
| 108 |
+
if scores[i] > 0.8:
|
| 109 |
+
if labels[i] == 'Face':
|
| 110 |
+
if np.sum(masks[i]) > np.sum(mask_face):
|
| 111 |
+
mask_face = masks[i]
|
| 112 |
+
elif labels[i] == 'Human':
|
| 113 |
+
if np.sum(masks[i]) > np.sum(mask_human):
|
| 114 |
+
mask_human = masks[i]
|
| 115 |
+
elif labels[i] == 'Hair':
|
| 116 |
+
if np.sum(masks[i]) > np.sum(mask_hair):
|
| 117 |
+
mask_hair = masks[i]
|
| 118 |
+
mask_rst = np.clip(mask_human - mask_hair - mask_face, 0, 1)
|
| 119 |
+
mask_rst = np.expand_dims(mask_rst, 2)
|
| 120 |
+
mask_rst = np.concatenate([mask_rst, mask_rst, mask_rst], axis=2)
|
| 121 |
+
return mask_rst
|
| 122 |
+
|
| 123 |
+
def main_diffusion_inference(pos_prompt, neg_prompt,
|
| 124 |
+
input_img_dir, base_model_path, style_model_path, lora_model_path,
|
| 125 |
+
multiplier_style=0.25,
|
| 126 |
+
multiplier_human=0.85):
|
| 127 |
+
if style_model_path is None:
|
| 128 |
+
model_dir = snapshot_download('Cherrytest/zjz_mj_jiyi_small_addtxt_fromleo', revision='v1.0.0')
|
| 129 |
+
style_model_path = os.path.join(model_dir, 'zjz_mj_jiyi_small_addtxt_fromleo.safetensors')
|
| 130 |
+
|
| 131 |
+
pipe = StableDiffusionPipeline.from_pretrained(base_model_path, safety_checker=None, torch_dtype=torch.float32)
|
| 132 |
+
lora_style_path = style_model_path
|
| 133 |
+
lora_human_path = lora_model_path
|
| 134 |
+
pipe = merge_lora(pipe, lora_style_path, multiplier_style, from_safetensor=True)
|
| 135 |
+
pipe = merge_lora(pipe, lora_human_path, multiplier_human, from_safetensor=lora_human_path.endswith('safetensors'))
|
| 136 |
+
print(f'multiplier_style:{multiplier_style}, multiplier_human:{multiplier_human}')
|
| 137 |
+
|
| 138 |
+
train_dir = str(input_img_dir) + '_labeled'
|
| 139 |
+
add_prompt_style = []
|
| 140 |
+
f = open(os.path.join(train_dir, 'metadata.jsonl'), 'r')
|
| 141 |
+
tags_all = []
|
| 142 |
+
cnt = 0
|
| 143 |
+
cnts_trigger = np.zeros(6)
|
| 144 |
+
for line in f:
|
| 145 |
+
cnt += 1
|
| 146 |
+
data = json.loads(line)['text'].split(', ')
|
| 147 |
+
tags_all.extend(data)
|
| 148 |
+
if data[1] == 'a boy':
|
| 149 |
+
cnts_trigger[0] += 1
|
| 150 |
+
elif data[1] == 'a girl':
|
| 151 |
+
cnts_trigger[1] += 1
|
| 152 |
+
elif data[1] == 'a handsome man':
|
| 153 |
+
cnts_trigger[2] += 1
|
| 154 |
+
elif data[1] == 'a beautiful woman':
|
| 155 |
+
cnts_trigger[3] += 1
|
| 156 |
+
elif data[1] == 'a mature man':
|
| 157 |
+
cnts_trigger[4] += 1
|
| 158 |
+
elif data[1] == 'a mature woman':
|
| 159 |
+
cnts_trigger[5] += 1
|
| 160 |
+
else:
|
| 161 |
+
print('Error.')
|
| 162 |
+
f.close()
|
| 163 |
+
|
| 164 |
+
attr_idx = np.argmax(cnts_trigger)
|
| 165 |
+
trigger_styles = ['a boy, children, ', 'a girl, children, ', 'a handsome man, ', 'a beautiful woman, ',
|
| 166 |
+
'a mature man, ', 'a mature woman, ']
|
| 167 |
+
trigger_style = '<fcsks>, ' + trigger_styles[attr_idx]
|
| 168 |
+
if attr_idx == 2 or attr_idx == 4:
|
| 169 |
+
neg_prompt += ', children'
|
| 170 |
+
|
| 171 |
+
for tag in tags_all:
|
| 172 |
+
if tags_all.count(tag) > 0.5 * cnt:
|
| 173 |
+
if ('hair' in tag or 'face' in tag or 'mouth' in tag or 'skin' in tag or 'smile' in tag):
|
| 174 |
+
if not tag in add_prompt_style:
|
| 175 |
+
add_prompt_style.append(tag)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
if len(add_prompt_style) > 0:
|
| 180 |
+
add_prompt_style = ", ".join(add_prompt_style) + ', '
|
| 181 |
+
else:
|
| 182 |
+
add_prompt_style = ''
|
| 183 |
+
|
| 184 |
+
pipe = pipe.to("cuda")
|
| 185 |
+
images_style = txt2img(pipe, trigger_style + add_prompt_style + pos_prompt, neg_prompt, num_images=10)
|
| 186 |
+
return images_style
|
| 187 |
+
|
| 188 |
+
def main_diffusion_inference_pose(pose_model_path, pose_image,
|
| 189 |
+
pos_prompt, neg_prompt,
|
| 190 |
+
input_img_dir, base_model_path, style_model_path, lora_model_path,
|
| 191 |
+
multiplier_style=0.25,
|
| 192 |
+
multiplier_human=0.85):
|
| 193 |
+
if style_model_path is None:
|
| 194 |
+
model_dir = snapshot_download('Cherrytest/zjz_mj_jiyi_small_addtxt_fromleo', revision='v1.0.0')
|
| 195 |
+
style_model_path = os.path.join(model_dir, 'zjz_mj_jiyi_small_addtxt_fromleo.safetensors')
|
| 196 |
+
|
| 197 |
+
controlnet = ControlNetModel.from_pretrained(pose_model_path, torch_dtype=torch.float32)
|
| 198 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(base_model_path, safety_checker=None, controlnet=controlnet, torch_dtype=torch.float32)
|
| 199 |
+
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
|
| 200 |
+
pose_im = Image.open(pose_image)
|
| 201 |
+
pose_im = img_pad(pose_im)
|
| 202 |
+
model_dir = snapshot_download('damo/face_chain_control_model',revision='v1.0.1')
|
| 203 |
+
openpose = OpenposeDetector.from_pretrained(os.path.join(model_dir, 'model_controlnet/ControlNet'))
|
| 204 |
+
pose_im = openpose(pose_im, include_hand=True)
|
| 205 |
+
|
| 206 |
+
lora_style_path = style_model_path
|
| 207 |
+
lora_human_path = lora_model_path
|
| 208 |
+
pipe = merge_lora(pipe, lora_style_path, multiplier_style, from_safetensor=True)
|
| 209 |
+
pipe = merge_lora(pipe, lora_human_path, multiplier_human, from_safetensor=False)
|
| 210 |
+
print(f'multiplier_style:{multiplier_style}, multiplier_human:{multiplier_human}')
|
| 211 |
+
|
| 212 |
+
train_dir = str(input_img_dir) + '_labeled'
|
| 213 |
+
add_prompt_style = []
|
| 214 |
+
f = open(os.path.join(train_dir, 'metadata.jsonl'), 'r')
|
| 215 |
+
tags_all = []
|
| 216 |
+
cnt = 0
|
| 217 |
+
cnts_trigger = np.zeros(6)
|
| 218 |
+
for line in f:
|
| 219 |
+
cnt += 1
|
| 220 |
+
data = json.loads(line)['text'].split(', ')
|
| 221 |
+
tags_all.extend(data)
|
| 222 |
+
if data[1] == 'a boy':
|
| 223 |
+
cnts_trigger[0] += 1
|
| 224 |
+
elif data[1] == 'a girl':
|
| 225 |
+
cnts_trigger[1] += 1
|
| 226 |
+
elif data[1] == 'a handsome man':
|
| 227 |
+
cnts_trigger[2] += 1
|
| 228 |
+
elif data[1] == 'a beautiful woman':
|
| 229 |
+
cnts_trigger[3] += 1
|
| 230 |
+
elif data[1] == 'a mature man':
|
| 231 |
+
cnts_trigger[4] += 1
|
| 232 |
+
elif data[1] == 'a mature woman':
|
| 233 |
+
cnts_trigger[5] += 1
|
| 234 |
+
else:
|
| 235 |
+
print('Error.')
|
| 236 |
+
f.close()
|
| 237 |
+
|
| 238 |
+
attr_idx = np.argmax(cnts_trigger)
|
| 239 |
+
trigger_styles = ['a boy, children, ', 'a girl, children, ', 'a handsome man, ', 'a beautiful woman, ',
|
| 240 |
+
'a mature man, ', 'a mature woman, ']
|
| 241 |
+
trigger_style = '<fcsks>, ' + trigger_styles[attr_idx]
|
| 242 |
+
if attr_idx == 2 or attr_idx == 4:
|
| 243 |
+
neg_prompt += ', children'
|
| 244 |
+
|
| 245 |
+
for tag in tags_all:
|
| 246 |
+
if tags_all.count(tag) > 0.5 * cnt:
|
| 247 |
+
if ('hair' in tag or 'face' in tag or 'mouth' in tag or 'skin' in tag or 'smile' in tag):
|
| 248 |
+
if not tag in add_prompt_style:
|
| 249 |
+
add_prompt_style.append(tag)
|
| 250 |
+
|
| 251 |
+
if len(add_prompt_style) > 0:
|
| 252 |
+
add_prompt_style = ", ".join(add_prompt_style) + ', '
|
| 253 |
+
else:
|
| 254 |
+
add_prompt_style = ''
|
| 255 |
+
# trigger_style = trigger_style + 'with <input_id> face, '
|
| 256 |
+
# pos_prompt = 'Generate a standard ID photo of a chinese {}, solo, wearing high-class business/working suit, beautiful smooth face, with high-class/simple pure color background, looking straight into the camera with shoulders parallel to the frame, smile, high detail face, best quality, photorealistic'.format(gender)
|
| 257 |
+
pipe = pipe.to("cuda")
|
| 258 |
+
# print(trigger_style + add_prompt_style + pos_prompt)
|
| 259 |
+
images_style = txt2img_pose(pipe, pose_im, trigger_style + add_prompt_style + pos_prompt, neg_prompt, num_images=10)
|
| 260 |
+
return images_style
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def main_diffusion_inference_multi(pose_model_path, pose_image,
|
| 264 |
+
pos_prompt, neg_prompt,
|
| 265 |
+
input_img_dir, base_model_path, style_model_path, lora_model_path,
|
| 266 |
+
multiplier_style=0.25,
|
| 267 |
+
multiplier_human=0.85):
|
| 268 |
+
if style_model_path is None:
|
| 269 |
+
model_dir = snapshot_download('Cherrytest/zjz_mj_jiyi_small_addtxt_fromleo', revision='v1.0.0')
|
| 270 |
+
style_model_path = os.path.join(model_dir, 'zjz_mj_jiyi_small_addtxt_fromleo.safetensors')
|
| 271 |
+
|
| 272 |
+
model_dir = snapshot_download('damo/face_chain_control_model', revision='v1.0.1')
|
| 273 |
+
controlnet = [
|
| 274 |
+
ControlNetModel.from_pretrained(pose_model_path, torch_dtype=torch.float32),
|
| 275 |
+
ControlNetModel.from_pretrained(os.path.join(model_dir, 'model_controlnet/control_v11p_sd15_depth'), torch_dtype=torch.float32)
|
| 276 |
+
]
|
| 277 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(base_model_path, safety_checker=None, controlnet=controlnet, torch_dtype=torch.float32)
|
| 278 |
+
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
|
| 279 |
+
pose_image = Image.open(pose_image)
|
| 280 |
+
pose_image = img_pad(pose_image)
|
| 281 |
+
openpose = OpenposeDetector.from_pretrained(os.path.join(model_dir, 'model_controlnet/ControlNet'))
|
| 282 |
+
pose_im = openpose(pose_image, include_hand=True)
|
| 283 |
+
segmentation_pipeline = pipeline(Tasks.image_segmentation,
|
| 284 |
+
'damo/cv_resnet101_image-multiple-human-parsing')
|
| 285 |
+
result = segmentation_pipeline(pose_image)
|
| 286 |
+
mask_rst = get_mask(result)
|
| 287 |
+
pose_image = np.array(pose_image)
|
| 288 |
+
pose_image = (pose_image * mask_rst).astype(np.uint8)
|
| 289 |
+
pose_image = Image.fromarray(pose_image)
|
| 290 |
+
depth_estimator = tpipeline('depth-estimation', os.path.join(model_dir, 'model_controlnet/dpt-large'))
|
| 291 |
+
depth_im = depth_estimator(pose_image)['depth']
|
| 292 |
+
depth_im = np.array(depth_im)
|
| 293 |
+
depth_im = depth_im[:, :, None]
|
| 294 |
+
depth_im = np.concatenate([depth_im, depth_im, depth_im], axis=2)
|
| 295 |
+
depth_im = Image.fromarray(depth_im)
|
| 296 |
+
control_im = [pose_im, depth_im]
|
| 297 |
+
|
| 298 |
+
lora_style_path = style_model_path
|
| 299 |
+
lora_human_path = lora_model_path
|
| 300 |
+
pipe = merge_lora(pipe, lora_style_path, multiplier_style, from_safetensor=True)
|
| 301 |
+
pipe = merge_lora(pipe, lora_human_path, multiplier_human, from_safetensor=False)
|
| 302 |
+
print(f'multiplier_style:{multiplier_style}, multiplier_human:{multiplier_human}')
|
| 303 |
+
|
| 304 |
+
train_dir = str(input_img_dir) + '_labeled'
|
| 305 |
+
add_prompt_style = []
|
| 306 |
+
f = open(os.path.join(train_dir, 'metadata.jsonl'), 'r')
|
| 307 |
+
tags_all = []
|
| 308 |
+
cnt = 0
|
| 309 |
+
cnts_trigger = np.zeros(6)
|
| 310 |
+
for line in f:
|
| 311 |
+
cnt += 1
|
| 312 |
+
data = json.loads(line)['text'].split(', ')
|
| 313 |
+
tags_all.extend(data)
|
| 314 |
+
if data[1] == 'a boy':
|
| 315 |
+
cnts_trigger[0] += 1
|
| 316 |
+
elif data[1] == 'a girl':
|
| 317 |
+
cnts_trigger[1] += 1
|
| 318 |
+
elif data[1] == 'a handsome man':
|
| 319 |
+
cnts_trigger[2] += 1
|
| 320 |
+
elif data[1] == 'a beautiful woman':
|
| 321 |
+
cnts_trigger[3] += 1
|
| 322 |
+
elif data[1] == 'a mature man':
|
| 323 |
+
cnts_trigger[4] += 1
|
| 324 |
+
elif data[1] == 'a mature woman':
|
| 325 |
+
cnts_trigger[5] += 1
|
| 326 |
+
else:
|
| 327 |
+
print('Error.')
|
| 328 |
+
f.close()
|
| 329 |
+
|
| 330 |
+
attr_idx = np.argmax(cnts_trigger)
|
| 331 |
+
trigger_styles = ['a boy, children, ', 'a girl, children, ', 'a handsome man, ', 'a beautiful woman, ',
|
| 332 |
+
'a mature man, ', 'a mature woman, ']
|
| 333 |
+
trigger_style = '<fcsks>, ' + trigger_styles[attr_idx]
|
| 334 |
+
if attr_idx == 2 or attr_idx == 4:
|
| 335 |
+
neg_prompt += ', children'
|
| 336 |
+
|
| 337 |
+
for tag in tags_all:
|
| 338 |
+
if tags_all.count(tag) > 0.5 * cnt:
|
| 339 |
+
if ('hair' in tag or 'face' in tag or 'mouth' in tag or 'skin' in tag or 'smile' in tag):
|
| 340 |
+
if not tag in add_prompt_style:
|
| 341 |
+
add_prompt_style.append(tag)
|
| 342 |
+
|
| 343 |
+
if len(add_prompt_style) > 0:
|
| 344 |
+
add_prompt_style = ", ".join(add_prompt_style) + ', '
|
| 345 |
+
else:
|
| 346 |
+
add_prompt_style = ''
|
| 347 |
+
# trigger_style = trigger_style + 'with <input_id> face, '
|
| 348 |
+
# pos_prompt = 'Generate a standard ID photo of a chinese {}, solo, wearing high-class business/working suit, beautiful smooth face, with high-class/simple pure color background, looking straight into the camera with shoulders parallel to the frame, smile, high detail face, best quality, photorealistic'.format(gender)
|
| 349 |
+
pipe = pipe.to("cuda")
|
| 350 |
+
# print(trigger_style + add_prompt_style + pos_prompt)
|
| 351 |
+
images_style = txt2img_multi(pipe, control_im, trigger_style + add_prompt_style + pos_prompt, neg_prompt, num_images=10)
|
| 352 |
+
return images_style
|
| 353 |
+
|
| 354 |
+
def stylization_fn(use_stylization, rank_results):
|
| 355 |
+
if use_stylization:
|
| 356 |
+
## TODO
|
| 357 |
+
pass
|
| 358 |
+
else:
|
| 359 |
+
return rank_results
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def main_model_inference(pose_model_path, pose_image, use_depth_control, pos_prompt, neg_prompt, style_model_path, multiplier_style, multiplier_human, use_main_model,
|
| 363 |
+
input_img_dir=None, base_model_path=None, lora_model_path=None):
|
| 364 |
+
if use_main_model:
|
| 365 |
+
multiplier_style_kwargs = {'multiplier_style': multiplier_style} if multiplier_style is not None else {}
|
| 366 |
+
multiplier_human_kwargs = {'multiplier_human': multiplier_human} if multiplier_human is not None else {}
|
| 367 |
+
if pose_image is None:
|
| 368 |
+
return main_diffusion_inference(pos_prompt, neg_prompt, input_img_dir, base_model_path,
|
| 369 |
+
style_model_path, lora_model_path,
|
| 370 |
+
**multiplier_style_kwargs, **multiplier_human_kwargs)
|
| 371 |
+
else:
|
| 372 |
+
pose_image = compress_image(pose_image, 1024 * 1024)
|
| 373 |
+
if use_depth_control:
|
| 374 |
+
return main_diffusion_inference_multi(pose_model_path, pose_image, pos_prompt,
|
| 375 |
+
neg_prompt, input_img_dir, base_model_path, style_model_path,
|
| 376 |
+
lora_model_path,
|
| 377 |
+
**multiplier_style_kwargs, **multiplier_human_kwargs)
|
| 378 |
+
else:
|
| 379 |
+
return main_diffusion_inference_pose(pose_model_path, pose_image, pos_prompt, neg_prompt,
|
| 380 |
+
input_img_dir, base_model_path, style_model_path, lora_model_path,
|
| 381 |
+
**multiplier_style_kwargs, **multiplier_human_kwargs)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def select_high_quality_face(input_img_dir):
|
| 385 |
+
input_img_dir = str(input_img_dir) + '_labeled'
|
| 386 |
+
quality_score_list = []
|
| 387 |
+
abs_img_path_list = []
|
| 388 |
+
## TODO
|
| 389 |
+
face_quality_func = pipeline(Tasks.face_quality_assessment, 'damo/cv_manual_face-quality-assessment_fqa', model_revision='v2.0')
|
| 390 |
+
|
| 391 |
+
for img_name in os.listdir(input_img_dir):
|
| 392 |
+
if img_name.endswith('jsonl') or img_name.startswith('.ipynb') or img_name.startswith('.safetensors'):
|
| 393 |
+
continue
|
| 394 |
+
|
| 395 |
+
if img_name.endswith('jpg') or img_name.endswith('png'):
|
| 396 |
+
abs_img_name = os.path.join(input_img_dir, img_name)
|
| 397 |
+
face_quality_score = face_quality_func(abs_img_name)[OutputKeys.SCORES]
|
| 398 |
+
if face_quality_score is None:
|
| 399 |
+
quality_score_list.append(0)
|
| 400 |
+
else:
|
| 401 |
+
quality_score_list.append(face_quality_score[0])
|
| 402 |
+
abs_img_path_list.append(abs_img_name)
|
| 403 |
+
|
| 404 |
+
sort_idx = np.argsort(quality_score_list)[::-1]
|
| 405 |
+
print('Selected face: ' + abs_img_path_list[sort_idx[0]])
|
| 406 |
+
|
| 407 |
+
return Image.open(abs_img_path_list[sort_idx[0]])
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def face_swap_fn(use_face_swap, gen_results, template_face):
|
| 411 |
+
if use_face_swap:
|
| 412 |
+
## TODO
|
| 413 |
+
out_img_list = []
|
| 414 |
+
image_face_fusion = pipeline('face_fusion_torch',
|
| 415 |
+
model='damo/cv_unet_face_fusion_torch', model_revision='v1.0.3')
|
| 416 |
+
for img in gen_results:
|
| 417 |
+
result = image_face_fusion(dict(template=img, user=template_face))[OutputKeys.OUTPUT_IMG]
|
| 418 |
+
out_img_list.append(result)
|
| 419 |
+
|
| 420 |
+
return out_img_list
|
| 421 |
+
else:
|
| 422 |
+
ret_results = []
|
| 423 |
+
for img in gen_results:
|
| 424 |
+
ret_results.append(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))
|
| 425 |
+
return ret_results
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def post_process_fn(use_post_process, swap_results_ori, selected_face, num_gen_images):
|
| 429 |
+
if use_post_process:
|
| 430 |
+
sim_list = []
|
| 431 |
+
## TODO
|
| 432 |
+
face_recognition_func = pipeline(Tasks.face_recognition, 'damo/cv_ir_face-recognition-ood_rts', model_revision='v2.5')
|
| 433 |
+
face_det_func = pipeline(task=Tasks.face_detection, model='damo/cv_ddsar_face-detection_iclr23-damofd', model_revision='v1.1')
|
| 434 |
+
swap_results = []
|
| 435 |
+
for img in swap_results_ori:
|
| 436 |
+
result_det = face_det_func(img)
|
| 437 |
+
bboxes = result_det['boxes']
|
| 438 |
+
if len(bboxes) == 1:
|
| 439 |
+
bbox = bboxes[0]
|
| 440 |
+
lenface = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
|
| 441 |
+
if 120 < lenface < 300:
|
| 442 |
+
swap_results.append(img)
|
| 443 |
+
|
| 444 |
+
select_face_emb = face_recognition_func(selected_face)[OutputKeys.IMG_EMBEDDING][0]
|
| 445 |
+
|
| 446 |
+
for img in swap_results:
|
| 447 |
+
emb = face_recognition_func(img)[OutputKeys.IMG_EMBEDDING]
|
| 448 |
+
if emb is None or select_face_emb is None:
|
| 449 |
+
sim_list.append(0)
|
| 450 |
+
else:
|
| 451 |
+
sim = np.dot(emb, select_face_emb)
|
| 452 |
+
sim_list.append(sim.item())
|
| 453 |
+
sort_idx = np.argsort(sim_list)[::-1]
|
| 454 |
+
|
| 455 |
+
return np.array(swap_results)[sort_idx[:min(int(num_gen_images), len(swap_results))]]
|
| 456 |
+
else:
|
| 457 |
+
return np.array(swap_results_ori)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
class GenPortrait:
|
| 461 |
+
def __init__(self, pose_model_path, pose_image, use_depth_control, pos_prompt, neg_prompt, style_model_path, multiplier_style, multiplier_human,
|
| 462 |
+
use_main_model=True, use_face_swap=True,
|
| 463 |
+
use_post_process=True, use_stylization=True):
|
| 464 |
+
self.use_main_model = use_main_model
|
| 465 |
+
self.use_face_swap = use_face_swap
|
| 466 |
+
self.use_post_process = use_post_process
|
| 467 |
+
self.use_stylization = use_stylization
|
| 468 |
+
self.multiplier_style = multiplier_style
|
| 469 |
+
self.multiplier_human = multiplier_human
|
| 470 |
+
self.style_model_path = style_model_path
|
| 471 |
+
self.pos_prompt = pos_prompt
|
| 472 |
+
self.neg_prompt = neg_prompt
|
| 473 |
+
self.pose_model_path = pose_model_path
|
| 474 |
+
self.pose_image = pose_image
|
| 475 |
+
self.use_depth_control = use_depth_control
|
| 476 |
+
|
| 477 |
+
def __call__(self, input_img_dir, num_gen_images=6, base_model_path=None,
|
| 478 |
+
lora_model_path=None, sub_path=None, revision=None):
|
| 479 |
+
base_model_path = snapshot_download(base_model_path, revision=revision)
|
| 480 |
+
if sub_path is not None and len(sub_path) > 0:
|
| 481 |
+
base_model_path = os.path.join(base_model_path, sub_path)
|
| 482 |
+
|
| 483 |
+
# main_model_inference PIL
|
| 484 |
+
gen_results = main_model_inference(self.pose_model_path, self.pose_image, self.use_depth_control,
|
| 485 |
+
self.pos_prompt, self.neg_prompt,
|
| 486 |
+
self.style_model_path, self.multiplier_style, self.multiplier_human,
|
| 487 |
+
self.use_main_model, input_img_dir=input_img_dir,
|
| 488 |
+
lora_model_path=lora_model_path, base_model_path=base_model_path)
|
| 489 |
+
|
| 490 |
+
# select_high_quality_face PIL
|
| 491 |
+
selected_face = select_high_quality_face(input_img_dir)
|
| 492 |
+
# face_swap cv2
|
| 493 |
+
swap_results = face_swap_fn(self.use_face_swap, gen_results, selected_face)
|
| 494 |
+
# pose_process
|
| 495 |
+
rank_results = post_process_fn(self.use_post_process, swap_results, selected_face,
|
| 496 |
+
num_gen_images=num_gen_images)
|
| 497 |
+
# stylization
|
| 498 |
+
final_gen_results = stylization_fn(self.use_stylization, rank_results)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
return final_gen_results
|
| 502 |
+
|
| 503 |
+
def compress_image(input_path, target_size):
|
| 504 |
+
output_path = change_extension_to_jpg(input_path)
|
| 505 |
+
|
| 506 |
+
image = cv2.imread(input_path)
|
| 507 |
+
|
| 508 |
+
quality = 95
|
| 509 |
+
try:
|
| 510 |
+
while cv2.imencode('.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, quality])[1].size > target_size:
|
| 511 |
+
quality -= 5
|
| 512 |
+
except:
|
| 513 |
+
import pdb;pdb.set_trace()
|
| 514 |
+
|
| 515 |
+
compressed_image = cv2.imencode('.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, quality])[1].tostring()
|
| 516 |
+
|
| 517 |
+
with open(output_path, 'wb') as f:
|
| 518 |
+
f.write(compressed_image)
|
| 519 |
+
return output_path
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def change_extension_to_jpg(image_path):
|
| 523 |
+
|
| 524 |
+
base_name = os.path.basename(image_path)
|
| 525 |
+
new_base_name = os.path.splitext(base_name)[0] + ".jpg"
|
| 526 |
+
|
| 527 |
+
direct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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 2 |
+
# Modified from the original implementation at https://github.com/modelscope/facechain/pull/104.
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
import cv2
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
from PIL import Image
|
| 11 |
+
from skimage import transform
|
| 12 |
+
from controlnet_aux import OpenposeDetector
|
| 13 |
+
from diffusers import StableDiffusionPipeline, StableDiffusionControlNetPipeline, \
|
| 14 |
+
StableDiffusionControlNetInpaintPipeline, ControlNetModel, UniPCMultistepScheduler
|
| 15 |
+
from facechain.utils import snapshot_download
|
| 16 |
+
from modelscope.outputs import OutputKeys
|
| 17 |
+
from modelscope.pipelines import pipeline
|
| 18 |
+
from modelscope.utils.constant import Tasks
|
| 19 |
+
from torch import multiprocessing
|
| 20 |
+
from transformers import pipeline as tpipeline
|
| 21 |
+
|
| 22 |
+
from facechain.data_process.preprocessing import Blipv2
|
| 23 |
+
from facechain.merge_lora import merge_lora
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _data_process_fn_process(input_img_dir):
|
| 27 |
+
Blipv2()(input_img_dir)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def concatenate_images(images):
|
| 31 |
+
heights = [img.shape[0] for img in images]
|
| 32 |
+
max_width = sum([img.shape[1] for img in images])
|
| 33 |
+
|
| 34 |
+
concatenated_image = np.zeros((max(heights), max_width, 3), dtype=np.uint8)
|
| 35 |
+
x_offset = 0
|
| 36 |
+
for img in images:
|
| 37 |
+
concatenated_image[0:img.shape[0], x_offset:x_offset + img.shape[1], :] = img
|
| 38 |
+
x_offset += img.shape[1]
|
| 39 |
+
return concatenated_image
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def data_process_fn(input_img_dir, use_data_process):
|
| 43 |
+
## TODO add face quality filter
|
| 44 |
+
if use_data_process:
|
| 45 |
+
## TODO
|
| 46 |
+
|
| 47 |
+
_process = multiprocessing.Process(target=_data_process_fn_process, args=(input_img_dir,))
|
| 48 |
+
_process.start()
|
| 49 |
+
_process.join()
|
| 50 |
+
|
| 51 |
+
return os.path.join(str(input_img_dir) + '_labeled', "metadata.jsonl")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def call_face_crop(det_pipeline, image, crop_ratio):
|
| 55 |
+
det_result = det_pipeline(image)
|
| 56 |
+
bboxes = det_result['boxes']
|
| 57 |
+
keypoints = det_result['keypoints']
|
| 58 |
+
area = 0
|
| 59 |
+
idx = 0
|
| 60 |
+
for i in range(len(bboxes)):
|
| 61 |
+
bbox = bboxes[i]
|
| 62 |
+
area_tmp = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
|
| 63 |
+
if area_tmp > area:
|
| 64 |
+
area = area_tmp
|
| 65 |
+
idx = i
|
| 66 |
+
bbox = bboxes[idx]
|
| 67 |
+
keypoint = keypoints[idx]
|
| 68 |
+
points_array = np.zeros((5, 2))
|
| 69 |
+
for k in range(5):
|
| 70 |
+
points_array[k, 0] = keypoint[2 * k]
|
| 71 |
+
points_array[k, 1] = keypoint[2 * k + 1]
|
| 72 |
+
w, h = image.size
|
| 73 |
+
face_w = bbox[2] - bbox[0]
|
| 74 |
+
face_h = bbox[3] - bbox[1]
|
| 75 |
+
bbox[0] = np.clip(np.array(bbox[0], np.int32) - face_w * (crop_ratio - 1) / 2, 0, w - 1)
|
| 76 |
+
bbox[1] = np.clip(np.array(bbox[1], np.int32) - face_h * (crop_ratio - 1) / 2, 0, h - 1)
|
| 77 |
+
bbox[2] = np.clip(np.array(bbox[2], np.int32) + face_w * (crop_ratio - 1) / 2, 0, w - 1)
|
| 78 |
+
bbox[3] = np.clip(np.array(bbox[3], np.int32) + face_h * (crop_ratio - 1) / 2, 0, h - 1)
|
| 79 |
+
bbox = np.array(bbox, np.int32)
|
| 80 |
+
return bbox, points_array
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def crop_and_paste(Source_image, Source_image_mask, Target_image, Source_Five_Point, Target_Five_Point, Source_box, use_warp=True):
|
| 84 |
+
if use_warp:
|
| 85 |
+
Source_Five_Point = np.reshape(Source_Five_Point, [5, 2]) - np.array(Source_box[:2])
|
| 86 |
+
Target_Five_Point = np.reshape(Target_Five_Point, [5, 2])
|
| 87 |
+
|
| 88 |
+
Crop_Source_image = Source_image.crop(np.int32(Source_box))
|
| 89 |
+
Crop_Source_image_mask = Source_image_mask.crop(np.int32(Source_box))
|
| 90 |
+
Source_Five_Point, Target_Five_Point = np.array(Source_Five_Point), np.array(Target_Five_Point)
|
| 91 |
+
|
| 92 |
+
tform = transform.SimilarityTransform()
|
| 93 |
+
tform.estimate(Source_Five_Point, Target_Five_Point)
|
| 94 |
+
M = tform.params[0:2, :]
|
| 95 |
+
|
| 96 |
+
warped = cv2.warpAffine(np.array(Crop_Source_image), M, np.shape(Target_image)[:2][::-1], borderValue=0.0)
|
| 97 |
+
warped_mask = cv2.warpAffine(np.array(Crop_Source_image_mask), M, np.shape(Target_image)[:2][::-1], borderValue=0.0)
|
| 98 |
+
|
| 99 |
+
mask = np.float32(warped_mask == 0)
|
| 100 |
+
output = mask * np.float32(Target_image) + (1 - mask) * np.float32(warped)
|
| 101 |
+
else:
|
| 102 |
+
mask = np.float32(np.array(Source_image_mask) == 0)
|
| 103 |
+
output = mask * np.float32(Target_image) + (1 - mask) * np.float32(Source_image)
|
| 104 |
+
return output, mask
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def segment(segmentation_pipeline, img, ksize=0, eyeh=0, ksize1=0, include_neck=False, warp_mask=None, return_human=False):
|
| 108 |
+
if True:
|
| 109 |
+
result = segmentation_pipeline(img)
|
| 110 |
+
masks = result['masks']
|
| 111 |
+
scores = result['scores']
|
| 112 |
+
labels = result['labels']
|
| 113 |
+
if len(masks) == 0:
|
| 114 |
+
return
|
| 115 |
+
h, w = masks[0].shape
|
| 116 |
+
mask_face = np.zeros((h, w))
|
| 117 |
+
mask_hair = np.zeros((h, w))
|
| 118 |
+
mask_neck = np.zeros((h, w))
|
| 119 |
+
mask_cloth = np.zeros((h, w))
|
| 120 |
+
mask_human = np.zeros((h, w))
|
| 121 |
+
for i in range(len(labels)):
|
| 122 |
+
if scores[i] > 0.8:
|
| 123 |
+
if labels[i] == 'Torso-skin':
|
| 124 |
+
mask_neck += masks[i]
|
| 125 |
+
elif labels[i] == 'Face':
|
| 126 |
+
mask_face += masks[i]
|
| 127 |
+
elif labels[i] == 'Human':
|
| 128 |
+
mask_human += masks[i]
|
| 129 |
+
elif labels[i] == 'Hair':
|
| 130 |
+
mask_hair += masks[i]
|
| 131 |
+
elif labels[i] == 'UpperClothes' or labels[i] == 'Coat':
|
| 132 |
+
mask_cloth += masks[i]
|
| 133 |
+
mask_face = np.clip(mask_face, 0, 1)
|
| 134 |
+
mask_hair = np.clip(mask_hair, 0, 1)
|
| 135 |
+
mask_neck = np.clip(mask_neck, 0, 1)
|
| 136 |
+
mask_cloth = np.clip(mask_cloth, 0, 1)
|
| 137 |
+
mask_human = np.clip(mask_human, 0, 1)
|
| 138 |
+
if np.sum(mask_face) > 0:
|
| 139 |
+
soft_mask = np.clip(mask_face, 0, 1)
|
| 140 |
+
if ksize1 > 0:
|
| 141 |
+
kernel_size1 = int(np.sqrt(np.sum(soft_mask)) * ksize1)
|
| 142 |
+
kernel1 = np.ones((kernel_size1, kernel_size1))
|
| 143 |
+
soft_mask = cv2.dilate(soft_mask, kernel1, iterations=1)
|
| 144 |
+
if ksize > 0:
|
| 145 |
+
kernel_size = int(np.sqrt(np.sum(soft_mask)) * ksize)
|
| 146 |
+
kernel = np.ones((kernel_size, kernel_size))
|
| 147 |
+
soft_mask_dilate = cv2.dilate(soft_mask, kernel, iterations=1)
|
| 148 |
+
if warp_mask is not None:
|
| 149 |
+
soft_mask_dilate = soft_mask_dilate * (np.clip(soft_mask + warp_mask[:, :, 0], 0, 1))
|
| 150 |
+
if eyeh > 0:
|
| 151 |
+
soft_mask = np.concatenate((soft_mask[:eyeh], soft_mask_dilate[eyeh:]), axis=0)
|
| 152 |
+
else:
|
| 153 |
+
soft_mask = soft_mask_dilate
|
| 154 |
+
else:
|
| 155 |
+
if ksize1 > 0:
|
| 156 |
+
kernel_size1 = int(np.sqrt(np.sum(soft_mask)) * ksize1)
|
| 157 |
+
kernel1 = np.ones((kernel_size1, kernel_size1))
|
| 158 |
+
soft_mask = cv2.dilate(mask_face, kernel1, iterations=1)
|
| 159 |
+
else:
|
| 160 |
+
soft_mask = mask_face
|
| 161 |
+
if include_neck:
|
| 162 |
+
soft_mask = np.clip(soft_mask + mask_neck, 0, 1)
|
| 163 |
+
|
| 164 |
+
if return_human:
|
| 165 |
+
mask_human = cv2.GaussianBlur(mask_human, (21, 21), 0) * mask_human
|
| 166 |
+
return soft_mask, mask_human
|
| 167 |
+
else:
|
| 168 |
+
return soft_mask
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def crop_bottom(pil_file, width):
|
| 172 |
+
if width == 512:
|
| 173 |
+
height = 768
|
| 174 |
+
else:
|
| 175 |
+
height = 1152
|
| 176 |
+
w, h = pil_file.size
|
| 177 |
+
factor = w / width
|
| 178 |
+
new_h = int(h / factor)
|
| 179 |
+
pil_file = pil_file.resize((width, new_h))
|
| 180 |
+
crop_h = min(int(new_h / 32) * 32, height)
|
| 181 |
+
array_file = np.array(pil_file)
|
| 182 |
+
array_file = array_file[:crop_h, :, :]
|
| 183 |
+
output_file = Image.fromarray(array_file)
|
| 184 |
+
return output_file
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def img2img_multicontrol(img, control_image, controlnet_conditioning_scale, pipe, mask, pos_prompt, neg_prompt,
|
| 188 |
+
strength, num=1, use_ori=False):
|
| 189 |
+
image_mask = Image.fromarray(np.uint8(mask * 255))
|
| 190 |
+
image_human = []
|
| 191 |
+
for i in range(num):
|
| 192 |
+
image_human.append(pipe(image=img, mask_image=image_mask, control_image=control_image, prompt=pos_prompt,
|
| 193 |
+
negative_prompt=neg_prompt, guidance_scale=7, strength=strength, num_inference_steps=40,
|
| 194 |
+
controlnet_conditioning_scale=controlnet_conditioning_scale,
|
| 195 |
+
num_images_per_prompt=1).images[0])
|
| 196 |
+
if use_ori:
|
| 197 |
+
image_human[i] = Image.fromarray((np.array(image_human[i]) * mask[:,:,None] + np.array(img) * (1 - mask[:,:,None])).astype(np.uint8))
|
| 198 |
+
return image_human
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def get_mask(result):
|
| 202 |
+
masks = result['masks']
|
| 203 |
+
scores = result['scores']
|
| 204 |
+
labels = result['labels']
|
| 205 |
+
h, w = masks[0].shape
|
| 206 |
+
mask_hair = np.zeros((h, w))
|
| 207 |
+
mask_face = np.zeros((h, w))
|
| 208 |
+
mask_human = np.zeros((h, w))
|
| 209 |
+
for i in range(len(labels)):
|
| 210 |
+
if scores[i] > 0.8:
|
| 211 |
+
if labels[i] == 'Face':
|
| 212 |
+
if np.sum(masks[i]) > np.sum(mask_face):
|
| 213 |
+
mask_face = masks[i]
|
| 214 |
+
elif labels[i] == 'Human':
|
| 215 |
+
if np.sum(masks[i]) > np.sum(mask_human):
|
| 216 |
+
mask_human = masks[i]
|
| 217 |
+
elif labels[i] == 'Hair':
|
| 218 |
+
if np.sum(masks[i]) > np.sum(mask_hair):
|
| 219 |
+
mask_hair = masks[i]
|
| 220 |
+
mask_rst = np.clip(mask_human - mask_hair - mask_face, 0, 1)
|
| 221 |
+
mask_rst = np.expand_dims(mask_rst, 2)
|
| 222 |
+
mask_rst = np.concatenate([mask_rst, mask_rst, mask_rst], axis=2)
|
| 223 |
+
return mask_rst
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def main_diffusion_inference_inpaint(inpaint_image, strength, output_img_size, pos_prompt, neg_prompt,
|
| 227 |
+
input_img_dir, base_model_path, style_model_path, lora_model_path,
|
| 228 |
+
multiplier_style=0.05,
|
| 229 |
+
multiplier_human=1.0):
|
| 230 |
+
if style_model_path is None:
|
| 231 |
+
model_dir = snapshot_download('Cherrytest/zjz_mj_jiyi_small_addtxt_fromleo', revision='v1.0.0')
|
| 232 |
+
style_model_path = os.path.join(model_dir, 'zjz_mj_jiyi_small_addtxt_fromleo.safetensors')
|
| 233 |
+
|
| 234 |
+
segmentation_pipeline = pipeline(Tasks.image_segmentation, 'damo/cv_resnet101_image-multiple-human-parsing')
|
| 235 |
+
det_pipeline = pipeline(Tasks.face_detection, 'damo/cv_ddsar_face-detection_iclr23-damofd')
|
| 236 |
+
model_dir = snapshot_download('damo/face_chain_control_model', revision='v1.0.1')
|
| 237 |
+
model_dir1 = snapshot_download('ly261666/cv_wanx_style_model',revision='v1.0.3')
|
| 238 |
+
|
| 239 |
+
if output_img_size == 512:
|
| 240 |
+
dtype = torch.float32
|
| 241 |
+
else:
|
| 242 |
+
dtype = torch.float16
|
| 243 |
+
|
| 244 |
+
train_dir = str(input_img_dir) + '_labeled'
|
| 245 |
+
add_prompt_style = []
|
| 246 |
+
f = open(os.path.join(train_dir, 'metadata.jsonl'), 'r')
|
| 247 |
+
tags_all = []
|
| 248 |
+
cnt = 0
|
| 249 |
+
cnts_trigger = np.zeros(6)
|
| 250 |
+
is_old = False
|
| 251 |
+
for line in f:
|
| 252 |
+
cnt += 1
|
| 253 |
+
data = json.loads(line)['text'].split(', ')
|
| 254 |
+
tags_all.extend(data)
|
| 255 |
+
if data[1] == 'a boy':
|
| 256 |
+
cnts_trigger[0] += 1
|
| 257 |
+
elif data[1] == 'a girl':
|
| 258 |
+
cnts_trigger[1] += 1
|
| 259 |
+
elif data[1] == 'a handsome man':
|
| 260 |
+
cnts_trigger[2] += 1
|
| 261 |
+
elif data[1] == 'a beautiful woman':
|
| 262 |
+
cnts_trigger[3] += 1
|
| 263 |
+
elif data[1] == 'a mature man':
|
| 264 |
+
cnts_trigger[4] += 1
|
| 265 |
+
is_old = True
|
| 266 |
+
elif data[1] == 'a mature woman':
|
| 267 |
+
cnts_trigger[5] += 1
|
| 268 |
+
is_old = True
|
| 269 |
+
else:
|
| 270 |
+
print('Error.')
|
| 271 |
+
f.close()
|
| 272 |
+
|
| 273 |
+
attr_idx = np.argmax(cnts_trigger)
|
| 274 |
+
trigger_styles = ['a boy, children, ', 'a girl, children, ', 'a handsome man, ', 'a beautiful woman, ',
|
| 275 |
+
'a mature man, ', 'a mature woman, ']
|
| 276 |
+
trigger_style = '<fcsks>, ' + trigger_styles[attr_idx]
|
| 277 |
+
if attr_idx == 2 or attr_idx == 4:
|
| 278 |
+
neg_prompt += ', children'
|
| 279 |
+
|
| 280 |
+
for tag in tags_all:
|
| 281 |
+
if tags_all.count(tag) > 0.5 * cnt:
|
| 282 |
+
if ('glasses' in tag or 'smile' in tag):
|
| 283 |
+
if not tag in add_prompt_style:
|
| 284 |
+
add_prompt_style.append(tag)
|
| 285 |
+
|
| 286 |
+
if len(add_prompt_style) > 0:
|
| 287 |
+
add_prompt_style = ", ".join(add_prompt_style) + ', '
|
| 288 |
+
else:
|
| 289 |
+
add_prompt_style = ''
|
| 290 |
+
|
| 291 |
+
if isinstance(inpaint_image, str):
|
| 292 |
+
inpaint_im = Image.open(inpaint_image)
|
| 293 |
+
else:
|
| 294 |
+
inpaint_im = inpaint_image
|
| 295 |
+
inpaint_im = crop_bottom(inpaint_im, output_img_size)
|
| 296 |
+
# return [inpaint_im, inpaint_im, inpaint_im]
|
| 297 |
+
openpose = OpenposeDetector.from_pretrained(os.path.join(model_dir, "model_controlnet/ControlNet"))
|
| 298 |
+
controlnet = ControlNetModel.from_pretrained(os.path.join(model_dir, "model_controlnet/control_v11p_sd15_openpose"), torch_dtype=dtype)
|
| 299 |
+
openpose_image = openpose(np.array(inpaint_im, np.uint8), include_hand=True, include_face=False)
|
| 300 |
+
w, h = inpaint_im.size
|
| 301 |
+
|
| 302 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(base_model_path, controlnet=controlnet, torch_dtype=dtype)
|
| 303 |
+
lora_style_path = style_model_path
|
| 304 |
+
lora_human_path = lora_model_path
|
| 305 |
+
pipe = merge_lora(pipe, lora_style_path, multiplier_style, from_safetensor=True)
|
| 306 |
+
pipe = merge_lora(pipe, lora_human_path, multiplier_human, from_safetensor=False)
|
| 307 |
+
pipe = pipe.to("cuda")
|
| 308 |
+
image_faces = []
|
| 309 |
+
for i in range(1):
|
| 310 |
+
image_face = pipe(prompt=trigger_style + add_prompt_style + pos_prompt, image=openpose_image, height=h, width=w,
|
| 311 |
+
guidance_scale=7, negative_prompt=neg_prompt,
|
| 312 |
+
num_inference_steps=40, num_images_per_prompt=1).images[0]
|
| 313 |
+
image_faces.append(image_face)
|
| 314 |
+
selected_face = select_high_quality_face(input_img_dir)
|
| 315 |
+
swap_results = face_swap_fn(True, image_faces, selected_face)
|
| 316 |
+
|
| 317 |
+
controlnet = [
|
| 318 |
+
ControlNetModel.from_pretrained(os.path.join(model_dir, "model_controlnet/control_v11p_sd15_openpose"), torch_dtype=dtype),
|
| 319 |
+
ControlNetModel.from_pretrained(os.path.join(model_dir1, "contronet-canny"), torch_dtype=dtype)
|
| 320 |
+
]
|
| 321 |
+
pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(base_model_path, controlnet=controlnet,
|
| 322 |
+
torch_dtype=dtype)
|
| 323 |
+
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
|
| 324 |
+
pipe = merge_lora(pipe, style_model_path, multiplier_style, from_safetensor=True)
|
| 325 |
+
pipe = merge_lora(pipe, lora_model_path, multiplier_human, from_safetensor=False)
|
| 326 |
+
pipe = pipe.to("cuda")
|
| 327 |
+
|
| 328 |
+
images_human = []
|
| 329 |
+
images_auto = []
|
| 330 |
+
inpaint_bbox, inpaint_keypoints = call_face_crop(det_pipeline, inpaint_im, 1.1)
|
| 331 |
+
eye_height = int((inpaint_keypoints[0, 1] + inpaint_keypoints[1, 1]) / 2)
|
| 332 |
+
canny_image = cv2.Canny(np.array(inpaint_im, np.uint8), 100, 200)[:, :, None]
|
| 333 |
+
mask = segment(segmentation_pipeline, inpaint_im, ksize=0.05, eyeh=eye_height)
|
| 334 |
+
canny_image = (canny_image * (1.0 - mask[:, :, None])).astype(np.uint8)
|
| 335 |
+
canny_image = Image.fromarray(np.concatenate([canny_image, canny_image, canny_image], axis=2))
|
| 336 |
+
# canny_image.save('canny.png')
|
| 337 |
+
for i in range(1):
|
| 338 |
+
image_face = swap_results[i]
|
| 339 |
+
image_face = Image.fromarray(image_face[:, :, ::-1])
|
| 340 |
+
|
| 341 |
+
face_bbox, face_keypoints = call_face_crop(det_pipeline, image_face, 1.5)
|
| 342 |
+
face_mask = segment(segmentation_pipeline, image_face)
|
| 343 |
+
face_mask = np.expand_dims((face_mask * 255).astype(np.uint8), axis=2)
|
| 344 |
+
face_mask = np.concatenate([face_mask, face_mask, face_mask], axis=2)
|
| 345 |
+
face_mask = Image.fromarray(face_mask)
|
| 346 |
+
replaced_input_image, warp_mask = crop_and_paste(image_face, face_mask, inpaint_im, face_keypoints,
|
| 347 |
+
inpaint_keypoints, face_bbox)
|
| 348 |
+
warp_mask = 1.0 - warp_mask
|
| 349 |
+
# cv2.imwrite('tmp_{}.png'.format(i), replaced_input_image[:, :, ::-1])
|
| 350 |
+
|
| 351 |
+
openpose_image = openpose(np.array(replaced_input_image * warp_mask, np.uint8), include_hand=True,
|
| 352 |
+
include_body=False, include_face=True)
|
| 353 |
+
# openpose_image.save('openpose_{}.png'.format(i))
|
| 354 |
+
read_control = [openpose_image, canny_image]
|
| 355 |
+
inpaint_mask, human_mask = segment(segmentation_pipeline, inpaint_im, ksize=0.1, ksize1=0.06, eyeh=eye_height, include_neck=False,
|
| 356 |
+
warp_mask=warp_mask, return_human=True)
|
| 357 |
+
inpaint_with_mask = ((1.0 - inpaint_mask[:,:,None]) * np.array(inpaint_im))[:,:,::-1]
|
| 358 |
+
# cv2.imwrite('inpaint_with_mask_{}.png'.format(i), inpaint_with_mask)
|
| 359 |
+
print('Finishing segmenting images.')
|
| 360 |
+
images_human.extend(img2img_multicontrol(inpaint_im, read_control, [1.0, 0.2], pipe, inpaint_mask,
|
| 361 |
+
trigger_style + add_prompt_style + pos_prompt, neg_prompt,
|
| 362 |
+
strength=strength))
|
| 363 |
+
images_auto.extend(img2img_multicontrol(inpaint_im, read_control, [1.0, 0.2], pipe, np.zeros_like(inpaint_mask),
|
| 364 |
+
trigger_style + add_prompt_style + pos_prompt, neg_prompt,
|
| 365 |
+
strength=0.025))
|
| 366 |
+
|
| 367 |
+
edge_add = np.array(inpaint_im).astype(np.int16) - np.array(images_auto[i]).astype(np.int16)
|
| 368 |
+
edge_add = edge_add * (1 - human_mask[:,:,None])
|
| 369 |
+
images_human[i] = Image.fromarray((np.clip(np.array(images_human[i]).astype(np.int16) + edge_add.astype(np.int16), 0, 255)).astype(np.uint8))
|
| 370 |
+
|
| 371 |
+
images_rst = []
|
| 372 |
+
|
| 373 |
+
for i in range(len(images_human)):
|
| 374 |
+
im = images_human[i]
|
| 375 |
+
canny_image = cv2.Canny(np.array(im, np.uint8), 100, 200)[:, :, None]
|
| 376 |
+
canny_image = Image.fromarray(np.concatenate([canny_image, canny_image, canny_image], axis=2))
|
| 377 |
+
openpose_image = openpose(np.array(im, np.uint8), include_hand=True, include_face=True)
|
| 378 |
+
read_control = [openpose_image, canny_image]
|
| 379 |
+
inpaint_mask, human_mask = segment(segmentation_pipeline, images_human[i], ksize=0.02, return_human=True)
|
| 380 |
+
print('Finishing segmenting images.')
|
| 381 |
+
image_rst = img2img_multicontrol(im, read_control, [0.8, 0.8], pipe, inpaint_mask,
|
| 382 |
+
trigger_style + add_prompt_style + pos_prompt, neg_prompt, strength=0.1,
|
| 383 |
+
num=1)[0]
|
| 384 |
+
image_auto = img2img_multicontrol(im, read_control, [0.8, 0.8], pipe, np.zeros_like(inpaint_mask),
|
| 385 |
+
trigger_style + add_prompt_style + pos_prompt, neg_prompt, strength=0.025,
|
| 386 |
+
num=1)[0]
|
| 387 |
+
edge_add = np.array(im).astype(np.int16) - np.array(image_auto).astype(np.int16)
|
| 388 |
+
edge_add = edge_add * (1 - human_mask[:,:,None])
|
| 389 |
+
image_rst = Image.fromarray((np.clip(np.array(image_rst).astype(np.int16) + edge_add.astype(np.int16), 0, 255)).astype(np.uint8))
|
| 390 |
+
|
| 391 |
+
images_rst.append(image_rst)
|
| 392 |
+
|
| 393 |
+
for i in range(1):
|
| 394 |
+
images_rst[i].save('inference_{}.png'.format(i))
|
| 395 |
+
|
| 396 |
+
return images_rst
|
| 397 |
+
|
| 398 |
+
def main_diffusion_inference_inpaint_multi(inpaint_images, strength, output_img_size, pos_prompt, neg_prompt,
|
| 399 |
+
input_img_dir, base_model_path, style_model_path, lora_model_path,
|
| 400 |
+
multiplier_style=0.05,
|
| 401 |
+
multiplier_human=1.0):
|
| 402 |
+
if style_model_path is None:
|
| 403 |
+
model_dir = snapshot_download('Cherrytest/zjz_mj_jiyi_small_addtxt_fromleo', revision='v1.0.0')
|
| 404 |
+
style_model_path = os.path.join(model_dir, 'zjz_mj_jiyi_small_addtxt_fromleo.safetensors')
|
| 405 |
+
|
| 406 |
+
segmentation_pipeline = pipeline(Tasks.image_segmentation, 'damo/cv_resnet101_image-multiple-human-parsing')
|
| 407 |
+
det_pipeline = pipeline(Tasks.face_detection, 'damo/cv_ddsar_face-detection_iclr23-damofd')
|
| 408 |
+
model_dir = snapshot_download('damo/face_chain_control_model', revision='v1.0.1')
|
| 409 |
+
model_dir1 = snapshot_download('ly261666/cv_wanx_style_model',revision='v1.0.3')
|
| 410 |
+
|
| 411 |
+
if output_img_size == 512:
|
| 412 |
+
dtype = torch.float32
|
| 413 |
+
else:
|
| 414 |
+
dtype = torch.float16
|
| 415 |
+
|
| 416 |
+
train_dir = str(input_img_dir) + '_labeled'
|
| 417 |
+
add_prompt_style = []
|
| 418 |
+
f = open(os.path.join(train_dir, 'metadata.jsonl'), 'r')
|
| 419 |
+
tags_all = []
|
| 420 |
+
cnt = 0
|
| 421 |
+
cnts_trigger = np.zeros(6)
|
| 422 |
+
is_old = False
|
| 423 |
+
for line in f:
|
| 424 |
+
cnt += 1
|
| 425 |
+
data = json.loads(line)['text'].split(', ')
|
| 426 |
+
tags_all.extend(data)
|
| 427 |
+
if data[1] == 'a boy':
|
| 428 |
+
cnts_trigger[0] += 1
|
| 429 |
+
elif data[1] == 'a girl':
|
| 430 |
+
cnts_trigger[1] += 1
|
| 431 |
+
elif data[1] == 'a handsome man':
|
| 432 |
+
cnts_trigger[2] += 1
|
| 433 |
+
elif data[1] == 'a beautiful woman':
|
| 434 |
+
cnts_trigger[3] += 1
|
| 435 |
+
elif data[1] == 'a mature man':
|
| 436 |
+
cnts_trigger[4] += 1
|
| 437 |
+
is_old = True
|
| 438 |
+
elif data[1] == 'a mature woman':
|
| 439 |
+
cnts_trigger[5] += 1
|
| 440 |
+
is_old = True
|
| 441 |
+
else:
|
| 442 |
+
print('Error.')
|
| 443 |
+
f.close()
|
| 444 |
+
|
| 445 |
+
attr_idx = np.argmax(cnts_trigger)
|
| 446 |
+
trigger_styles = ['a boy, children, ', 'a girl, children, ', 'a handsome man, ', 'a beautiful woman, ',
|
| 447 |
+
'a mature man, ', 'a mature woman, ']
|
| 448 |
+
trigger_style = '<fcsks>, ' + trigger_styles[attr_idx]
|
| 449 |
+
if attr_idx == 2 or attr_idx == 4:
|
| 450 |
+
neg_prompt += ', children'
|
| 451 |
+
|
| 452 |
+
for tag in tags_all:
|
| 453 |
+
if tags_all.count(tag) > 0.5 * cnt:
|
| 454 |
+
if ('glasses' in tag or 'smile' in tag):
|
| 455 |
+
if not tag in add_prompt_style:
|
| 456 |
+
add_prompt_style.append(tag)
|
| 457 |
+
|
| 458 |
+
if len(add_prompt_style) > 0:
|
| 459 |
+
add_prompt_style = ", ".join(add_prompt_style) + ', '
|
| 460 |
+
else:
|
| 461 |
+
add_prompt_style = ''
|
| 462 |
+
|
| 463 |
+
openpose = OpenposeDetector.from_pretrained(os.path.join(model_dir, "model_controlnet/ControlNet"))
|
| 464 |
+
controlnet = ControlNetModel.from_pretrained(os.path.join(model_dir, "model_controlnet/control_v11p_sd15_openpose"), torch_dtype=dtype)
|
| 465 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(base_model_path, controlnet=controlnet, torch_dtype=dtype)
|
| 466 |
+
lora_style_path = style_model_path
|
| 467 |
+
lora_human_path = lora_model_path
|
| 468 |
+
pipe = merge_lora(pipe, lora_style_path, multiplier_style, from_safetensor=True)
|
| 469 |
+
pipe = merge_lora(pipe, lora_human_path, multiplier_human, from_safetensor=False)
|
| 470 |
+
pipe = pipe.to("cuda")
|
| 471 |
+
image_faces = []
|
| 472 |
+
|
| 473 |
+
for i in range(1):
|
| 474 |
+
inpaint_im = inpaint_images[i]
|
| 475 |
+
inpaint_im = crop_bottom(inpaint_im, output_img_size)
|
| 476 |
+
|
| 477 |
+
openpose_image = openpose(np.array(inpaint_im, np.uint8), include_hand=True, include_face=False)
|
| 478 |
+
w, h = inpaint_im.size
|
| 479 |
+
image_face = pipe(prompt=trigger_style + add_prompt_style + pos_prompt, image=openpose_image, height=h, width=w,
|
| 480 |
+
guidance_scale=7, negative_prompt=neg_prompt,
|
| 481 |
+
num_inference_steps=40, num_images_per_prompt=1).images[0]
|
| 482 |
+
image_faces.append(image_face)
|
| 483 |
+
|
| 484 |
+
selected_face = select_high_quality_face(input_img_dir)
|
| 485 |
+
swap_results = face_swap_fn(True, image_faces, selected_face)
|
| 486 |
+
|
| 487 |
+
controlnet = [
|
| 488 |
+
ControlNetModel.from_pretrained(os.path.join(model_dir, "model_controlnet/control_v11p_sd15_openpose"), torch_dtype=dtype),
|
| 489 |
+
ControlNetModel.from_pretrained(os.path.join(model_dir1, "contronet-canny"), torch_dtype=dtype)
|
| 490 |
+
]
|
| 491 |
+
pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(base_model_path, controlnet=controlnet,
|
| 492 |
+
torch_dtype=dtype)
|
| 493 |
+
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
|
| 494 |
+
pipe = merge_lora(pipe, style_model_path, multiplier_style, from_safetensor=True)
|
| 495 |
+
pipe = merge_lora(pipe, lora_model_path, multiplier_human, from_safetensor=False)
|
| 496 |
+
pipe = pipe.to("cuda")
|
| 497 |
+
|
| 498 |
+
images_human = []
|
| 499 |
+
images_auto = []
|
| 500 |
+
for i in range(1):
|
| 501 |
+
inpaint_im = inpaint_images[i]
|
| 502 |
+
inpaint_bbox, inpaint_keypoints = call_face_crop(det_pipeline, inpaint_im, 1.1)
|
| 503 |
+
eye_height = int((inpaint_keypoints[0, 1] + inpaint_keypoints[1, 1]) / 2)
|
| 504 |
+
canny_image = cv2.Canny(np.array(inpaint_im, np.uint8), 100, 200)[:, :, None]
|
| 505 |
+
mask = segment(segmentation_pipeline, inpaint_im, ksize=0.05, eyeh=eye_height)
|
| 506 |
+
canny_image = (canny_image * (1.0 - mask[:, :, None])).astype(np.uint8)
|
| 507 |
+
canny_image = Image.fromarray(np.concatenate([canny_image, canny_image, canny_image], axis=2))
|
| 508 |
+
|
| 509 |
+
image_face = swap_results[i]
|
| 510 |
+
image_face = Image.fromarray(image_face[:, :, ::-1])
|
| 511 |
+
|
| 512 |
+
face_bbox, face_keypoints = call_face_crop(det_pipeline, image_face, 1.5)
|
| 513 |
+
face_mask = segment(segmentation_pipeline, image_face)
|
| 514 |
+
face_mask = np.expand_dims((face_mask * 255).astype(np.uint8), axis=2)
|
| 515 |
+
face_mask = np.concatenate([face_mask, face_mask, face_mask], axis=2)
|
| 516 |
+
face_mask = Image.fromarray(face_mask)
|
| 517 |
+
replaced_input_image, warp_mask = crop_and_paste(image_face, face_mask, inpaint_im, face_keypoints,
|
| 518 |
+
inpaint_keypoints, face_bbox)
|
| 519 |
+
warp_mask = 1.0 - warp_mask
|
| 520 |
+
# cv2.imwrite('tmp_{}.png'.format(i), replaced_input_image[:, :, ::-1])
|
| 521 |
+
|
| 522 |
+
openpose_image = openpose(np.array(replaced_input_image * warp_mask, np.uint8), include_hand=True,
|
| 523 |
+
include_body=False, include_face=True)
|
| 524 |
+
# openpose_image.save('openpose_{}.png'.format(i))
|
| 525 |
+
read_control = [openpose_image, canny_image]
|
| 526 |
+
inpaint_mask, human_mask = segment(segmentation_pipeline, inpaint_im, ksize=0.1, ksize1=0.06, eyeh=eye_height, include_neck=False,
|
| 527 |
+
warp_mask=warp_mask, return_human=True)
|
| 528 |
+
inpaint_with_mask = ((1.0 - inpaint_mask[:,:,None]) * np.array(inpaint_im))[:,:,::-1]
|
| 529 |
+
# cv2.imwrite('inpaint_with_mask_{}.png'.format(i), inpaint_with_mask)
|
| 530 |
+
print('Finishing segmenting images.')
|
| 531 |
+
images_human.extend(img2img_multicontrol(inpaint_im, read_control, [1.0, 0.2], pipe, inpaint_mask,
|
| 532 |
+
trigger_style + add_prompt_style + pos_prompt, neg_prompt,
|
| 533 |
+
strength=strength))
|
| 534 |
+
images_auto.extend(img2img_multicontrol(inpaint_im, read_control, [1.0, 0.2], pipe, np.zeros_like(inpaint_mask),
|
| 535 |
+
trigger_style + add_prompt_style + pos_prompt, neg_prompt,
|
| 536 |
+
strength=0.025))
|
| 537 |
+
|
| 538 |
+
edge_add = np.array(inpaint_im).astype(np.int16) - np.array(images_auto[i]).astype(np.int16)
|
| 539 |
+
edge_add = edge_add * (1 - human_mask[:,:,None])
|
| 540 |
+
images_human[i] = Image.fromarray((np.clip(np.array(images_human[i]).astype(np.int16) + edge_add.astype(np.int16), 0, 255)).astype(np.uint8))
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
images_rst = []
|
| 544 |
+
for i in range(len(images_human)):
|
| 545 |
+
im = images_human[i]
|
| 546 |
+
canny_image = cv2.Canny(np.array(im, np.uint8), 100, 200)[:, :, None]
|
| 547 |
+
canny_image = Image.fromarray(np.concatenate([canny_image, canny_image, canny_image], axis=2))
|
| 548 |
+
openpose_image = openpose(np.array(im, np.uint8), include_hand=True, include_face=True)
|
| 549 |
+
read_control = [openpose_image, canny_image]
|
| 550 |
+
inpaint_mask, human_mask = segment(segmentation_pipeline, images_human[i], ksize=0.02, return_human=True)
|
| 551 |
+
print('Finishing segmenting images.')
|
| 552 |
+
image_rst = img2img_multicontrol(im, read_control, [0.8, 0.8], pipe, np.zeros_like(inpaint_mask),
|
| 553 |
+
trigger_style + add_prompt_style + pos_prompt, neg_prompt, strength=0.1,
|
| 554 |
+
num=1)[0]
|
| 555 |
+
image_auto = img2img_multicontrol(im, read_control, [0.8, 0.8], pipe, np.zeros_like(inpaint_mask),
|
| 556 |
+
trigger_style + add_prompt_style + pos_prompt, neg_prompt, strength=0.025,
|
| 557 |
+
num=1)[0]
|
| 558 |
+
edge_add = np.array(im).astype(np.int16) - np.array(image_auto).astype(np.int16)
|
| 559 |
+
edge_add = edge_add * (1 - human_mask[:,:,None])
|
| 560 |
+
image_rst = Image.fromarray((np.clip(np.array(image_rst).astype(np.int16) + edge_add.astype(np.int16), 0, 255)).astype(np.uint8))
|
| 561 |
+
|
| 562 |
+
images_rst.append(image_rst)
|
| 563 |
+
|
| 564 |
+
for i in range(1):
|
| 565 |
+
images_rst[i].save('inference_{}.png'.format(i))
|
| 566 |
+
|
| 567 |
+
return images_rst
|
| 568 |
+
|
| 569 |
+
def stylization_fn(use_stylization, rank_results):
|
| 570 |
+
if use_stylization:
|
| 571 |
+
## TODO
|
| 572 |
+
pass
|
| 573 |
+
else:
|
| 574 |
+
return rank_results
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def main_model_inference(inpaint_image, strength, output_img_size,
|
| 578 |
+
pos_prompt, neg_prompt, style_model_path, multiplier_style, multiplier_human, use_main_model,
|
| 579 |
+
input_img_dir=None, base_model_path=None, lora_model_path=None):
|
| 580 |
+
|
| 581 |
+
if use_main_model:
|
| 582 |
+
multiplier_style_kwargs = {'multiplier_style': multiplier_style} if multiplier_style is not None else {}
|
| 583 |
+
multiplier_human_kwargs = {'multiplier_human': multiplier_human} if multiplier_human is not None else {}
|
| 584 |
+
return main_diffusion_inference_inpaint(inpaint_image, strength, output_img_size, pos_prompt, neg_prompt,
|
| 585 |
+
input_img_dir, base_model_path, style_model_path, lora_model_path,
|
| 586 |
+
**multiplier_style_kwargs, **multiplier_human_kwargs)
|
| 587 |
+
|
| 588 |
+
def main_model_inference_multi(inpaint_image, strength, output_img_size,
|
| 589 |
+
pos_prompt, neg_prompt, style_model_path, multiplier_style, multiplier_human, use_main_model,
|
| 590 |
+
input_img_dir=None, base_model_path=None, lora_model_path=None):
|
| 591 |
+
|
| 592 |
+
if use_main_model:
|
| 593 |
+
multiplier_style_kwargs = {'multiplier_style': multiplier_style} if multiplier_style is not None else {}
|
| 594 |
+
multiplier_human_kwargs = {'multiplier_human': multiplier_human} if multiplier_human is not None else {}
|
| 595 |
+
return main_diffusion_inference_inpaint_multi(inpaint_image, strength, output_img_size, pos_prompt, neg_prompt,
|
| 596 |
+
input_img_dir, base_model_path, style_model_path, lora_model_path,
|
| 597 |
+
**multiplier_style_kwargs, **multiplier_human_kwargs)
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
def select_high_quality_face(input_img_dir):
|
| 601 |
+
input_img_dir = str(input_img_dir) + '_labeled'
|
| 602 |
+
quality_score_list = []
|
| 603 |
+
abs_img_path_list = []
|
| 604 |
+
## TODO
|
| 605 |
+
face_quality_func = pipeline(Tasks.face_quality_assessment, 'damo/cv_manual_face-quality-assessment_fqa',
|
| 606 |
+
model_revision='v2.0')
|
| 607 |
+
|
| 608 |
+
for img_name in os.listdir(input_img_dir):
|
| 609 |
+
if img_name.endswith('jsonl') or img_name.startswith('.ipynb') or img_name.startswith('.safetensors'):
|
| 610 |
+
continue
|
| 611 |
+
|
| 612 |
+
if img_name.endswith('jpg') or img_name.endswith('png'):
|
| 613 |
+
abs_img_name = os.path.join(input_img_dir, img_name)
|
| 614 |
+
face_quality_score = face_quality_func(abs_img_name)[OutputKeys.SCORES]
|
| 615 |
+
if face_quality_score is None:
|
| 616 |
+
quality_score_list.append(0)
|
| 617 |
+
else:
|
| 618 |
+
quality_score_list.append(face_quality_score[0])
|
| 619 |
+
abs_img_path_list.append(abs_img_name)
|
| 620 |
+
|
| 621 |
+
sort_idx = np.argsort(quality_score_list)[::-1]
|
| 622 |
+
print('Selected face: ' + abs_img_path_list[sort_idx[0]])
|
| 623 |
+
|
| 624 |
+
return Image.open(abs_img_path_list[sort_idx[0]])
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def face_swap_fn(use_face_swap, gen_results, template_face):
|
| 628 |
+
if use_face_swap:
|
| 629 |
+
## TODO
|
| 630 |
+
out_img_list = []
|
| 631 |
+
image_face_fusion = pipeline('face_fusion_torch',
|
| 632 |
+
model='damo/cv_unet_face_fusion_torch', model_revision='v1.0.5')
|
| 633 |
+
segmentation_pipeline = pipeline(Tasks.image_segmentation, 'damo/cv_resnet101_image-multiple-human-parsing')
|
| 634 |
+
for img in gen_results:
|
| 635 |
+
result = image_face_fusion(dict(template=img, user=template_face))[OutputKeys.OUTPUT_IMG]
|
| 636 |
+
face_mask = segment(segmentation_pipeline, img, ksize=0.1)
|
| 637 |
+
result = (result * face_mask[:,:,None] + np.array(img)[:,:,::-1] * (1 - face_mask[:,:,None])).astype(np.uint8)
|
| 638 |
+
out_img_list.append(result)
|
| 639 |
+
return out_img_list
|
| 640 |
+
else:
|
| 641 |
+
ret_results = []
|
| 642 |
+
for img in gen_results:
|
| 643 |
+
ret_results.append(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))
|
| 644 |
+
return ret_results
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def post_process_fn(use_post_process, swap_results_ori, selected_face, num_gen_images):
|
| 648 |
+
if use_post_process:
|
| 649 |
+
sim_list = []
|
| 650 |
+
## TODO
|
| 651 |
+
face_recognition_func = pipeline(Tasks.face_recognition, 'damo/cv_ir_face-recognition-ood_rts',
|
| 652 |
+
model_revision='v2.5')
|
| 653 |
+
face_det_func = pipeline(task=Tasks.face_detection, model='damo/cv_ddsar_face-detection_iclr23-damofd',
|
| 654 |
+
model_revision='v1.1')
|
| 655 |
+
swap_results = swap_results_ori
|
| 656 |
+
|
| 657 |
+
select_face_emb = face_recognition_func(selected_face)[OutputKeys.IMG_EMBEDDING][0]
|
| 658 |
+
|
| 659 |
+
for img in swap_results:
|
| 660 |
+
emb = face_recognition_func(img)[OutputKeys.IMG_EMBEDDING]
|
| 661 |
+
if emb is None or select_face_emb is None:
|
| 662 |
+
sim_list.append(0)
|
| 663 |
+
else:
|
| 664 |
+
sim = np.dot(emb, select_face_emb)
|
| 665 |
+
sim_list.append(sim.item())
|
| 666 |
+
sort_idx = np.argsort(sim_list)[::-1]
|
| 667 |
+
|
| 668 |
+
return np.array(swap_results)[sort_idx[:min(int(num_gen_images), len(swap_results))]]
|
| 669 |
+
else:
|
| 670 |
+
return np.array(swap_results_ori)
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
class GenPortrait_inpaint:
|
| 674 |
+
def __init__(self, inpaint_img, strength, num_faces,
|
| 675 |
+
pos_prompt, neg_prompt, style_model_path, multiplier_style, multiplier_human,
|
| 676 |
+
use_main_model=True, use_face_swap=True,
|
| 677 |
+
use_post_process=True, use_stylization=True):
|
| 678 |
+
self.use_main_model = use_main_model
|
| 679 |
+
self.use_face_swap = use_face_swap
|
| 680 |
+
self.use_post_process = use_post_process
|
| 681 |
+
self.use_stylization = use_stylization
|
| 682 |
+
self.multiplier_style = multiplier_style
|
| 683 |
+
self.multiplier_human = multiplier_human
|
| 684 |
+
self.style_model_path = style_model_path
|
| 685 |
+
self.pos_prompt = pos_prompt
|
| 686 |
+
self.neg_prompt = neg_prompt
|
| 687 |
+
self.inpaint_img = inpaint_img
|
| 688 |
+
self.strength = strength
|
| 689 |
+
self.num_faces = num_faces
|
| 690 |
+
|
| 691 |
+
def __call__(self, input_img_dir1=None, input_img_dir2=None, base_model_path=None,
|
| 692 |
+
lora_model_path1=None, lora_model_path2=None, sub_path=None, revision=None):
|
| 693 |
+
base_model_path = snapshot_download(base_model_path, revision=revision)
|
| 694 |
+
if sub_path is not None and len(sub_path) > 0:
|
| 695 |
+
base_model_path = os.path.join(base_model_path, sub_path)
|
| 696 |
+
|
| 697 |
+
face_detection = pipeline(task=Tasks.face_detection, model='damo/cv_ddsar_face-detection_iclr23-damofd',
|
| 698 |
+
model_revision='v1.1')
|
| 699 |
+
result_det = face_detection(self.inpaint_img)
|
| 700 |
+
bboxes = result_det['boxes']
|
| 701 |
+
assert(len(bboxes)) == self.num_faces
|
| 702 |
+
bboxes = np.array(bboxes).astype(np.int16)
|
| 703 |
+
lefts = []
|
| 704 |
+
for bbox in bboxes:
|
| 705 |
+
lefts.append(bbox[0])
|
| 706 |
+
idxs = np.argsort(lefts)
|
| 707 |
+
|
| 708 |
+
if lora_model_path1 != None:
|
| 709 |
+
face_box = bboxes[idxs[0]]
|
| 710 |
+
inpaint_img_large = cv2.imread(self.inpaint_img)
|
| 711 |
+
mask_large = np.ones_like(inpaint_img_large)
|
| 712 |
+
mask_large1 = np.zeros_like(inpaint_img_large)
|
| 713 |
+
h,w,_ = inpaint_img_large.shape
|
| 714 |
+
for i in range(len(bboxes)):
|
| 715 |
+
if i != idxs[0]:
|
| 716 |
+
bbox = bboxes[i]
|
| 717 |
+
inpaint_img_large[bbox[1]:bbox[3], bbox[0]:bbox[2]] = 0
|
| 718 |
+
mask_large[bbox[1]:bbox[3], bbox[0]:bbox[2]] = 0
|
| 719 |
+
|
| 720 |
+
face_ratio = 0.45
|
| 721 |
+
cropl = int(max(face_box[3] - face_box[1], face_box[2] - face_box[0]) / face_ratio / 2)
|
| 722 |
+
cx = int((face_box[2] + face_box[0])/2)
|
| 723 |
+
cy = int((face_box[1] + face_box[3])/2)
|
| 724 |
+
cropup = min(cy, cropl)
|
| 725 |
+
cropbo = min(h-cy, cropl)
|
| 726 |
+
crople = min(cx, cropl)
|
| 727 |
+
cropri = min(w-cx, cropl)
|
| 728 |
+
inpaint_img = np.pad(inpaint_img_large[cy-cropup:cy+cropbo, cx-crople:cx+cropri], ((cropl-cropup, cropl-cropbo), (cropl-crople, cropl-cropri), (0, 0)), 'constant')
|
| 729 |
+
inpaint_img = cv2.resize(inpaint_img, (512, 512))
|
| 730 |
+
inpaint_img = Image.fromarray(inpaint_img[:,:,::-1])
|
| 731 |
+
mask_large1[cy-cropup:cy+cropbo, cx-crople:cx+cropri] = 1
|
| 732 |
+
mask_large = mask_large * mask_large1
|
| 733 |
+
|
| 734 |
+
gen_results = main_model_inference(inpaint_img, self.strength, 512,
|
| 735 |
+
self.pos_prompt, self.neg_prompt,
|
| 736 |
+
self.style_model_path, self.multiplier_style, self.multiplier_human,
|
| 737 |
+
self.use_main_model, input_img_dir=input_img_dir1,
|
| 738 |
+
lora_model_path=lora_model_path1, base_model_path=base_model_path)
|
| 739 |
+
|
| 740 |
+
# select_high_quality_face PIL
|
| 741 |
+
selected_face = select_high_quality_face(input_img_dir1)
|
| 742 |
+
# face_swap cv2
|
| 743 |
+
swap_results = face_swap_fn(self.use_face_swap, gen_results, selected_face)
|
| 744 |
+
# stylization
|
| 745 |
+
final_gen_results = swap_results
|
| 746 |
+
|
| 747 |
+
print(len(final_gen_results))
|
| 748 |
+
|
| 749 |
+
final_gen_results_new = []
|
| 750 |
+
inpaint_img_large = cv2.imread(self.inpaint_img)
|
| 751 |
+
ksize = int(10 * cropl / 256)
|
| 752 |
+
for i in range(len(final_gen_results)):
|
| 753 |
+
print('Start cropping.')
|
| 754 |
+
rst_gen = cv2.resize(final_gen_results[i], (cropl * 2, cropl * 2))
|
| 755 |
+
rst_crop = rst_gen[cropl-cropup:cropl+cropbo, cropl-crople:cropl+cropri]
|
| 756 |
+
print(rst_crop.shape)
|
| 757 |
+
inpaint_img_rst = np.zeros_like(inpaint_img_large)
|
| 758 |
+
print('Start pasting.')
|
| 759 |
+
inpaint_img_rst[cy-cropup:cy+cropbo, cx-crople:cx+cropri] = rst_crop
|
| 760 |
+
print('Fininsh pasting.')
|
| 761 |
+
print(inpaint_img_rst.shape, mask_large.shape, inpaint_img_large.shape)
|
| 762 |
+
mask_large = mask_large.astype(np.float32)
|
| 763 |
+
kernel = np.ones((ksize * 2, ksize * 2))
|
| 764 |
+
mask_large1 = cv2.erode(mask_large, kernel, iterations=1)
|
| 765 |
+
mask_large1 = cv2.GaussianBlur(mask_large1, (int(ksize * 1.8) * 2 + 1, int(ksize * 1.8) * 2 + 1), 0)
|
| 766 |
+
mask_large1[face_box[1]:face_box[3], face_box[0]:face_box[2]] = 1
|
| 767 |
+
mask_large = mask_large * mask_large1
|
| 768 |
+
final_inpaint_rst = (inpaint_img_rst.astype(np.float32) * mask_large.astype(np.float32) + inpaint_img_large.astype(np.float32) * (1.0 - mask_large.astype(np.float32))).astype(np.uint8)
|
| 769 |
+
print('Finish masking.')
|
| 770 |
+
final_gen_results_new.append(final_inpaint_rst)
|
| 771 |
+
print('Finish generating.')
|
| 772 |
+
else:
|
| 773 |
+
inpaint_img_large = cv2.imread(self.inpaint_img)
|
| 774 |
+
inpaint_img_le = cv2.imread(self.inpaint_img)
|
| 775 |
+
final_gen_results_new = [inpaint_img_le, inpaint_img_le, inpaint_img_le]
|
| 776 |
+
|
| 777 |
+
for i in range(1):
|
| 778 |
+
cv2.imwrite('tmp_inpaint_left_{}.png'.format(i), final_gen_results_new[i])
|
| 779 |
+
|
| 780 |
+
if lora_model_path2 != None and self.num_faces == 2:
|
| 781 |
+
face_box = bboxes[idxs[1]]
|
| 782 |
+
mask_large = np.ones_like(inpaint_img_large)
|
| 783 |
+
mask_large1 = np.zeros_like(inpaint_img_large)
|
| 784 |
+
h,w,_ = inpaint_img_large.shape
|
| 785 |
+
for i in range(len(bboxes)):
|
| 786 |
+
if i != idxs[1]:
|
| 787 |
+
bbox = bboxes[i]
|
| 788 |
+
inpaint_img_large[bbox[1]:bbox[3], bbox[0]:bbox[2]] = 0
|
| 789 |
+
mask_large[bbox[1]:bbox[3], bbox[0]:bbox[2]] = 0
|
| 790 |
+
|
| 791 |
+
face_ratio = 0.45
|
| 792 |
+
cropl = int(max(face_box[3] - face_box[1], face_box[2] - face_box[0]) / face_ratio / 2)
|
| 793 |
+
cx = int((face_box[2] + face_box[0])/2)
|
| 794 |
+
cy = int((face_box[1] + face_box[3])/2)
|
| 795 |
+
cropup = min(cy, cropl)
|
| 796 |
+
cropbo = min(h-cy, cropl)
|
| 797 |
+
crople = min(cx, cropl)
|
| 798 |
+
cropri = min(w-cx, cropl)
|
| 799 |
+
mask_large1[cy-cropup:cy+cropbo, cx-crople:cx+cropri] = 1
|
| 800 |
+
mask_large = mask_large * mask_large1
|
| 801 |
+
|
| 802 |
+
inpaint_imgs = []
|
| 803 |
+
for i in range(1):
|
| 804 |
+
inpaint_img_large = final_gen_results_new[i] * mask_large
|
| 805 |
+
inpaint_img = np.pad(inpaint_img_large[cy-cropup:cy+cropbo, cx-crople:cx+cropri], ((cropl-cropup, cropl-cropbo), (cropl-crople, cropl-cropri), (0, 0)), 'constant')
|
| 806 |
+
inpaint_img = cv2.resize(inpaint_img, (512, 512))
|
| 807 |
+
inpaint_img = Image.fromarray(inpaint_img[:,:,::-1])
|
| 808 |
+
inpaint_imgs.append(inpaint_img)
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
gen_results = main_model_inference_multi(inpaint_imgs, self.strength, 512,
|
| 812 |
+
self.pos_prompt, self.neg_prompt,
|
| 813 |
+
self.style_model_path, self.multiplier_style, self.multiplier_human,
|
| 814 |
+
self.use_main_model, input_img_dir=input_img_dir2,
|
| 815 |
+
lora_model_path=lora_model_path2, base_model_path=base_model_path)
|
| 816 |
+
|
| 817 |
+
# select_high_quality_face PIL
|
| 818 |
+
selected_face = select_high_quality_face(input_img_dir2)
|
| 819 |
+
# face_swap cv2
|
| 820 |
+
swap_results = face_swap_fn(self.use_face_swap, gen_results, selected_face)
|
| 821 |
+
# stylization
|
| 822 |
+
final_gen_results = swap_results
|
| 823 |
+
|
| 824 |
+
print(len(final_gen_results))
|
| 825 |
+
|
| 826 |
+
final_gen_results_final = []
|
| 827 |
+
inpaint_img_large = cv2.imread(self.inpaint_img)
|
| 828 |
+
ksize = int(10 * cropl / 256)
|
| 829 |
+
for i in range(len(final_gen_results)):
|
| 830 |
+
print('Start cropping.')
|
| 831 |
+
rst_gen = cv2.resize(final_gen_results[i], (cropl * 2, cropl * 2))
|
| 832 |
+
rst_crop = rst_gen[cropl-cropup:cropl+cropbo, cropl-crople:cropl+cropri]
|
| 833 |
+
print(rst_crop.shape)
|
| 834 |
+
inpaint_img_rst = np.zeros_like(inpaint_img_large)
|
| 835 |
+
print('Start pasting.')
|
| 836 |
+
inpaint_img_rst[cy-cropup:cy+cropbo, cx-crople:cx+cropri] = rst_crop
|
| 837 |
+
print('Fininsh pasting.')
|
| 838 |
+
print(inpaint_img_rst.shape, mask_large.shape, inpaint_img_large.shape)
|
| 839 |
+
mask_large = mask_large.astype(np.float32)
|
| 840 |
+
kernel = np.ones((ksize * 2, ksize * 2))
|
| 841 |
+
mask_large1 = cv2.erode(mask_large, kernel, iterations=1)
|
| 842 |
+
mask_large1 = cv2.GaussianBlur(mask_large1, (int(ksize * 1.8) * 2 + 1, int(ksize * 1.8) * 2 + 1), 0)
|
| 843 |
+
mask_large1[face_box[1]:face_box[3], face_box[0]:face_box[2]] = 1
|
| 844 |
+
mask_large = mask_large * mask_large1
|
| 845 |
+
final_inpaint_rst = (inpaint_img_rst.astype(np.float32) * mask_large.astype(np.float32) + final_gen_results_new[i].astype(np.float32) * (1.0 - mask_large.astype(np.float32))).astype(np.uint8)
|
| 846 |
+
print('Finish masking.')
|
| 847 |
+
final_gen_results_final.append(final_inpaint_rst)
|
| 848 |
+
print('Finish generating.')
|
| 849 |
+
else:
|
| 850 |
+
final_gen_results_final = final_gen_results_new
|
| 851 |
+
|
| 852 |
+
outputs = final_gen_results_final
|
| 853 |
+
outputs_RGB = []
|
| 854 |
+
for out_tmp in outputs:
|
| 855 |
+
outputs_RGB.append(cv2.cvtColor(out_tmp, cv2.COLOR_BGR2RGB))
|
| 856 |
+
image_path = './lora_result.png'
|
| 857 |
+
if len(outputs) > 0:
|
| 858 |
+
result = concatenate_images(outputs)
|
| 859 |
+
cv2.imwrite(image_path, result)
|
| 860 |
+
|
| 861 |
+
return final_gen_results_final
|
| 862 |
+
|
| 863 |
+
def compress_image(input_path, target_size):
|
| 864 |
+
output_path = change_extension_to_jpg(input_path)
|
| 865 |
+
|
| 866 |
+
image = cv2.imread(input_path)
|
| 867 |
+
|
| 868 |
+
quality = 95
|
| 869 |
+
try:
|
| 870 |
+
while cv2.imencode('.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, quality])[1].size > target_size:
|
| 871 |
+
quality -= 5
|
| 872 |
+
except:
|
| 873 |
+
import pdb;pdb.set_trace()
|
| 874 |
+
|
| 875 |
+
compressed_image = cv2.imencode('.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, quality])[1].tostring()
|
| 876 |
+
|
| 877 |
+
with open(output_path, 'wb') as f:
|
| 878 |
+
f.write(compressed_image)
|
| 879 |
+
return output_path
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
def change_extension_to_jpg(image_path):
|
| 883 |
+
|
| 884 |
+
base_name = os.path.basename(image_path)
|
| 885 |
+
new_base_name = os.path.splitext(base_name)[0] + ".jpg"
|
| 886 |
+
|
| 887 |
+
directory = os.path.dirname(image_path)
|
| 888 |
+
|
| 889 |
+
new_image_path = os.path.join(directory, new_base_name)
|
| 890 |
+
return new_image_path
|
facechain/facechain/merge_lora.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 2 |
+
import torch
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from safetensors.torch import load_file
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def merge_lora(pipeline, lora_path, multiplier, from_safetensor=False, device='cpu', dtype=torch.float32):
|
| 10 |
+
LORA_PREFIX_UNET = "lora_unet"
|
| 11 |
+
LORA_PREFIX_TEXT_ENCODER = "lora_te"
|
| 12 |
+
if from_safetensor:
|
| 13 |
+
state_dict = load_file(lora_path, device=device)
|
| 14 |
+
else:
|
| 15 |
+
if os.path.exists(os.path.join(lora_path, 'pytorch_lora_weights.bin')):
|
| 16 |
+
checkpoint = torch.load(os.path.join(lora_path, 'pytorch_lora_weights.bin'), map_location=torch.device(device))
|
| 17 |
+
elif os.path.exists(os.path.join(lora_path, 'pytorch_lora_weights.safetensors')):
|
| 18 |
+
checkpoint= load_file(os.path.join(lora_path,'pytorch_lora_weights.safetensors'), device=device)
|
| 19 |
+
new_dict = dict()
|
| 20 |
+
for idx, key in enumerate(checkpoint):
|
| 21 |
+
new_key = re.sub(r'\.processor\.', '_', key)
|
| 22 |
+
new_key = re.sub(r'mid_block\.', 'mid_block_', new_key)
|
| 23 |
+
new_key = re.sub('_lora.up.', '.lora_up.', new_key)
|
| 24 |
+
new_key = re.sub('_lora.down.', '.lora_down.', new_key)
|
| 25 |
+
new_key = re.sub(r'\.(\d+)\.', '_\\1_', new_key)
|
| 26 |
+
new_key = re.sub('to_out', 'to_out_0', new_key)
|
| 27 |
+
new_key = 'lora_unet_' + new_key
|
| 28 |
+
new_dict[new_key] = checkpoint[key]
|
| 29 |
+
state_dict = new_dict
|
| 30 |
+
updates = defaultdict(dict)
|
| 31 |
+
for key, value in state_dict.items():
|
| 32 |
+
layer, elem = key.split('.', 1)
|
| 33 |
+
updates[layer][elem] = value
|
| 34 |
+
|
| 35 |
+
for layer, elems in updates.items():
|
| 36 |
+
|
| 37 |
+
if "text" in layer:
|
| 38 |
+
layer_infos = layer.split(LORA_PREFIX_TEXT_ENCODER + "_")[-1].split("_")
|
| 39 |
+
curr_layer = pipeline.text_encoder
|
| 40 |
+
else:
|
| 41 |
+
layer_infos = layer.split(LORA_PREFIX_UNET + "_")[-1].split("_")
|
| 42 |
+
curr_layer = pipeline.unet
|
| 43 |
+
|
| 44 |
+
temp_name = layer_infos.pop(0)
|
| 45 |
+
while len(layer_infos) > -1:
|
| 46 |
+
try:
|
| 47 |
+
curr_layer = curr_layer.__getattr__(temp_name)
|
| 48 |
+
if len(layer_infos) > 0:
|
| 49 |
+
temp_name = layer_infos.pop(0)
|
| 50 |
+
elif len(layer_infos) == 0:
|
| 51 |
+
break
|
| 52 |
+
except Exception:
|
| 53 |
+
if len(layer_infos) == 0:
|
| 54 |
+
print('Error loading layer')
|
| 55 |
+
if len(temp_name) > 0:
|
| 56 |
+
temp_name += "_" + layer_infos.pop(0)
|
| 57 |
+
else:
|
| 58 |
+
temp_name = layer_infos.pop(0)
|
| 59 |
+
|
| 60 |
+
weight_up = elems['lora_up.weight'].to(dtype)
|
| 61 |
+
weight_down = elems['lora_down.weight'].to(dtype)
|
| 62 |
+
if 'alpha' in elems.keys():
|
| 63 |
+
alpha = elems['alpha'].item() / weight_up.shape[1]
|
| 64 |
+
else:
|
| 65 |
+
alpha = 1.0
|
| 66 |
+
|
| 67 |
+
curr_layer.weight.data = curr_layer.weight.data.to(device)
|
| 68 |
+
if len(weight_up.shape) == 4:
|
| 69 |
+
curr_layer.weight.data += multiplier * alpha * torch.mm(weight_up.squeeze(3).squeeze(2),
|
| 70 |
+
weight_down.squeeze(3).squeeze(2)).unsqueeze(
|
| 71 |
+
2).unsqueeze(3)
|
| 72 |
+
else:
|
| 73 |
+
curr_layer.weight.data += multiplier * alpha * torch.mm(weight_up, weight_down)
|
| 74 |
+
|
| 75 |
+
return pipeline
|
facechain/facechain/train_text_to_image_lora.py
ADDED
|
@@ -0,0 +1,1161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 3 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""Fine-tuning script for Stable Diffusion for text2image with support for LoRA."""
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import base64
|
| 20 |
+
import itertools
|
| 21 |
+
import json
|
| 22 |
+
import logging
|
| 23 |
+
import math
|
| 24 |
+
import os
|
| 25 |
+
import random
|
| 26 |
+
import shutil
|
| 27 |
+
from glob import glob
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
import cv2
|
| 31 |
+
import datasets
|
| 32 |
+
import diffusers
|
| 33 |
+
import numpy as np
|
| 34 |
+
import onnxruntime
|
| 35 |
+
import PIL.Image
|
| 36 |
+
import torch
|
| 37 |
+
import torch.nn.functional as F
|
| 38 |
+
import torch.utils.checkpoint
|
| 39 |
+
from torch import Tensor
|
| 40 |
+
from typing import List, Optional, Tuple, Union
|
| 41 |
+
import torchvision.transforms.functional as Ft
|
| 42 |
+
import transformers
|
| 43 |
+
from accelerate import Accelerator
|
| 44 |
+
from accelerate.logging import get_logger
|
| 45 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 46 |
+
from datasets import load_dataset
|
| 47 |
+
from diffusers import (AutoencoderKL, DDPMScheduler, DiffusionPipeline,
|
| 48 |
+
DPMSolverMultistepScheduler,
|
| 49 |
+
StableDiffusionInpaintPipeline, UNet2DConditionModel)
|
| 50 |
+
from diffusers.loaders import AttnProcsLayers
|
| 51 |
+
from diffusers.models.attention_processor import LoRAAttnProcessor
|
| 52 |
+
from diffusers.optimization import get_scheduler
|
| 53 |
+
from diffusers.utils import check_min_version, is_wandb_available
|
| 54 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 55 |
+
from huggingface_hub import create_repo, upload_folder
|
| 56 |
+
from facechain.utils import snapshot_download
|
| 57 |
+
|
| 58 |
+
from packaging import version
|
| 59 |
+
from PIL import Image
|
| 60 |
+
from torchvision import transforms
|
| 61 |
+
from tqdm.auto import tqdm
|
| 62 |
+
from torch import multiprocessing
|
| 63 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 64 |
+
|
| 65 |
+
from facechain.inference import data_process_fn
|
| 66 |
+
|
| 67 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 68 |
+
check_min_version("0.14.0.dev0")
|
| 69 |
+
|
| 70 |
+
logger = get_logger(__name__, log_level="INFO")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class FaceCrop(torch.nn.Module):
|
| 74 |
+
|
| 75 |
+
@staticmethod
|
| 76 |
+
def get_params(img: Tensor) -> Tuple[int, int, int, int]:
|
| 77 |
+
_, h, w = Ft.get_dimensions(img)
|
| 78 |
+
if h != w:
|
| 79 |
+
raise ValueError(f"The input image is not square.")
|
| 80 |
+
ratio = torch.rand(size=(1,)).item() * 0.1 + 0.35
|
| 81 |
+
yc = torch.rand(size=(1,)).item() * 0.15 + 0.35
|
| 82 |
+
|
| 83 |
+
th = int(h / 1.15 * 0.35 / ratio)
|
| 84 |
+
tw = th
|
| 85 |
+
|
| 86 |
+
cx = int(0.5 * w)
|
| 87 |
+
cy = int(0.5 / 1.15 * h)
|
| 88 |
+
|
| 89 |
+
i = min(max(int(cy - yc * th), 0), h - th)
|
| 90 |
+
j = int(cx - 0.5 * tw)
|
| 91 |
+
|
| 92 |
+
return i, j, th, tw
|
| 93 |
+
|
| 94 |
+
def __init__(self):
|
| 95 |
+
super().__init__()
|
| 96 |
+
|
| 97 |
+
def forward(self, img):
|
| 98 |
+
i, j, h, w = self.get_params(img)
|
| 99 |
+
|
| 100 |
+
return Ft.crop(img, i, j, h, w)
|
| 101 |
+
|
| 102 |
+
def __repr__(self) -> str:
|
| 103 |
+
return f"{self.__class__.__name__}"
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def save_model_card(repo_id: str, images=None, base_model=str, dataset_name=str, repo_folder=None):
|
| 107 |
+
img_str = ""
|
| 108 |
+
for i, image in enumerate(images):
|
| 109 |
+
image.save(os.path.join(repo_folder, f"image_{i}.png"))
|
| 110 |
+
img_str += f"\n"
|
| 111 |
+
|
| 112 |
+
yaml = f"""
|
| 113 |
+
---
|
| 114 |
+
license: creativeml-openrail-m
|
| 115 |
+
base_model: {base_model}
|
| 116 |
+
tags:
|
| 117 |
+
- stable-diffusion
|
| 118 |
+
- stable-diffusion-diffusers
|
| 119 |
+
- text-to-image
|
| 120 |
+
- diffusers
|
| 121 |
+
- lora
|
| 122 |
+
inference: true
|
| 123 |
+
---
|
| 124 |
+
"""
|
| 125 |
+
model_card = f"""
|
| 126 |
+
# LoRA text2image fine-tuning - {repo_id}
|
| 127 |
+
These are LoRA adaption weights for {base_model}. The weights were fine-tuned on the {dataset_name} dataset. You can find some example images in the following. \n
|
| 128 |
+
{img_str}
|
| 129 |
+
"""
|
| 130 |
+
with open(os.path.join(repo_folder, "README.md"), "w") as f:
|
| 131 |
+
f.write(yaml + model_card)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def softmax(x):
|
| 135 |
+
x -= np.max(x, axis=0, keepdims=True)
|
| 136 |
+
x = np.exp(x) / np.sum(np.exp(x), axis=0, keepdims=True)
|
| 137 |
+
return x
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def get_rot(image):
|
| 141 |
+
model_dir = snapshot_download('Cherrytest/rot_bgr',
|
| 142 |
+
revision='v1.0.0')
|
| 143 |
+
model_path = os.path.join(model_dir, 'rot_bgr.onnx')
|
| 144 |
+
ort_session = onnxruntime.InferenceSession(model_path)
|
| 145 |
+
|
| 146 |
+
img_cv = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
|
| 147 |
+
img_clone = img_cv.copy()
|
| 148 |
+
img_np = cv2.resize(img_cv, (224, 224))
|
| 149 |
+
img_np = img_np.astype(np.float32)
|
| 150 |
+
mean = np.array([103.53, 116.28, 123.675], dtype=np.float32).reshape((1, 1, 3))
|
| 151 |
+
norm = np.array([0.01742919, 0.017507, 0.01712475], dtype=np.float32).reshape((1, 1, 3))
|
| 152 |
+
img_np = (img_np - mean) * norm
|
| 153 |
+
img_tensor = torch.from_numpy(img_np)
|
| 154 |
+
img_tensor = img_tensor.unsqueeze(0)
|
| 155 |
+
img_nchw = img_tensor.permute(0, 3, 1, 2)
|
| 156 |
+
ort_inputs = {ort_session.get_inputs()[0].name: img_nchw.numpy()}
|
| 157 |
+
outputs = ort_session.run(None, ort_inputs)
|
| 158 |
+
logits = outputs[0].reshape((-1,))
|
| 159 |
+
probs = softmax(logits)
|
| 160 |
+
rot_idx = np.argmax(probs)
|
| 161 |
+
if rot_idx == 1:
|
| 162 |
+
print('rot 90')
|
| 163 |
+
img_clone = cv2.transpose(img_clone)
|
| 164 |
+
img_clone = np.flip(img_clone, 1)
|
| 165 |
+
return Image.fromarray(cv2.cvtColor(img_clone, cv2.COLOR_BGR2RGB))
|
| 166 |
+
elif rot_idx == 2:
|
| 167 |
+
print('rot 180')
|
| 168 |
+
img_clone = cv2.flip(img_clone, -1)
|
| 169 |
+
return Image.fromarray(cv2.cvtColor(img_clone, cv2.COLOR_BGR2RGB))
|
| 170 |
+
elif rot_idx == 3:
|
| 171 |
+
print('rot 270')
|
| 172 |
+
img_clone = cv2.transpose(img_clone)
|
| 173 |
+
img_clone = np.flip(img_clone, 0)
|
| 174 |
+
return Image.fromarray(cv2.cvtColor(img_clone, cv2.COLOR_BGR2RGB))
|
| 175 |
+
else:
|
| 176 |
+
return image
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def prepare_dataset(instance_images: list, output_dataset_dir):
|
| 180 |
+
if not os.path.exists(output_dataset_dir):
|
| 181 |
+
os.makedirs(output_dataset_dir)
|
| 182 |
+
for i, temp_path in enumerate(instance_images):
|
| 183 |
+
image = PIL.Image.open(temp_path)
|
| 184 |
+
# image = PIL.Image.open(temp_path.name)
|
| 185 |
+
'''
|
| 186 |
+
w, h = image.size
|
| 187 |
+
max_size = max(w, h)
|
| 188 |
+
ratio = 1024 / max_size
|
| 189 |
+
new_w = round(w * ratio)
|
| 190 |
+
new_h = round(h * ratio)
|
| 191 |
+
'''
|
| 192 |
+
image = image.convert('RGB')
|
| 193 |
+
image = get_rot(image)
|
| 194 |
+
# image = image.resize((new_w, new_h))
|
| 195 |
+
# image = image.resize((new_w, new_h), PIL.Image.ANTIALIAS)
|
| 196 |
+
out_path = f'{output_dataset_dir}/{i:03d}.jpg'
|
| 197 |
+
image.save(out_path, format='JPEG', quality=100)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def parse_args():
|
| 201 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 202 |
+
parser.add_argument(
|
| 203 |
+
"--pretrained_model_name_or_path",
|
| 204 |
+
type=str,
|
| 205 |
+
default=None,
|
| 206 |
+
required=True,
|
| 207 |
+
help="Path to pretrained model or model identifier.",
|
| 208 |
+
)
|
| 209 |
+
parser.add_argument(
|
| 210 |
+
"--revision",
|
| 211 |
+
type=str,
|
| 212 |
+
default=None,
|
| 213 |
+
required=False,
|
| 214 |
+
help="Revision of pretrained model identifier.",
|
| 215 |
+
)
|
| 216 |
+
parser.add_argument(
|
| 217 |
+
"--sub_path",
|
| 218 |
+
type=str,
|
| 219 |
+
default=None,
|
| 220 |
+
required=False,
|
| 221 |
+
help="The sub model path of the `pretrained_model_name_or_path`",
|
| 222 |
+
)
|
| 223 |
+
parser.add_argument(
|
| 224 |
+
"--dataset_name",
|
| 225 |
+
type=str,
|
| 226 |
+
default=None,
|
| 227 |
+
help=(
|
| 228 |
+
"The data images dir"
|
| 229 |
+
),
|
| 230 |
+
)
|
| 231 |
+
parser.add_argument(
|
| 232 |
+
"--dataset_config_name",
|
| 233 |
+
type=str,
|
| 234 |
+
default=None,
|
| 235 |
+
help="The config of the Dataset, leave as None if there's only one config.",
|
| 236 |
+
)
|
| 237 |
+
parser.add_argument(
|
| 238 |
+
"--train_data_dir",
|
| 239 |
+
type=str,
|
| 240 |
+
default=None,
|
| 241 |
+
help=(
|
| 242 |
+
"A folder containing the training data. Folder contents must follow the structure described in"
|
| 243 |
+
" https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
|
| 244 |
+
" must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
|
| 245 |
+
),
|
| 246 |
+
)
|
| 247 |
+
parser.add_argument(
|
| 248 |
+
"--output_dataset_name",
|
| 249 |
+
type=str,
|
| 250 |
+
default=None,
|
| 251 |
+
help=(
|
| 252 |
+
"The dataset dir after processing"
|
| 253 |
+
),
|
| 254 |
+
)
|
| 255 |
+
parser.add_argument(
|
| 256 |
+
"--image_column", type=str, default="image", help="The column of the dataset containing an image."
|
| 257 |
+
)
|
| 258 |
+
parser.add_argument(
|
| 259 |
+
"--caption_column",
|
| 260 |
+
type=str,
|
| 261 |
+
default="text",
|
| 262 |
+
help="The column of the dataset containing a caption or a list of captions.",
|
| 263 |
+
)
|
| 264 |
+
parser.add_argument(
|
| 265 |
+
"--validation_prompt", type=str, default=None, help="A prompt that is sampled during training for inference."
|
| 266 |
+
)
|
| 267 |
+
parser.add_argument(
|
| 268 |
+
"--num_validation_images",
|
| 269 |
+
type=int,
|
| 270 |
+
default=1,
|
| 271 |
+
help="Number of images that should be generated during validation with `validation_prompt`.",
|
| 272 |
+
)
|
| 273 |
+
parser.add_argument(
|
| 274 |
+
"--validation_epochs",
|
| 275 |
+
type=int,
|
| 276 |
+
default=1,
|
| 277 |
+
help=(
|
| 278 |
+
"Run fine-tuning validation every X epochs. The validation process consists of running the prompt"
|
| 279 |
+
" `args.validation_prompt` multiple times: `args.num_validation_images`."
|
| 280 |
+
),
|
| 281 |
+
)
|
| 282 |
+
parser.add_argument(
|
| 283 |
+
"--max_train_samples",
|
| 284 |
+
type=int,
|
| 285 |
+
default=None,
|
| 286 |
+
help=(
|
| 287 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
| 288 |
+
"value if set."
|
| 289 |
+
),
|
| 290 |
+
)
|
| 291 |
+
parser.add_argument(
|
| 292 |
+
"--output_dir",
|
| 293 |
+
type=str,
|
| 294 |
+
default="sd-model-finetuned-lora",
|
| 295 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 296 |
+
)
|
| 297 |
+
parser.add_argument(
|
| 298 |
+
"--cache_dir",
|
| 299 |
+
type=str,
|
| 300 |
+
default=None,
|
| 301 |
+
help="The directory where the downloaded models and datasets will be stored.",
|
| 302 |
+
)
|
| 303 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 304 |
+
parser.add_argument(
|
| 305 |
+
"--resolution",
|
| 306 |
+
type=int,
|
| 307 |
+
default=512,
|
| 308 |
+
help=(
|
| 309 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 310 |
+
" resolution"
|
| 311 |
+
),
|
| 312 |
+
)
|
| 313 |
+
parser.add_argument(
|
| 314 |
+
"--center_crop",
|
| 315 |
+
default=False,
|
| 316 |
+
action="store_true",
|
| 317 |
+
help=(
|
| 318 |
+
"Whether to center crop the input images to the resolution. If not set, the images will be randomly"
|
| 319 |
+
" cropped. The images will be resized to the resolution first before cropping."
|
| 320 |
+
),
|
| 321 |
+
)
|
| 322 |
+
parser.add_argument(
|
| 323 |
+
"--random_flip",
|
| 324 |
+
action="store_true",
|
| 325 |
+
help="whether to randomly flip images horizontally",
|
| 326 |
+
)
|
| 327 |
+
parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder")
|
| 328 |
+
|
| 329 |
+
# lora args
|
| 330 |
+
parser.add_argument("--use_peft", action="store_true", help="Whether to use peft to support lora")
|
| 331 |
+
parser.add_argument("--lora_r", type=int, default=4, help="Lora rank, only used if use_lora is True")
|
| 332 |
+
parser.add_argument("--lora_alpha", type=int, default=32, help="Lora alpha, only used if lora is True")
|
| 333 |
+
parser.add_argument("--lora_dropout", type=float, default=0.0, help="Lora dropout, only used if use_lora is True")
|
| 334 |
+
parser.add_argument(
|
| 335 |
+
"--lora_bias",
|
| 336 |
+
type=str,
|
| 337 |
+
default="none",
|
| 338 |
+
help="Bias type for Lora. Can be 'none', 'all' or 'lora_only', only used if use_lora is True",
|
| 339 |
+
)
|
| 340 |
+
parser.add_argument(
|
| 341 |
+
"--lora_text_encoder_r",
|
| 342 |
+
type=int,
|
| 343 |
+
default=4,
|
| 344 |
+
help="Lora rank for text encoder, only used if `use_lora` and `train_text_encoder` are True",
|
| 345 |
+
)
|
| 346 |
+
parser.add_argument(
|
| 347 |
+
"--lora_text_encoder_alpha",
|
| 348 |
+
type=int,
|
| 349 |
+
default=32,
|
| 350 |
+
help="Lora alpha for text encoder, only used if `use_lora` and `train_text_encoder` are True",
|
| 351 |
+
)
|
| 352 |
+
parser.add_argument(
|
| 353 |
+
"--lora_text_encoder_dropout",
|
| 354 |
+
type=float,
|
| 355 |
+
default=0.0,
|
| 356 |
+
help="Lora dropout for text encoder, only used if `use_lora` and `train_text_encoder` are True",
|
| 357 |
+
)
|
| 358 |
+
parser.add_argument(
|
| 359 |
+
"--lora_text_encoder_bias",
|
| 360 |
+
type=str,
|
| 361 |
+
default="none",
|
| 362 |
+
help="Bias type for Lora. Can be 'none', 'all' or 'lora_only', only used if use_lora and `train_text_encoder` are True",
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
parser.add_argument(
|
| 366 |
+
"--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
|
| 367 |
+
)
|
| 368 |
+
parser.add_argument("--num_train_epochs", type=int, default=100)
|
| 369 |
+
parser.add_argument(
|
| 370 |
+
"--max_train_steps",
|
| 371 |
+
type=int,
|
| 372 |
+
default=None,
|
| 373 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 374 |
+
)
|
| 375 |
+
parser.add_argument(
|
| 376 |
+
"--gradient_accumulation_steps",
|
| 377 |
+
type=int,
|
| 378 |
+
default=1,
|
| 379 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 380 |
+
)
|
| 381 |
+
parser.add_argument(
|
| 382 |
+
"--gradient_checkpointing",
|
| 383 |
+
action="store_true",
|
| 384 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 385 |
+
)
|
| 386 |
+
parser.add_argument(
|
| 387 |
+
"--learning_rate",
|
| 388 |
+
type=float,
|
| 389 |
+
default=1e-4,
|
| 390 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 391 |
+
)
|
| 392 |
+
parser.add_argument(
|
| 393 |
+
"--scale_lr",
|
| 394 |
+
action="store_true",
|
| 395 |
+
default=False,
|
| 396 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 397 |
+
)
|
| 398 |
+
parser.add_argument(
|
| 399 |
+
"--lr_scheduler",
|
| 400 |
+
type=str,
|
| 401 |
+
default="constant",
|
| 402 |
+
help=(
|
| 403 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 404 |
+
' "constant", "constant_with_warmup"]'
|
| 405 |
+
),
|
| 406 |
+
)
|
| 407 |
+
parser.add_argument(
|
| 408 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 409 |
+
)
|
| 410 |
+
parser.add_argument(
|
| 411 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
| 412 |
+
)
|
| 413 |
+
parser.add_argument(
|
| 414 |
+
"--allow_tf32",
|
| 415 |
+
action="store_true",
|
| 416 |
+
help=(
|
| 417 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 418 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 419 |
+
),
|
| 420 |
+
)
|
| 421 |
+
parser.add_argument(
|
| 422 |
+
"--dataloader_num_workers",
|
| 423 |
+
type=int,
|
| 424 |
+
default=0,
|
| 425 |
+
help=(
|
| 426 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 427 |
+
),
|
| 428 |
+
)
|
| 429 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 430 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 431 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 432 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 433 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 434 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 435 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 436 |
+
parser.add_argument(
|
| 437 |
+
"--hub_model_id",
|
| 438 |
+
type=str,
|
| 439 |
+
default=None,
|
| 440 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 441 |
+
)
|
| 442 |
+
parser.add_argument(
|
| 443 |
+
"--logging_dir",
|
| 444 |
+
type=str,
|
| 445 |
+
default="logs",
|
| 446 |
+
help=(
|
| 447 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 448 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 449 |
+
),
|
| 450 |
+
)
|
| 451 |
+
parser.add_argument(
|
| 452 |
+
"--mixed_precision",
|
| 453 |
+
type=str,
|
| 454 |
+
default=None,
|
| 455 |
+
choices=["no", "fp16", "bf16"],
|
| 456 |
+
help=(
|
| 457 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 458 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 459 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 460 |
+
),
|
| 461 |
+
)
|
| 462 |
+
parser.add_argument(
|
| 463 |
+
"--report_to",
|
| 464 |
+
type=str,
|
| 465 |
+
default="tensorboard",
|
| 466 |
+
help=(
|
| 467 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 468 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 469 |
+
),
|
| 470 |
+
)
|
| 471 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 472 |
+
parser.add_argument(
|
| 473 |
+
"--checkpointing_steps",
|
| 474 |
+
type=int,
|
| 475 |
+
default=500,
|
| 476 |
+
help=(
|
| 477 |
+
"Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
|
| 478 |
+
" training using `--resume_from_checkpoint`."
|
| 479 |
+
),
|
| 480 |
+
)
|
| 481 |
+
parser.add_argument(
|
| 482 |
+
"--checkpoints_total_limit",
|
| 483 |
+
type=int,
|
| 484 |
+
default=None,
|
| 485 |
+
help=(
|
| 486 |
+
"Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
|
| 487 |
+
" See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
|
| 488 |
+
" for more docs"
|
| 489 |
+
),
|
| 490 |
+
)
|
| 491 |
+
parser.add_argument(
|
| 492 |
+
"--resume_from_checkpoint",
|
| 493 |
+
type=str,
|
| 494 |
+
default=None,
|
| 495 |
+
help=(
|
| 496 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 497 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 498 |
+
),
|
| 499 |
+
)
|
| 500 |
+
parser.add_argument(
|
| 501 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
args = parser.parse_args()
|
| 505 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 506 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 507 |
+
args.local_rank = env_local_rank
|
| 508 |
+
|
| 509 |
+
# Sanity checks
|
| 510 |
+
if args.dataset_name is None and args.train_data_dir is None and args.output_dataset_name is None:
|
| 511 |
+
raise ValueError("Need either a dataset name or a training folder.")
|
| 512 |
+
|
| 513 |
+
return args
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
DATASET_NAME_MAPPING = {
|
| 517 |
+
"lambdalabs/pokemon-blip-captions": ("image", "text"),
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def main():
|
| 522 |
+
|
| 523 |
+
args = parse_args()
|
| 524 |
+
logging_dir = os.path.join(args.output_dir, args.logging_dir)
|
| 525 |
+
shutil.rmtree(args.output_dir, ignore_errors=True)
|
| 526 |
+
os.makedirs(args.output_dir)
|
| 527 |
+
|
| 528 |
+
if args.dataset_name is not None:
|
| 529 |
+
# if dataset_name is None, then it's called from the gradio
|
| 530 |
+
# the data processing will be executed in the app.py to save the gpu memory.
|
| 531 |
+
print('All input images:', args.dataset_name)
|
| 532 |
+
args.dataset_name = [os.path.join(args.dataset_name, x) for x in os.listdir(args.dataset_name)]
|
| 533 |
+
shutil.rmtree(args.output_dataset_name, ignore_errors=True)
|
| 534 |
+
prepare_dataset(args.dataset_name, args.output_dataset_name)
|
| 535 |
+
## Our data process fn
|
| 536 |
+
data_process_fn(input_img_dir=args.output_dataset_name, use_data_process=True)
|
| 537 |
+
|
| 538 |
+
args.dataset_name = args.output_dataset_name + '_labeled'
|
| 539 |
+
|
| 540 |
+
accelerator_project_config = ProjectConfiguration(
|
| 541 |
+
total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
accelerator = Accelerator(
|
| 545 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 546 |
+
mixed_precision=args.mixed_precision,
|
| 547 |
+
log_with=args.report_to,
|
| 548 |
+
project_config=accelerator_project_config,
|
| 549 |
+
)
|
| 550 |
+
if args.report_to == "wandb":
|
| 551 |
+
if not is_wandb_available():
|
| 552 |
+
raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
|
| 553 |
+
import wandb
|
| 554 |
+
|
| 555 |
+
# Make one log on every process with the configuration for debugging.
|
| 556 |
+
logging.basicConfig(
|
| 557 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 558 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 559 |
+
level=logging.INFO,
|
| 560 |
+
)
|
| 561 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 562 |
+
if accelerator.is_local_main_process:
|
| 563 |
+
datasets.utils.logging.set_verbosity_warning()
|
| 564 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 565 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 566 |
+
else:
|
| 567 |
+
datasets.utils.logging.set_verbosity_error()
|
| 568 |
+
transformers.utils.logging.set_verbosity_error()
|
| 569 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 570 |
+
|
| 571 |
+
# If passed along, set the training seed now.
|
| 572 |
+
if args.seed is not None:
|
| 573 |
+
set_seed(args.seed)
|
| 574 |
+
|
| 575 |
+
# Handle the repository creation
|
| 576 |
+
if accelerator.is_main_process:
|
| 577 |
+
if args.output_dir is not None:
|
| 578 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 579 |
+
|
| 580 |
+
if args.push_to_hub:
|
| 581 |
+
repo_id = create_repo(
|
| 582 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 583 |
+
).repo_id
|
| 584 |
+
|
| 585 |
+
## Download foundation Model
|
| 586 |
+
model_dir = snapshot_download(args.pretrained_model_name_or_path,
|
| 587 |
+
revision=args.revision,
|
| 588 |
+
user_agent={'invoked_by': 'trainer', 'third_party': 'facechain'})
|
| 589 |
+
|
| 590 |
+
if args.sub_path is not None and len(args.sub_path) > 0:
|
| 591 |
+
model_dir = os.path.join(model_dir, args.sub_path)
|
| 592 |
+
|
| 593 |
+
# Load scheduler, tokenizer and models.
|
| 594 |
+
noise_scheduler = DDPMScheduler.from_pretrained(model_dir, subfolder="scheduler")
|
| 595 |
+
tokenizer = CLIPTokenizer.from_pretrained(
|
| 596 |
+
model_dir, subfolder="tokenizer"
|
| 597 |
+
)
|
| 598 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
| 599 |
+
model_dir, subfolder="text_encoder"
|
| 600 |
+
)
|
| 601 |
+
vae = AutoencoderKL.from_pretrained(model_dir, subfolder="vae")
|
| 602 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 603 |
+
model_dir, subfolder="unet"
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
| 607 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 608 |
+
weight_dtype = torch.float32
|
| 609 |
+
if accelerator.mixed_precision == "fp16":
|
| 610 |
+
weight_dtype = torch.float16
|
| 611 |
+
elif accelerator.mixed_precision == "bf16":
|
| 612 |
+
weight_dtype = torch.bfloat16
|
| 613 |
+
|
| 614 |
+
if args.use_peft:
|
| 615 |
+
from peft import LoraConfig, LoraModel, get_peft_model_state_dict, set_peft_model_state_dict
|
| 616 |
+
|
| 617 |
+
UNET_TARGET_MODULES = ["to_q", "to_v", "query", "value"]
|
| 618 |
+
TEXT_ENCODER_TARGET_MODULES = ["q_proj", "v_proj"]
|
| 619 |
+
|
| 620 |
+
config = LoraConfig(
|
| 621 |
+
r=args.lora_r,
|
| 622 |
+
lora_alpha=args.lora_alpha,
|
| 623 |
+
target_modules=UNET_TARGET_MODULES,
|
| 624 |
+
lora_dropout=args.lora_dropout,
|
| 625 |
+
bias=args.lora_bias,
|
| 626 |
+
)
|
| 627 |
+
unet = LoraModel(config, unet)
|
| 628 |
+
|
| 629 |
+
vae.requires_grad_(False)
|
| 630 |
+
if args.train_text_encoder:
|
| 631 |
+
config = LoraConfig(
|
| 632 |
+
r=args.lora_text_encoder_r,
|
| 633 |
+
lora_alpha=args.lora_text_encoder_alpha,
|
| 634 |
+
target_modules=TEXT_ENCODER_TARGET_MODULES,
|
| 635 |
+
lora_dropout=args.lora_text_encoder_dropout,
|
| 636 |
+
bias=args.lora_text_encoder_bias,
|
| 637 |
+
)
|
| 638 |
+
text_encoder = LoraModel(config, text_encoder)
|
| 639 |
+
else:
|
| 640 |
+
# freeze parameters of models to save more memory
|
| 641 |
+
unet.requires_grad_(False)
|
| 642 |
+
vae.requires_grad_(False)
|
| 643 |
+
|
| 644 |
+
text_encoder.requires_grad_(False)
|
| 645 |
+
|
| 646 |
+
# now we will add new LoRA weights to the attention layers
|
| 647 |
+
# It's important to realize here how many attention weights will be added and of which sizes
|
| 648 |
+
# The sizes of the attention layers consist only of two different variables:
|
| 649 |
+
# 1) - the "hidden_size", which is increased according to `unet.config.block_out_channels`.
|
| 650 |
+
# 2) - the "cross attention size", which is set to `unet.config.cross_attention_dim`.
|
| 651 |
+
|
| 652 |
+
# Let's first see how many attention processors we will have to set.
|
| 653 |
+
# For Stable Diffusion, it should be equal to:
|
| 654 |
+
# - down blocks (2x attention layers) * (2x transformer layers) * (3x down blocks) = 12
|
| 655 |
+
# - mid blocks (2x attention layers) * (1x transformer layers) * (1x mid blocks) = 2
|
| 656 |
+
# - up blocks (2x attention layers) * (3x transformer layers) * (3x down blocks) = 18
|
| 657 |
+
# => 32 layers
|
| 658 |
+
|
| 659 |
+
# Set correct lora layers
|
| 660 |
+
lora_attn_procs = {}
|
| 661 |
+
for name in unet.attn_processors.keys():
|
| 662 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
| 663 |
+
if name.startswith("mid_block"):
|
| 664 |
+
hidden_size = unet.config.block_out_channels[-1]
|
| 665 |
+
elif name.startswith("up_blocks"):
|
| 666 |
+
block_id = int(name[len("up_blocks.")])
|
| 667 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
| 668 |
+
elif name.startswith("down_blocks"):
|
| 669 |
+
block_id = int(name[len("down_blocks.")])
|
| 670 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
| 671 |
+
|
| 672 |
+
lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=args.lora_r)
|
| 673 |
+
|
| 674 |
+
unet.set_attn_processor(lora_attn_procs)
|
| 675 |
+
lora_layers = AttnProcsLayers(unet.attn_processors)
|
| 676 |
+
|
| 677 |
+
# Move unet, vae and text_encoder to device and cast to weight_dtype
|
| 678 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 679 |
+
if not args.train_text_encoder:
|
| 680 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 681 |
+
|
| 682 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 683 |
+
if is_xformers_available():
|
| 684 |
+
import xformers
|
| 685 |
+
|
| 686 |
+
xformers_version = version.parse(xformers.__version__)
|
| 687 |
+
if xformers_version == version.parse("0.0.16"):
|
| 688 |
+
logger.warn(
|
| 689 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
| 690 |
+
)
|
| 691 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 692 |
+
else:
|
| 693 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 694 |
+
|
| 695 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 696 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 697 |
+
if args.allow_tf32:
|
| 698 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 699 |
+
|
| 700 |
+
if args.scale_lr:
|
| 701 |
+
args.learning_rate = (
|
| 702 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
# Initialize the optimizer
|
| 706 |
+
if args.use_8bit_adam:
|
| 707 |
+
try:
|
| 708 |
+
import bitsandbytes as bnb
|
| 709 |
+
except ImportError:
|
| 710 |
+
raise ImportError(
|
| 711 |
+
"Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
|
| 712 |
+
)
|
| 713 |
+
|
| 714 |
+
optimizer_cls = bnb.optim.AdamW8bit
|
| 715 |
+
else:
|
| 716 |
+
optimizer_cls = torch.optim.AdamW
|
| 717 |
+
|
| 718 |
+
if args.use_peft:
|
| 719 |
+
# Optimizer creation
|
| 720 |
+
params_to_optimize = (
|
| 721 |
+
itertools.chain(unet.parameters(), text_encoder.parameters())
|
| 722 |
+
if args.train_text_encoder
|
| 723 |
+
else unet.parameters()
|
| 724 |
+
)
|
| 725 |
+
optimizer = optimizer_cls(
|
| 726 |
+
params_to_optimize,
|
| 727 |
+
lr=args.learning_rate,
|
| 728 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 729 |
+
weight_decay=args.adam_weight_decay,
|
| 730 |
+
eps=args.adam_epsilon,
|
| 731 |
+
)
|
| 732 |
+
else:
|
| 733 |
+
optimizer = optimizer_cls(
|
| 734 |
+
lora_layers.parameters(),
|
| 735 |
+
lr=args.learning_rate,
|
| 736 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 737 |
+
weight_decay=args.adam_weight_decay,
|
| 738 |
+
eps=args.adam_epsilon,
|
| 739 |
+
)
|
| 740 |
+
|
| 741 |
+
# Get the datasets: you can either provide your own training and evaluation files (see below)
|
| 742 |
+
# or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
|
| 743 |
+
|
| 744 |
+
# In distributed training, the load_dataset function guarantees that only one local process can concurrently
|
| 745 |
+
# download the dataset.
|
| 746 |
+
if args.dataset_name is not None:
|
| 747 |
+
# Downloading and loading a dataset from the hub.
|
| 748 |
+
dataset = load_dataset(
|
| 749 |
+
args.dataset_name,
|
| 750 |
+
args.dataset_config_name,
|
| 751 |
+
cache_dir=args.cache_dir,
|
| 752 |
+
)
|
| 753 |
+
else:
|
| 754 |
+
# This branch will not be called
|
| 755 |
+
data_files = {}
|
| 756 |
+
if args.train_data_dir is not None:
|
| 757 |
+
data_files["train"] = os.path.join(args.train_data_dir, "**")
|
| 758 |
+
dataset = load_dataset(
|
| 759 |
+
"imagefolder",
|
| 760 |
+
data_files=data_files,
|
| 761 |
+
cache_dir=args.cache_dir,
|
| 762 |
+
)
|
| 763 |
+
# See more about loading custom images at
|
| 764 |
+
# https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
|
| 765 |
+
|
| 766 |
+
# Preprocessing the datasets.
|
| 767 |
+
# We need to tokenize inputs and targets.
|
| 768 |
+
column_names = dataset["train"].column_names
|
| 769 |
+
|
| 770 |
+
# 6. Get the column names for input/target.
|
| 771 |
+
dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None)
|
| 772 |
+
if args.image_column is None:
|
| 773 |
+
image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
|
| 774 |
+
else:
|
| 775 |
+
image_column = args.image_column
|
| 776 |
+
if image_column not in column_names:
|
| 777 |
+
raise ValueError(
|
| 778 |
+
f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}"
|
| 779 |
+
)
|
| 780 |
+
if args.caption_column is None:
|
| 781 |
+
caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
|
| 782 |
+
else:
|
| 783 |
+
caption_column = args.caption_column
|
| 784 |
+
if caption_column not in column_names:
|
| 785 |
+
raise ValueError(
|
| 786 |
+
f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}"
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
# Preprocessing the datasets.
|
| 790 |
+
# We need to tokenize input captions and transform the images.
|
| 791 |
+
def tokenize_captions(examples, is_train=True):
|
| 792 |
+
captions = []
|
| 793 |
+
for caption in examples[caption_column]:
|
| 794 |
+
if isinstance(caption, str):
|
| 795 |
+
captions.append(caption)
|
| 796 |
+
elif isinstance(caption, (list, np.ndarray)):
|
| 797 |
+
# take a random caption if there are multiple
|
| 798 |
+
captions.append(random.choice(caption) if is_train else caption[0])
|
| 799 |
+
else:
|
| 800 |
+
raise ValueError(
|
| 801 |
+
f"Caption column `{caption_column}` should contain either strings or lists of strings."
|
| 802 |
+
)
|
| 803 |
+
inputs = tokenizer(
|
| 804 |
+
captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
|
| 805 |
+
)
|
| 806 |
+
return inputs.input_ids
|
| 807 |
+
|
| 808 |
+
# Preprocessing the datasets.
|
| 809 |
+
train_transforms = transforms.Compose(
|
| 810 |
+
[
|
| 811 |
+
#transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 812 |
+
#transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
|
| 813 |
+
FaceCrop(),
|
| 814 |
+
transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 815 |
+
transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
|
| 816 |
+
transforms.ToTensor(),
|
| 817 |
+
transforms.Normalize([0.5], [0.5]),
|
| 818 |
+
]
|
| 819 |
+
)
|
| 820 |
+
|
| 821 |
+
def preprocess_train(examples):
|
| 822 |
+
images = [image.convert("RGB") for image in examples[image_column]]
|
| 823 |
+
examples["pixel_values"] = [train_transforms(image) for image in images]
|
| 824 |
+
examples["input_ids"] = tokenize_captions(examples)
|
| 825 |
+
return examples
|
| 826 |
+
|
| 827 |
+
with accelerator.main_process_first():
|
| 828 |
+
if args.max_train_samples is not None:
|
| 829 |
+
dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
|
| 830 |
+
# Set the training transforms
|
| 831 |
+
train_dataset = dataset["train"].with_transform(preprocess_train)
|
| 832 |
+
|
| 833 |
+
def collate_fn(examples):
|
| 834 |
+
pixel_values = torch.stack([example["pixel_values"] for example in examples])
|
| 835 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 836 |
+
input_ids = torch.stack([example["input_ids"] for example in examples])
|
| 837 |
+
return {"pixel_values": pixel_values, "input_ids": input_ids}
|
| 838 |
+
|
| 839 |
+
# DataLoaders creation:
|
| 840 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 841 |
+
train_dataset,
|
| 842 |
+
shuffle=True,
|
| 843 |
+
collate_fn=collate_fn,
|
| 844 |
+
batch_size=args.train_batch_size,
|
| 845 |
+
num_workers=args.dataloader_num_workers,
|
| 846 |
+
)
|
| 847 |
+
|
| 848 |
+
# Scheduler and math around the number of training steps.
|
| 849 |
+
overrode_max_train_steps = False
|
| 850 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 851 |
+
if args.max_train_steps is None:
|
| 852 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 853 |
+
overrode_max_train_steps = True
|
| 854 |
+
|
| 855 |
+
lr_scheduler = get_scheduler(
|
| 856 |
+
args.lr_scheduler,
|
| 857 |
+
optimizer=optimizer,
|
| 858 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 859 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 860 |
+
)
|
| 861 |
+
|
| 862 |
+
# Prepare everything with our `accelerator`.
|
| 863 |
+
if args.use_peft:
|
| 864 |
+
if args.train_text_encoder:
|
| 865 |
+
unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 866 |
+
unet, text_encoder, optimizer, train_dataloader, lr_scheduler
|
| 867 |
+
)
|
| 868 |
+
else:
|
| 869 |
+
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 870 |
+
unet, optimizer, train_dataloader, lr_scheduler
|
| 871 |
+
)
|
| 872 |
+
else:
|
| 873 |
+
lora_layers, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 874 |
+
lora_layers, optimizer, train_dataloader, lr_scheduler
|
| 875 |
+
)
|
| 876 |
+
unet = unet.cuda()
|
| 877 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 878 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 879 |
+
if overrode_max_train_steps:
|
| 880 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 881 |
+
# Afterwards we recalculate our number of training epochs
|
| 882 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 883 |
+
|
| 884 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 885 |
+
# The trackers initializes automatically on the main process.
|
| 886 |
+
if accelerator.is_main_process:
|
| 887 |
+
accelerator.init_trackers("text2image-fine-tune", config=vars(args))
|
| 888 |
+
|
| 889 |
+
# Train!
|
| 890 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 891 |
+
|
| 892 |
+
logger.info("***** Running training *****")
|
| 893 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 894 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 895 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 896 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 897 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 898 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 899 |
+
global_step = 0
|
| 900 |
+
first_epoch = 0
|
| 901 |
+
|
| 902 |
+
# Potentially load in the weights and states from a previous save
|
| 903 |
+
if args.resume_from_checkpoint:
|
| 904 |
+
if args.resume_from_checkpoint == 'fromfacecommon':
|
| 905 |
+
weight_model_dir = snapshot_download('damo/face_frombase_c4',
|
| 906 |
+
revision='v1.0.0',
|
| 907 |
+
user_agent={'invoked_by': 'trainer', 'third_party': 'facechain'})
|
| 908 |
+
path = os.path.join(weight_model_dir, 'face_frombase_c4.bin')
|
| 909 |
+
elif args.resume_from_checkpoint != "latest":
|
| 910 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 911 |
+
else:
|
| 912 |
+
# Get the most recent checkpoint
|
| 913 |
+
dirs = os.listdir(args.output_dir)
|
| 914 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 915 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 916 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 917 |
+
|
| 918 |
+
if path is None:
|
| 919 |
+
accelerator.print(
|
| 920 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 921 |
+
)
|
| 922 |
+
args.resume_from_checkpoint = None
|
| 923 |
+
else:
|
| 924 |
+
if args.resume_from_checkpoint == 'fromfacecommon':
|
| 925 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 926 |
+
unet_state_dict = torch.load(path, map_location='cpu')
|
| 927 |
+
accelerator._models[-1].load_state_dict(unet_state_dict)
|
| 928 |
+
global_step = 0
|
| 929 |
+
else:
|
| 930 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 931 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 932 |
+
global_step = int(path.split("-")[1])
|
| 933 |
+
|
| 934 |
+
resume_global_step = global_step * args.gradient_accumulation_steps
|
| 935 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 936 |
+
resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
|
| 937 |
+
|
| 938 |
+
# Only show the progress bar once on each machine.
|
| 939 |
+
progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
|
| 940 |
+
progress_bar.set_description("Steps")
|
| 941 |
+
|
| 942 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 943 |
+
unet.train()
|
| 944 |
+
if args.train_text_encoder:
|
| 945 |
+
text_encoder.train()
|
| 946 |
+
train_loss = 0.0
|
| 947 |
+
for step, batch in enumerate(train_dataloader):
|
| 948 |
+
# Skip steps until we reach the resumed step
|
| 949 |
+
if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
|
| 950 |
+
if step % args.gradient_accumulation_steps == 0:
|
| 951 |
+
progress_bar.update(1)
|
| 952 |
+
continue
|
| 953 |
+
|
| 954 |
+
with accelerator.accumulate(unet):
|
| 955 |
+
# Convert images to latent space
|
| 956 |
+
latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
|
| 957 |
+
latents = latents * vae.config.scaling_factor
|
| 958 |
+
|
| 959 |
+
# Sample noise that we'll add to the latents
|
| 960 |
+
noise = torch.randn_like(latents)
|
| 961 |
+
bsz = latents.shape[0]
|
| 962 |
+
# Sample a random timestep for each image
|
| 963 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
| 964 |
+
timesteps = timesteps.long()
|
| 965 |
+
|
| 966 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 967 |
+
# (this is the forward diffusion process)
|
| 968 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 969 |
+
|
| 970 |
+
# Get the text embedding for conditioning
|
| 971 |
+
encoder_hidden_states = text_encoder(batch["input_ids"])[0]
|
| 972 |
+
|
| 973 |
+
# Get the target for loss depending on the prediction type
|
| 974 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 975 |
+
target = noise
|
| 976 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 977 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 978 |
+
else:
|
| 979 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 980 |
+
|
| 981 |
+
# Predict the noise residual and compute loss
|
| 982 |
+
model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
| 983 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
| 984 |
+
|
| 985 |
+
# Gather the losses across all processes for logging (if we use distributed training).
|
| 986 |
+
avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
|
| 987 |
+
train_loss += avg_loss.item() / args.gradient_accumulation_steps
|
| 988 |
+
|
| 989 |
+
# Backpropagate
|
| 990 |
+
accelerator.backward(loss)
|
| 991 |
+
if accelerator.sync_gradients:
|
| 992 |
+
if args.use_peft:
|
| 993 |
+
params_to_clip = (
|
| 994 |
+
itertools.chain(unet.parameters(), text_encoder.parameters())
|
| 995 |
+
if args.train_text_encoder
|
| 996 |
+
else unet.parameters()
|
| 997 |
+
)
|
| 998 |
+
else:
|
| 999 |
+
params_to_clip = lora_layers.parameters()
|
| 1000 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
| 1001 |
+
optimizer.step()
|
| 1002 |
+
lr_scheduler.step()
|
| 1003 |
+
optimizer.zero_grad()
|
| 1004 |
+
|
| 1005 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 1006 |
+
if accelerator.sync_gradients:
|
| 1007 |
+
progress_bar.update(1)
|
| 1008 |
+
global_step += 1
|
| 1009 |
+
accelerator.log({"train_loss": train_loss}, step=global_step)
|
| 1010 |
+
train_loss = 0.0
|
| 1011 |
+
|
| 1012 |
+
if global_step % args.checkpointing_steps == 0:
|
| 1013 |
+
if accelerator.is_main_process:
|
| 1014 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 1015 |
+
accelerator.save_state(save_path)
|
| 1016 |
+
logger.info(f"Saved state to {save_path}")
|
| 1017 |
+
|
| 1018 |
+
logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 1019 |
+
progress_bar.set_postfix(**logs)
|
| 1020 |
+
|
| 1021 |
+
if global_step >= args.max_train_steps:
|
| 1022 |
+
break
|
| 1023 |
+
|
| 1024 |
+
|
| 1025 |
+
if accelerator.is_main_process:
|
| 1026 |
+
if args.validation_prompt is not None and epoch % args.validation_epochs == 0:
|
| 1027 |
+
logger.info(
|
| 1028 |
+
f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
|
| 1029 |
+
f" {args.validation_prompt}."
|
| 1030 |
+
)
|
| 1031 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 1032 |
+
model_dir,
|
| 1033 |
+
unet=accelerator.unwrap_model(unet),
|
| 1034 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
| 1035 |
+
torch_dtype=weight_dtype,
|
| 1036 |
+
)
|
| 1037 |
+
pipeline = pipeline.to(accelerator.device)
|
| 1038 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 1039 |
+
|
| 1040 |
+
# run inference
|
| 1041 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
|
| 1042 |
+
images = []
|
| 1043 |
+
for _ in range(args.num_validation_images):
|
| 1044 |
+
images.append(
|
| 1045 |
+
pipeline(args.validation_prompt, num_inference_steps=30, generator=generator).images[0]
|
| 1046 |
+
)
|
| 1047 |
+
|
| 1048 |
+
if accelerator.is_main_process:
|
| 1049 |
+
for tracker in accelerator.trackers:
|
| 1050 |
+
if tracker.name == "tensorboard":
|
| 1051 |
+
np_images = np.stack([np.asarray(img) for img in images])
|
| 1052 |
+
tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
|
| 1053 |
+
if tracker.name == "wandb":
|
| 1054 |
+
tracker.log(
|
| 1055 |
+
{
|
| 1056 |
+
"validation": [
|
| 1057 |
+
wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
|
| 1058 |
+
for i, image in enumerate(images)
|
| 1059 |
+
]
|
| 1060 |
+
}
|
| 1061 |
+
)
|
| 1062 |
+
|
| 1063 |
+
del pipeline
|
| 1064 |
+
torch.cuda.empty_cache()
|
| 1065 |
+
|
| 1066 |
+
# Save the lora layers
|
| 1067 |
+
accelerator.wait_for_everyone()
|
| 1068 |
+
if accelerator.is_main_process:
|
| 1069 |
+
if args.use_peft:
|
| 1070 |
+
lora_config = {}
|
| 1071 |
+
unwarpped_unet = accelerator.unwrap_model(unet)
|
| 1072 |
+
state_dict = get_peft_model_state_dict(unwarpped_unet, state_dict=accelerator.get_state_dict(unet))
|
| 1073 |
+
lora_config["peft_config"] = unwarpped_unet.get_peft_config_as_dict(inference=True)
|
| 1074 |
+
if args.train_text_encoder:
|
| 1075 |
+
unwarpped_text_encoder = accelerator.unwrap_model(text_encoder)
|
| 1076 |
+
text_encoder_state_dict = get_peft_model_state_dict(
|
| 1077 |
+
unwarpped_text_encoder, state_dict=accelerator.get_state_dict(text_encoder)
|
| 1078 |
+
)
|
| 1079 |
+
text_encoder_state_dict = {f"text_encoder_{k}": v for k, v in text_encoder_state_dict.items()}
|
| 1080 |
+
state_dict.update(text_encoder_state_dict)
|
| 1081 |
+
lora_config["text_encoder_peft_config"] = unwarpped_text_encoder.get_peft_config_as_dict(
|
| 1082 |
+
inference=True
|
| 1083 |
+
)
|
| 1084 |
+
|
| 1085 |
+
accelerator.save(state_dict, os.path.join(args.output_dir, f"{global_step}_lora.pt"))
|
| 1086 |
+
with open(os.path.join(args.output_dir, f"{global_step}_lora_config.json"), "w") as f:
|
| 1087 |
+
json.dump(lora_config, f)
|
| 1088 |
+
else:
|
| 1089 |
+
unet = unet.to(torch.float32)
|
| 1090 |
+
unet.save_attn_procs(args.output_dir, safe_serialization=False)
|
| 1091 |
+
|
| 1092 |
+
if args.push_to_hub:
|
| 1093 |
+
save_model_card(
|
| 1094 |
+
repo_id,
|
| 1095 |
+
images=images,
|
| 1096 |
+
base_model=model_dir,
|
| 1097 |
+
dataset_name=args.dataset_name,
|
| 1098 |
+
repo_folder=args.output_dir,
|
| 1099 |
+
)
|
| 1100 |
+
upload_folder(
|
| 1101 |
+
repo_id=repo_id,
|
| 1102 |
+
folder_path=args.output_dir,
|
| 1103 |
+
commit_message="End of training",
|
| 1104 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 1105 |
+
)
|
| 1106 |
+
|
| 1107 |
+
# Final inference
|
| 1108 |
+
# Load previous pipeline
|
| 1109 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 1110 |
+
model_dir, torch_dtype=weight_dtype
|
| 1111 |
+
)
|
| 1112 |
+
|
| 1113 |
+
if args.use_peft:
|
| 1114 |
+
def load_and_set_lora_ckpt(pipe, ckpt_dir, global_step, device, dtype):
|
| 1115 |
+
with open(os.path.join(args.output_dir, f"{global_step}_lora_config.json"), "r") as f:
|
| 1116 |
+
lora_config = json.load(f)
|
| 1117 |
+
print(lora_config)
|
| 1118 |
+
|
| 1119 |
+
checkpoint = os.path.join(args.output_dir, f"{global_step}_lora.pt")
|
| 1120 |
+
lora_checkpoint_sd = torch.load(checkpoint)
|
| 1121 |
+
unet_lora_ds = {k: v for k, v in lora_checkpoint_sd.items() if "text_encoder_" not in k}
|
| 1122 |
+
text_encoder_lora_ds = {
|
| 1123 |
+
k.replace("text_encoder_", ""): v for k, v in lora_checkpoint_sd.items() if "text_encoder_" in k
|
| 1124 |
+
}
|
| 1125 |
+
|
| 1126 |
+
unet_config = LoraConfig(**lora_config["peft_config"])
|
| 1127 |
+
pipe.unet = LoraModel(unet_config, pipe.unet)
|
| 1128 |
+
set_peft_model_state_dict(pipe.unet, unet_lora_ds)
|
| 1129 |
+
|
| 1130 |
+
if "text_encoder_peft_config" in lora_config:
|
| 1131 |
+
text_encoder_config = LoraConfig(**lora_config["text_encoder_peft_config"])
|
| 1132 |
+
pipe.text_encoder = LoraModel(text_encoder_config, pipe.text_encoder)
|
| 1133 |
+
set_peft_model_state_dict(pipe.text_encoder, text_encoder_lora_ds)
|
| 1134 |
+
|
| 1135 |
+
if dtype in (torch.float16, torch.bfloat16):
|
| 1136 |
+
pipe.unet.half()
|
| 1137 |
+
pipe.text_encoder.half()
|
| 1138 |
+
|
| 1139 |
+
pipe.to(device)
|
| 1140 |
+
return pipe
|
| 1141 |
+
|
| 1142 |
+
pipeline = load_and_set_lora_ckpt(pipeline, args.output_dir, global_step, accelerator.device, weight_dtype)
|
| 1143 |
+
|
| 1144 |
+
else:
|
| 1145 |
+
pipeline = pipeline.to(accelerator.device)
|
| 1146 |
+
# load attention processors
|
| 1147 |
+
pipeline.unet.load_attn_procs(args.output_dir)
|
| 1148 |
+
|
| 1149 |
+
# run inference
|
| 1150 |
+
if args.seed is not None:
|
| 1151 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
|
| 1152 |
+
else:
|
| 1153 |
+
generator = None
|
| 1154 |
+
images = []
|
| 1155 |
+
|
| 1156 |
+
accelerator.end_training()
|
| 1157 |
+
|
| 1158 |
+
|
| 1159 |
+
if __name__ == "__main__":
|
| 1160 |
+
multiprocessing.set_start_method('spawn')
|
| 1161 |
+
main()
|
facechain/facechain/utils.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 2 |
+
|
| 3 |
+
import time
|
| 4 |
+
from modelscope import snapshot_download as ms_snapshot_download
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def max_retries(max_attempts):
|
| 8 |
+
def decorator(func):
|
| 9 |
+
def wrapper(*args, **kwargs):
|
| 10 |
+
attempts = 0
|
| 11 |
+
while attempts < max_attempts:
|
| 12 |
+
try:
|
| 13 |
+
return func(*args, **kwargs)
|
| 14 |
+
except Exception as e:
|
| 15 |
+
attempts += 1
|
| 16 |
+
print(f"Retry {attempts}/{max_attempts}: {e}")
|
| 17 |
+
# wait 1 sec
|
| 18 |
+
time.sleep(1)
|
| 19 |
+
raise Exception(f"Max retries ({max_attempts}) exceeded.")
|
| 20 |
+
return wrapper
|
| 21 |
+
return decorator
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@max_retries(3)
|
| 25 |
+
def snapshot_download(*args, **kwargs):
|
| 26 |
+
return ms_snapshot_download(*args, **kwargs)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def pre_download_models():
|
| 30 |
+
snapshot_download('ly261666/cv_portrait_model', revision='v4.0')
|
| 31 |
+
snapshot_download('YorickHe/majicmixRealistic_v6', revision='v1.0.0')
|
| 32 |
+
snapshot_download('damo/face_chain_control_model', revision='v1.0.1')
|
| 33 |
+
snapshot_download('ly261666/cv_wanx_style_model', revision='v1.0.3')
|
| 34 |
+
snapshot_download('damo/face_chain_control_model', revision='v1.0.1')
|
| 35 |
+
snapshot_download('Cherrytest/z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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 0,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"colab": {
|
| 6 |
+
"private_outputs": true,
|
| 7 |
+
"provenance": [],
|
| 8 |
+
"machine_shape": "hm",
|
| 9 |
+
"name": "facechain-demo.ipynb"
|
| 10 |
+
},
|
| 11 |
+
"kernelspec": {
|
| 12 |
+
"name": "python3",
|
| 13 |
+
"display_name": "Python 3"
|
| 14 |
+
}
|
| 15 |
+
},
|
| 16 |
+
"cells": [
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "markdown",
|
| 19 |
+
"source": [
|
| 20 |
+
"Requirements:\n",
|
| 21 |
+
"- GPU Mem Usage: 19G\n",
|
| 22 |
+
"- Disk Usage: About 50G"
|
| 23 |
+
],
|
| 24 |
+
"metadata": {
|
| 25 |
+
"id": "AzOycrSUkK-0"
|
| 26 |
+
}
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"cell_type": "markdown",
|
| 30 |
+
"source": [
|
| 31 |
+
"## Get facechain source code from GitHub"
|
| 32 |
+
],
|
| 33 |
+
"metadata": {
|
| 34 |
+
"id": "8yQEWTkekIx9"
|
| 35 |
+
}
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"cell_type": "code",
|
| 39 |
+
"source": [
|
| 40 |
+
"!GIT_LFS_SKIP_SMUDGE=1 git clone https://github.com/modelscope/facechain.git --depth 1"
|
| 41 |
+
],
|
| 42 |
+
"metadata": {
|
| 43 |
+
"id": "WK_uDw0NkHTP"
|
| 44 |
+
},
|
| 45 |
+
"execution_count": null,
|
| 46 |
+
"outputs": []
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"cell_type": "markdown",
|
| 50 |
+
"source": [
|
| 51 |
+
"## Installation requirements\n",
|
| 52 |
+
"- Note that you can ignore warning on dependencies conflicts at the end\n",
|
| 53 |
+
"- You may use conda virtual env to avoid warning info."
|
| 54 |
+
],
|
| 55 |
+
"metadata": {
|
| 56 |
+
"id": "jUWWSGDG1ZGK"
|
| 57 |
+
}
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "code",
|
| 61 |
+
"source": [
|
| 62 |
+
"!pip3 install -r facechain/requirements.txt"
|
| 63 |
+
],
|
| 64 |
+
"metadata": {
|
| 65 |
+
"id": "QrwRDBipxKZw"
|
| 66 |
+
},
|
| 67 |
+
"execution_count": null,
|
| 68 |
+
"outputs": []
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"cell_type": "markdown",
|
| 72 |
+
"source": [
|
| 73 |
+
"## Check environment informaiton"
|
| 74 |
+
],
|
| 75 |
+
"metadata": {
|
| 76 |
+
"id": "0miaB1nC2VrA"
|
| 77 |
+
}
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "code",
|
| 81 |
+
"source": [
|
| 82 |
+
"!nvidia-smi\n",
|
| 83 |
+
"!pip3 show torch\n",
|
| 84 |
+
"\n",
|
| 85 |
+
"# Note that this setup is verified on (cuda 12.0, torch2.0.1+cu118, Nvidia-A100 40G)"
|
| 86 |
+
],
|
| 87 |
+
"metadata": {
|
| 88 |
+
"id": "uvNE0kRxyI4q"
|
| 89 |
+
},
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"outputs": []
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "markdown",
|
| 95 |
+
"source": [],
|
| 96 |
+
"metadata": {
|
| 97 |
+
"id": "klba298h2bbu"
|
| 98 |
+
}
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "markdown",
|
| 102 |
+
"source": [
|
| 103 |
+
"## Installing mmcv-full\n",
|
| 104 |
+
"- Several of the underlying models depend on mmcv-full, which could be tricky to install since it is environment-dependent, you may refer to [mmcv's official documentation](https://mmcv.readthedocs.io/zh_CN/latest/get_started/installation.html) for more details..\n",
|
| 105 |
+
"- A prebuilt package is provided here for convenience, and was verified on (cuda 12.0, torch2.0.1+cu118, Nvidia-A100 40G)\n",
|
| 106 |
+
"- If the prebuilt package does not work on your env setup, please use the alternative installation as suggested by [mmcv's official documentation](https://mmcv.readthedocs.io/zh_CN/latest/get_started/)"
|
| 107 |
+
],
|
| 108 |
+
"metadata": {
|
| 109 |
+
"id": "ciSxxSzI4l_u"
|
| 110 |
+
}
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"cell_type": "code",
|
| 114 |
+
"source": [
|
| 115 |
+
"# use prebuilt mmcv-full package provided by ModelScope (verified on cuda 12.0, torch2.0.1+cu118, Nvidia-A100 40G)\n",
|
| 116 |
+
"!pip3 install https://modelscope.oss-cn-beijing.aliyuncs.com/packages/mmcv/mmcv_full-1.7.0-cp310-cp310-linux_x86_64.whl\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"# alternative manual installtation. note that it may take 30+ mins for building dependencies.\n",
|
| 119 |
+
"# !pip3 install -U openmim\n",
|
| 120 |
+
"# !mim install mmcv-full==1.7.0\n"
|
| 121 |
+
],
|
| 122 |
+
"metadata": {
|
| 123 |
+
"id": "t2lciBXyyuzA"
|
| 124 |
+
},
|
| 125 |
+
"execution_count": null,
|
| 126 |
+
"outputs": []
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "markdown",
|
| 130 |
+
"source": [
|
| 131 |
+
"## Pre-download models to mitigate connection timeout issue"
|
| 132 |
+
],
|
| 133 |
+
"metadata": {
|
| 134 |
+
"collapsed": false
|
| 135 |
+
}
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "code",
|
| 139 |
+
"execution_count": null,
|
| 140 |
+
"outputs": [],
|
| 141 |
+
"source": [
|
| 142 |
+
"import os\n",
|
| 143 |
+
"os.chdir('/content/facechain') # Note: replace with your facechain root\n",
|
| 144 |
+
"print(os.getcwd())\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"# Not required\n",
|
| 147 |
+
"from facechain.utils import pre_download_models\n",
|
| 148 |
+
"pre_download_models()"
|
| 149 |
+
],
|
| 150 |
+
"metadata": {
|
| 151 |
+
"collapsed": false
|
| 152 |
+
}
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "markdown",
|
| 156 |
+
"source": [
|
| 157 |
+
"## Start facechain WebUI service"
|
| 158 |
+
],
|
| 159 |
+
"metadata": {
|
| 160 |
+
"id": "OxDgRY8H4vta"
|
| 161 |
+
}
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"source": [
|
| 166 |
+
"# Install service dependencies\n",
|
| 167 |
+
"!pip3 install gradio\n",
|
| 168 |
+
"!pip3 install controlnet_aux==0.0.6\n",
|
| 169 |
+
"!pip3 install python-slugify\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"# Click on the gradio URL to start building your FaceChain digital-twin!\n",
|
| 172 |
+
"!python3 app.py"
|
| 173 |
+
],
|
| 174 |
+
"metadata": {
|
| 175 |
+
"id": "NW5o0iiezTCg"
|
| 176 |
+
},
|
| 177 |
+
"execution_count": null,
|
| 178 |
+
"outputs": []
|
| 179 |
+
}
|
| 180 |
+
]
|
| 181 |
+
}
|
facechain/poses/man/pose1.png
ADDED
|
Git LFS Details
|
facechain/poses/man/pose2.png
ADDED
|
Git LFS Details
|
facechain/poses/man/pose3.png
ADDED
|
Git LFS Details
|
facechain/poses/man/pose4.png
ADDED
|
Git LFS Details
|
facechain/poses/woman/pose1.png
ADDED
|
Git LFS Details
|
facechain/poses/woman/pose2.png
ADDED
|
Git LFS Details
|
facechain/poses/woman/pose3.png
ADDED
|
Git LFS Details
|
facechain/poses/woman/pose4.png
ADDED
|
Git LFS Details
|
facechain/requirements.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accelerate
|
| 2 |
+
transformers
|
| 3 |
+
diffusers
|
| 4 |
+
onnxruntime
|
| 5 |
+
modelscope
|
| 6 |
+
Pillow
|
| 7 |
+
opencv-python
|
| 8 |
+
torchvision
|
| 9 |
+
mmdet==2.26.0
|
| 10 |
+
mmengine
|
| 11 |
+
numpy==1.22.0
|
| 12 |
+
protobuf==3.20.1
|
| 13 |
+
timm
|
| 14 |
+
scikit-image
|
| 15 |
+
gradio
|
| 16 |
+
controlnet_aux==0.0.6
|
| 17 |
+
mediapipe
|
| 18 |
+
python-slugify
|
| 19 |
+
#tensorflow==2.8.0
|
| 20 |
+
#tensorflow-cpu # slower but no cuda conflicts
|
| 21 |
+
|
| 22 |
+
# mmcv-full (need mim install)
|
facechain/resources/awesome-prompts-facechain.txt
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# style model: default
|
| 2 |
+
an elegant evening gown, upper_body, best quality, Professional
|
| 3 |
+
|
| 4 |
+
# style model: default
|
| 5 |
+
beautiful traditional hanfu, upper_body, best quality, Professional
|
| 6 |
+
|
| 7 |
+
# style model: default
|
| 8 |
+
The lord of the rings, ELF, Arwen Undomiel, beautiful, upper_body, best quality, Professional
|
| 9 |
+
|
| 10 |
+
# style model: default
|
| 11 |
+
Beautiful and cute girl, 16 years old, denim jacket, gradient background, soft colors, soft lighting, cinematic edge lighting, light and dark contrast, anime, art station Seraflur, blind box, super detail, 8k,--iw 1
|
| 12 |
+
|
| 13 |
+
# style model: default
|
| 14 |
+
beautiful woman, realistic, Dappled Light, analog style, cinematic light, sidelighting, ultra high res, best shadow, RAW, beautiful hair, designer jacket, fashionable pants, turtleneck shirt, fall forest, Looking over the shoulder pose, professional model photoshoot, hdr, sunset
|
facechain/resources/example1.jpg
ADDED
|
Git LFS Details
|
facechain/resources/example2.jpg
ADDED
|
Git LFS Details
|
facechain/resources/example3.jpg
ADDED
|
Git LFS Details
|
facechain/resources/framework.jpg
ADDED
|
Git LFS Details
|
facechain/resources/framework_eng.jpg
ADDED
|
Git LFS Details
|
facechain/resources/git_cover.jpg
ADDED
|
Git LFS Details
|
facechain/resources/git_cover_1.jpg
ADDED
|
Git LFS Details
|
facechain/resources/git_cover_2.jpg
ADDED
|
Git LFS Details
|
facechain/resources/git_cover_CH.jpg
ADDED
|
Git LFS Details
|
facechain/resources/inpaint_template/1.jpg
ADDED
|
Git LFS Details
|
facechain/resources/inpaint_template/2.jpg
ADDED
|
Git LFS Details
|
facechain/resources/inpaint_template/3.jpg
ADDED
|
Git LFS Details
|
facechain/resources/inpaint_template/4.jpg
ADDED
|
Git LFS Details
|
facechain/resources/inpaint_template/5.jpg
ADDED
|
Git LFS Details
|
facechain/resources/prompt_elf_lord_of_rings.jpg
ADDED
|
Git LFS Details
|
facechain/resources/style_lora_xiapei.jpg
ADDED
|
Git LFS Details
|
facechain/run_inference.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
from facechain.inference import GenPortrait
|
| 5 |
+
import cv2
|
| 6 |
+
from facechain.utils import snapshot_download
|
| 7 |
+
from facechain.constants import neg_prompt, pos_prompt_with_cloth, pos_prompt_with_style, styles, base_models
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def generate_pos_prompt(style_model, prompt_cloth):
|
| 11 |
+
if style_model in base_models[0]['style_list'][:-1] or style_model is None:
|
| 12 |
+
pos_prompt = pos_prompt_with_cloth.format(prompt_cloth)
|
| 13 |
+
else:
|
| 14 |
+
matched = list(filter(lambda style: style_model == style['name'], styles))
|
| 15 |
+
if len(matched) == 0:
|
| 16 |
+
raise ValueError(f'styles not found: {style_model}')
|
| 17 |
+
matched = matched[0]
|
| 18 |
+
pos_prompt = pos_prompt_with_style.format(matched['add_prompt_style'])
|
| 19 |
+
return pos_prompt
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
use_main_model = True
|
| 23 |
+
use_face_swap = True
|
| 24 |
+
use_post_process = True
|
| 25 |
+
use_stylization = False
|
| 26 |
+
use_depth_control = False
|
| 27 |
+
use_pose_model = False
|
| 28 |
+
pose_image = 'poses/man/pose1.png'
|
| 29 |
+
processed_dir = './processed'
|
| 30 |
+
num_generate = 5
|
| 31 |
+
base_model = 'ly261666/cv_portrait_model'
|
| 32 |
+
revision = 'v2.0'
|
| 33 |
+
multiplier_style = 0.25
|
| 34 |
+
multiplier_human = 0.85
|
| 35 |
+
base_model_sub_dir = 'film/film'
|
| 36 |
+
train_output_dir = './output'
|
| 37 |
+
output_dir = './generated'
|
| 38 |
+
style = styles[0]
|
| 39 |
+
model_id = style['model_id']
|
| 40 |
+
|
| 41 |
+
if model_id == None:
|
| 42 |
+
style_model_path = None
|
| 43 |
+
pos_prompt = generate_pos_prompt(style['name'], style['add_prompt_style'])
|
| 44 |
+
else:
|
| 45 |
+
if os.path.exists(model_id):
|
| 46 |
+
model_dir = model_id
|
| 47 |
+
else:
|
| 48 |
+
model_dir = snapshot_download(model_id, revision=style['revision'])
|
| 49 |
+
style_model_path = os.path.join(model_dir, style['bin_file'])
|
| 50 |
+
pos_prompt = generate_pos_prompt(style['name'], style['add_prompt_style']) # style has its own prompt
|
| 51 |
+
|
| 52 |
+
if not use_pose_model:
|
| 53 |
+
pose_model_path = None
|
| 54 |
+
use_depth_control = False
|
| 55 |
+
pose_image = None
|
| 56 |
+
else:
|
| 57 |
+
model_dir = snapshot_download('damo/face_chain_control_model', revision='v1.0.1')
|
| 58 |
+
pose_model_path = os.path.join(model_dir, 'model_controlnet/control_v11p_sd15_openpose')
|
| 59 |
+
|
| 60 |
+
gen_portrait = GenPortrait(pose_model_path, pose_image, use_depth_control, pos_prompt, neg_prompt, style_model_path,
|
| 61 |
+
multiplier_style, multiplier_human, use_main_model,
|
| 62 |
+
use_face_swap, use_post_process,
|
| 63 |
+
use_stylization)
|
| 64 |
+
|
| 65 |
+
outputs = gen_portrait(processed_dir, num_generate, base_model,
|
| 66 |
+
train_output_dir, base_model_sub_dir, revision)
|
| 67 |
+
|
| 68 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 69 |
+
|
| 70 |
+
for i, out_tmp in enumerate(outputs):
|
| 71 |
+
cv2.imwrite(os.path.join(output_dir, f'{i}.png'), out_tmp)
|
| 72 |
+
|
facechain/style_image/Armor.jpg
ADDED
|
Git LFS Details
|
facechain/style_image/Chinese_traditional_gorgeous_suit.jpg
ADDED
|
Git LFS Details
|
facechain/style_image/Chinese_winter_hanfu.jpg
ADDED
|
Git LFS Details
|
facechain/style_image/Cybernetics_punk.jpg
ADDED
|
Git LFS Details
|