Fernando22 fffiloni commited on
Commit
875c77e
0 Parent(s):

Duplicate from fffiloni/ControlNet-Video

Browse files

Co-authored-by: Sylvain Filoni <fffiloni@users.noreply.huggingface.co>

Files changed (14) hide show
  1. .gitattributes +34 -0
  2. .gitignore +162 -0
  3. .gitmodules +3 -0
  4. .pre-commit-config.yaml +37 -0
  5. .style.yapf +5 -0
  6. ControlNet +1 -0
  7. LICENSE.ControlNet +201 -0
  8. README.md +14 -0
  9. app.py +344 -0
  10. model.py +760 -0
  11. patch +115 -0
  12. requirements.txt +24 -0
  13. share_btn.py +86 -0
  14. style.css +105 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ models/
2
+
3
+ # Byte-compiled / optimized / DLL files
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+
8
+ # C extensions
9
+ *.so
10
+
11
+ # Distribution / packaging
12
+ .Python
13
+ build/
14
+ develop-eggs/
15
+ dist/
16
+ downloads/
17
+ eggs/
18
+ .eggs/
19
+ lib/
20
+ lib64/
21
+ parts/
22
+ sdist/
23
+ var/
24
+ wheels/
25
+ share/python-wheels/
26
+ *.egg-info/
27
+ .installed.cfg
28
+ *.egg
29
+ MANIFEST
30
+
31
+ # PyInstaller
32
+ # Usually these files are written by a python script from a template
33
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
34
+ *.manifest
35
+ *.spec
36
+
37
+ # Installer logs
38
+ pip-log.txt
39
+ pip-delete-this-directory.txt
40
+
41
+ # Unit test / coverage reports
42
+ htmlcov/
43
+ .tox/
44
+ .nox/
45
+ .coverage
46
+ .coverage.*
47
+ .cache
48
+ nosetests.xml
49
+ coverage.xml
50
+ *.cover
51
+ *.py,cover
52
+ .hypothesis/
53
+ .pytest_cache/
54
+ cover/
55
+
56
+ # Translations
57
+ *.mo
58
+ *.pot
59
+
60
+ # Django stuff:
61
+ *.log
62
+ local_settings.py
63
+ db.sqlite3
64
+ db.sqlite3-journal
65
+
66
+ # Flask stuff:
67
+ instance/
68
+ .webassets-cache
69
+
70
+ # Scrapy stuff:
71
+ .scrapy
72
+
73
+ # Sphinx documentation
74
+ docs/_build/
75
+
76
+ # PyBuilder
77
+ .pybuilder/
78
+ target/
79
+
80
+ # Jupyter Notebook
81
+ .ipynb_checkpoints
82
+
83
+ # IPython
84
+ profile_default/
85
+ ipython_config.py
86
+
87
+ # pyenv
88
+ # For a library or package, you might want to ignore these files since the code is
89
+ # intended to run in multiple environments; otherwise, check them in:
90
+ # .python-version
91
+
92
+ # pipenv
93
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
94
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
95
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
96
+ # install all needed dependencies.
97
+ #Pipfile.lock
98
+
99
+ # poetry
100
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
101
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
102
+ # commonly ignored for libraries.
103
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
104
+ #poetry.lock
105
+
106
+ # pdm
107
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
108
+ #pdm.lock
109
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
110
+ # in version control.
111
+ # https://pdm.fming.dev/#use-with-ide
112
+ .pdm.toml
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "ControlNet"]
2
+ path = ControlNet
3
+ url = https://github.com/lllyasviel/ControlNet
.pre-commit-config.yaml ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ exclude: patch
2
+ repos:
3
+ - repo: https://github.com/pre-commit/pre-commit-hooks
4
+ rev: v4.2.0
5
+ hooks:
6
+ - id: check-executables-have-shebangs
7
+ - id: check-json
8
+ - id: check-merge-conflict
9
+ - id: check-shebang-scripts-are-executable
10
+ - id: check-toml
11
+ - id: check-yaml
12
+ - id: double-quote-string-fixer
13
+ - id: end-of-file-fixer
14
+ - id: mixed-line-ending
15
+ args: ['--fix=lf']
16
+ - id: requirements-txt-fixer
17
+ - id: trailing-whitespace
18
+ - repo: https://github.com/myint/docformatter
19
+ rev: v1.4
20
+ hooks:
21
+ - id: docformatter
22
+ args: ['--in-place']
23
+ - repo: https://github.com/pycqa/isort
24
+ rev: 5.12.0
25
+ hooks:
26
+ - id: isort
27
+ - repo: https://github.com/pre-commit/mirrors-mypy
28
+ rev: v0.991
29
+ hooks:
30
+ - id: mypy
31
+ args: ['--ignore-missing-imports']
32
+ additional_dependencies: ['types-python-slugify']
33
+ - repo: https://github.com/google/yapf
34
+ rev: v0.32.0
35
+ hooks:
36
+ - id: yapf
37
+ args: ['--parallel', '--in-place']
.style.yapf ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [style]
2
+ based_on_style = pep8
3
+ blank_line_before_nested_class_or_def = false
4
+ spaces_before_comment = 2
5
+ split_before_logical_operator = true
ControlNet ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit f4748e3630d8141d7765e2bd9b1e348f47847707
LICENSE.ControlNet ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: ControlNet-Video
3
+ emoji: 🕹
4
+ colorFrom: pink
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 3.34.0
8
+ python_version: 3.10.9
9
+ app_file: app.py
10
+ pinned: false
11
+ duplicated_from: fffiloni/ControlNet-Video
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import gradio as gr
3
+ import os
4
+ import cv2
5
+ import numpy as np
6
+ from PIL import Image
7
+ from moviepy.editor import *
8
+ from share_btn import community_icon_html, loading_icon_html, share_js
9
+
10
+ import pathlib
11
+ import shlex
12
+ import subprocess
13
+
14
+ if os.getenv('SYSTEM') == 'spaces':
15
+ with open('patch') as f:
16
+ subprocess.run(shlex.split('patch -p1'), stdin=f, cwd='ControlNet')
17
+
18
+ base_url = 'https://huggingface.co/lllyasviel/ControlNet/resolve/main/annotator/ckpts/'
19
+
20
+ names = [
21
+ 'body_pose_model.pth',
22
+ 'dpt_hybrid-midas-501f0c75.pt',
23
+ 'hand_pose_model.pth',
24
+ 'mlsd_large_512_fp32.pth',
25
+ 'mlsd_tiny_512_fp32.pth',
26
+ 'network-bsds500.pth',
27
+ 'upernet_global_small.pth',
28
+ ]
29
+
30
+ for name in names:
31
+ command = f'wget https://huggingface.co/lllyasviel/ControlNet/resolve/main/annotator/ckpts/{name} -O {name}'
32
+ out_path = pathlib.Path(f'ControlNet/annotator/ckpts/{name}')
33
+ if out_path.exists():
34
+ continue
35
+ subprocess.run(shlex.split(command), cwd='ControlNet/annotator/ckpts/')
36
+
37
+ from model import (DEFAULT_BASE_MODEL_FILENAME, DEFAULT_BASE_MODEL_REPO,
38
+ DEFAULT_BASE_MODEL_URL, Model)
39
+
40
+ model = Model()
41
+
42
+
43
+ def controlnet(i, prompt, control_task, seed_in, ddim_steps, scale, low_threshold, high_threshold, value_threshold, distance_threshold, bg_threshold):
44
+ img= Image.open(i)
45
+ np_img = np.array(img)
46
+
47
+ a_prompt = "best quality, extremely detailed"
48
+ n_prompt = "longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality"
49
+ num_samples = 1
50
+ image_resolution = 512
51
+ detect_resolution = 512
52
+ eta = 0.0
53
+ #low_threshold = 100
54
+ #high_threshold = 200
55
+ #value_threshold = 0.1
56
+ #distance_threshold = 0.1
57
+ #bg_threshold = 0.4
58
+
59
+ if control_task == 'Canny':
60
+ result = model.process_canny(np_img, prompt, a_prompt, n_prompt, num_samples,
61
+ image_resolution, ddim_steps, scale, seed_in, eta, low_threshold, high_threshold)
62
+ elif control_task == 'Depth':
63
+ result = model.process_depth(np_img, prompt, a_prompt, n_prompt, num_samples,
64
+ image_resolution, detect_resolution, ddim_steps, scale, seed_in, eta)
65
+ elif control_task == 'Hed':
66
+ result = model.process_hed(np_img, prompt, a_prompt, n_prompt, num_samples,
67
+ image_resolution, detect_resolution, ddim_steps, scale, seed_in, eta)
68
+ elif control_task == 'Hough':
69
+ result = model.process_hough(np_img, prompt, a_prompt, n_prompt, num_samples,
70
+ image_resolution, detect_resolution, ddim_steps, scale, seed_in, eta, value_threshold,
71
+ distance_threshold)
72
+ elif control_task == 'Normal':
73
+ result = model.process_normal(np_img, prompt, a_prompt, n_prompt, num_samples,
74
+ image_resolution, detect_resolution, ddim_steps, scale, seed_in, eta, bg_threshold)
75
+ elif control_task == 'Pose':
76
+ result = model.process_pose(np_img, prompt, a_prompt, n_prompt, num_samples,
77
+ image_resolution, detect_resolution, ddim_steps, scale, seed_in, eta)
78
+ elif control_task == 'Scribble':
79
+ result = model.process_scribble(np_img, prompt, a_prompt, n_prompt, num_samples,
80
+ image_resolution, ddim_steps, scale, seed_in, eta)
81
+ elif control_task == 'Seg':
82
+ result = model.process_seg(np_img, prompt, a_prompt, n_prompt, num_samples,
83
+ image_resolution, detect_resolution, ddim_steps, scale, seed_in, eta)
84
+
85
+ #print(result[0])
86
+ processor_im = Image.fromarray(result[0])
87
+ processor_im.save("process_" + control_task + "_" + str(i) + ".jpeg")
88
+ im = Image.fromarray(result[1])
89
+ im.save("your_file" + str(i) + ".jpeg")
90
+ return "your_file" + str(i) + ".jpeg", "process_" + control_task + "_" + str(i) + ".jpeg"
91
+
92
+ def change_task_options(task):
93
+ if task == "Canny" :
94
+ return canny_opt.update(visible=True), hough_opt.update(visible=False), normal_opt.update(visible=False)
95
+ elif task == "Hough" :
96
+ return canny_opt.update(visible=False),hough_opt.update(visible=True), normal_opt.update(visible=False)
97
+ elif task == "Normal" :
98
+ return canny_opt.update(visible=False),hough_opt.update(visible=False), normal_opt.update(visible=True)
99
+ else :
100
+ return canny_opt.update(visible=False),hough_opt.update(visible=False), normal_opt.update(visible=False)
101
+
102
+ def get_frames(video_in):
103
+ frames = []
104
+ #resize the video
105
+ clip = VideoFileClip(video_in)
106
+
107
+ #check fps
108
+ if clip.fps > 30:
109
+ print("vide rate is over 30, resetting to 30")
110
+ clip_resized = clip.resize(height=512)
111
+ clip_resized.write_videofile("video_resized.mp4", fps=30)
112
+ else:
113
+ print("video rate is OK")
114
+ clip_resized = clip.resize(height=512)
115
+ clip_resized.write_videofile("video_resized.mp4", fps=clip.fps)
116
+
117
+ print("video resized to 512 height")
118
+
119
+ # Opens the Video file with CV2
120
+ cap= cv2.VideoCapture("video_resized.mp4")
121
+
122
+ fps = cap.get(cv2.CAP_PROP_FPS)
123
+ print("video fps: " + str(fps))
124
+ i=0
125
+ while(cap.isOpened()):
126
+ ret, frame = cap.read()
127
+ if ret == False:
128
+ break
129
+ cv2.imwrite('kang'+str(i)+'.jpg',frame)
130
+ frames.append('kang'+str(i)+'.jpg')
131
+ i+=1
132
+
133
+ cap.release()
134
+ cv2.destroyAllWindows()
135
+ print("broke the video into frames")
136
+
137
+ return frames, fps
138
+
139
+
140
+ def convert(gif):
141
+ if gif != None:
142
+ clip = VideoFileClip(gif.name)
143
+ clip.write_videofile("my_gif_video.mp4")
144
+ return "my_gif_video.mp4"
145
+ else:
146
+ pass
147
+
148
+
149
+ def create_video(frames, fps, type):
150
+ print("building video result")
151
+ clip = ImageSequenceClip(frames, fps=fps)
152
+ clip.write_videofile(type + "_result.mp4", fps=fps)
153
+
154
+ return type + "_result.mp4"
155
+
156
+
157
+ def infer(prompt,video_in, control_task, seed_in, trim_value, ddim_steps, scale, low_threshold, high_threshold, value_threshold, distance_threshold, bg_threshold, gif_import):
158
+ print(f"""
159
+ ———————————————
160
+ {prompt}
161
+ ———————————————""")
162
+
163
+ # 1. break video into frames and get FPS
164
+ break_vid = get_frames(video_in)
165
+ frames_list= break_vid[0]
166
+ fps = break_vid[1]
167
+ n_frame = int(trim_value*fps)
168
+
169
+ if n_frame >= len(frames_list):
170
+ print("video is shorter than the cut value")
171
+ n_frame = len(frames_list)
172
+
173
+ # 2. prepare frames result arrays
174
+ processor_result_frames = []
175
+ result_frames = []
176
+ print("set stop frames to: " + str(n_frame))
177
+
178
+ for i in frames_list[0:int(n_frame)]:
179
+ controlnet_img = controlnet(i, prompt,control_task, seed_in, ddim_steps, scale, low_threshold, high_threshold, value_threshold, distance_threshold, bg_threshold)
180
+ #images = controlnet_img[0]
181
+ #rgb_im = images[0].convert("RGB")
182
+
183
+ # exporting the image
184
+ #rgb_im.save(f"result_img-{i}.jpg")
185
+ processor_result_frames.append(controlnet_img[1])
186
+ result_frames.append(controlnet_img[0])
187
+ print("frame " + i + "/" + str(n_frame) + ": done;")
188
+
189
+ processor_vid = create_video(processor_result_frames, fps, "processor")
190
+ final_vid = create_video(result_frames, fps, "final")
191
+
192
+ files = [processor_vid, final_vid]
193
+ if gif_import != None:
194
+ final_gif = VideoFileClip(final_vid)
195
+ final_gif.write_gif("final_result.gif")
196
+ final_gif = "final_result.gif"
197
+
198
+ files.append(final_gif)
199
+ print("finished !")
200
+
201
+ return final_vid, gr.Accordion.update(visible=True), gr.Video.update(value=processor_vid, visible=True), gr.File.update(value=files, visible=True), gr.Group.update(visible=True)
202
+
203
+
204
+ def clean():
205
+ return gr.Accordion.update(visible=False),gr.Video.update(value=None, visible=False), gr.Video.update(value=None), gr.File.update(value=None, visible=False), gr.Group.update(visible=False)
206
+
207
+ title = """
208
+ <div style="text-align: center; max-width: 700px; margin: 0 auto;">
209
+ <div
210
+ style="
211
+ display: inline-flex;
212
+ align-items: center;
213
+ gap: 0.8rem;
214
+ font-size: 1.75rem;
215
+ "
216
+ >
217
+ <h1 style="font-weight: 900; margin-bottom: 7px; margin-top: 5px;">
218
+ ControlNet Video
219
+ </h1>
220
+ </div>
221
+ <p style="margin-bottom: 10px; font-size: 94%">
222
+ Apply ControlNet to a video
223
+ </p>
224
+ </div>
225
+ """
226
+
227
+ article = """
228
+
229
+ <div class="footer">
230
+ <p>
231
+ Follow <a href="https://twitter.com/fffiloni" target="_blank">Sylvain Filoni</a> for future updates 🤗
232
+ </p>
233
+ </div>
234
+ <div id="may-like-container" style="display: flex;justify-content: center;flex-direction: column;align-items: center;margin-bottom: 30px;">
235
+ <p>You may also like: </p>
236
+ <div id="may-like-content" style="display:flex;flex-wrap: wrap;align-items:center;height:20px;">
237
+
238
+ <svg height="20" width="148" style="margin-left:4px;margin-bottom: 6px;">
239
+ <a href="https://huggingface.co/spaces/fffiloni/Pix2Pix-Video" target="_blank">
240
+ <image href="https://img.shields.io/badge/🤗 Spaces-Pix2Pix_Video-blue" src="https://img.shields.io/badge/🤗 Spaces-Pix2Pix_Video-blue.png" height="20"/>
241
+ </a>
242
+ </svg>
243
+
244
+ </div>
245
+
246
+ </div>
247
+
248
+ """
249
+
250
+ with gr.Blocks(css='style.css') as demo:
251
+ with gr.Column(elem_id="col-container"):
252
+ gr.HTML(title)
253
+ gr.HTML("""
254
+ <a style="display:inline-block" href="https://huggingface.co/spaces/fffiloni/ControlNet-Video?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a>
255
+ """, elem_id="duplicate-container")
256
+ with gr.Row():
257
+ with gr.Column():
258
+ video_inp = gr.Video(label="Video source", source="upload", type="filepath", elem_id="input-vid")
259
+ video_out = gr.Video(label="ControlNet video result", elem_id="video-output")
260
+
261
+ with gr.Group(elem_id="share-btn-container", visible=False) as share_group:
262
+ community_icon = gr.HTML(community_icon_html)
263
+ loading_icon = gr.HTML(loading_icon_html)
264
+ share_button = gr.Button("Share to community", elem_id="share-btn")
265
+
266
+ with gr.Accordion("Detailed results", visible=False) as detailed_result:
267
+ prep_video_out = gr.Video(label="Preprocessor video result", visible=False, elem_id="prep-video-output")
268
+ files = gr.File(label="Files can be downloaded ;)", visible=False)
269
+
270
+ with gr.Column():
271
+ #status = gr.Textbox()
272
+
273
+ prompt = gr.Textbox(label="Prompt", placeholder="enter prompt", show_label=True, elem_id="prompt-in")
274
+
275
+ with gr.Row():
276
+ control_task = gr.Dropdown(label="Control Task", choices=["Canny", "Depth", "Hed", "Hough", "Normal", "Pose", "Scribble", "Seg"], value="Pose", multiselect=False, elem_id="controltask-in")
277
+ seed_inp = gr.Slider(label="Seed", minimum=0, maximum=2147483647, step=1, value=123456, elem_id="seed-in")
278
+
279
+ with gr.Row():
280
+ trim_in = gr.Slider(label="Cut video at (s)", minimun=1, maximum=5, step=1, value=1)
281
+
282
+ with gr.Accordion("Advanced Options", open=False):
283
+ with gr.Tab("Diffusion Settings"):
284
+ with gr.Row(visible=False) as canny_opt:
285
+ low_threshold = gr.Slider(label='Canny low threshold', minimum=1, maximum=255, value=100, step=1)
286
+ high_threshold = gr.Slider(label='Canny high threshold', minimum=1, maximum=255, value=200, step=1)
287
+
288
+ with gr.Row(visible=False) as hough_opt:
289
+ value_threshold = gr.Slider(label='Hough value threshold (MLSD)', minimum=0.01, maximum=2.0, value=0.1, step=0.01)
290
+ distance_threshold = gr.Slider(label='Hough distance threshold (MLSD)', minimum=0.01, maximum=20.0, value=0.1, step=0.01)
291
+
292
+ with gr.Row(visible=False) as normal_opt:
293
+ bg_threshold = gr.Slider(label='Normal background threshold', minimum=0.0, maximum=1.0, value=0.4, step=0.01)
294
+
295
+ ddim_steps = gr.Slider(label='Steps', minimum=1, maximum=100, value=20, step=1)
296
+ scale = gr.Slider(label='Guidance Scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1)
297
+
298
+ with gr.Tab("GIF import"):
299
+ gif_import = gr.File(label="import a GIF instead", file_types=['.gif'])
300
+ gif_import.change(convert, gif_import, video_inp, queue=False)
301
+
302
+ with gr.Tab("Custom Model"):
303
+ current_base_model = gr.Text(label='Current base model',
304
+ value=DEFAULT_BASE_MODEL_URL)
305
+ with gr.Row():
306
+ with gr.Column():
307
+ base_model_repo = gr.Text(label='Base model repo',
308
+ max_lines=1,
309
+ placeholder=DEFAULT_BASE_MODEL_REPO,
310
+ interactive=True)
311
+ base_model_filename = gr.Text(
312
+ label='Base model file',
313
+ max_lines=1,
314
+ placeholder=DEFAULT_BASE_MODEL_FILENAME,
315
+ interactive=True)
316
+ change_base_model_button = gr.Button('Change base model')
317
+
318
+ gr.HTML(
319
+ '''<p>You can use other base models by specifying the repository name and filename.<br />
320
+ The base model must be compatible with Stable Diffusion v1.5.</p>''')
321
+
322
+ change_base_model_button.click(fn=model.set_base_model,
323
+ inputs=[
324
+ base_model_repo,
325
+ base_model_filename,
326
+ ],
327
+ outputs=current_base_model, queue=False)
328
+
329
+ submit_btn = gr.Button("Generate ControlNet video")
330
+
331
+ inputs = [prompt,video_inp,control_task, seed_inp, trim_in, ddim_steps, scale, low_threshold, high_threshold, value_threshold, distance_threshold, bg_threshold, gif_import]
332
+ outputs = [video_out, detailed_result, prep_video_out, files, share_group]
333
+ #outputs = [status]
334
+
335
+
336
+ gr.HTML(article)
337
+ control_task.change(change_task_options, inputs=[control_task], outputs=[canny_opt, hough_opt, normal_opt], queue=False)
338
+ submit_btn.click(clean, inputs=[], outputs=[detailed_result, prep_video_out, video_out, files, share_group], queue=False)
339
+ submit_btn.click(infer, inputs, outputs)
340
+ share_button.click(None, [], [], _js=share_js)
341
+
342
+
343
+
344
+ demo.queue(max_size=12).launch()
model.py ADDED
@@ -0,0 +1,760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is adapted from gradio_*.py in https://github.com/lllyasviel/ControlNet/tree/f4748e3630d8141d7765e2bd9b1e348f47847707
2
+ # The original license file is LICENSE.ControlNet in this repo.
3
+ from __future__ import annotations
4
+
5
+ import pathlib
6
+ import random
7
+ import shlex
8
+ import subprocess
9
+ import sys
10
+
11
+ import cv2
12
+ import einops
13
+ import numpy as np
14
+ import torch
15
+ from huggingface_hub import hf_hub_url
16
+ from pytorch_lightning import seed_everything
17
+
18
+ sys.path.append('ControlNet')
19
+
20
+ import config
21
+ from annotator.canny import apply_canny
22
+ from annotator.hed import apply_hed, nms
23
+ from annotator.midas import apply_midas
24
+ from annotator.mlsd import apply_mlsd
25
+ from annotator.openpose import apply_openpose
26
+ from annotator.uniformer import apply_uniformer
27
+ from annotator.util import HWC3, resize_image
28
+ from cldm.model import create_model, load_state_dict
29
+ from ldm.models.diffusion.ddim import DDIMSampler
30
+ from share import *
31
+
32
+
33
+ MODEL_NAMES = {
34
+ 'canny': 'control_canny-fp16.safetensors',
35
+ 'hough': 'control_mlsd-fp16.safetensors',
36
+ 'hed': 'control_hed-fp16.safetensors',
37
+ 'scribble': 'control_scribble-fp16.safetensors',
38
+ 'pose': 'control_openpose-fp16.safetensors',
39
+ 'seg': 'control_seg-fp16.safetensors',
40
+ 'depth': 'control_depth-fp16.safetensors',
41
+ 'normal': 'control_normal-fp16.safetensors',
42
+ }
43
+
44
+ MODEL_REPO = 'webui/ControlNet-modules-safetensors'
45
+
46
+ DEFAULT_BASE_MODEL_REPO = 'runwayml/stable-diffusion-v1-5'
47
+ DEFAULT_BASE_MODEL_FILENAME = 'v1-5-pruned-emaonly.safetensors'
48
+ DEFAULT_BASE_MODEL_URL = 'https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.safetensors'
49
+
50
+ class Model:
51
+ def __init__(self,
52
+ model_config_path: str = 'ControlNet/models/cldm_v15.yaml',
53
+ model_dir: str = 'models'):
54
+ self.device = torch.device(
55
+ 'cuda:0' if torch.cuda.is_available() else 'cpu')
56
+ self.model = create_model(model_config_path).to(self.device)
57
+ self.ddim_sampler = DDIMSampler(self.model)
58
+ self.task_name = ''
59
+
60
+ self.base_model_url = ''
61
+
62
+ self.model_dir = pathlib.Path(model_dir)
63
+ self.model_dir.mkdir(exist_ok=True, parents=True)
64
+
65
+ self.download_models()
66
+ self.set_base_model(DEFAULT_BASE_MODEL_REPO,
67
+ DEFAULT_BASE_MODEL_FILENAME)
68
+
69
+ def set_base_model(self, model_id: str, filename: str) -> str:
70
+ if not model_id or not filename:
71
+ return self.base_model_url
72
+ base_model_url = hf_hub_url(model_id, filename)
73
+ if base_model_url != self.base_model_url:
74
+ self.load_base_model(base_model_url)
75
+ self.base_model_url = base_model_url
76
+ return self.base_model_url
77
+
78
+
79
+ def download_base_model(self, model_url: str) -> pathlib.Path:
80
+ self.model_dir.mkdir(exist_ok=True, parents=True)
81
+ model_name = model_url.split('/')[-1]
82
+ out_path = self.model_dir / model_name
83
+ if not out_path.exists():
84
+ subprocess.run(shlex.split(f'wget {model_url} -O {out_path}'))
85
+ return out_path
86
+
87
+ def load_base_model(self, model_url: str) -> None:
88
+ model_path = self.download_base_model(model_url)
89
+ self.model.load_state_dict(load_state_dict(model_path,
90
+ location=self.device.type),
91
+ strict=False)
92
+
93
+ def load_weight(self, task_name: str) -> None:
94
+ if task_name == self.task_name:
95
+ return
96
+ weight_path = self.get_weight_path(task_name)
97
+ self.model.control_model.load_state_dict(
98
+ load_state_dict(weight_path, location=self.device.type))
99
+ self.task_name = task_name
100
+
101
+ def get_weight_path(self, task_name: str) -> str:
102
+ if 'scribble' in task_name:
103
+ task_name = 'scribble'
104
+ return f'{self.model_dir}/{MODEL_NAMES[task_name]}'
105
+
106
+ def download_models(self) -> None:
107
+ self.model_dir.mkdir(exist_ok=True, parents=True)
108
+ for name in MODEL_NAMES.values():
109
+ out_path = self.model_dir / name
110
+ if out_path.exists():
111
+ continue
112
+ model_url = hf_hub_url(MODEL_REPO, name)
113
+ subprocess.run(shlex.split(f'wget {model_url} -O {out_path}'))
114
+
115
+ @torch.inference_mode()
116
+ def process_canny(self, input_image, prompt, a_prompt, n_prompt,
117
+ num_samples, image_resolution, ddim_steps, scale, seed,
118
+ eta, low_threshold, high_threshold):
119
+ self.load_weight('canny')
120
+
121
+ img = resize_image(HWC3(input_image), image_resolution)
122
+ H, W, C = img.shape
123
+
124
+ detected_map = apply_canny(img, low_threshold, high_threshold)
125
+ detected_map = HWC3(detected_map)
126
+
127
+ control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
128
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
129
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
130
+
131
+ if seed == -1:
132
+ seed = random.randint(0, 65535)
133
+ seed_everything(seed)
134
+
135
+ if config.save_memory:
136
+ self.model.low_vram_shift(is_diffusing=False)
137
+
138
+ cond = {
139
+ 'c_concat': [control],
140
+ 'c_crossattn': [
141
+ self.model.get_learned_conditioning(
142
+ [prompt + ', ' + a_prompt] * num_samples)
143
+ ]
144
+ }
145
+ un_cond = {
146
+ 'c_concat': [control],
147
+ 'c_crossattn':
148
+ [self.model.get_learned_conditioning([n_prompt] * num_samples)]
149
+ }
150
+ shape = (4, H // 8, W // 8)
151
+
152
+ if config.save_memory:
153
+ self.model.low_vram_shift(is_diffusing=True)
154
+
155
+ samples, intermediates = self.ddim_sampler.sample(
156
+ ddim_steps,
157
+ num_samples,
158
+ shape,
159
+ cond,
160
+ verbose=False,
161
+ eta=eta,
162
+ unconditional_guidance_scale=scale,
163
+ unconditional_conditioning=un_cond)
164
+
165
+ if config.save_memory:
166
+ self.model.low_vram_shift(is_diffusing=False)
167
+
168
+ x_samples = self.model.decode_first_stage(samples)
169
+ x_samples = (
170
+ einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 +
171
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
172
+
173
+ results = [x_samples[i] for i in range(num_samples)]
174
+ return [255 - detected_map] + results
175
+
176
+ @torch.inference_mode()
177
+ def process_hough(self, input_image, prompt, a_prompt, n_prompt,
178
+ num_samples, image_resolution, detect_resolution,
179
+ ddim_steps, scale, seed, eta, value_threshold,
180
+ distance_threshold):
181
+ self.load_weight('hough')
182
+
183
+ input_image = HWC3(input_image)
184
+ detected_map = apply_mlsd(resize_image(input_image, detect_resolution),
185
+ value_threshold, distance_threshold)
186
+ detected_map = HWC3(detected_map)
187
+ img = resize_image(input_image, image_resolution)
188
+ H, W, C = img.shape
189
+
190
+ detected_map = cv2.resize(detected_map, (W, H),
191
+ interpolation=cv2.INTER_NEAREST)
192
+
193
+ control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
194
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
195
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
196
+
197
+ if seed == -1:
198
+ seed = random.randint(0, 65535)
199
+ seed_everything(seed)
200
+
201
+ if config.save_memory:
202
+ self.model.low_vram_shift(is_diffusing=False)
203
+
204
+ cond = {
205
+ 'c_concat': [control],
206
+ 'c_crossattn': [
207
+ self.model.get_learned_conditioning(
208
+ [prompt + ', ' + a_prompt] * num_samples)
209
+ ]
210
+ }
211
+ un_cond = {
212
+ 'c_concat': [control],
213
+ 'c_crossattn':
214
+ [self.model.get_learned_conditioning([n_prompt] * num_samples)]
215
+ }
216
+ shape = (4, H // 8, W // 8)
217
+
218
+ if config.save_memory:
219
+ self.model.low_vram_shift(is_diffusing=True)
220
+
221
+ samples, intermediates = self.ddim_sampler.sample(
222
+ ddim_steps,
223
+ num_samples,
224
+ shape,
225
+ cond,
226
+ verbose=False,
227
+ eta=eta,
228
+ unconditional_guidance_scale=scale,
229
+ unconditional_conditioning=un_cond)
230
+
231
+ if config.save_memory:
232
+ self.model.low_vram_shift(is_diffusing=False)
233
+
234
+ x_samples = self.model.decode_first_stage(samples)
235
+ x_samples = (
236
+ einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 +
237
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
238
+
239
+ results = [x_samples[i] for i in range(num_samples)]
240
+ return [
241
+ 255 - cv2.dilate(detected_map,
242
+ np.ones(shape=(3, 3), dtype=np.uint8),
243
+ iterations=1)
244
+ ] + results
245
+
246
+ @torch.inference_mode()
247
+ def process_hed(self, input_image, prompt, a_prompt, n_prompt, num_samples,
248
+ image_resolution, detect_resolution, ddim_steps, scale,
249
+ seed, eta):
250
+ self.load_weight('hed')
251
+
252
+ input_image = HWC3(input_image)
253
+ detected_map = apply_hed(resize_image(input_image, detect_resolution))
254
+ detected_map = HWC3(detected_map)
255
+ img = resize_image(input_image, image_resolution)
256
+ H, W, C = img.shape
257
+
258
+ detected_map = cv2.resize(detected_map, (W, H),
259
+ interpolation=cv2.INTER_LINEAR)
260
+
261
+ control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
262
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
263
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
264
+
265
+ if seed == -1:
266
+ seed = random.randint(0, 65535)
267
+ seed_everything(seed)
268
+
269
+ if config.save_memory:
270
+ self.model.low_vram_shift(is_diffusing=False)
271
+
272
+ cond = {
273
+ 'c_concat': [control],
274
+ 'c_crossattn': [
275
+ self.model.get_learned_conditioning(
276
+ [prompt + ', ' + a_prompt] * num_samples)
277
+ ]
278
+ }
279
+ un_cond = {
280
+ 'c_concat': [control],
281
+ 'c_crossattn':
282
+ [self.model.get_learned_conditioning([n_prompt] * num_samples)]
283
+ }
284
+ shape = (4, H // 8, W // 8)
285
+
286
+ if config.save_memory:
287
+ self.model.low_vram_shift(is_diffusing=True)
288
+
289
+ samples, intermediates = self.ddim_sampler.sample(
290
+ ddim_steps,
291
+ num_samples,
292
+ shape,
293
+ cond,
294
+ verbose=False,
295
+ eta=eta,
296
+ unconditional_guidance_scale=scale,
297
+ unconditional_conditioning=un_cond)
298
+
299
+ if config.save_memory:
300
+ self.model.low_vram_shift(is_diffusing=False)
301
+
302
+ x_samples = self.model.decode_first_stage(samples)
303
+ x_samples = (
304
+ einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 +
305
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
306
+
307
+ results = [x_samples[i] for i in range(num_samples)]
308
+ return [detected_map] + results
309
+
310
+ @torch.inference_mode()
311
+ def process_scribble(self, input_image, prompt, a_prompt, n_prompt,
312
+ num_samples, image_resolution, ddim_steps, scale,
313
+ seed, eta):
314
+ self.load_weight('scribble')
315
+
316
+ img = resize_image(HWC3(input_image), image_resolution)
317
+ H, W, C = img.shape
318
+
319
+ detected_map = np.zeros_like(img, dtype=np.uint8)
320
+ detected_map[np.min(img, axis=2) < 127] = 255
321
+
322
+ control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
323
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
324
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
325
+
326
+ if seed == -1:
327
+ seed = random.randint(0, 65535)
328
+ seed_everything(seed)
329
+
330
+ if config.save_memory:
331
+ self.model.low_vram_shift(is_diffusing=False)
332
+
333
+ cond = {
334
+ 'c_concat': [control],
335
+ 'c_crossattn': [
336
+ self.model.get_learned_conditioning(
337
+ [prompt + ', ' + a_prompt] * num_samples)
338
+ ]
339
+ }
340
+ un_cond = {
341
+ 'c_concat': [control],
342
+ 'c_crossattn':
343
+ [self.model.get_learned_conditioning([n_prompt] * num_samples)]
344
+ }
345
+ shape = (4, H // 8, W // 8)
346
+
347
+ if config.save_memory:
348
+ self.model.low_vram_shift(is_diffusing=True)
349
+
350
+ samples, intermediates = self.ddim_sampler.sample(
351
+ ddim_steps,
352
+ num_samples,
353
+ shape,
354
+ cond,
355
+ verbose=False,
356
+ eta=eta,
357
+ unconditional_guidance_scale=scale,
358
+ unconditional_conditioning=un_cond)
359
+
360
+ if config.save_memory:
361
+ self.model.low_vram_shift(is_diffusing=False)
362
+
363
+ x_samples = self.model.decode_first_stage(samples)
364
+ x_samples = (
365
+ einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 +
366
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
367
+
368
+ results = [x_samples[i] for i in range(num_samples)]
369
+ return [255 - detected_map] + results
370
+
371
+ @torch.inference_mode()
372
+ def process_scribble_interactive(self, input_image, prompt, a_prompt,
373
+ n_prompt, num_samples, image_resolution,
374
+ ddim_steps, scale, seed, eta):
375
+ self.load_weight('scribble')
376
+
377
+ img = resize_image(HWC3(input_image['mask'][:, :, 0]),
378
+ image_resolution)
379
+ H, W, C = img.shape
380
+
381
+ detected_map = np.zeros_like(img, dtype=np.uint8)
382
+ detected_map[np.min(img, axis=2) > 127] = 255
383
+
384
+ control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
385
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
386
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
387
+
388
+ if seed == -1:
389
+ seed = random.randint(0, 65535)
390
+ seed_everything(seed)
391
+
392
+ if config.save_memory:
393
+ self.model.low_vram_shift(is_diffusing=False)
394
+
395
+ cond = {
396
+ 'c_concat': [control],
397
+ 'c_crossattn': [
398
+ self.model.get_learned_conditioning(
399
+ [prompt + ', ' + a_prompt] * num_samples)
400
+ ]
401
+ }
402
+ un_cond = {
403
+ 'c_concat': [control],
404
+ 'c_crossattn':
405
+ [self.model.get_learned_conditioning([n_prompt] * num_samples)]
406
+ }
407
+ shape = (4, H // 8, W // 8)
408
+
409
+ if config.save_memory:
410
+ self.model.low_vram_shift(is_diffusing=True)
411
+
412
+ samples, intermediates = self.ddim_sampler.sample(
413
+ ddim_steps,
414
+ num_samples,
415
+ shape,
416
+ cond,
417
+ verbose=False,
418
+ eta=eta,
419
+ unconditional_guidance_scale=scale,
420
+ unconditional_conditioning=un_cond)
421
+
422
+ if config.save_memory:
423
+ self.model.low_vram_shift(is_diffusing=False)
424
+
425
+ x_samples = self.model.decode_first_stage(samples)
426
+ x_samples = (
427
+ einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 +
428
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
429
+
430
+ results = [x_samples[i] for i in range(num_samples)]
431
+ return [255 - detected_map] + results
432
+
433
+ @torch.inference_mode()
434
+ def process_fake_scribble(self, input_image, prompt, a_prompt, n_prompt,
435
+ num_samples, image_resolution, detect_resolution,
436
+ ddim_steps, scale, seed, eta):
437
+ self.load_weight('scribble')
438
+
439
+ input_image = HWC3(input_image)
440
+ detected_map = apply_hed(resize_image(input_image, detect_resolution))
441
+ detected_map = HWC3(detected_map)
442
+ img = resize_image(input_image, image_resolution)
443
+ H, W, C = img.shape
444
+
445
+ detected_map = cv2.resize(detected_map, (W, H),
446
+ interpolation=cv2.INTER_LINEAR)
447
+ detected_map = nms(detected_map, 127, 3.0)
448
+ detected_map = cv2.GaussianBlur(detected_map, (0, 0), 3.0)
449
+ detected_map[detected_map > 4] = 255
450
+ detected_map[detected_map < 255] = 0
451
+
452
+ control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
453
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
454
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
455
+
456
+ if seed == -1:
457
+ seed = random.randint(0, 65535)
458
+ seed_everything(seed)
459
+
460
+ if config.save_memory:
461
+ self.model.low_vram_shift(is_diffusing=False)
462
+
463
+ cond = {
464
+ 'c_concat': [control],
465
+ 'c_crossattn': [
466
+ self.model.get_learned_conditioning(
467
+ [prompt + ', ' + a_prompt] * num_samples)
468
+ ]
469
+ }
470
+ un_cond = {
471
+ 'c_concat': [control],
472
+ 'c_crossattn':
473
+ [self.model.get_learned_conditioning([n_prompt] * num_samples)]
474
+ }
475
+ shape = (4, H // 8, W // 8)
476
+
477
+ if config.save_memory:
478
+ self.model.low_vram_shift(is_diffusing=True)
479
+
480
+ samples, intermediates = self.ddim_sampler.sample(
481
+ ddim_steps,
482
+ num_samples,
483
+ shape,
484
+ cond,
485
+ verbose=False,
486
+ eta=eta,
487
+ unconditional_guidance_scale=scale,
488
+ unconditional_conditioning=un_cond)
489
+
490
+ if config.save_memory:
491
+ self.model.low_vram_shift(is_diffusing=False)
492
+
493
+ x_samples = self.model.decode_first_stage(samples)
494
+ x_samples = (
495
+ einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 +
496
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
497
+
498
+ results = [x_samples[i] for i in range(num_samples)]
499
+ return [255 - detected_map] + results
500
+
501
+ @torch.inference_mode()
502
+ def process_pose(self, input_image, prompt, a_prompt, n_prompt,
503
+ num_samples, image_resolution, detect_resolution,
504
+ ddim_steps, scale, seed, eta):
505
+ self.load_weight('pose')
506
+
507
+ input_image = HWC3(input_image)
508
+ detected_map, _ = apply_openpose(
509
+ resize_image(input_image, detect_resolution))
510
+ detected_map = HWC3(detected_map)
511
+ img = resize_image(input_image, image_resolution)
512
+ H, W, C = img.shape
513
+
514
+ detected_map = cv2.resize(detected_map, (W, H),
515
+ interpolation=cv2.INTER_NEAREST)
516
+
517
+ control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
518
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
519
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
520
+
521
+ if seed == -1:
522
+ seed = random.randint(0, 65535)
523
+ seed_everything(seed)
524
+
525
+ if config.save_memory:
526
+ self.model.low_vram_shift(is_diffusing=False)
527
+
528
+ cond = {
529
+ 'c_concat': [control],
530
+ 'c_crossattn': [
531
+ self.model.get_learned_conditioning(
532
+ [prompt + ', ' + a_prompt] * num_samples)
533
+ ]
534
+ }
535
+ un_cond = {
536
+ 'c_concat': [control],
537
+ 'c_crossattn':
538
+ [self.model.get_learned_conditioning([n_prompt] * num_samples)]
539
+ }
540
+ shape = (4, H // 8, W // 8)
541
+
542
+ if config.save_memory:
543
+ self.model.low_vram_shift(is_diffusing=True)
544
+
545
+ samples, intermediates = self.ddim_sampler.sample(
546
+ ddim_steps,
547
+ num_samples,
548
+ shape,
549
+ cond,
550
+ verbose=False,
551
+ eta=eta,
552
+ unconditional_guidance_scale=scale,
553
+ unconditional_conditioning=un_cond)
554
+
555
+ if config.save_memory:
556
+ self.model.low_vram_shift(is_diffusing=False)
557
+
558
+ x_samples = self.model.decode_first_stage(samples)
559
+ x_samples = (
560
+ einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 +
561
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
562
+
563
+ results = [x_samples[i] for i in range(num_samples)]
564
+ return [detected_map] + results
565
+
566
+ @torch.inference_mode()
567
+ def process_seg(self, input_image, prompt, a_prompt, n_prompt, num_samples,
568
+ image_resolution, detect_resolution, ddim_steps, scale,
569
+ seed, eta):
570
+ self.load_weight('seg')
571
+
572
+ input_image = HWC3(input_image)
573
+ detected_map = apply_uniformer(
574
+ resize_image(input_image, detect_resolution))
575
+ img = resize_image(input_image, image_resolution)
576
+ H, W, C = img.shape
577
+
578
+ detected_map = cv2.resize(detected_map, (W, H),
579
+ interpolation=cv2.INTER_NEAREST)
580
+
581
+ control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
582
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
583
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
584
+
585
+ if seed == -1:
586
+ seed = random.randint(0, 65535)
587
+ seed_everything(seed)
588
+
589
+ if config.save_memory:
590
+ self.model.low_vram_shift(is_diffusing=False)
591
+
592
+ cond = {
593
+ 'c_concat': [control],
594
+ 'c_crossattn': [
595
+ self.model.get_learned_conditioning(
596
+ [prompt + ', ' + a_prompt] * num_samples)
597
+ ]
598
+ }
599
+ un_cond = {
600
+ 'c_concat': [control],
601
+ 'c_crossattn':
602
+ [self.model.get_learned_conditioning([n_prompt] * num_samples)]
603
+ }
604
+ shape = (4, H // 8, W // 8)
605
+
606
+ if config.save_memory:
607
+ self.model.low_vram_shift(is_diffusing=True)
608
+
609
+ samples, intermediates = self.ddim_sampler.sample(
610
+ ddim_steps,
611
+ num_samples,
612
+ shape,
613
+ cond,
614
+ verbose=False,
615
+ eta=eta,
616
+ unconditional_guidance_scale=scale,
617
+ unconditional_conditioning=un_cond)
618
+
619
+ if config.save_memory:
620
+ self.model.low_vram_shift(is_diffusing=False)
621
+
622
+ x_samples = self.model.decode_first_stage(samples)
623
+ x_samples = (
624
+ einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 +
625
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
626
+
627
+ results = [x_samples[i] for i in range(num_samples)]
628
+ return [detected_map] + results
629
+
630
+ @torch.inference_mode()
631
+ def process_depth(self, input_image, prompt, a_prompt, n_prompt,
632
+ num_samples, image_resolution, detect_resolution,
633
+ ddim_steps, scale, seed, eta):
634
+ self.load_weight('depth')
635
+
636
+ input_image = HWC3(input_image)
637
+ detected_map, _ = apply_midas(
638
+ resize_image(input_image, detect_resolution))
639
+ detected_map = HWC3(detected_map)
640
+ img = resize_image(input_image, image_resolution)
641
+ H, W, C = img.shape
642
+
643
+ detected_map = cv2.resize(detected_map, (W, H),
644
+ interpolation=cv2.INTER_LINEAR)
645
+
646
+ control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
647
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
648
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
649
+
650
+ if seed == -1:
651
+ seed = random.randint(0, 65535)
652
+ seed_everything(seed)
653
+
654
+ if config.save_memory:
655
+ self.model.low_vram_shift(is_diffusing=False)
656
+
657
+ cond = {
658
+ 'c_concat': [control],
659
+ 'c_crossattn': [
660
+ self.model.get_learned_conditioning(
661
+ [prompt + ', ' + a_prompt] * num_samples)
662
+ ]
663
+ }
664
+ un_cond = {
665
+ 'c_concat': [control],
666
+ 'c_crossattn':
667
+ [self.model.get_learned_conditioning([n_prompt] * num_samples)]
668
+ }
669
+ shape = (4, H // 8, W // 8)
670
+
671
+ if config.save_memory:
672
+ self.model.low_vram_shift(is_diffusing=True)
673
+
674
+ samples, intermediates = self.ddim_sampler.sample(
675
+ ddim_steps,
676
+ num_samples,
677
+ shape,
678
+ cond,
679
+ verbose=False,
680
+ eta=eta,
681
+ unconditional_guidance_scale=scale,
682
+ unconditional_conditioning=un_cond)
683
+
684
+ if config.save_memory:
685
+ self.model.low_vram_shift(is_diffusing=False)
686
+
687
+ x_samples = self.model.decode_first_stage(samples)
688
+ x_samples = (
689
+ einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 +
690
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
691
+
692
+ results = [x_samples[i] for i in range(num_samples)]
693
+ return [detected_map] + results
694
+
695
+ @torch.inference_mode()
696
+ def process_normal(self, input_image, prompt, a_prompt, n_prompt,
697
+ num_samples, image_resolution, detect_resolution,
698
+ ddim_steps, scale, seed, eta, bg_threshold):
699
+ self.load_weight('normal')
700
+
701
+ input_image = HWC3(input_image)
702
+ _, detected_map = apply_midas(resize_image(input_image,
703
+ detect_resolution),
704
+ bg_th=bg_threshold)
705
+ detected_map = HWC3(detected_map)
706
+ img = resize_image(input_image, image_resolution)
707
+ H, W, C = img.shape
708
+
709
+ detected_map = cv2.resize(detected_map, (W, H),
710
+ interpolation=cv2.INTER_LINEAR)
711
+
712
+ control = torch.from_numpy(
713
+ detected_map[:, :, ::-1].copy()).float().cuda() / 255.0
714
+ control = torch.stack([control for _ in range(num_samples)], dim=0)
715
+ control = einops.rearrange(control, 'b h w c -> b c h w').clone()
716
+
717
+ if seed == -1:
718
+ seed = random.randint(0, 65535)
719
+ seed_everything(seed)
720
+
721
+ if config.save_memory:
722
+ self.model.low_vram_shift(is_diffusing=False)
723
+
724
+ cond = {
725
+ 'c_concat': [control],
726
+ 'c_crossattn': [
727
+ self.model.get_learned_conditioning(
728
+ [prompt + ', ' + a_prompt] * num_samples)
729
+ ]
730
+ }
731
+ un_cond = {
732
+ 'c_concat': [control],
733
+ 'c_crossattn':
734
+ [self.model.get_learned_conditioning([n_prompt] * num_samples)]
735
+ }
736
+ shape = (4, H // 8, W // 8)
737
+
738
+ if config.save_memory:
739
+ self.model.low_vram_shift(is_diffusing=True)
740
+
741
+ samples, intermediates = self.ddim_sampler.sample(
742
+ ddim_steps,
743
+ num_samples,
744
+ shape,
745
+ cond,
746
+ verbose=False,
747
+ eta=eta,
748
+ unconditional_guidance_scale=scale,
749
+ unconditional_conditioning=un_cond)
750
+
751
+ if config.save_memory:
752
+ self.model.low_vram_shift(is_diffusing=False)
753
+
754
+ x_samples = self.model.decode_first_stage(samples)
755
+ x_samples = (
756
+ einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 +
757
+ 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
758
+
759
+ results = [x_samples[i] for i in range(num_samples)]
760
+ return [detected_map] + results
patch ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/annotator/hed/__init__.py b/annotator/hed/__init__.py
2
+ index 42d8dc6..1587035 100644
3
+ --- a/annotator/hed/__init__.py
4
+ +++ b/annotator/hed/__init__.py
5
+ @@ -1,8 +1,12 @@
6
+ +import pathlib
7
+ +
8
+ import numpy as np
9
+ import cv2
10
+ import torch
11
+ from einops import rearrange
12
+
13
+ +root_dir = pathlib.Path(__file__).parents[2]
14
+ +
15
+
16
+ class Network(torch.nn.Module):
17
+ def __init__(self):
18
+ @@ -64,7 +68,7 @@ class Network(torch.nn.Module):
19
+ torch.nn.Sigmoid()
20
+ )
21
+
22
+ - self.load_state_dict({strKey.replace('module', 'net'): tenWeight for strKey, tenWeight in torch.load('./annotator/ckpts/network-bsds500.pth').items()})
23
+ + self.load_state_dict({strKey.replace('module', 'net'): tenWeight for strKey, tenWeight in torch.load(f'{root_dir}/annotator/ckpts/network-bsds500.pth').items()})
24
+ # end
25
+
26
+ def forward(self, tenInput):
27
+ diff --git a/annotator/midas/api.py b/annotator/midas/api.py
28
+ index 9fa305e..d8594ea 100644
29
+ --- a/annotator/midas/api.py
30
+ +++ b/annotator/midas/api.py
31
+ @@ -1,5 +1,7 @@
32
+ # based on https://github.com/isl-org/MiDaS
33
+
34
+ +import pathlib
35
+ +
36
+ import cv2
37
+ import torch
38
+ import torch.nn as nn
39
+ @@ -10,10 +12,11 @@ from .midas.midas_net import MidasNet
40
+ from .midas.midas_net_custom import MidasNet_small
41
+ from .midas.transforms import Resize, NormalizeImage, PrepareForNet
42
+
43
+ +root_dir = pathlib.Path(__file__).parents[2]
44
+
45
+ ISL_PATHS = {
46
+ - "dpt_large": "annotator/ckpts/dpt_large-midas-2f21e586.pt",
47
+ - "dpt_hybrid": "annotator/ckpts/dpt_hybrid-midas-501f0c75.pt",
48
+ + "dpt_large": f"{root_dir}/annotator/ckpts/dpt_large-midas-2f21e586.pt",
49
+ + "dpt_hybrid": f"{root_dir}/annotator/ckpts/dpt_hybrid-midas-501f0c75.pt",
50
+ "midas_v21": "",
51
+ "midas_v21_small": "",
52
+ }
53
+ diff --git a/annotator/mlsd/__init__.py b/annotator/mlsd/__init__.py
54
+ index 75db717..f310fe6 100644
55
+ --- a/annotator/mlsd/__init__.py
56
+ +++ b/annotator/mlsd/__init__.py
57
+ @@ -1,3 +1,5 @@
58
+ +import pathlib
59
+ +
60
+ import cv2
61
+ import numpy as np
62
+ import torch
63
+ @@ -8,8 +10,9 @@ from .models.mbv2_mlsd_tiny import MobileV2_MLSD_Tiny
64
+ from .models.mbv2_mlsd_large import MobileV2_MLSD_Large
65
+ from .utils import pred_lines
66
+
67
+ +root_dir = pathlib.Path(__file__).parents[2]
68
+
69
+ -model_path = './annotator/ckpts/mlsd_large_512_fp32.pth'
70
+ +model_path = f'{root_dir}/annotator/ckpts/mlsd_large_512_fp32.pth'
71
+ model = MobileV2_MLSD_Large()
72
+ model.load_state_dict(torch.load(model_path), strict=True)
73
+ model = model.cuda().eval()
74
+ diff --git a/annotator/openpose/__init__.py b/annotator/openpose/__init__.py
75
+ index 47d50a5..2369eed 100644
76
+ --- a/annotator/openpose/__init__.py
77
+ +++ b/annotator/openpose/__init__.py
78
+ @@ -1,4 +1,5 @@
79
+ import os
80
+ +import pathlib
81
+ os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
82
+
83
+ import torch
84
+ @@ -7,8 +8,10 @@ from . import util
85
+ from .body import Body
86
+ from .hand import Hand
87
+
88
+ -body_estimation = Body('./annotator/ckpts/body_pose_model.pth')
89
+ -hand_estimation = Hand('./annotator/ckpts/hand_pose_model.pth')
90
+ +root_dir = pathlib.Path(__file__).parents[2]
91
+ +
92
+ +body_estimation = Body(f'{root_dir}/annotator/ckpts/body_pose_model.pth')
93
+ +hand_estimation = Hand(f'{root_dir}/annotator/ckpts/hand_pose_model.pth')
94
+
95
+
96
+ def apply_openpose(oriImg, hand=False):
97
+ diff --git a/annotator/uniformer/__init__.py b/annotator/uniformer/__init__.py
98
+ index 500e53c..4061dbe 100644
99
+ --- a/annotator/uniformer/__init__.py
100
+ +++ b/annotator/uniformer/__init__.py
101
+ @@ -1,9 +1,12 @@
102
+ +import pathlib
103
+ +
104
+ from annotator.uniformer.mmseg.apis import init_segmentor, inference_segmentor, show_result_pyplot
105
+ from annotator.uniformer.mmseg.core.evaluation import get_palette
106
+
107
+ +root_dir = pathlib.Path(__file__).parents[2]
108
+
109
+ -checkpoint_file = "annotator/ckpts/upernet_global_small.pth"
110
+ -config_file = 'annotator/uniformer/exp/upernet_global_small/config.py'
111
+ +checkpoint_file = f"{root_dir}/annotator/ckpts/upernet_global_small.pth"
112
+ +config_file = f'{root_dir}/annotator/uniformer/exp/upernet_global_small/config.py'
113
+ model = init_segmentor(config_file, checkpoint_file).cuda()
114
+
115
+
requirements.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ opencv-python
2
+ ffmpeg-python
3
+ moviepy
4
+ addict==2.4.0
5
+ albumentations==1.3.0
6
+ einops==0.6.0
7
+ gradio==3.18.0
8
+ huggingface-hub==0.12.0
9
+ imageio==2.25.0
10
+ imageio-ffmpeg==0.4.8
11
+ kornia==0.6.9
12
+ omegaconf==2.3.0
13
+ open-clip-torch==2.13.0
14
+ opencv-contrib-python==4.7.0.68
15
+ opencv-python-headless==4.7.0.68
16
+ prettytable==3.6.0
17
+ pytorch-lightning==1.9.0
18
+ safetensors==0.2.8
19
+ timm==0.6.12
20
+ torch==1.13.1
21
+ torchvision==0.14.1
22
+ transformers==4.26.1
23
+ xformers==0.0.16
24
+ yapf==0.32.0
share_btn.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
2
+ <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
3
+ <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
4
+ </svg>"""
5
+
6
+ loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
7
+ style="color: #ffffff;
8
+ "
9
+ xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
10
+
11
+ share_js = """async () => {
12
+ async function uploadFile(file){
13
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
14
+ const response = await fetch(UPLOAD_URL, {
15
+ method: 'POST',
16
+ headers: {
17
+ 'Content-Type': file.type,
18
+ 'X-Requested-With': 'XMLHttpRequest',
19
+ },
20
+ body: file, /// <- File inherits from Blob
21
+ });
22
+ const url = await response.text();
23
+ return url;
24
+ }
25
+
26
+ async function getVideoBlobFile(videoEL){
27
+ const res = await fetch(videoEL.src);
28
+ const blob = await res.blob();
29
+ const videoId = Date.now() % 200;
30
+ const fileName = `vid-pix2pix-${{videoId}}.wav`;
31
+ const videoBlob = new File([blob], fileName, { type: 'video/mp4' });
32
+ console.log(videoBlob);
33
+ return videoBlob;
34
+ }
35
+
36
+ const gradioEl = document.querySelector("gradio-app").shadowRoot || document.querySelector('body > gradio-app');
37
+ const captionTxt = gradioEl.querySelector('#prompt-in textarea').value;
38
+ const controlTask = gradioEl.querySelector('#controltask-in select').value;
39
+ const seedValue = gradioEl.querySelector('#seed-in input').value;
40
+ const inputVidEl = gradioEl.querySelector('#input-vid video');
41
+ const outputVideo = gradioEl.querySelector('#video-output video');
42
+ const outputPrepVideo = gradioEl.querySelector('#prep-video-output video');
43
+
44
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
45
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
46
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
47
+ if(!outputVideo){
48
+ return;
49
+ };
50
+ shareBtnEl.style.pointerEvents = 'none';
51
+ shareIconEl.style.display = 'none';
52
+ loadingIconEl.style.removeProperty('display');
53
+
54
+ const inputFile = await getVideoBlobFile(inputVidEl);
55
+ const urlInputVid = await uploadFile(inputFile);
56
+
57
+ const prepVideoOutFile = await getVideoBlobFile(outputPrepVideo);
58
+ const dataOutputPrepVid = await uploadFile(prepVideoOutFile);
59
+
60
+ const videoOutFile = await getVideoBlobFile(outputVideo);
61
+ const dataOutputVid = await uploadFile(videoOutFile);
62
+
63
+ const descriptionMd = `
64
+ #### Settings
65
+ Prompt: ${captionTxt}
66
+ Control Task: ${controlTask} • Seed: ${seedValue}
67
+
68
+ #### Video input:
69
+ ${urlInputVid}
70
+
71
+ #### Preprcessor output:
72
+ ${dataOutputPrepVid}
73
+
74
+ #### ControlNet result:
75
+ ${dataOutputVid}
76
+ `;
77
+ const params = new URLSearchParams({
78
+ title: captionTxt,
79
+ description: descriptionMd,
80
+ });
81
+ const paramsStr = params.toString();
82
+ window.open(`https://huggingface.co/spaces/fffiloni/ControlNet-Video/discussions/new?${paramsStr}`, '_blank');
83
+ shareBtnEl.style.removeProperty('pointer-events');
84
+ shareIconEl.style.removeProperty('display');
85
+ loadingIconEl.style.display = 'none';
86
+ }"""
style.css ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #col-container {max-width: 820px; margin-left: auto; margin-right: auto;}
2
+ #duplicate-container{
3
+ display: flex;
4
+ justify-content: space-between;
5
+ align-items: center;
6
+ line-height: 1em;
7
+ flex-direction: row-reverse;
8
+ font-size:1em;
9
+ }
10
+ a, a:hover, a:visited {
11
+ text-decoration-line: underline;
12
+ font-weight: 600;
13
+ color: #1f2937 !important;
14
+ }
15
+
16
+ .dark a, .dark a:hover, .dark a:visited {
17
+ color: #f3f4f6 !important;
18
+ }
19
+
20
+ .label-wrap {
21
+ margin-bottom: 12px;
22
+ }
23
+
24
+ .footer {
25
+ margin-bottom: 45px;
26
+ margin-top: 10px;
27
+ text-align: center;
28
+ border-bottom: 1px solid #e5e5e5;
29
+ }
30
+
31
+ .footer>p {
32
+ font-size: .8rem!important;
33
+ display: inline-block;
34
+ padding: 0 10px;
35
+ transform: translateY(26px);
36
+ background: white;
37
+ }
38
+ .dark .footer {
39
+ border-color: #303030;
40
+ }
41
+ .dark .footer>p {
42
+ background: #0b0f19;
43
+ }
44
+
45
+ div#may-like-container > p {
46
+ font-size: .8em;
47
+ margin-bottom: 4px;
48
+ }
49
+
50
+ .animate-spin {
51
+ animation: spin 1s linear infinite;
52
+ }
53
+
54
+ @keyframes spin {
55
+ from {
56
+ transform: rotate(0deg);
57
+ }
58
+ to {
59
+ transform: rotate(360deg);
60
+ }
61
+ }
62
+
63
+ #share-btn-container {
64
+ display: flex;
65
+ padding-left: 0.5rem !important;
66
+ padding-right: 0.5rem !important;
67
+ background-color: #000000;
68
+ justify-content: center;
69
+ align-items: center;
70
+ border-radius: 9999px !important;
71
+ max-width: 13rem;
72
+ }
73
+
74
+ #share-btn-container:hover {
75
+ background-color: #060606;
76
+ }
77
+
78
+ #share-btn {
79
+ all: initial;
80
+ color: #ffffff;
81
+ font-weight: 600;
82
+ cursor:pointer;
83
+ font-family: 'IBM Plex Sans', sans-serif;
84
+ margin-left: 0.5rem !important;
85
+ padding-top: 0.5rem !important;
86
+ padding-bottom: 0.5rem !important;
87
+ right:0;
88
+ }
89
+
90
+ #share-btn * {
91
+ all: unset;
92
+ }
93
+
94
+ #share-btn-container div:nth-child(-n+2){
95
+ width: auto !important;
96
+ min-height: 0px !important;
97
+ }
98
+
99
+ #share-btn-container .wrap {
100
+ display: none !important;
101
+ }
102
+
103
+ #share-btn-container.hidden {
104
+ display: none!important;
105
+ }