xiaozhongji commited on
Commit
79d88c4
·
1 Parent(s): b98caf0

init spaces

Browse files
.gitattributes CHANGED
@@ -1,35 +1,8 @@
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
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.pth filter=lfs diff=lfs merge=lfs -text
2
+ *.pkl filter=lfs diff=lfs merge=lfs -text
3
  *.safetensors filter=lfs diff=lfs merge=lfs -text
4
+ *.pt filter=lfs diff=lfs merge=lfs -text
5
+ tools/ffmpeg filter=lfs diff=lfs merge=lfs -text
6
+ *.bin filter=lfs diff=lfs merge=lfs -text
7
+ *.wav filter=lfs diff=lfs merge=lfs -text
8
+ *.MP3 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+
53
+ # Translations
54
+ *.mo
55
+ *.pot
56
+
57
+ # Django stuff:
58
+ *.log
59
+ local_settings.py
60
+ db.sqlite3
61
+
62
+ # Flask stuff:
63
+ instance/
64
+ .webassets-cache
65
+
66
+ # Scrapy stuff:
67
+ .scrapy
68
+
69
+ # Sphinx documentation
70
+ docs/_build/
71
+
72
+ # PyBuilder
73
+ target/
74
+
75
+ # Jupyter Notebook
76
+ .ipynb_checkpoints
77
+
78
+ # IPython
79
+ profile_default/
80
+ ipython_config.py
81
+
82
+ # pyenv
83
+ .python-version
84
+
85
+ # pipenv
86
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
87
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
88
+ # having no cross-platform support, pipenv may install dependencies that don’t work, or not
89
+ # install all needed dependencies.
90
+ #Pipfile.lock
91
+
92
+ # celery beat schedule file
93
+ celerybeat-schedule
94
+
95
+ # SageMath parsed files
96
+ *.sage.py
97
+
98
+ # Environments
99
+ .env
100
+ .venv
101
+ env/
102
+ venv/
103
+ ENV/
104
+ env.bak/
105
+ venv.bak/
106
+
107
+ # Spyder project settings
108
+ .spyderproject
109
+ .spyproject
110
+
111
+ # Rope project settings
112
+ .ropeproject
113
+
114
+ # mkdocs documentation
115
+ /site
116
+
117
+ # mypy
118
+ .mypy_cache/
119
+ .dmypy.json
120
+ dmypy.json
121
+
122
+ # Pyre type checker
123
+ .pyre/
124
+
125
+ *.swp
126
+ .*.swp
127
+
128
+ .DS_Store
129
+
130
+ # project
131
+
132
+ .idea
133
+ .vscode
134
+ *.mp4
135
+ res_path/
136
+ tmp_path/
137
+ flagged/
LICENSE ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
2
+
3
+ Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
4
+
5
+ Using Creative Commons Public Licenses
6
+
7
+ Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
8
+
9
+ Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors : wiki.creativecommons.org/Considerations_for_licensors
10
+
11
+ Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public : wiki.creativecommons.org/Considerations_for_licensees
12
+
13
+ Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
14
+
15
+ By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
16
+
17
+ Section 1 – Definitions.
18
+
19
+ a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
20
+ b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
21
+ c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
22
+ d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
23
+ e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
24
+ f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
25
+ g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.
26
+ h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
27
+ i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
28
+ j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
29
+ k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
30
+ l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
31
+ m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
32
+ n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
33
+ Section 2 – Scope.
34
+
35
+ a. License grant.
36
+ 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
37
+ A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
38
+ B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
39
+ 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
40
+ 3. Term. The term of this Public License is specified in Section 6(a).
41
+ 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
42
+ 5. Downstream recipients.
43
+ A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
44
+ B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply.
45
+ C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
46
+ 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
47
+ b. Other rights.
48
+ 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
49
+ 2. Patent and trademark rights are not licensed under this Public License.
50
+ 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
51
+ Section 3 – License Conditions.
52
+
53
+ Your exercise of the Licensed Rights is expressly made subject to the following conditions.
54
+
55
+ a. Attribution.
56
+ 1. If You Share the Licensed Material (including in modified form), You must:
57
+ A. retain the following if it is supplied by the Licensor with the Licensed Material:
58
+ i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
59
+ ii. a copyright notice;
60
+ iii. a notice that refers to this Public License;
61
+ iv. a notice that refers to the disclaimer of warranties;
62
+ v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
63
+
64
+ B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
65
+ C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
66
+ 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
67
+ 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
68
+ b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
69
+ 1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.
70
+ 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
71
+ 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
72
+ Section 4 – Sui Generis Database Rights.
73
+
74
+ Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
75
+
76
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
77
+ b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
78
+ c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
79
+ For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
80
+ Section 5 – Disclaimer of Warranties and Limitation of Liability.
81
+
82
+ a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
83
+ b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
84
+ c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
85
+ Section 6 – Term and Termination.
86
+
87
+ a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
88
+ b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
89
+ 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
90
+ 2. upon express reinstatement by the Licensor.
91
+ For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
92
+
93
+ c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
94
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
95
+ Section 7 – Other Terms and Conditions.
96
+
97
+ a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
98
+ b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
99
+ Section 8 – Interpretation.
100
+
101
+ a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
102
+ b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
103
+ c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
104
+ d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
105
+ Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the "Licensor." The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
106
+
107
+ Creative Commons may be contacted at creativecommons.org.
app.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import numpy as np
4
+ from pydub import AudioSegment
5
+ import hashlib
6
+ from sonic import Sonic
7
+
8
+ cmd = 'python3 -m pip install "huggingface_hub[cli]"; \
9
+ huggingface-cli download LeonJoe13/Sonic --local-dir checkpoints; \
10
+ huggingface-cli download stabilityai/stable-video-diffusion-img2vid-xt --local-dir checkpoints/stable-video-diffusion-img2vid-xt; \
11
+ huggingface-cli download openai/whisper-tiny --local-dir checkpoints/whisper-tiny'
12
+ os.system(cmd)
13
+
14
+
15
+ pipe = Sonic(0)
16
+
17
+ def get_md5(content):
18
+ md5hash = hashlib.md5(content)
19
+ md5 = md5hash.hexdigest()
20
+ return md5
21
+
22
+ def get_video_res(img_path, audio_path, res_video_path, dynamic_scale=1.0):
23
+
24
+ expand_ratio = 0.5
25
+ min_resolution = 512
26
+ inference_steps = 25
27
+
28
+ face_info = pipe.preprocess(img_path, expand_ratio=expand_ratio)
29
+ print(face_info)
30
+ if face_info['face_num'] > 0:
31
+ crop_image_path = img_path + '.crop.png'
32
+ pipe.crop_image(img_path, crop_image_path, face_info['crop_bbox'])
33
+ img_path = crop_image_path
34
+ os.makedirs(os.path.dirname(res_video_path), exist_ok=True)
35
+ pipe.process(img_path, audio_path, res_video_path, min_resolution=min_resolution, inference_steps=inference_steps, dynamic_scale=dynamic_scale)
36
+ else:
37
+ return -1
38
+ tmp_path = './tmp_path/'
39
+ res_path = './res_path/'
40
+ os.makedirs(tmp_path,exist_ok=1)
41
+ os.makedirs(res_path,exist_ok=1)
42
+
43
+ def process_sonic(image,audio,s0):
44
+ img_md5= get_md5(np.array(image))
45
+ audio_md5 = get_md5(audio[1])
46
+ print(img_md5,audio_md5)
47
+ sampling_rate, arr = audio[:2]
48
+ if len(arr.shape)==1:
49
+ arr = arr[:,None]
50
+ audio = AudioSegment(
51
+ arr.tobytes(),
52
+ frame_rate=sampling_rate,
53
+ sample_width=arr.dtype.itemsize,
54
+ channels=arr.shape[1]
55
+ )
56
+ audio = audio.set_frame_rate(sampling_rate)
57
+ image_path = os.path.abspath(tmp_path+'{0}.png'.format(img_md5))
58
+ audio_path = os.path.abspath(tmp_path+'{0}.wav'.format(audio_md5))
59
+ if not os.path.exists(image_path):
60
+ image.save(image_path)
61
+ if not os.path.exists(audio_path):
62
+ audio.export(audio_path, format="wav")
63
+ res_video_path = os.path.abspath(res_path+f'{img_md5}_{audio_md5}_{s0}.mp4')
64
+ if os.path.exists(res_video_path):
65
+ return res_video_path
66
+ else:
67
+ get_video_res(image_path, audio_path, res_video_path,s0)
68
+ return res_video_path
69
+
70
+ inputs = [
71
+ gr.Image(type='pil',label="Upload Image"),
72
+ gr.Audio(label="Upload Audio"),
73
+ gr.Slider(0.5, 2.0, value=1.0, step=0.1, label="Dynamic scale", info="Increase/decrease to obtain more/less movements"),
74
+ ]
75
+ outputs = gr.Video(label="output.mp4")
76
+
77
+
78
+ html_description = """
79
+ <div style="display: flex; justify-content: center; align-items: center;">
80
+ <a href="https://github.com/jixiaozhong/Sonic.git" style="margin: 0 2px;">
81
+ <img src='https://img.shields.io/badge/GitHub-Repo-blue?style=flat&logo=GitHub' alt='GitHub'>
82
+ </a>
83
+ <a href="https://arxiv.org/pdf/2411.16331" style="margin: 0 2px;">
84
+ <img src='https://img.shields.io/badge/arXiv-2411.16331-red?style=flat&logo=arXiv&logoColor=red' alt='arxiv'>
85
+ </a>
86
+ <a href='https://jixiaozhong.github.io/Sonic/' style="margin: 0 2px;">
87
+ <img src='https://img.shields.io/badge/Webpage-Project-silver?style=flat&logo=&logoColor=orange' alt='webpage'>
88
+ </a>
89
+ <a href="https://github.com/jixiaozhong/Sonic/blob/main/LICENSE" style="margin: 0 2px;">
90
+ <img src='https://img.shields.io/badge/License-CC BY--NC--SA--4.0-lightgreen?style=flat&logo=Lisence' alt='License'>
91
+ </a>
92
+ </div>
93
+
94
+ The demo can only be used for <b>Non-commercial Use</b>.
95
+ <br>If you like our work, please star <a href='https://jixiaozhong.github.io/Sonic/' style="margin: 0 2px;">Sonic</a>.
96
+ <br>Note: Audio longer than 10s will be truncated due to computing resources.
97
+ """
98
+ TAIL = """
99
+ <div style="display: flex; justify-content: center; align-items: center;">
100
+ <a href="https://clustrmaps.com/site/1c38t" title="ClustrMaps"><img src="//www.clustrmaps.com/map_v2.png?d=BI2nzSldyixPC88l8Kev4wjjqsU4IOk7gcvpOijolGI&cl=ffffff" /></a>
101
+ </div>
102
+ """
103
+
104
+ def get_example():
105
+ return [
106
+ ["examples/image/female_diaosu.png", "examples/wav/sing_female_rap_10s.MP3", 1.0],
107
+ ["examples/image/hair.png", "examples/wav/sing_female_10s.wav", 1.0],
108
+ ["examples/image/anime1.png", "examples/wav/talk_female_english_10s.MP3", 1.0],
109
+ ["examples/image/leonnado.jpg", "examples/wav/talk_male_law_10s.wav", 1.0],
110
+
111
+ ]
112
+
113
+ with gr.Blocks(title="Sonic") as demo:
114
+ gr.Interface(fn=process_sonic, inputs=inputs, outputs=outputs, title="Sonic: Shifting Focus to Global Audio Perception in Portrait Animation", description=html_description)
115
+ gr.Examples(
116
+ examples=get_example(),
117
+ fn=process_sonic,
118
+ inputs=inputs,
119
+ outputs=outputs,
120
+ cache_examples=False,)
121
+ gr.Markdown(TAIL)
122
+
123
+ demo.launch(server_name='0.0.0.0', server_port=8081, share=True, enable_queue=True)
124
+
125
+
config/inference/sonic.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pretrained_model_name_or_path: "checkpoints/stable-video-diffusion-img2vid-xt"
2
+ unet_checkpoint_path: "checkpoints/Sonic/unet.pth"
3
+ audio2token_checkpoint_path: "checkpoints/Sonic/audio2token.pth"
4
+ audio2bucket_checkpoint_path: "checkpoints/Sonic/audio2bucket.pth"
5
+
6
+ weight_dtype: 'fp16' # [fp16, fp32]
7
+
8
+ num_inference_steps: 25
9
+ n_sample_frames: 25
10
+ fps: 12.5
11
+ decode_chunk_size: 8
12
+ motion_bucket_scale: 1.0
13
+ image_size: 512
14
+ area: 1.1
15
+ frame_num: 10000
16
+ step: 2
17
+ overlap: 0
18
+ shift_offset: 7
19
+ min_appearance_guidance_scale: 2.0
20
+ max_appearance_guidance_scale: 2.0
21
+ audio_guidance_scale: 7.5
22
+ i2i_noise_strength: 1.0
23
+ ip_audio_scale: 1.0
24
+ noise_aug_strength: 0.00
25
+
26
+ use_interframe: True
27
+
28
+ seed: 72589
examples/image/anime1.png ADDED
examples/image/female_diaosu.png ADDED
examples/image/hair.png ADDED
examples/image/leonnado.jpg ADDED
examples/wav/sing_female_10s.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:104729e65b4824df3caa05786508fddea5ccd4dfbe6c66a01dd311f82e725428
3
+ size 640078
examples/wav/sing_female_rap_10s.MP3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:44333e198b646dfb5389513961609515558276daefc9114336dc3ee5d75ce902
3
+ size 160749
examples/wav/talk_female_english_10s.MP3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a6fac3e0fa99dab99a2049d3658f31651ec687ba670f47e6e57d8632ac30a29
3
+ size 160749
examples/wav/talk_male_law_10s.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:686fb83475d540edd6c2899e01d57119cefb8fb441734ed10cc55819fc83d3f0
3
+ size 1764078
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diffusers==0.29.0
2
+ torch==2.2.1
3
+ torchaudio==2.2.1
4
+ torchvision==0.17.1
5
+ transformers==4.43.2
6
+ imageio==2.31.1
7
+ imageio-ffmpeg==0.5.1
8
+ gradio==3.50.0
9
+ omegaconf==2.3.0
10
+ tqdm==4.65.2
11
+ librosa==0.10.2.post1
12
+ einops==0.7.0
13
+ pydub==0.25.1
14
+ gradio==4.3.0
sonic.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.utils.checkpoint
4
+ from PIL import Image
5
+ import numpy as np
6
+ from omegaconf import OmegaConf
7
+ from tqdm import tqdm
8
+ import cv2
9
+
10
+ from diffusers import AutoencoderKLTemporalDecoder
11
+ from diffusers.schedulers import EulerDiscreteScheduler
12
+ from transformers import WhisperModel, CLIPVisionModelWithProjection, AutoFeatureExtractor
13
+
14
+ from src.utils.util import save_videos_grid, seed_everything
15
+ from src.dataset.test_preprocess import process_bbox, image_audio_to_tensor
16
+ from src.models.base.unet_spatio_temporal_condition import UNetSpatioTemporalConditionModel, add_ip_adapters
17
+ from src.pipelines.pipeline_sonic import SonicPipeline
18
+ from src.models.audio_adapter.audio_proj import AudioProjModel
19
+ from src.models.audio_adapter.audio_to_bucket import Audio2bucketModel
20
+ from src.utils.RIFE.RIFE_HDv3 import RIFEModel
21
+ from src.dataset.face_align.align import AlignImage
22
+
23
+
24
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
25
+
26
+ def test(
27
+ pipe,
28
+ config,
29
+ wav_enc,
30
+ audio_pe,
31
+ audio2bucket,
32
+ image_encoder,
33
+ width,
34
+ height,
35
+ batch
36
+ ):
37
+ for k, v in batch.items():
38
+ if isinstance(v, torch.Tensor):
39
+ batch[k] = v.unsqueeze(0).to(pipe.device).float()
40
+ ref_img = batch['ref_img']
41
+ clip_img = batch['clip_images']
42
+ face_mask = batch['face_mask']
43
+ image_embeds = image_encoder(
44
+ clip_img
45
+ ).image_embeds
46
+
47
+ audio_feature = batch['audio_feature']
48
+ audio_len = batch['audio_len']
49
+ step = int(config.step)
50
+
51
+ window = 3000
52
+ audio_prompts = []
53
+ last_audio_prompts = []
54
+ for i in range(0, audio_feature.shape[-1], window):
55
+ audio_prompt = wav_enc.encoder(audio_feature[:,:,i:i+window], output_hidden_states=True).hidden_states
56
+ last_audio_prompt = wav_enc.encoder(audio_feature[:,:,i:i+window]).last_hidden_state
57
+ last_audio_prompt = last_audio_prompt.unsqueeze(-2)
58
+ audio_prompt = torch.stack(audio_prompt, dim=2)
59
+ audio_prompts.append(audio_prompt)
60
+ last_audio_prompts.append(last_audio_prompt)
61
+
62
+ audio_prompts = torch.cat(audio_prompts, dim=1)
63
+ audio_prompts = audio_prompts[:,:audio_len*2]
64
+ audio_prompts = torch.cat([torch.zeros_like(audio_prompts[:,:4]), audio_prompts, torch.zeros_like(audio_prompts[:,:6])], 1)
65
+
66
+ last_audio_prompts = torch.cat(last_audio_prompts, dim=1)
67
+ last_audio_prompts = last_audio_prompts[:,:audio_len*2]
68
+ last_audio_prompts = torch.cat([torch.zeros_like(last_audio_prompts[:,:24]), last_audio_prompts, torch.zeros_like(last_audio_prompts[:,:26])], 1)
69
+
70
+
71
+ ref_tensor_list = []
72
+ audio_tensor_list = []
73
+ uncond_audio_tensor_list = []
74
+ motion_buckets = []
75
+ for i in tqdm(range(audio_len//step)):
76
+
77
+
78
+ audio_clip = audio_prompts[:,i*2*step:i*2*step+10].unsqueeze(0)
79
+ audio_clip_for_bucket = last_audio_prompts[:,i*2*step:i*2*step+50].unsqueeze(0)
80
+ motion_bucket = audio2bucket(audio_clip_for_bucket, image_embeds)
81
+ motion_bucket = motion_bucket * 16 + 16
82
+ motion_buckets.append(motion_bucket[0])
83
+
84
+ cond_audio_clip = audio_pe(audio_clip).squeeze(0)
85
+ uncond_audio_clip = audio_pe(torch.zeros_like(audio_clip)).squeeze(0)
86
+
87
+ ref_tensor_list.append(ref_img[0])
88
+ audio_tensor_list.append(cond_audio_clip[0])
89
+ uncond_audio_tensor_list.append(uncond_audio_clip[0])
90
+
91
+ video = pipe(
92
+ ref_img,
93
+ clip_img,
94
+ face_mask,
95
+ audio_tensor_list,
96
+ uncond_audio_tensor_list,
97
+ motion_buckets,
98
+ height=height,
99
+ width=width,
100
+ num_frames=len(audio_tensor_list),
101
+ decode_chunk_size=config.decode_chunk_size,
102
+ motion_bucket_scale=config.motion_bucket_scale,
103
+ fps=config.fps,
104
+ noise_aug_strength=config.noise_aug_strength,
105
+ min_guidance_scale1=config.min_appearance_guidance_scale, # 1.0,
106
+ max_guidance_scale1=config.max_appearance_guidance_scale,
107
+ min_guidance_scale2=config.audio_guidance_scale, # 1.0,
108
+ max_guidance_scale2=config.audio_guidance_scale,
109
+ overlap=config.overlap,
110
+ shift_offset=config.shift_offset,
111
+ frames_per_batch=config.n_sample_frames,
112
+ num_inference_steps=config.num_inference_steps,
113
+ i2i_noise_strength=config.i2i_noise_strength
114
+ ).frames
115
+
116
+
117
+ # Concat it with pose tensor
118
+ # pose_tensor = torch.stack(pose_tensor_list,1).unsqueeze(0)
119
+ video = (video*0.5 + 0.5).clamp(0, 1)
120
+ video = torch.cat([video.to(pipe.device)], dim=0).cpu()
121
+
122
+ return video
123
+
124
+
125
+ class Sonic():
126
+ config_file = os.path.join(BASE_DIR, 'config/inference/sonic.yaml')
127
+ config = OmegaConf.load(config_file)
128
+
129
+ def __init__(self,
130
+ device_id=0,
131
+ enable_interpolate_frame=True,
132
+ ):
133
+
134
+ config = self.config
135
+ config.use_interframe = enable_interpolate_frame
136
+
137
+ device = 'cuda:{}'.format(device_id) if device_id > -1 else 'cpu'
138
+
139
+ config.pretrained_model_name_or_path = os.path.join(BASE_DIR, config.pretrained_model_name_or_path)
140
+
141
+ vae = AutoencoderKLTemporalDecoder.from_pretrained(
142
+ config.pretrained_model_name_or_path,
143
+ subfolder="vae",
144
+ variant="fp16")
145
+
146
+ val_noise_scheduler = EulerDiscreteScheduler.from_pretrained(
147
+ config.pretrained_model_name_or_path,
148
+ subfolder="scheduler")
149
+
150
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
151
+ config.pretrained_model_name_or_path,
152
+ subfolder="image_encoder",
153
+ variant="fp16")
154
+ unet = UNetSpatioTemporalConditionModel.from_pretrained(
155
+ config.pretrained_model_name_or_path,
156
+ subfolder="unet",
157
+ variant="fp16")
158
+ add_ip_adapters(unet, [32], [config.ip_audio_scale])
159
+
160
+ audio2token = AudioProjModel(seq_len=10, blocks=5, channels=384, intermediate_dim=1024, output_dim=1024, context_tokens=32).to(device)
161
+ audio2bucket = Audio2bucketModel(seq_len=50, blocks=1, channels=384, clip_channels=1024, intermediate_dim=1024, output_dim=1, context_tokens=2).to(device)
162
+
163
+ unet_checkpoint_path = os.path.join(BASE_DIR, config.unet_checkpoint_path)
164
+ audio2token_checkpoint_path = os.path.join(BASE_DIR, config.audio2token_checkpoint_path)
165
+ audio2bucket_checkpoint_path = os.path.join(BASE_DIR, config.audio2bucket_checkpoint_path)
166
+
167
+ unet.load_state_dict(
168
+ torch.load(unet_checkpoint_path, map_location="cpu"),
169
+ strict=True,
170
+ )
171
+
172
+ audio2token.load_state_dict(
173
+ torch.load(audio2token_checkpoint_path, map_location="cpu"),
174
+ strict=True,
175
+ )
176
+
177
+ audio2bucket.load_state_dict(
178
+ torch.load(audio2bucket_checkpoint_path, map_location="cpu"),
179
+ strict=True,
180
+ )
181
+
182
+
183
+ if config.weight_dtype == "fp16":
184
+ weight_dtype = torch.float16
185
+ elif config.weight_dtype == "fp32":
186
+ weight_dtype = torch.float32
187
+ elif config.weight_dtype == "bf16":
188
+ weight_dtype = torch.bfloat16
189
+ else:
190
+ raise ValueError(
191
+ f"Do not support weight dtype: {config.weight_dtype} during training"
192
+ )
193
+
194
+ whisper = WhisperModel.from_pretrained(os.path.join(BASE_DIR, 'checkpoints/whisper-tiny/')).to(device).eval()
195
+
196
+ whisper.requires_grad_(False)
197
+
198
+ self.feature_extractor = AutoFeatureExtractor.from_pretrained(os.path.join(BASE_DIR, 'checkpoints/whisper-tiny/'))
199
+
200
+ det_path = os.path.join(BASE_DIR, os.path.join(BASE_DIR, 'checkpoints/yoloface_v5m.pt'))
201
+ self.face_det = AlignImage(device, det_path=det_path)
202
+ if config.use_interframe:
203
+ rife = RIFEModel(device=device)
204
+ rife.load_model(os.path.join(BASE_DIR, 'checkpoints', 'RIFE/'))
205
+ self.rife = rife
206
+
207
+
208
+ image_encoder.to(weight_dtype)
209
+ vae.to(weight_dtype)
210
+ unet.to(weight_dtype)
211
+
212
+ pipe = SonicPipeline(
213
+ unet=unet,
214
+ image_encoder=image_encoder,
215
+ vae=vae,
216
+ scheduler=val_noise_scheduler,
217
+ )
218
+ pipe = pipe.to(device=device, dtype=weight_dtype)
219
+
220
+
221
+ self.pipe = pipe
222
+ self.whisper = whisper
223
+ self.audio2token = audio2token
224
+ self.audio2bucket = audio2bucket
225
+ self.image_encoder = image_encoder
226
+ self.device = device
227
+
228
+ print('init done')
229
+
230
+
231
+ def preprocess(self,
232
+ image_path, expand_ratio=1.0):
233
+ face_image = cv2.imread(image_path)
234
+ h, w = face_image.shape[:2]
235
+ _, _, bboxes = self.face_det(face_image, maxface=True)
236
+ face_num = len(bboxes)
237
+ bbox = []
238
+ if face_num > 0:
239
+ x1, y1, ww, hh = bboxes[0]
240
+ x2, y2 = x1 + ww, y1 + hh
241
+ bbox = x1, y1, x2, y2
242
+ bbox_s = process_bbox(bbox, expand_radio=expand_ratio, height=h, width=w)
243
+
244
+ return {
245
+ 'face_num': face_num,
246
+ 'crop_bbox': bbox_s,
247
+ }
248
+
249
+ def crop_image(self,
250
+ input_image_path,
251
+ output_image_path,
252
+ crop_bbox):
253
+ face_image = cv2.imread(input_image_path)
254
+ crop_image = face_image[crop_bbox[1]:crop_bbox[3], crop_bbox[0]:crop_bbox[2]]
255
+ cv2.imwrite(output_image_path, crop_image)
256
+
257
+ @torch.no_grad()
258
+ def process(self,
259
+ image_path,
260
+ audio_path,
261
+ output_path,
262
+ min_resolution=512,
263
+ inference_steps=25,
264
+ dynamic_scale=1.0,
265
+ keep_resolution=False,
266
+ seed=None):
267
+
268
+ config = self.config
269
+ device = self.device
270
+ pipe = self.pipe
271
+ whisper = self.whisper
272
+ audio2token = self.audio2token
273
+ audio2bucket = self.audio2bucket
274
+ image_encoder = self.image_encoder
275
+
276
+ # specific parameters
277
+ if seed:
278
+ config.seed = seed
279
+
280
+ config.num_inference_steps = inference_steps
281
+
282
+ config.motion_bucket_scale = dynamic_scale
283
+
284
+ seed_everything(config.seed)
285
+
286
+ video_path = output_path.replace('.mp4', '_noaudio.mp4')
287
+ audio_video_path = output_path
288
+
289
+ imSrc_ = Image.open(image_path).convert('RGB')
290
+ raw_w, raw_h = imSrc_.size
291
+
292
+ test_data = image_audio_to_tensor(self.face_det, self.feature_extractor, image_path, audio_path, limit=config.frame_num, image_size=min_resolution, area=config.area)
293
+ if test_data is None:
294
+ return -1
295
+ height, width = test_data['ref_img'].shape[-2:]
296
+ if keep_resolution:
297
+ resolution = f'{raw_w//2*2}x{raw_h//2*2}'
298
+ else:
299
+ resolution = f'{width}x{height}'
300
+
301
+ video = test(
302
+ pipe,
303
+ config,
304
+ wav_enc=whisper,
305
+ audio_pe=audio2token,
306
+ audio2bucket=audio2bucket,
307
+ image_encoder=image_encoder,
308
+ width=width,
309
+ height=height,
310
+ batch=test_data,
311
+ )
312
+
313
+ if config.use_interframe:
314
+ rife = self.rife
315
+ out = video.to(device)
316
+ results = []
317
+ video_len = out.shape[2]
318
+ for idx in tqdm(range(video_len-1), ncols=0):
319
+ I1 = out[:, :, idx]
320
+ I2 = out[:, :, idx+1]
321
+ middle = rife.inference(I1, I2).clamp(0, 1).detach()
322
+ results.append(out[:, :, idx])
323
+ results.append(middle)
324
+ results.append(out[:, :, video_len-1])
325
+ video = torch.stack(results, 2).cpu()
326
+
327
+ save_videos_grid(video, video_path, n_rows=video.shape[0], fps=config.fps * 2 if config.use_interframe else config.fps)
328
+ os.system(f"ffmpeg -i '{video_path}' -i '{audio_path}' -s {resolution} -vcodec libx264 -acodec aac -crf 18 -shortest '{audio_video_path}' -y; rm '{video_path}'")
329
+ return 0
330
+
src/dataset/face_align/align.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
4
+ sys.path.append(BASE_DIR)
5
+ import torch
6
+ from src.dataset.face_align.yoloface import YoloFace
7
+
8
+ class AlignImage(object):
9
+ def __init__(self, device='cuda', det_path='checkpoints/yoloface_v5m.pt'):
10
+ self.facedet = YoloFace(pt_path=det_path, confThreshold=0.5, nmsThreshold=0.45, device=device)
11
+
12
+ @torch.no_grad()
13
+ def __call__(self, im, maxface=False):
14
+ bboxes, kpss, scores = self.facedet.detect(im)
15
+ face_num = bboxes.shape[0]
16
+
17
+ five_pts_list = []
18
+ scores_list = []
19
+ bboxes_list = []
20
+ for i in range(face_num):
21
+ five_pts_list.append(kpss[i].reshape(5,2))
22
+ scores_list.append(scores[i])
23
+ bboxes_list.append(bboxes[i])
24
+
25
+ if maxface and face_num>1:
26
+ max_idx = 0
27
+ max_area = (bboxes[0, 2])*(bboxes[0, 3])
28
+ for i in range(1, face_num):
29
+ area = (bboxes[i,2])*(bboxes[i,3])
30
+ if area>max_area:
31
+ max_idx = i
32
+ five_pts_list = [five_pts_list[max_idx]]
33
+ scores_list = [scores_list[max_idx]]
34
+ bboxes_list = [bboxes_list[max_idx]]
35
+
36
+ return five_pts_list, scores_list, bboxes_list
src/dataset/face_align/yoloface.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: UTF-8 -*-
2
+ import os
3
+ import cv2
4
+ import numpy as np
5
+ import torch
6
+ import torchvision
7
+
8
+
9
+ def xyxy2xywh(x):
10
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
11
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
12
+ y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
13
+ y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
14
+ y[:, 2] = x[:, 2] - x[:, 0] # width
15
+ y[:, 3] = x[:, 3] - x[:, 1] # height
16
+ return y
17
+
18
+
19
+ def xywh2xyxy(x):
20
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
21
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
22
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
23
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
24
+ y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
25
+ y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
26
+ return y
27
+
28
+
29
+ def box_iou(box1, box2):
30
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
31
+ """
32
+ Return intersection-over-union (Jaccard index) of boxes.
33
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
34
+ Arguments:
35
+ box1 (Tensor[N, 4])
36
+ box2 (Tensor[M, 4])
37
+ Returns:
38
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
39
+ IoU values for every element in boxes1 and boxes2
40
+ """
41
+
42
+ def box_area(box):
43
+ # box = 4xn
44
+ return (box[2] - box[0]) * (box[3] - box[1])
45
+
46
+ area1 = box_area(box1.T)
47
+ area2 = box_area(box2.T)
48
+
49
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
50
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) -
51
+ torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
52
+ # iou = inter / (area1 + area2 - inter)
53
+ return inter / (area1[:, None] + area2 - inter)
54
+
55
+
56
+ def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
57
+ # Rescale coords (xyxy) from img1_shape to img0_shape
58
+ if ratio_pad is None: # calculate from img0_shape
59
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
60
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
61
+ else:
62
+ gain = ratio_pad[0][0]
63
+ pad = ratio_pad[1]
64
+
65
+ coords[:, [0, 2]] -= pad[0] # x padding
66
+ coords[:, [1, 3]] -= pad[1] # y padding
67
+ coords[:, :4] /= gain
68
+ clip_coords(coords, img0_shape)
69
+ return coords
70
+
71
+
72
+ def clip_coords(boxes, img_shape):
73
+ # Clip bounding xyxy bounding boxes to image shape (height, width)
74
+ boxes[:, 0].clamp_(0, img_shape[1]) # x1
75
+ boxes[:, 1].clamp_(0, img_shape[0]) # y1
76
+ boxes[:, 2].clamp_(0, img_shape[1]) # x2
77
+ boxes[:, 3].clamp_(0, img_shape[0]) # y2
78
+
79
+
80
+ def scale_coords_landmarks(img1_shape, coords, img0_shape, ratio_pad=None):
81
+ # Rescale coords (xyxy) from img1_shape to img0_shape
82
+ if ratio_pad is None: # calculate from img0_shape
83
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
84
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
85
+ else:
86
+ gain = ratio_pad[0][0]
87
+ pad = ratio_pad[1]
88
+
89
+ coords[:, [0, 2, 4, 6, 8]] -= pad[0] # x padding
90
+ coords[:, [1, 3, 5, 7, 9]] -= pad[1] # y padding
91
+ coords[:, :10] /= gain
92
+ #clip_coords(coords, img0_shape)
93
+ coords[:, 0].clamp_(0, img0_shape[1]) # x1
94
+ coords[:, 1].clamp_(0, img0_shape[0]) # y1
95
+ coords[:, 2].clamp_(0, img0_shape[1]) # x2
96
+ coords[:, 3].clamp_(0, img0_shape[0]) # y2
97
+ coords[:, 4].clamp_(0, img0_shape[1]) # x3
98
+ coords[:, 5].clamp_(0, img0_shape[0]) # y3
99
+ coords[:, 6].clamp_(0, img0_shape[1]) # x4
100
+ coords[:, 7].clamp_(0, img0_shape[0]) # y4
101
+ coords[:, 8].clamp_(0, img0_shape[1]) # x5
102
+ coords[:, 9].clamp_(0, img0_shape[0]) # y5
103
+ return coords
104
+
105
+
106
+ def show_results(img, xywh, conf, landmarks, class_num):
107
+ h,w,c = img.shape
108
+ tl = 1 or round(0.002 * (h + w) / 2) + 1 # line/font thickness
109
+ x1 = int(xywh[0] * w - 0.5 * xywh[2] * w)
110
+ y1 = int(xywh[1] * h - 0.5 * xywh[3] * h)
111
+ x2 = int(xywh[0] * w + 0.5 * xywh[2] * w)
112
+ y2 = int(xywh[1] * h + 0.5 * xywh[3] * h)
113
+ cv2.rectangle(img, (x1,y1), (x2, y2), (0,255,0), thickness=tl, lineType=cv2.LINE_AA)
114
+
115
+ clors = [(255,0,0),(0,255,0),(0,0,255),(255,255,0),(0,255,255)]
116
+
117
+ for i in range(5):
118
+ point_x = int(landmarks[2 * i] * w)
119
+ point_y = int(landmarks[2 * i + 1] * h)
120
+ cv2.circle(img, (point_x, point_y), tl+1, clors[i], -1)
121
+
122
+ tf = max(tl - 1, 1) # font thickness
123
+ label = str(conf)[:5]
124
+ cv2.putText(img, label, (x1, y1 - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
125
+ return img
126
+
127
+
128
+ def make_divisible(x, divisor):
129
+ # Returns x evenly divisible by divisor
130
+ return (x // divisor) * divisor
131
+
132
+
133
+ def non_max_suppression_face(prediction, conf_thres=0.5, iou_thres=0.45, classes=None, agnostic=False, labels=()):
134
+ """Performs Non-Maximum Suppression (NMS) on inference results
135
+ Returns:
136
+ detections with shape: nx6 (x1, y1, x2, y2, conf, cls)
137
+ """
138
+
139
+ nc = prediction.shape[2] - 15 # number of classes
140
+ xc = prediction[..., 4] > conf_thres # candidates
141
+
142
+ # Settings
143
+ min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
144
+ # time_limit = 10.0 # seconds to quit after
145
+ redundant = True # require redundant detections
146
+ multi_label = nc > 1 # multiple labels per box (adds 0.5ms/img)
147
+ merge = False # use merge-NMS
148
+
149
+ # t = time.time()
150
+ output = [torch.zeros((0, 16), device=prediction.device)] * prediction.shape[0]
151
+ for xi, x in enumerate(prediction): # image index, image inference
152
+ # Apply constraints
153
+ # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
154
+ x = x[xc[xi]] # confidence
155
+
156
+ # Cat apriori labels if autolabelling
157
+ if labels and len(labels[xi]):
158
+ l = labels[xi]
159
+ v = torch.zeros((len(l), nc + 15), device=x.device)
160
+ v[:, :4] = l[:, 1:5] # box
161
+ v[:, 4] = 1.0 # conf
162
+ v[range(len(l)), l[:, 0].long() + 15] = 1.0 # cls
163
+ x = torch.cat((x, v), 0)
164
+
165
+ # If none remain process next image
166
+ if not x.shape[0]:
167
+ continue
168
+
169
+ # Compute conf
170
+ x[:, 15:] *= x[:, 4:5] # conf = obj_conf * cls_conf
171
+
172
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
173
+ box = xywh2xyxy(x[:, :4])
174
+
175
+ # Detections matrix nx6 (xyxy, conf, landmarks, cls)
176
+ if multi_label:
177
+ i, j = (x[:, 15:] > conf_thres).nonzero(as_tuple=False).T
178
+ x = torch.cat((box[i], x[i, j + 15, None], x[i, 5:15] ,j[:, None].float()), 1)
179
+ else: # best class only
180
+ conf, j = x[:, 15:].max(1, keepdim=True)
181
+ x = torch.cat((box, conf, x[:, 5:15], j.float()), 1)[conf.view(-1) > conf_thres]
182
+
183
+ # Filter by class
184
+ if classes is not None:
185
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
186
+
187
+ # If none remain process next image
188
+ n = x.shape[0] # number of boxes
189
+ if not n:
190
+ continue
191
+
192
+ # Batched NMS
193
+ c = x[:, 15:16] * (0 if agnostic else max_wh) # classes
194
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
195
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
196
+ #if i.shape[0] > max_det: # limit detections
197
+ # i = i[:max_det]
198
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
199
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
200
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
201
+ weights = iou * scores[None] # box weights
202
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
203
+ if redundant:
204
+ i = i[iou.sum(1) > 1] # require redundancy
205
+
206
+ output[xi] = x[i]
207
+ # if (time.time() - t) > time_limit:
208
+ # break # time limit exceeded
209
+
210
+ return output
211
+
212
+
213
+ class YoloFace():
214
+ def __init__(self, pt_path='checkpoints/yolov5m-face.pt', confThreshold=0.5, nmsThreshold=0.45, device='cuda'):
215
+ assert os.path.exists(pt_path)
216
+
217
+ self.inpSize = 416
218
+ self.conf_thres = confThreshold
219
+ self.iou_thres = nmsThreshold
220
+ self.test_device = torch.device(device if torch.cuda.is_available() else "cpu")
221
+ self.model = torch.jit.load(pt_path).to(self.test_device)
222
+ self.last_w = 416
223
+ self.last_h = 416
224
+ self.grids = None
225
+
226
+ @torch.no_grad()
227
+ def detect(self, srcimg):
228
+ # t0=time.time()
229
+
230
+ h0, w0 = srcimg.shape[:2] # orig hw
231
+ r = self.inpSize / min(h0, w0) # resize image to img_size
232
+ h1 = int(h0*r+31)//32*32
233
+ w1 = int(w0*r+31)//32*32
234
+
235
+ img = cv2.resize(srcimg, (w1,h1), interpolation=cv2.INTER_LINEAR)
236
+
237
+ # Convert
238
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # BGR to RGB
239
+
240
+ # Run inference
241
+ img = torch.from_numpy(img).to(self.test_device).permute(2,0,1)
242
+ img = img.float()/255 # uint8 to fp16/32 0-1
243
+ if img.ndimension() == 3:
244
+ img = img.unsqueeze(0)
245
+
246
+ # Inference
247
+ if h1 != self.last_h or w1 != self.last_w or self.grids is None:
248
+ grids = []
249
+ for scale in [8,16,32]:
250
+ ny = h1//scale
251
+ nx = w1//scale
252
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
253
+ grid = torch.stack((xv, yv), 2).view((1,1,ny, nx, 2)).float()
254
+ grids.append(grid.to(self.test_device))
255
+ self.grids = grids
256
+ self.last_w = w1
257
+ self.last_h = h1
258
+
259
+ pred = self.model(img, self.grids).cpu()
260
+
261
+ # Apply NMS
262
+ det = non_max_suppression_face(pred, self.conf_thres, self.iou_thres)[0]
263
+ # Process detections
264
+ # det = pred[0]
265
+ bboxes = np.zeros((det.shape[0], 4))
266
+ kpss = np.zeros((det.shape[0], 5, 2))
267
+ scores = np.zeros((det.shape[0]))
268
+ # gn = torch.tensor([w0, h0, w0, h0]).to(pred) # normalization gain whwh
269
+ # gn_lks = torch.tensor([w0, h0, w0, h0, w0, h0, w0, h0, w0, h0]).to(pred) # normalization gain landmarks
270
+ det = det.cpu().numpy()
271
+
272
+ for j in range(det.shape[0]):
273
+ # xywh = (xyxy2xywh(det[j, :4].view(1, 4)) / gn).view(4).cpu().numpy()
274
+ bboxes[j, 0] = det[j, 0] * w0/w1
275
+ bboxes[j, 1] = det[j, 1] * h0/h1
276
+ bboxes[j, 2] = det[j, 2] * w0/w1 - bboxes[j, 0]
277
+ bboxes[j, 3] = det[j, 3] * h0/h1 - bboxes[j, 1]
278
+ scores[j] = det[j, 4]
279
+ # landmarks = (det[j, 5:15].view(1, 10) / gn_lks).view(5,2).cpu().numpy()
280
+ kpss[j, :, :] = det[j, 5:15].reshape(5, 2) * np.array([[w0/w1,h0/h1]])
281
+ # class_num = det[j, 15].cpu().numpy()
282
+ # orgimg = show_results(orgimg, xywh, conf, landmarks, class_num)
283
+ return bboxes, kpss, scores
284
+
285
+
286
+
287
+ if __name__ == '__main__':
288
+ import time
289
+
290
+ imgpath = 'test.png'
291
+
292
+ yoloface = YoloFace(pt_path='../checkpoints/yoloface_v5m.pt')
293
+ srcimg = cv2.imread(imgpath)
294
+
295
+ #warpup
296
+ bboxes, kpss, scores = yoloface.detect(srcimg)
297
+ bboxes, kpss, scores = yoloface.detect(srcimg)
298
+ bboxes, kpss, scores = yoloface.detect(srcimg)
299
+
300
+ t1 = time.time()
301
+ for _ in range(10):
302
+ bboxes, kpss, scores = yoloface.detect(srcimg)
303
+ t2 = time.time()
304
+ print('total time: {} ms'.format((t2 - t1) * 1000))
305
+ for i in range(bboxes.shape[0]):
306
+ xmin, ymin, xamx, ymax = int(bboxes[i, 0]), int(bboxes[i, 1]), int(bboxes[i, 0] + bboxes[i, 2]), int(bboxes[i, 1] + bboxes[i, 3])
307
+ cv2.rectangle(srcimg, (xmin, ymin), (xamx, ymax), (0, 0, 255), thickness=2)
308
+ for j in range(5):
309
+ cv2.circle(srcimg, (int(kpss[i, j, 0]), int(kpss[i, j, 1])), 1, (0, 255, 0), thickness=5)
310
+ cv2.imwrite('test_yoloface.jpg', srcimg)
src/dataset/test_preprocess.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ from PIL import Image
4
+ import torch
5
+ import torchvision.transforms as transforms
6
+ from transformers import CLIPImageProcessor
7
+ import librosa
8
+
9
+
10
+ def process_bbox(bbox, expand_radio, height, width):
11
+ """
12
+ raw_vid_path:
13
+ bbox: format: x1, y1, x2, y2
14
+ radio: expand radio against bbox size
15
+ height,width: source image height and width
16
+ """
17
+
18
+ def expand(bbox, ratio, height, width):
19
+
20
+ bbox_h = bbox[3] - bbox[1]
21
+ bbox_w = bbox[2] - bbox[0]
22
+
23
+ expand_x1 = max(bbox[0] - ratio * bbox_w, 0)
24
+ expand_y1 = max(bbox[1] - ratio * bbox_h, 0)
25
+ expand_x2 = min(bbox[2] + ratio * bbox_w, width)
26
+ expand_y2 = min(bbox[3] + ratio * bbox_h, height)
27
+
28
+ return [expand_x1,expand_y1,expand_x2,expand_y2]
29
+
30
+ def to_square(bbox_src, bbox_expend, height, width):
31
+
32
+ h = bbox_expend[3] - bbox_expend[1]
33
+ w = bbox_expend[2] - bbox_expend[0]
34
+ c_h = (bbox_expend[1] + bbox_expend[3]) / 2
35
+ c_w = (bbox_expend[0] + bbox_expend[2]) / 2
36
+
37
+ c = min(h, w) / 2
38
+
39
+ c_src_h = (bbox_src[1] + bbox_src[3]) / 2
40
+ c_src_w = (bbox_src[0] + bbox_src[2]) / 2
41
+
42
+ s_h, s_w = 0, 0
43
+ if w < h:
44
+ d = abs((h - w) / 2)
45
+ s_h = min(d, abs(c_src_h-c_h))
46
+ s_h = s_h if c_src_h > c_h else s_h * (-1)
47
+ else:
48
+ d = abs((h - w) / 2)
49
+ s_w = min(d, abs(c_src_w-c_w))
50
+ s_w = s_w if c_src_w > c_w else s_w * (-1)
51
+
52
+
53
+ c_h = (bbox_expend[1] + bbox_expend[3]) / 2 + s_h
54
+ c_w = (bbox_expend[0] + bbox_expend[2]) / 2 + s_w
55
+
56
+ square_x1 = c_w - c
57
+ square_y1 = c_h - c
58
+ square_x2 = c_w + c
59
+ square_y2 = c_h + c
60
+
61
+ x1, y1, x2, y2 = square_x1, square_y1, square_x2, square_y2
62
+ ww = x2 - x1
63
+ hh = y2 - y1
64
+ cc_x = (x1 + x2)/2
65
+ cc_y = (y1 + y2)/2
66
+ # 1:1
67
+ ww = hh = min(ww, hh)
68
+ x1, x2 = round(cc_x - ww/2), round(cc_x + ww/2)
69
+ y1, y2 = round(cc_y - hh/2), round(cc_y + hh/2)
70
+
71
+ return [round(x1), round(y1), round(x2), round(y2)]
72
+
73
+
74
+ bbox_expend = expand(bbox, expand_radio, height=height, width=width)
75
+ processed_bbox = to_square(bbox, bbox_expend, height=height, width=width)
76
+
77
+ return processed_bbox
78
+
79
+
80
+ def get_audio_feature(audio_path, feature_extractor):
81
+ audio_input, sampling_rate = librosa.load(audio_path, sr=16000)
82
+ assert sampling_rate == 16000
83
+
84
+ audio_features = []
85
+ window = 750*640
86
+ for i in range(0, len(audio_input), window):
87
+ audio_feature = feature_extractor(audio_input[i:i+window],
88
+ sampling_rate=sampling_rate,
89
+ return_tensors="pt",
90
+ ).input_features
91
+ audio_features.append(audio_feature)
92
+ audio_features = torch.cat(audio_features, dim=-1)
93
+ return audio_features, len(audio_input) // 640
94
+
95
+ def image_audio_to_tensor(align_instance, feature_extractor, image_path, audio_path, limit=100, image_size=512, area=1.25):
96
+
97
+ clip_processor = CLIPImageProcessor()
98
+
99
+ to_tensor = transforms.Compose([
100
+ transforms.ToTensor(),
101
+ transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
102
+ ])
103
+ mask_to_tensor = transforms.Compose([
104
+ transforms.ToTensor(),
105
+ ])
106
+
107
+
108
+ imSrc_ = Image.open(image_path).convert('RGB')
109
+ w, h = imSrc_.size
110
+
111
+ _, _, bboxes_list = align_instance(np.array(imSrc_)[:,:,[2,1,0]], maxface=True)
112
+
113
+ if len(bboxes_list) == 0:
114
+ return None
115
+ bboxSrc = bboxes_list[0]
116
+
117
+ x1, y1, ww, hh = bboxSrc
118
+ x2, y2 = x1 + ww, y1 + hh
119
+
120
+ mask_img = np.zeros_like(np.array(imSrc_))
121
+ ww, hh = (x2-x1) * area, (y2-y1) * area
122
+ center = [(x2+x1)//2, (y2+y1)//2]
123
+ x1 = max(center[0] - ww//2, 0)
124
+ y1 = max(center[1] - hh//2, 0)
125
+ x2 = min(center[0] + ww//2, w)
126
+ y2 = min(center[1] + hh//2, h)
127
+ mask_img[int(y1):int(y2), int(x1):int(x2)] = 255
128
+ mask_img = Image.fromarray(mask_img)
129
+
130
+ w, h = imSrc_.size
131
+ scale = image_size / min(w, h)
132
+ new_w = round(w * scale / 64) * 64
133
+ new_h = round(h * scale / 64) * 64
134
+ if new_h != h or new_w != w:
135
+ imSrc = imSrc_.resize((new_w, new_h), Image.LANCZOS)
136
+ mask_img = mask_img.resize((new_w, new_h), Image.LANCZOS)
137
+ else:
138
+ imSrc = imSrc_
139
+
140
+ clip_image = clip_processor(
141
+ images=imSrc.resize((224, 224), Image.LANCZOS), return_tensors="pt"
142
+ ).pixel_values[0]
143
+ audio_input, audio_len = get_audio_feature(audio_path, feature_extractor)
144
+
145
+ audio_len = min(limit, audio_len)
146
+
147
+ sample = dict(
148
+ face_mask=mask_to_tensor(mask_img),
149
+ ref_img=to_tensor(imSrc),
150
+ clip_images=clip_image,
151
+ audio_feature=audio_input[0],
152
+ audio_len=audio_len
153
+ )
154
+
155
+ return sample
src/models/audio_adapter/audio_proj.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module provides the implementation of an Audio Projection Model, which is designed for
3
+ audio processing tasks. The model takes audio embeddings as input and outputs context tokens
4
+ that can be used for various downstream applications, such as audio analysis or synthesis.
5
+
6
+ The AudioProjModel class is based on the ModelMixin class from the diffusers library, which
7
+ provides a foundation for building custom models. This implementation includes multiple linear
8
+ layers with ReLU activation functions and a LayerNorm for normalization.
9
+
10
+ Key Features:
11
+ - Audio embedding input with flexible sequence length and block structure.
12
+ - Multiple linear layers for feature transformation.
13
+ - ReLU activation for non-linear transformation.
14
+ - LayerNorm for stabilizing and speeding up training.
15
+ - Rearrangement of input embeddings to match the model's expected input shape.
16
+ - Customizable number of blocks, channels, and context tokens for adaptability.
17
+
18
+ The module is structured to be easily integrated into larger systems or used as a standalone
19
+ component for audio feature extraction and processing.
20
+
21
+ Classes:
22
+ - AudioProjModel: A class representing the audio projection model with configurable parameters.
23
+
24
+ Functions:
25
+ - (none)
26
+
27
+ Dependencies:
28
+ - torch: For tensor operations and neural network components.
29
+ - diffusers: For the ModelMixin base class.
30
+ - einops: For tensor rearrangement operations.
31
+
32
+ """
33
+
34
+ import torch
35
+ from diffusers import ModelMixin
36
+ from einops import rearrange
37
+ from torch import nn
38
+
39
+
40
+ class AudioProjModel(ModelMixin):
41
+ """Audio Projection Model
42
+
43
+ This class defines an audio projection model that takes audio embeddings as input
44
+ and produces context tokens as output. The model is based on the ModelMixin class
45
+ and consists of multiple linear layers and activation functions. It can be used
46
+ for various audio processing tasks.
47
+
48
+ Attributes:
49
+ seq_len (int): The length of the audio sequence.
50
+ blocks (int): The number of blocks in the audio projection model.
51
+ channels (int): The number of channels in the audio projection model.
52
+ intermediate_dim (int): The intermediate dimension of the model.
53
+ context_tokens (int): The number of context tokens in the output.
54
+ output_dim (int): The output dimension of the context tokens.
55
+
56
+ Methods:
57
+ __init__(self, seq_len=5, blocks=12, channels=768, intermediate_dim=512, context_tokens=32, output_dim=768):
58
+ Initializes the AudioProjModel with the given parameters.
59
+ forward(self, audio_embeds):
60
+ Defines the forward pass for the AudioProjModel.
61
+ Parameters:
62
+ audio_embeds (torch.Tensor): The input audio embeddings with shape (batch_size, video_length, blocks, channels).
63
+ Returns:
64
+ context_tokens (torch.Tensor): The output context tokens with shape (batch_size, video_length, context_tokens, output_dim).
65
+
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ seq_len=5,
71
+ blocks=12, # add a new parameter blocks
72
+ channels=768, # add a new parameter channels
73
+ intermediate_dim=512,
74
+ output_dim=768,
75
+ context_tokens=32,
76
+ ):
77
+ super().__init__()
78
+
79
+ self.seq_len = seq_len
80
+ self.blocks = blocks
81
+ self.channels = channels
82
+ self.input_dim = (
83
+ seq_len * blocks * channels
84
+ ) # update input_dim to be the product of blocks and channels.
85
+ self.intermediate_dim = intermediate_dim
86
+ self.context_tokens = context_tokens
87
+ self.output_dim = output_dim
88
+
89
+ # define multiple linear layers
90
+ self.proj1 = nn.Linear(self.input_dim, intermediate_dim)
91
+ self.proj2 = nn.Linear(intermediate_dim, intermediate_dim)
92
+ self.proj3 = nn.Linear(intermediate_dim, context_tokens * output_dim)
93
+
94
+ self.norm = nn.LayerNorm(output_dim)
95
+
96
+ def forward(self, audio_embeds):
97
+ """
98
+ Defines the forward pass for the AudioProjModel.
99
+
100
+ Parameters:
101
+ audio_embeds (torch.Tensor): The input audio embeddings with shape (batch_size, video_length, blocks, channels).
102
+
103
+ Returns:
104
+ context_tokens (torch.Tensor): The output context tokens with shape (batch_size, video_length, context_tokens, output_dim).
105
+ """
106
+ # merge
107
+ video_length = audio_embeds.shape[1]
108
+ audio_embeds = rearrange(audio_embeds, "bz f w b c -> (bz f) w b c")
109
+ batch_size, window_size, blocks, channels = audio_embeds.shape
110
+ audio_embeds = audio_embeds.view(batch_size, window_size * blocks * channels)
111
+
112
+ audio_embeds = torch.relu(self.proj1(audio_embeds))
113
+ audio_embeds = torch.relu(self.proj2(audio_embeds))
114
+
115
+ context_tokens = self.proj3(audio_embeds).reshape(
116
+ batch_size, self.context_tokens, self.output_dim
117
+ )
118
+
119
+ context_tokens = self.norm(context_tokens)
120
+ context_tokens = rearrange(
121
+ context_tokens, "(bz f) m c -> bz f m c", f=video_length
122
+ )
123
+
124
+ return context_tokens
src/models/audio_adapter/audio_to_bucket.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module provides the implementation of an Audio Projection Model, which is designed for
3
+ audio processing tasks. The model takes audio embeddings as input and outputs context tokens
4
+ that can be used for various downstream applications, such as audio analysis or synthesis.
5
+
6
+ The AudioProjModel class is based on the ModelMixin class from the diffusers library, which
7
+ provides a foundation for building custom models. This implementation includes multiple linear
8
+ layers with ReLU activation functions and a LayerNorm for normalization.
9
+
10
+ Key Features:
11
+ - Audio embedding input with flexible sequence length and block structure.
12
+ - Multiple linear layers for feature transformation.
13
+ - ReLU activation for non-linear transformation.
14
+ - LayerNorm for stabilizing and speeding up training.
15
+ - Rearrangement of input embeddings to match the model's expected input shape.
16
+ - Customizable number of blocks, channels, and context tokens for adaptability.
17
+
18
+ The module is structured to be easily integrated into larger systems or used as a standalone
19
+ component for audio feature extraction and processing.
20
+
21
+ Classes:
22
+ - AudioProjModel: A class representing the audio projection model with configurable parameters.
23
+
24
+ Functions:
25
+ - (none)
26
+
27
+ Dependencies:
28
+ - torch: For tensor operations and neural network components.
29
+ - diffusers: For the ModelMixin base class.
30
+ - einops: For tensor rearrangement operations.
31
+
32
+ """
33
+
34
+ import torch
35
+ from diffusers import ModelMixin
36
+ from einops import rearrange
37
+ from torch import nn
38
+
39
+
40
+ class Audio2bucketModel(ModelMixin):
41
+ """Audio Projection Model
42
+
43
+ This class defines an audio projection model that takes audio embeddings as input
44
+ and produces context tokens as output. The model is based on the ModelMixin class
45
+ and consists of multiple linear layers and activation functions. It can be used
46
+ for various audio processing tasks.
47
+
48
+ Attributes:
49
+ seq_len (int): The length of the audio sequence.
50
+ blocks (int): The number of blocks in the audio projection model.
51
+ channels (int): The number of channels in the audio projection model.
52
+ intermediate_dim (int): The intermediate dimension of the model.
53
+ context_tokens (int): The number of context tokens in the output.
54
+ output_dim (int): The output dimension of the context tokens.
55
+
56
+ Methods:
57
+ __init__(self, seq_len=5, blocks=12, channels=768, intermediate_dim=512, context_tokens=32, output_dim=768):
58
+ Initializes the AudioProjModel with the given parameters.
59
+ forward(self, audio_embeds):
60
+ Defines the forward pass for the AudioProjModel.
61
+ Parameters:
62
+ audio_embeds (torch.Tensor): The input audio embeddings with shape (batch_size, video_length, blocks, channels).
63
+ Returns:
64
+ context_tokens (torch.Tensor): The output context tokens with shape (batch_size, video_length, context_tokens, output_dim).
65
+
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ seq_len=5,
71
+ blocks=12, # add a new parameter blocks
72
+ channels=768, # add a new parameter channels
73
+ clip_channels=768, # add a new parameter channels
74
+ intermediate_dim=512,
75
+ output_dim=768,
76
+ context_tokens=32,
77
+ ):
78
+ super().__init__()
79
+
80
+ self.seq_len = seq_len
81
+ self.blocks = blocks
82
+ self.channels = channels
83
+ self.input_dim = (
84
+ seq_len * blocks * channels + clip_channels
85
+ ) # update input_dim to be the product of blocks and channels.
86
+ self.intermediate_dim = intermediate_dim
87
+ self.context_tokens = context_tokens
88
+ self.output_dim = output_dim
89
+
90
+ # define multiple linear layers
91
+ self.proj1 = nn.Linear(self.input_dim, intermediate_dim)
92
+ self.proj2 = nn.Linear(intermediate_dim, intermediate_dim)
93
+ self.proj3 = nn.Linear(intermediate_dim, context_tokens * output_dim)
94
+ self.act = nn.SiLU()
95
+
96
+ # self.norm = nn.LayerNorm(output_dim)
97
+
98
+ def forward(self, audio_embeds, clip_embeds):
99
+ """
100
+ Defines the forward pass for the AudioProjModel.
101
+
102
+ Parameters:
103
+ audio_embeds (torch.Tensor): The input audio embeddings with shape (batch_size, video_length, blocks, channels).
104
+
105
+ Returns:
106
+ context_tokens (torch.Tensor): The output context tokens with shape (batch_size, video_length, context_tokens, output_dim).
107
+ """
108
+ # merge
109
+ video_length = audio_embeds.shape[1]
110
+ audio_embeds = rearrange(audio_embeds, "bz f w b c -> (bz f) w b c")
111
+ batch_size, window_size, blocks, channels = audio_embeds.shape
112
+ audio_embeds = audio_embeds.view(batch_size, window_size * blocks * channels)
113
+ audio_embeds = torch.cat([audio_embeds, clip_embeds], dim=-1)
114
+
115
+ audio_embeds = self.act(self.proj1(audio_embeds))
116
+ audio_embeds = self.act(self.proj2(audio_embeds))
117
+
118
+ context_tokens = self.proj3(audio_embeds).reshape(
119
+ batch_size, self.context_tokens, self.output_dim
120
+ )
121
+
122
+ # context_tokens = self.norm(context_tokens)
123
+ context_tokens = rearrange(
124
+ context_tokens, "(bz f) m c -> bz f m c", f=video_length
125
+ )
126
+
127
+ return context_tokens
src/models/base/__init__.py ADDED
File without changes
src/models/base/attention_processor.py ADDED
The diff for this file is too large to render. See raw diff
 
src/models/base/unet_3d_blocks.py ADDED
The diff for this file is too large to render. See raw diff
 
src/models/base/unet_spatio_temporal_condition.py ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Dict, Optional, Tuple, Union, Any
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
8
+ from diffusers.loaders import UNet2DConditionLoadersMixin
9
+ from diffusers.utils import BaseOutput, logging
10
+ # from diffusers.models.attention_processor import CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnProcessor
11
+
12
+ from diffusers.models.embeddings import TimestepEmbedding, Timesteps
13
+ from diffusers.models.modeling_utils import ModelMixin
14
+ from .unet_3d_blocks import UNetMidBlockSpatioTemporal, get_down_block, get_up_block
15
+ from .attention_processor import CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnProcessor, AttnProcessor2_0, IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0
16
+
17
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
18
+
19
+
20
+ @dataclass
21
+ class UNetSpatioTemporalConditionOutput(BaseOutput):
22
+ """
23
+ The output of [`UNetSpatioTemporalConditionModel`].
24
+
25
+ Args:
26
+ sample (`torch.Tensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
27
+ The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
28
+ """
29
+
30
+ sample: torch.Tensor = None
31
+
32
+
33
+ class UNetSpatioTemporalConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
34
+ r"""
35
+ A conditional Spatio-Temporal UNet model that takes a noisy video frames, conditional state, and a timestep and
36
+ returns a sample shaped output.
37
+
38
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
39
+ for all models (such as downloading or saving).
40
+
41
+ Parameters:
42
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
43
+ Height and width of input/output sample.
44
+ in_channels (`int`, *optional*, defaults to 8): Number of channels in the input sample.
45
+ out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
46
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "DownBlockSpatioTemporal")`):
47
+ The tuple of downsample blocks to use.
48
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal")`):
49
+ The tuple of upsample blocks to use.
50
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
51
+ The tuple of output channels for each block.
52
+ addition_time_embed_dim: (`int`, defaults to 256):
53
+ Dimension to to encode the additional time ids.
54
+ projection_class_embeddings_input_dim (`int`, defaults to 768):
55
+ The dimension of the projection of encoded `added_time_ids`.
56
+ layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
57
+ cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
58
+ The dimension of the cross attention features.
59
+ transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
60
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
61
+ [`~models.unets.unet_3d_blocks.CrossAttnDownBlockSpatioTemporal`],
62
+ [`~models.unets.unet_3d_blocks.CrossAttnUpBlockSpatioTemporal`],
63
+ [`~models.unets.unet_3d_blocks.UNetMidBlockSpatioTemporal`].
64
+ num_attention_heads (`int`, `Tuple[int]`, defaults to `(5, 10, 10, 20)`):
65
+ The number of attention heads.
66
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
67
+ """
68
+
69
+ _supports_gradient_checkpointing = True
70
+
71
+ @register_to_config
72
+ def __init__(
73
+ self,
74
+ sample_size: Optional[int] = None,
75
+ in_channels: int = 8,
76
+ out_channels: int = 4,
77
+ down_block_types: Tuple[str] = (
78
+ "CrossAttnDownBlockSpatioTemporal",
79
+ "CrossAttnDownBlockSpatioTemporal",
80
+ "CrossAttnDownBlockSpatioTemporal",
81
+ "DownBlockSpatioTemporal",
82
+ ),
83
+ up_block_types: Tuple[str] = (
84
+ "UpBlockSpatioTemporal",
85
+ "CrossAttnUpBlockSpatioTemporal",
86
+ "CrossAttnUpBlockSpatioTemporal",
87
+ "CrossAttnUpBlockSpatioTemporal",
88
+ ),
89
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
90
+ addition_time_embed_dim: int = 256,
91
+ projection_class_embeddings_input_dim: int = 768,
92
+ layers_per_block: Union[int, Tuple[int]] = 2,
93
+ cross_attention_dim: Union[int, Tuple[int]] = 1024,
94
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
95
+ num_attention_heads: Union[int, Tuple[int]] = (5, 10, 20, 20),
96
+ num_frames: int = 25,
97
+ ):
98
+ super().__init__()
99
+
100
+ self.sample_size = sample_size
101
+
102
+ # Check inputs
103
+ if len(down_block_types) != len(up_block_types):
104
+ raise ValueError(
105
+ f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."
106
+ )
107
+
108
+ if len(block_out_channels) != len(down_block_types):
109
+ raise ValueError(
110
+ f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
111
+ )
112
+
113
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
114
+ raise ValueError(
115
+ f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
116
+ )
117
+
118
+ if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
119
+ raise ValueError(
120
+ f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}."
121
+ )
122
+
123
+ if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
124
+ raise ValueError(
125
+ f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
126
+ )
127
+
128
+ # input
129
+ self.conv_in = nn.Conv2d(
130
+ in_channels,
131
+ block_out_channels[0],
132
+ kernel_size=3,
133
+ padding=1,
134
+ )
135
+
136
+ # time
137
+ time_embed_dim = block_out_channels[0] * 4
138
+
139
+ self.time_proj = Timesteps(block_out_channels[0], True, downscale_freq_shift=0)
140
+ timestep_input_dim = block_out_channels[0]
141
+
142
+ self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
143
+
144
+ self.add_time_proj = Timesteps(addition_time_embed_dim, True, downscale_freq_shift=0)
145
+ self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
146
+
147
+ self.down_blocks = nn.ModuleList([])
148
+ self.up_blocks = nn.ModuleList([])
149
+
150
+ if isinstance(num_attention_heads, int):
151
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
152
+
153
+ if isinstance(cross_attention_dim, int):
154
+ cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
155
+
156
+ if isinstance(layers_per_block, int):
157
+ layers_per_block = [layers_per_block] * len(down_block_types)
158
+
159
+ if isinstance(transformer_layers_per_block, int):
160
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
161
+
162
+ blocks_time_embed_dim = time_embed_dim
163
+
164
+ # down
165
+ output_channel = block_out_channels[0]
166
+ for i, down_block_type in enumerate(down_block_types):
167
+ input_channel = output_channel
168
+ output_channel = block_out_channels[i]
169
+ is_final_block = i == len(block_out_channels) - 1
170
+
171
+ down_block = get_down_block(
172
+ down_block_type,
173
+ num_layers=layers_per_block[i],
174
+ transformer_layers_per_block=transformer_layers_per_block[i],
175
+ in_channels=input_channel,
176
+ out_channels=output_channel,
177
+ temb_channels=blocks_time_embed_dim,
178
+ add_downsample=not is_final_block,
179
+ resnet_eps=1e-5,
180
+ cross_attention_dim=cross_attention_dim[i],
181
+ num_attention_heads=num_attention_heads[i],
182
+ resnet_act_fn="silu",
183
+ )
184
+ self.down_blocks.append(down_block)
185
+
186
+ # mid
187
+ self.mid_block = UNetMidBlockSpatioTemporal(
188
+ block_out_channels[-1],
189
+ temb_channels=blocks_time_embed_dim,
190
+ transformer_layers_per_block=transformer_layers_per_block[-1],
191
+ cross_attention_dim=cross_attention_dim[-1],
192
+ num_attention_heads=num_attention_heads[-1],
193
+ )
194
+
195
+ # count how many layers upsample the images
196
+ self.num_upsamplers = 0
197
+
198
+ # up
199
+ reversed_block_out_channels = list(reversed(block_out_channels))
200
+ reversed_num_attention_heads = list(reversed(num_attention_heads))
201
+ reversed_layers_per_block = list(reversed(layers_per_block))
202
+ reversed_cross_attention_dim = list(reversed(cross_attention_dim))
203
+ reversed_transformer_layers_per_block = list(reversed(transformer_layers_per_block))
204
+
205
+ output_channel = reversed_block_out_channels[0]
206
+ for i, up_block_type in enumerate(up_block_types):
207
+ is_final_block = i == len(block_out_channels) - 1
208
+
209
+ prev_output_channel = output_channel
210
+ output_channel = reversed_block_out_channels[i]
211
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
212
+
213
+ # add upsample block for all BUT final layer
214
+ if not is_final_block:
215
+ add_upsample = True
216
+ self.num_upsamplers += 1
217
+ else:
218
+ add_upsample = False
219
+
220
+ up_block = get_up_block(
221
+ up_block_type,
222
+ num_layers=reversed_layers_per_block[i] + 1,
223
+ transformer_layers_per_block=reversed_transformer_layers_per_block[i],
224
+ in_channels=input_channel,
225
+ out_channels=output_channel,
226
+ prev_output_channel=prev_output_channel,
227
+ temb_channels=blocks_time_embed_dim,
228
+ add_upsample=add_upsample,
229
+ resnet_eps=1e-5,
230
+ resolution_idx=i,
231
+ cross_attention_dim=reversed_cross_attention_dim[i],
232
+ num_attention_heads=reversed_num_attention_heads[i],
233
+ resnet_act_fn="silu",
234
+ )
235
+ self.up_blocks.append(up_block)
236
+ prev_output_channel = output_channel
237
+
238
+ # out
239
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=32, eps=1e-5)
240
+ self.conv_act = nn.SiLU()
241
+
242
+ self.conv_out = nn.Conv2d(
243
+ block_out_channels[0],
244
+ out_channels,
245
+ kernel_size=3,
246
+ padding=1,
247
+ )
248
+
249
+ @property
250
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
251
+ r"""
252
+ Returns:
253
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
254
+ indexed by its weight name.
255
+ """
256
+ # set recursively
257
+ processors = {}
258
+
259
+ def fn_recursive_add_processors(
260
+ name: str,
261
+ module: torch.nn.Module,
262
+ processors: Dict[str, AttentionProcessor],
263
+ ):
264
+ if hasattr(module, "get_processor"):
265
+ processors[f"{name}.processor"] = module.get_processor()
266
+
267
+ for sub_name, child in module.named_children():
268
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
269
+
270
+ return processors
271
+
272
+ for name, module in self.named_children():
273
+ fn_recursive_add_processors(name, module, processors)
274
+
275
+ return processors
276
+
277
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
278
+ r"""
279
+ Sets the attention processor to use to compute attention.
280
+
281
+ Parameters:
282
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
283
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
284
+ for **all** `Attention` layers.
285
+
286
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
287
+ processor. This is strongly recommended when setting trainable attention processors.
288
+
289
+ """
290
+ count = len(self.attn_processors.keys())
291
+
292
+ if isinstance(processor, dict) and len(processor) != count:
293
+ raise ValueError(
294
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
295
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
296
+ )
297
+
298
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
299
+ if hasattr(module, "set_processor"):
300
+ if not isinstance(processor, dict):
301
+ module.set_processor(processor)
302
+ else:
303
+ module.set_processor(processor.pop(f"{name}.processor"))
304
+
305
+ for sub_name, child in module.named_children():
306
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
307
+
308
+ for name, module in self.named_children():
309
+ fn_recursive_attn_processor(name, module, processor)
310
+
311
+ def set_default_attn_processor(self):
312
+ """
313
+ Disables custom attention processors and sets the default attention implementation.
314
+ """
315
+ if all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
316
+ processor = AttnProcessor()
317
+ else:
318
+ raise ValueError(
319
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
320
+ )
321
+
322
+ self.set_attn_processor(processor)
323
+
324
+ def _set_gradient_checkpointing(self, module, value=False):
325
+ if hasattr(module, "gradient_checkpointing"):
326
+ module.gradient_checkpointing = value
327
+
328
+ # Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
329
+ def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
330
+ """
331
+ Sets the attention processor to use [feed forward
332
+ chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
333
+
334
+ Parameters:
335
+ chunk_size (`int`, *optional*):
336
+ The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
337
+ over each tensor of dim=`dim`.
338
+ dim (`int`, *optional*, defaults to `0`):
339
+ The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
340
+ or dim=1 (sequence length).
341
+ """
342
+ if dim not in [0, 1]:
343
+ raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}")
344
+
345
+ # By default chunk size is 1
346
+ chunk_size = chunk_size or 1
347
+
348
+ def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
349
+ if hasattr(module, "set_chunk_feed_forward"):
350
+ module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
351
+
352
+ for child in module.children():
353
+ fn_recursive_feed_forward(child, chunk_size, dim)
354
+
355
+ for module in self.children():
356
+ fn_recursive_feed_forward(module, chunk_size, dim)
357
+
358
+ def forward(
359
+ self,
360
+ sample: torch.Tensor,
361
+ timestep: Union[torch.Tensor, float, int],
362
+ encoder_hidden_states: torch.Tensor,
363
+ added_time_ids: torch.Tensor,
364
+ spatial_condition: Optional[torch.Tensor] = None,
365
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
366
+ return_dict: bool = True,
367
+ ) -> Union[UNetSpatioTemporalConditionOutput, Tuple]:
368
+ r"""
369
+ The [`UNetSpatioTemporalConditionModel`] forward method.
370
+
371
+ Args:
372
+ sample (`torch.Tensor`):
373
+ The noisy input tensor with the following shape `(batch, num_frames, channel, height, width)`.
374
+ timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
375
+ encoder_hidden_states (`torch.Tensor`):
376
+ The encoder hidden states with shape `(batch*num_frames, sequence_length, cross_attention_dim)`.
377
+ added_time_ids: (`torch.Tensor`):
378
+ The additional time ids with shape `(batch, num_additional_ids)`. These are encoded with sinusoidal
379
+ embeddings and added to the time embeddings.
380
+ spatial_condition (`torch.Tensor`, *optional*, defaults to `None`):
381
+ The spatial_condition embedding with shape `(batch, num_frames, channel_in(320), height, width)`.
382
+ return_dict (`bool`, *optional*, defaults to `True`):
383
+ Whether or not to return a [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] instead
384
+ of a plain tuple.
385
+ Returns:
386
+ [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] or `tuple`:
387
+ If `return_dict` is True, an [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] is
388
+ returned, otherwise a `tuple` is returned where the first element is the sample tensor.
389
+ """
390
+ # 1. time
391
+ timesteps = timestep
392
+ if not torch.is_tensor(timesteps):
393
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
394
+ # This would be a good case for the `match` statement (Python 3.10+)
395
+ is_mps = sample.device.type == "mps"
396
+ if isinstance(timestep, float):
397
+ dtype = torch.float32 if is_mps else torch.float64
398
+ else:
399
+ dtype = torch.int32 if is_mps else torch.int64
400
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
401
+ elif len(timesteps.shape) == 0:
402
+ timesteps = timesteps[None].to(sample.device)
403
+
404
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
405
+ batch_size, num_frames = sample.shape[:2]
406
+ timesteps = timesteps.expand(batch_size)
407
+
408
+ t_emb = self.time_proj(timesteps)
409
+
410
+ # `Timesteps` does not contain any weights and will always return f32 tensors
411
+ # but time_embedding might actually be running in fp16. so we need to cast here.
412
+ # there might be better ways to encapsulate this.
413
+ t_emb = t_emb.to(dtype=sample.dtype)
414
+
415
+ emb = self.time_embedding(t_emb)
416
+
417
+ time_embeds = self.add_time_proj(added_time_ids.flatten())
418
+ # import ipdb
419
+ # ipdb.set_trace()
420
+ time_embeds = time_embeds.reshape((batch_size, -1))
421
+ time_embeds = time_embeds.to(emb.dtype)
422
+ aug_emb = self.add_embedding(time_embeds)
423
+ emb = emb + aug_emb
424
+
425
+ # Flatten the batch and frames dimensions
426
+ # sample: [batch, frames, channels, height, width] -> [batch * frames, channels, height, width]
427
+ sample = sample.flatten(0, 1)
428
+ # Repeat the embeddings num_video_frames times
429
+ # emb: [batch, channels] -> [batch * frames, channels]
430
+ emb = emb.repeat_interleave(num_frames, dim=0)
431
+ # encoder_hidden_states: [batch, 1, channels] -> [batch * frames, 1, channels]
432
+
433
+ ### 20240731 process encoder_hidden_states ###
434
+ if isinstance(encoder_hidden_states, tuple):
435
+ # ip_hidden_states is a list
436
+ encoder_hidden_states, ip_hidden_states = encoder_hidden_states
437
+ if encoder_hidden_states.shape[0]==batch_size:
438
+ encoder_hidden_states = encoder_hidden_states.repeat_interleave(num_frames, dim=0)
439
+ encoder_hidden_states = (encoder_hidden_states, ip_hidden_states)
440
+ elif encoder_hidden_states.shape[0]==batch_size:
441
+ ### if framewised feature is not provided, repeat_interleave
442
+ encoder_hidden_states = encoder_hidden_states.repeat_interleave(num_frames, dim=0)
443
+
444
+
445
+ # 2. pre-process
446
+ sample = self.conv_in(sample)
447
+
448
+ ### 20240731 add spatial_condition here ###
449
+ if spatial_condition is not None:
450
+ sample = sample + spatial_condition.flatten(0,1)
451
+
452
+ image_only_indicator = torch.zeros(batch_size, num_frames, dtype=sample.dtype, device=sample.device)
453
+
454
+ down_block_res_samples = (sample,)
455
+ for downsample_block in self.down_blocks:
456
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
457
+ sample, res_samples = downsample_block(
458
+ hidden_states=sample,
459
+ temb=emb,
460
+ encoder_hidden_states=encoder_hidden_states,
461
+ cross_attention_kwargs=cross_attention_kwargs,
462
+ image_only_indicator=image_only_indicator,
463
+ )
464
+ else:
465
+ sample, res_samples = downsample_block(
466
+ hidden_states=sample,
467
+ temb=emb,
468
+ image_only_indicator=image_only_indicator,
469
+ )
470
+
471
+ down_block_res_samples += res_samples
472
+
473
+ # 4. mid
474
+ sample = self.mid_block(
475
+ hidden_states=sample,
476
+ temb=emb,
477
+ encoder_hidden_states=encoder_hidden_states,
478
+ cross_attention_kwargs=cross_attention_kwargs,
479
+ image_only_indicator=image_only_indicator,
480
+ )
481
+
482
+ # 5. up
483
+ for i, upsample_block in enumerate(self.up_blocks):
484
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
485
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
486
+
487
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
488
+ sample = upsample_block(
489
+ hidden_states=sample,
490
+ temb=emb,
491
+ res_hidden_states_tuple=res_samples,
492
+ encoder_hidden_states=encoder_hidden_states,
493
+ cross_attention_kwargs=cross_attention_kwargs,
494
+ image_only_indicator=image_only_indicator,
495
+ )
496
+ else:
497
+ sample = upsample_block(
498
+ hidden_states=sample,
499
+ temb=emb,
500
+ res_hidden_states_tuple=res_samples,
501
+ image_only_indicator=image_only_indicator,
502
+ )
503
+
504
+ # 6. post-process
505
+ sample = self.conv_norm_out(sample)
506
+ sample = self.conv_act(sample)
507
+ sample = self.conv_out(sample)
508
+
509
+ # 7. Reshape back to original shape
510
+ sample = sample.reshape(batch_size, num_frames, *sample.shape[1:])
511
+
512
+ if not return_dict:
513
+ return (sample,)
514
+
515
+ return UNetSpatioTemporalConditionOutput(sample=sample)
516
+
517
+
518
+
519
+ def add_ip_adapters(unet, num_adapter_embeds=[32,], scale=[1.0,]):
520
+
521
+ assert len(num_adapter_embeds)==len(scale)
522
+
523
+
524
+ # init adapter modules
525
+ attn_procs = {}
526
+ unet_sd = unet.state_dict()
527
+ for name in unet.attn_processors.keys():
528
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
529
+ if name.startswith("mid_block"):
530
+ hidden_size = unet.config.block_out_channels[-1]
531
+ elif name.startswith("up_blocks"):
532
+ block_id = int(name[len("up_blocks.")])
533
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
534
+ elif name.startswith("down_blocks"):
535
+ block_id = int(name[len("down_blocks.")])
536
+ hidden_size = unet.config.block_out_channels[block_id]
537
+ # if cross_attention_dim is None or "temporal_transformer_blocks" in name:
538
+ if cross_attention_dim is None:
539
+ attn_processor_class = (
540
+ AttnProcessor2_0 if hasattr(torch.nn.functional, "scaled_dot_product_attention") else AttnProcessor
541
+ )
542
+ attn_procs[name] = attn_processor_class()
543
+ else:
544
+ attn_processor_class = (
545
+ IPAdapterAttnProcessor2_0 if hasattr(torch.nn.functional, "scaled_dot_product_attention") else IPAdapterAttnProcessor
546
+ )
547
+
548
+ attn_procs[name] = attn_processor_class(
549
+ hidden_size=hidden_size,
550
+ cross_attention_dim=cross_attention_dim,
551
+ num_tokens=num_adapter_embeds,
552
+ scale=scale
553
+ ).to(device=unet.device, dtype=unet.dtype)
554
+
555
+ layer_name = name.split(".processor")[0]
556
+ weights = {}
557
+
558
+ for i in range(len(num_adapter_embeds)):
559
+ weights.update({f"to_k_ip.{i}.weight": unet_sd[layer_name + ".to_k.weight"]})
560
+ weights.update({f"to_v_ip.{i}.weight": unet_sd[layer_name + ".to_v.weight"]})
561
+
562
+
563
+ attn_procs[name].load_state_dict(weights)
564
+
565
+ unet.set_attn_processor(attn_procs)
566
+
567
+ adapter_modules = torch.nn.ModuleList([m for m in unet.attn_processors.values() if isinstance(m, IPAdapterAttnProcessor) or isinstance(m, IPAdapterAttnProcessor2_0)])
568
+ return adapter_modules
569
+
570
+
571
+ def load_adapter_states(adapter_modules, state_dict_list):
572
+ assert len(state_dict_list)>0
573
+
574
+ merged_stete_dict = {}
575
+ for state_dict in state_dict_list:
576
+ for k, v in state_dict.items():
577
+ if k in merged_stete_dict.keys():
578
+ k_split = k.split('.')
579
+ adapter_idx = int(k_split[2])
580
+ adapter_idx += 1
581
+ k_split[2] = str(adapter_idx)
582
+ new_k = '.'.join(k_split)
583
+ while(new_k in merged_stete_dict.keys()):
584
+ adapter_idx += 1
585
+ k_split[2] = str(adapter_idx)
586
+ new_k = '.'.join(k_split)
587
+ merged_stete_dict[new_k] = v
588
+ else:
589
+ merged_stete_dict[k] = v
590
+
591
+ info = adapter_modules.load_state_dict(merged_stete_dict, strict=True)
592
+ return info
593
+
594
+
595
+
596
+
597
+
598
+
599
+
600
+
src/pipelines/pipeline_sonic.py ADDED
@@ -0,0 +1,632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from dataclasses import dataclass
3
+ from typing import Callable, Dict, List, Optional, Union
4
+
5
+ import numpy as np
6
+ import PIL.Image
7
+ import torch
8
+ from transformers import CLIPVisionModelWithProjection
9
+
10
+ from diffusers.image_processor import VaeImageProcessor
11
+ from diffusers.utils import BaseOutput, logging
12
+ from diffusers.utils.torch_utils import randn_tensor, is_compiled_module
13
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
14
+ from diffusers import (
15
+ AutoencoderKLTemporalDecoder,
16
+ EulerDiscreteScheduler,
17
+ )
18
+
19
+ from src.models.base.unet_spatio_temporal_condition import UNetSpatioTemporalConditionModel
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ @dataclass
25
+ class Pose2VideoSVDPipelineOutput(BaseOutput):
26
+ r"""
27
+ Output class for zero-shot text-to-video pipeline.
28
+
29
+ Args:
30
+ frames (`[List[PIL.Image.Image]`, `np.ndarray`]):
31
+ List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width,
32
+ num_channels)`.
33
+ """
34
+
35
+ frames: Union[List[PIL.Image.Image], np.ndarray]
36
+
37
+
38
+ class SonicPipeline(DiffusionPipeline):
39
+ r"""
40
+ Pipeline to generate video from an input image using Stable Video Diffusion.
41
+
42
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
43
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
44
+
45
+ Args:
46
+ vae ([`AutoencoderKL`]):
47
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
48
+ image_encoder ([`~transformers.CLIPVisionModelWithProjection`]):
49
+ Frozen CLIP image-encoder ([laion/CLIP-ViT-H-14-laion2B-s32B-b79K](https://huggingface.co/laion/CLIP-ViT-H-14-laion2B-s32B-b79K)).
50
+ unet ([`UNetSpatioTemporalConditionModel`]):
51
+ A `UNetSpatioTemporalConditionModel` to denoise the encoded image latents.
52
+ scheduler ([`EulerDiscreteScheduler`]):
53
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents.
54
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
55
+ A `CLIPImageProcessor` to extract features from generated images.
56
+ """
57
+
58
+ model_cpu_offload_seq = "image_encoder->unet->vae"
59
+ _callback_tensor_inputs = ["latents"]
60
+
61
+ def __init__(
62
+ self,
63
+ vae: AutoencoderKLTemporalDecoder,
64
+ image_encoder: CLIPVisionModelWithProjection,
65
+ unet: UNetSpatioTemporalConditionModel,
66
+ scheduler: EulerDiscreteScheduler,
67
+ ):
68
+ super().__init__()
69
+ self.register_modules(
70
+ vae=vae,
71
+ image_encoder=image_encoder,
72
+ unet=unet,
73
+ scheduler=scheduler,
74
+ )
75
+
76
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
77
+
78
+ self.image_processor = VaeImageProcessor(
79
+ vae_scale_factor=self.vae_scale_factor,
80
+ do_convert_rgb=True)
81
+
82
+ self.pose_image_processor = VaeImageProcessor(
83
+ vae_scale_factor=self.vae_scale_factor,
84
+ do_convert_rgb=True,
85
+ do_normalize=False,
86
+ )
87
+
88
+
89
+ def _clip_encode_image(self, image, audio_prompts, uncond_audio_prompts, num_frames, device, num_videos_per_prompt, do_classifier_free_guidance, frames_per_batch):
90
+ dtype = next(self.image_encoder.parameters()).dtype
91
+
92
+ image = image.to(device=device, dtype=dtype)
93
+ image_embeddings = self.image_encoder(image).image_embeds
94
+ image_embeddings = image_embeddings.unsqueeze(1)
95
+
96
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
97
+ bs_embed, seq_len, _ = image_embeddings.shape
98
+ image_embeddings = image_embeddings.repeat(1, num_videos_per_prompt, 1)
99
+ image_embeddings = image_embeddings.view(bs_embed * num_videos_per_prompt, seq_len, -1)
100
+
101
+ image_embeddings = image_embeddings.unsqueeze(1).repeat((1, num_frames, 1, 1))
102
+
103
+ if do_classifier_free_guidance:
104
+ negative_image_embeddings = torch.zeros_like(image_embeddings)
105
+
106
+
107
+ audio_prompts = torch.stack(audio_prompts, dim=0).to(device=device, dtype=dtype)
108
+ audio_prompts = audio_prompts.unsqueeze(0)
109
+ image_embeddings = torch.cat([negative_image_embeddings, image_embeddings, image_embeddings])
110
+
111
+
112
+ uncond_audio_prompts = torch.stack(uncond_audio_prompts, dim=0).to(device=device, dtype=dtype)
113
+ uncond_audio_prompts = uncond_audio_prompts.unsqueeze(0)
114
+
115
+
116
+ # For classifier free guidance, we need to do two forward passes.
117
+ # Here we concatenate the unconditional and text embeddings into a single batch
118
+ # to avoid doing two forward passes
119
+ audio_prompts = torch.cat([uncond_audio_prompts, uncond_audio_prompts, audio_prompts])
120
+
121
+ return image_embeddings, audio_prompts
122
+
123
+ def _encode_vae_image(
124
+ self,
125
+ image: torch.Tensor,
126
+ device,
127
+ num_videos_per_prompt,
128
+ do_classifier_free_guidance,
129
+ ):
130
+ image = image.to(device=device)
131
+ image_latents = self.vae.encode(image).latent_dist.mode()
132
+
133
+ if do_classifier_free_guidance:
134
+ negative_image_latents = torch.zeros_like(image_latents)
135
+
136
+ # For classifier free guidance, we need to do two forward passes.
137
+ # Here we concatenate the unconditional and text embeddings into a single batch
138
+ # to avoid doing two forward passes
139
+ image_latents = torch.cat([negative_image_latents, image_latents, image_latents])
140
+
141
+ # duplicate image_latents for each generation per prompt, using mps friendly method
142
+ image_latents = image_latents.repeat(num_videos_per_prompt, 1, 1, 1)
143
+
144
+ return image_latents
145
+
146
+ def _get_add_time_ids(
147
+ self,
148
+ fps,
149
+ motion_bucket_id,
150
+ noise_aug_strength,
151
+ dtype,
152
+ batch_size,
153
+ num_videos_per_prompt,
154
+ do_classifier_free_guidance,
155
+ ):
156
+ add_time_ids = [fps, motion_bucket_id, noise_aug_strength]
157
+
158
+ passed_add_embed_dim = self.unet.config.addition_time_embed_dim * len(add_time_ids)
159
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
160
+
161
+ if expected_add_embed_dim != passed_add_embed_dim:
162
+ raise ValueError(
163
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
164
+ )
165
+
166
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
167
+ add_time_ids = add_time_ids.repeat(batch_size * num_videos_per_prompt, 1)
168
+
169
+ if do_classifier_free_guidance:
170
+ add_time_ids = torch.cat([add_time_ids, add_time_ids, add_time_ids])
171
+
172
+ return add_time_ids
173
+
174
+ def decode_latents(self, latents, num_frames, decode_chunk_size=14):
175
+ # [batch, frames, channels, height, width] -> [batch*frames, channels, height, width]
176
+ latents = latents.flatten(0, 1)
177
+
178
+ latents = 1 / self.vae.config.scaling_factor * latents
179
+
180
+ forward_vae_fn = self.vae._orig_mod.forward if is_compiled_module(self.vae) else self.vae.forward
181
+ accepts_num_frames = "num_frames" in set(inspect.signature(forward_vae_fn).parameters.keys())
182
+
183
+ # decode decode_chunk_size frames at a time to avoid OOM
184
+ frames = []
185
+ for i in range(0, latents.shape[0], decode_chunk_size):
186
+ num_frames_in = latents[i : i + decode_chunk_size].shape[0]
187
+ decode_kwargs = {}
188
+ if accepts_num_frames:
189
+ # we only pass num_frames_in if it's expected
190
+ decode_kwargs["num_frames"] = num_frames_in
191
+
192
+ frame = self.vae.decode(latents[i : i + decode_chunk_size], **decode_kwargs).sample
193
+ frames.append(frame.cpu())
194
+ frames = torch.cat(frames, dim=0)
195
+
196
+ # [batch*frames, channels, height, width] -> [batch, channels, frames, height, width]
197
+ frames = frames.reshape(-1, num_frames, *frames.shape[1:]).permute(0, 2, 1, 3, 4)
198
+
199
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
200
+ frames = frames.float()
201
+ return frames
202
+
203
+ def check_inputs(self, image, height, width):
204
+ if (
205
+ not isinstance(image, torch.Tensor)
206
+ and not isinstance(image, PIL.Image.Image)
207
+ and not isinstance(image, list)
208
+ ):
209
+ raise ValueError(
210
+ "`image` has to be of type `torch.FloatTensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is"
211
+ f" {type(image)}"
212
+ )
213
+
214
+ if height % 8 != 0 or width % 8 != 0:
215
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
216
+
217
+ def prepare_latents(
218
+ self,
219
+ batch_size,
220
+ num_frames,
221
+ num_channels_latents,
222
+ height,
223
+ width,
224
+ dtype,
225
+ device,
226
+ generator,
227
+ latents=None,
228
+ ref_image_latents=None,
229
+ timestep=None
230
+ ):
231
+ shape = (
232
+ batch_size,
233
+ num_frames,
234
+ num_channels_latents // 2,
235
+ height // self.vae_scale_factor,
236
+ width // self.vae_scale_factor,
237
+ )
238
+ if isinstance(generator, list) and len(generator) != batch_size:
239
+ raise ValueError(
240
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
241
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
242
+ )
243
+
244
+ if latents is None:
245
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
246
+ else:
247
+ noise = latents.to(device)
248
+
249
+ # scale the initial noise by the standard deviation required by the scheduler
250
+ if timestep is not None:
251
+ init_latents = ref_image_latents.unsqueeze(1)
252
+ latents = self.scheduler.add_noise(init_latents, noise, timestep)
253
+ else:
254
+ latents = noise * self.scheduler.init_noise_sigma
255
+ return latents
256
+
257
+ def get_timesteps(self, num_inference_steps, strength, device):
258
+ # get the original timestep using init_timestep
259
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
260
+
261
+ t_start = max(num_inference_steps - init_timestep, 0)
262
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
263
+
264
+ return timesteps, num_inference_steps - t_start
265
+
266
+ @property
267
+ def guidance_scale1(self):
268
+ return self._guidance_scale1
269
+
270
+ @property
271
+ def guidance_scale2(self):
272
+ return self._guidance_scale2
273
+
274
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
275
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
276
+ # corresponds to doing no classifier free guidance.
277
+ @property
278
+ def do_classifier_free_guidance(self):
279
+ return True
280
+
281
+ @property
282
+ def num_timesteps(self):
283
+ return self._num_timesteps
284
+
285
+ @torch.no_grad()
286
+ def __call__(
287
+ self,
288
+ ref_image: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor],
289
+ clip_image: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor],
290
+ face_mask: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor],
291
+ audio_prompts: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor],
292
+ uncond_audio_prompts: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor],
293
+ motion_buckets: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor],
294
+ height: int = 576,
295
+ width: int = 1024,
296
+ num_frames: Optional[int] = None,
297
+ num_inference_steps: int = 25,
298
+ min_guidance_scale1=1.0, # 1.0,
299
+ max_guidance_scale1=3.0,
300
+ min_guidance_scale2=1.0, # 1.0,
301
+ max_guidance_scale2=3.0,
302
+ fps: int = 7,
303
+ motion_bucket_scale=1.0,
304
+ noise_aug_strength: int = 0.02,
305
+ decode_chunk_size: Optional[int] = None,
306
+ num_videos_per_prompt: Optional[int] = 1,
307
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
308
+ latents: Optional[torch.FloatTensor] = None,
309
+ output_type: Optional[str] = "pil",
310
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
311
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
312
+ return_dict: bool = True,
313
+ overlap=7,
314
+ shift_offset=3,
315
+ frames_per_batch=14,
316
+ i2i_noise_strength=1.0,
317
+ ):
318
+ r"""
319
+ The call function to the pipeline for generation.
320
+
321
+ Args:
322
+ image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.FloatTensor`):
323
+ Image or images to guide image generation. If you provide a tensor, it needs to be compatible with
324
+ [`CLIPImageProcessor`](https://huggingface.co/lambdalabs/sd-image-variations-diffusers/blob/main/feature_extractor/preprocessor_config.json).
325
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
326
+ The height in pixels of the generated image.
327
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
328
+ The width in pixels of the generated image.
329
+ num_frames (`int`, *optional*):
330
+ The number of video frames to generate. Defaults to 14 for `stable-video-diffusion-img2vid` and to 25 for `stable-video-diffusion-img2vid-xt`
331
+ num_inference_steps (`int`, *optional*, defaults to 25):
332
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
333
+ expense of slower inference. This parameter is modulated by `strength`.
334
+ min_guidance_scale (`float`, *optional*, defaults to 1.0):
335
+ The minimum guidance scale. Used for the classifier free guidance with first frame.
336
+ max_guidance_scale (`float`, *optional*, defaults to 3.0):
337
+ The maximum guidance scale. Used for the classifier free guidance with last frame.
338
+ fps (`int`, *optional*, defaults to 7):
339
+ Frames per second. The rate at which the generated images shall be exported to a video after generation.
340
+ Note that Stable Diffusion Video's UNet was micro-conditioned on fps-1 during training.
341
+ motion_bucket_id (`int`, *optional*, defaults to 127):
342
+ The motion bucket ID. Used as conditioning for the generation. The higher the number the more motion will be in the video.
343
+ noise_aug_strength (`int`, *optional*, defaults to 0.02):
344
+ The amount of noise added to the init image, the higher it is the less the video will look like the init image. Increase it for more motion.
345
+ decode_chunk_size (`int`, *optional*):
346
+ The number of frames to decode at a time. The higher the chunk size, the higher the temporal consistency
347
+ between frames, but also the higher the memory consumption. By default, the decoder will decode all frames at once
348
+ for maximal quality. Reduce `decode_chunk_size` to reduce memory usage.
349
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
350
+ The number of images to generate per prompt.
351
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
352
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
353
+ generation deterministic.
354
+ latents (`torch.FloatTensor`, *optional*):
355
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
356
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
357
+ tensor is generated by sampling using the supplied random `generator`.
358
+ output_type (`str`, *optional*, defaults to `"pil"`):
359
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
360
+ callback_on_step_end (`Callable`, *optional*):
361
+ A function that calls at the end of each denoising steps during the inference. The function is called
362
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
363
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
364
+ `callback_on_step_end_tensor_inputs`.
365
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
366
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
367
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
368
+ `._callback_tensor_inputs` attribute of your pipeline class.
369
+ return_dict (`bool`, *optional*, defaults to `True`):
370
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
371
+ plain tuple.
372
+
373
+ Returns:
374
+ [`~pipelines.stable_diffusion.StableVideoDiffusionPipelineOutput`] or `tuple`:
375
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableVideoDiffusionPipelineOutput`] is returned,
376
+ otherwise a `tuple` is returned where the first element is a list of list with the generated frames.
377
+
378
+ Examples:
379
+
380
+ ```py
381
+ from diffusers import StableVideoDiffusionPipeline
382
+ from diffusers.utils import load_image, export_to_video
383
+
384
+ pipe = StableVideoDiffusionPipeline.from_pretrained("stabilityai/stable-video-diffusion-img2vid-xt", torch_dtype=torch.float16, variant="fp16")
385
+ pipe.to("cuda")
386
+
387
+ image = load_image("https://lh3.googleusercontent.com/y-iFOHfLTwkuQSUegpwDdgKmOjRSTvPxat63dQLB25xkTs4lhIbRUFeNBWZzYf370g=s1200")
388
+ image = image.resize((1024, 576))
389
+
390
+ frames = pipe(image, num_frames=25, decode_chunk_size=8).frames[0]
391
+ export_to_video(frames, "generated.mp4", fps=7)
392
+ ```
393
+ """
394
+ # 0. Default height and width to unet
395
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
396
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
397
+
398
+
399
+ num_frames = num_frames if num_frames is not None else self.unet.config.num_frames
400
+ decode_chunk_size = decode_chunk_size if decode_chunk_size is not None else num_frames
401
+
402
+ # 1. Check inputs. Raise error if not correct
403
+ self.check_inputs(ref_image, height, width)
404
+
405
+ # 2. Define call parameters
406
+ if isinstance(ref_image, PIL.Image.Image):
407
+ batch_size = 1
408
+ elif isinstance(ref_image, list):
409
+ batch_size = len(ref_image)
410
+ else:
411
+ batch_size = ref_image.shape[0]
412
+
413
+ device = self._execution_device
414
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
415
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
416
+ # corresponds to doing no classifier free guidance.
417
+ do_classifier_free_guidance = True
418
+
419
+ # 3. Prepare clip image embeds
420
+ image_embeddings, audio_prompts = self._clip_encode_image(
421
+ clip_image,
422
+ audio_prompts,
423
+ uncond_audio_prompts,
424
+ num_frames,
425
+ device,
426
+ num_videos_per_prompt,
427
+ do_classifier_free_guidance,
428
+ frames_per_batch)
429
+ motion_buckets = torch.stack(motion_buckets, dim=0).to(device=device)
430
+ motion_buckets = motion_buckets.unsqueeze(0)
431
+ # NOTE: Stable Diffusion Video was conditioned on fps - 1, which
432
+ # is why it is reduced here.
433
+ # See: https://github.com/Stability-AI/generative-models/blob/ed0997173f98eaf8f4edf7ba5fe8f15c6b877fd3/scripts/sampling/simple_video_sample.py#L188
434
+ # fps = fps - 1
435
+
436
+ # 4. Encode input image using VAE
437
+ # needs_upcasting = (self.vae.dtype == torch.float16 or self.vae.dtype == torch.bfloat16) and self.vae.config.force_upcast
438
+ needs_upcasting = False
439
+ vae_dtype = self.vae.dtype
440
+ if needs_upcasting:
441
+ self.vae.to(dtype=torch.float32)
442
+
443
+ # Prepare ref image latents
444
+ ref_image_tensor = ref_image.to(
445
+ dtype=self.vae.dtype, device=self.vae.device
446
+ )
447
+
448
+ ref_image_latents = self.vae.encode(ref_image_tensor).latent_dist.mean
449
+ ref_image_latents = ref_image_latents * 0.18215 # (b, 4, h, w)
450
+
451
+ noise = randn_tensor(
452
+ ref_image_tensor.shape,
453
+ generator=generator,
454
+ device=self.vae.device,
455
+ dtype=self.vae.dtype)
456
+
457
+ ref_image_tensor = ref_image_tensor + noise_aug_strength * noise
458
+
459
+ image_latents = self._encode_vae_image(
460
+ ref_image_tensor,
461
+ device=device,
462
+ num_videos_per_prompt=num_videos_per_prompt,
463
+ do_classifier_free_guidance=do_classifier_free_guidance,
464
+ )
465
+ image_latents = image_latents.to(image_embeddings.dtype)
466
+ ref_image_latents = ref_image_latents.to(image_embeddings.dtype)
467
+
468
+ # cast back to fp16 if needed
469
+ if needs_upcasting:
470
+ self.vae.to(dtype=vae_dtype)
471
+
472
+ # Repeat the image latents for each frame so we can concatenate them with the noise
473
+ # image_latents [batch, channels, height, width] ->[batch, num_frames, channels, height, width]
474
+ image_latents = image_latents.unsqueeze(1).repeat(1, num_frames, 1, 1, 1)
475
+
476
+ motion_buckets = motion_buckets * motion_bucket_scale
477
+
478
+ # 4. Prepare timesteps
479
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
480
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, i2i_noise_strength, device)
481
+ latent_timestep = timesteps[:1].repeat(batch_size * num_videos_per_prompt)
482
+
483
+
484
+ # 5. Prepare latent variables
485
+ num_channels_latents = self.unet.config.in_channels
486
+ latents = self.prepare_latents(
487
+ batch_size * num_videos_per_prompt,
488
+ num_frames,
489
+ num_channels_latents,
490
+ height,
491
+ width,
492
+ image_embeddings.dtype,
493
+ device,
494
+ generator,
495
+ latents,
496
+ ref_image_latents,
497
+ timestep=latent_timestep
498
+ )
499
+
500
+ # Prepare a list of pose condition images
501
+
502
+
503
+ face_mask = face_mask.to(
504
+ device=device, dtype=self.unet.dtype
505
+ )[:,:1]
506
+
507
+ # 7. Prepare guidance scale
508
+ guidance_scale = torch.linspace(
509
+ min_guidance_scale1,
510
+ max_guidance_scale1,
511
+ num_inference_steps)
512
+ guidance_scale1 = guidance_scale.to(device, latents.dtype)
513
+
514
+ guidance_scale = torch.linspace(
515
+ min_guidance_scale2,
516
+ max_guidance_scale2,
517
+ num_inference_steps)
518
+ guidance_scale2 = guidance_scale.to(device, latents.dtype)
519
+
520
+ self._guidance_scale1 = guidance_scale1
521
+ self._guidance_scale2 = guidance_scale2
522
+
523
+ # 8. Denoising loop
524
+ latents_all = latents # for any-frame generation
525
+
526
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
527
+ self._num_timesteps = len(timesteps)
528
+ shift = 0
529
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
530
+ for i, t in enumerate(timesteps):
531
+
532
+ # init
533
+ pred_latents = torch.zeros_like(
534
+ latents_all,
535
+ dtype=self.unet.dtype,
536
+ )
537
+ counter = torch.zeros(
538
+ (latents_all.shape[0], num_frames, 1, 1, 1),
539
+ dtype=self.unet.dtype,
540
+ ).to(device=latents_all.device)
541
+
542
+ for batch, index_start in enumerate(range(0, num_frames, frames_per_batch - overlap)):
543
+ self.scheduler._step_index = None
544
+ index_start -= shift
545
+ def indice_slice(tensor, idx_list):
546
+ tensor_list = []
547
+ for idx in idx_list:
548
+ idx = idx % tensor.shape[1]
549
+ tensor_list.append(tensor[:,idx])
550
+ return torch.stack(tensor_list, 1)
551
+ idx_list = list(range(index_start, index_start+frames_per_batch))
552
+ latents = indice_slice(latents_all, idx_list)
553
+ image_latents_input = indice_slice(image_latents, idx_list)
554
+ batch_image_embeddings = indice_slice(image_embeddings, idx_list)
555
+ batch_audio_prompts = indice_slice(audio_prompts, idx_list)
556
+
557
+ cross_attention_kwargs = {'ip_adapter_masks': [face_mask]}
558
+ latent_model_input = torch.cat([latents] * 3) if do_classifier_free_guidance else latents
559
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
560
+
561
+ # Concatenate image_latents over channels dimention
562
+ latent_model_input = torch.cat([
563
+ latent_model_input,
564
+ image_latents_input], dim=2)
565
+
566
+ motion_bucket = indice_slice(motion_buckets, idx_list)
567
+ motion_bucket = torch.mean(motion_bucket, dim=1).squeeze()
568
+ motion_bucket_id = motion_bucket[0]
569
+ motion_bucket_id_exp = motion_bucket[1]
570
+ added_time_ids = self._get_add_time_ids(
571
+ fps,
572
+ motion_bucket_id,
573
+ motion_bucket_id_exp,
574
+ image_embeddings.dtype,
575
+ batch_size,
576
+ num_videos_per_prompt,
577
+ do_classifier_free_guidance,
578
+ )
579
+ added_time_ids = added_time_ids.to(device, dtype=self.unet.dtype)
580
+
581
+ # predict the noise residual
582
+ noise_pred = self.unet(
583
+ latent_model_input,
584
+ t,
585
+ encoder_hidden_states=(batch_image_embeddings.flatten(0,1), [batch_audio_prompts.flatten(0,1)]),
586
+ cross_attention_kwargs=cross_attention_kwargs,
587
+ added_time_ids=added_time_ids,
588
+ return_dict=False,
589
+ )[0]
590
+ # perform guidance
591
+ if do_classifier_free_guidance:
592
+ noise_pred_uncond, noise_pred_drop_audio, noise_pred_cond = noise_pred.chunk(3)
593
+ noise_pred = noise_pred_uncond + self.guidance_scale1[i] * (noise_pred_drop_audio - noise_pred_uncond) + self.guidance_scale2[i] * (noise_pred_cond - noise_pred_drop_audio)
594
+
595
+ # compute the previous noisy sample x_t -> x_t-1
596
+ latents = self.scheduler.step(noise_pred, t.to(self.unet.dtype), latents).prev_sample
597
+
598
+ if callback_on_step_end is not None:
599
+ callback_kwargs = {}
600
+ for k in callback_on_step_end_tensor_inputs:
601
+ callback_kwargs[k] = locals()[k]
602
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
603
+
604
+ latents = callback_outputs.pop("latents", latents)
605
+
606
+ # if batch == 0:
607
+ for iii in range(frames_per_batch):
608
+ p = (index_start + iii) % pred_latents.shape[1]
609
+ pred_latents[:, p] += latents[:, iii]
610
+ counter[:, p] += 1
611
+ shift += shift_offset
612
+
613
+ pred_latents = pred_latents / counter
614
+ latents_all = pred_latents
615
+
616
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
617
+ progress_bar.update()
618
+
619
+ latents = latents_all
620
+ if not output_type == "latent":
621
+ # cast back to fp16 if needed
622
+ if needs_upcasting:
623
+ self.vae.to(dtype=vae_dtype)
624
+ frames = self.decode_latents(latents, num_frames, decode_chunk_size)
625
+ else:
626
+ frames = latents
627
+
628
+ self.maybe_free_model_hooks()
629
+
630
+ if not return_dict:
631
+ return frames
632
+ return Pose2VideoSVDPipelineOutput(frames=frames)
src/utils/RIFE/IFNet_HDv3.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from .warplayer import warp
5
+
6
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
7
+
8
+ def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
9
+ return nn.Sequential(
10
+ nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
11
+ padding=padding, dilation=dilation, bias=True),
12
+ nn.PReLU(out_planes)
13
+ )
14
+
15
+ def conv_bn(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
16
+ return nn.Sequential(
17
+ nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
18
+ padding=padding, dilation=dilation, bias=False),
19
+ nn.BatchNorm2d(out_planes),
20
+ nn.PReLU(out_planes)
21
+ )
22
+
23
+ class IFBlock(nn.Module):
24
+ def __init__(self, in_planes, c=64):
25
+ super(IFBlock, self).__init__()
26
+ self.conv0 = nn.Sequential(
27
+ conv(in_planes, c//2, 3, 2, 1),
28
+ conv(c//2, c, 3, 2, 1),
29
+ )
30
+ self.convblock0 = nn.Sequential(
31
+ conv(c, c),
32
+ conv(c, c)
33
+ )
34
+ self.convblock1 = nn.Sequential(
35
+ conv(c, c),
36
+ conv(c, c)
37
+ )
38
+ self.convblock2 = nn.Sequential(
39
+ conv(c, c),
40
+ conv(c, c)
41
+ )
42
+ self.convblock3 = nn.Sequential(
43
+ conv(c, c),
44
+ conv(c, c)
45
+ )
46
+ self.conv1 = nn.Sequential(
47
+ nn.ConvTranspose2d(c, c//2, 4, 2, 1),
48
+ nn.PReLU(c//2),
49
+ nn.ConvTranspose2d(c//2, 4, 4, 2, 1),
50
+ )
51
+ self.conv2 = nn.Sequential(
52
+ nn.ConvTranspose2d(c, c//2, 4, 2, 1),
53
+ nn.PReLU(c//2),
54
+ nn.ConvTranspose2d(c//2, 1, 4, 2, 1),
55
+ )
56
+
57
+ def forward(self, x, flow, scale=1):
58
+ x = F.interpolate(x, scale_factor= 1. / scale, mode="bilinear", align_corners=False, recompute_scale_factor=False)
59
+ flow = F.interpolate(flow, scale_factor= 1. / scale, mode="bilinear", align_corners=False, recompute_scale_factor=False) * 1. / scale
60
+ feat = self.conv0(torch.cat((x, flow), 1))
61
+ feat = self.convblock0(feat) + feat
62
+ feat = self.convblock1(feat) + feat
63
+ feat = self.convblock2(feat) + feat
64
+ feat = self.convblock3(feat) + feat
65
+ flow = self.conv1(feat)
66
+ mask = self.conv2(feat)
67
+ flow = F.interpolate(flow, scale_factor=scale, mode="bilinear", align_corners=False, recompute_scale_factor=False) * scale
68
+ mask = F.interpolate(mask, scale_factor=scale, mode="bilinear", align_corners=False, recompute_scale_factor=False)
69
+ return flow, mask
70
+
71
+ class IFNet(nn.Module):
72
+ def __init__(self):
73
+ super(IFNet, self).__init__()
74
+ self.block0 = IFBlock(7+4, c=90)
75
+ self.block1 = IFBlock(7+4, c=90)
76
+ self.block2 = IFBlock(7+4, c=90)
77
+ self.block_tea = IFBlock(10+4, c=90)
78
+ # self.contextnet = Contextnet()
79
+ # self.unet = Unet()
80
+
81
+ def forward(self, x, scale_list=[4, 2, 1], training=False):
82
+ if training == False:
83
+ channel = x.shape[1] // 2
84
+ img0 = x[:, :channel]
85
+ img1 = x[:, channel:]
86
+ flow_list = []
87
+ merged = []
88
+ mask_list = []
89
+ warped_img0 = img0
90
+ warped_img1 = img1
91
+ flow = (x[:, :4]).detach() * 0
92
+ mask = (x[:, :1]).detach() * 0
93
+ loss_cons = 0
94
+ block = [self.block0, self.block1, self.block2]
95
+ for i in range(3):
96
+ f0, m0 = block[i](torch.cat((warped_img0[:, :3], warped_img1[:, :3], mask), 1), flow, scale=scale_list[i])
97
+ f1, m1 = block[i](torch.cat((warped_img1[:, :3], warped_img0[:, :3], -mask), 1), torch.cat((flow[:, 2:4], flow[:, :2]), 1), scale=scale_list[i])
98
+ flow = flow + (f0 + torch.cat((f1[:, 2:4], f1[:, :2]), 1)) / 2
99
+ mask = mask + (m0 + (-m1)) / 2
100
+ mask_list.append(mask)
101
+ flow_list.append(flow)
102
+ warped_img0 = warp(img0, flow[:, :2])
103
+ warped_img1 = warp(img1, flow[:, 2:4])
104
+ merged.append((warped_img0, warped_img1))
105
+ '''
106
+ c0 = self.contextnet(img0, flow[:, :2])
107
+ c1 = self.contextnet(img1, flow[:, 2:4])
108
+ tmp = self.unet(img0, img1, warped_img0, warped_img1, mask, flow, c0, c1)
109
+ res = tmp[:, 1:4] * 2 - 1
110
+ '''
111
+ for i in range(3):
112
+ mask_list[i] = torch.sigmoid(mask_list[i])
113
+ merged[i] = merged[i][0] * mask_list[i] + merged[i][1] * (1 - mask_list[i])
114
+ # merged[i] = torch.clamp(merged[i] + res, 0, 1)
115
+ return flow_list, mask_list[2], merged
src/utils/RIFE/RIFE_HDv3.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .IFNet_HDv3 import *
3
+ import torch.nn.functional as F
4
+
5
+ class RIFEModel:
6
+ def __init__(self, device=None):
7
+ if device is None:
8
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
9
+ else:
10
+ self.device = device
11
+ self.flownet = IFNet().to(self.device).eval()
12
+
13
+ def train(self):
14
+ self.flownet.train()
15
+
16
+ def eval(self):
17
+ self.flownet.eval()
18
+
19
+
20
+ def load_model(self, path, rank=-1):
21
+ def convert(param):
22
+ if rank == -1:
23
+ return {
24
+ k.replace("module.", ""): v
25
+ for k, v in param.items()
26
+ if "module." in k
27
+ }
28
+ else:
29
+ return param
30
+ self.flownet.load_state_dict(convert(torch.load('{}/flownet.pkl'.format(path), map_location ='cpu')))
31
+
32
+
33
+ def inference(self, img0, img1, scale=1.0):
34
+ imgs = torch.cat((img0, img1), 1)
35
+ scale_list = [4/scale, 2/scale, 1/scale]
36
+ flow, mask, merged = self.flownet(imgs, scale_list)
37
+ return merged[2]
src/utils/RIFE/warplayer.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ backwarp_tenGrid = {}
5
+
6
+
7
+ def warp(tenInput, tenFlow):
8
+ device = tenFlow.device
9
+ k = (str(tenFlow.device), str(tenFlow.size()))
10
+ if k not in backwarp_tenGrid:
11
+ tenHorizontal = torch.linspace(-1.0, 1.0, tenFlow.shape[3], device=device).view(
12
+ 1, 1, 1, tenFlow.shape[3]).expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1)
13
+ tenVertical = torch.linspace(-1.0, 1.0, tenFlow.shape[2], device=device).view(
14
+ 1, 1, tenFlow.shape[2], 1).expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3])
15
+ backwarp_tenGrid[k] = torch.cat(
16
+ [tenHorizontal, tenVertical], 1).to(device)
17
+
18
+ tenFlow = torch.cat([tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0),
19
+ tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0)], 1)
20
+
21
+ g = (backwarp_tenGrid[k] + tenFlow).permute(0, 2, 3, 1)
22
+ return torch.nn.functional.grid_sample(input=tenInput, grid=g, mode='bilinear', padding_mode='border', align_corners=True)
src/utils/mask_processer.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import math
3
+ import warnings
4
+ from typing import List, Optional, Tuple, Union
5
+
6
+ import numpy as np
7
+ import PIL.Image
8
+ import torch
9
+ import torch.nn.functional as F
10
+ from PIL import Image, ImageFilter, ImageOps
11
+
12
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
13
+ from diffusers.utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate
14
+ from diffusers.image_processor import VaeImageProcessor
15
+
16
+ class IPAdapterMaskProcessor(VaeImageProcessor):
17
+ """
18
+ Image processor for IP Adapter image masks.
19
+
20
+ Args:
21
+ do_resize (`bool`, *optional*, defaults to `True`):
22
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
23
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
24
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
25
+ resample (`str`, *optional*, defaults to `lanczos`):
26
+ Resampling filter to use when resizing the image.
27
+ do_normalize (`bool`, *optional*, defaults to `False`):
28
+ Whether to normalize the image to [-1,1].
29
+ do_binarize (`bool`, *optional*, defaults to `True`):
30
+ Whether to binarize the image to 0/1.
31
+ do_convert_grayscale (`bool`, *optional*, defaults to be `True`):
32
+ Whether to convert the images to grayscale format.
33
+
34
+ """
35
+
36
+ config_name = CONFIG_NAME
37
+
38
+ @register_to_config
39
+ def __init__(
40
+ self,
41
+ do_resize: bool = True,
42
+ vae_scale_factor: int = 8,
43
+ resample: str = "lanczos",
44
+ do_normalize: bool = False,
45
+ do_binarize: bool = True,
46
+ do_convert_grayscale: bool = True,
47
+ ):
48
+ super().__init__(
49
+ do_resize=do_resize,
50
+ vae_scale_factor=vae_scale_factor,
51
+ resample=resample,
52
+ do_normalize=do_normalize,
53
+ do_binarize=do_binarize,
54
+ do_convert_grayscale=do_convert_grayscale,
55
+ )
56
+
57
+ @staticmethod
58
+ def downsample(mask: torch.Tensor, batch_size: int, num_queries: int, value_embed_dim: int):
59
+ """
60
+ Downsamples the provided mask tensor to match the expected dimensions for scaled dot-product attention. If the
61
+ aspect ratio of the mask does not match the aspect ratio of the output image, a warning is issued.
62
+
63
+ Args:
64
+ mask (`torch.Tensor`):
65
+ The input mask tensor generated with `IPAdapterMaskProcessor.preprocess()`.
66
+ batch_size (`int`):
67
+ The batch size.
68
+ num_queries (`int`):
69
+ The number of queries.
70
+ value_embed_dim (`int`):
71
+ The dimensionality of the value embeddings.
72
+
73
+ Returns:
74
+ `torch.Tensor`:
75
+ The downsampled mask tensor.
76
+
77
+ """
78
+ o_h = mask.shape[1]
79
+ o_w = mask.shape[2]
80
+ ratio = o_w / o_h
81
+ mask_h = int(torch.sqrt(torch.FloatTensor([num_queries / ratio]))[0])
82
+ mask_h = int(mask_h) + int((num_queries % int(mask_h)) != 0)
83
+ mask_w = num_queries // mask_h
84
+
85
+ mask_downsample = F.interpolate(mask.unsqueeze(0), size=(mask_h, mask_w), mode="bicubic").squeeze(0)
86
+
87
+ # Repeat batch_size times
88
+ if mask_downsample.shape[0] < batch_size:
89
+ mask_downsample = mask_downsample.repeat(batch_size, 1, 1)
90
+
91
+ mask_downsample = mask_downsample.view(mask_downsample.shape[0], -1)
92
+
93
+ downsampled_area = mask_h * mask_w
94
+ # If the output image and the mask do not have the same aspect ratio, tensor shapes will not match
95
+ # Pad tensor if downsampled_mask.shape[1] is smaller than num_queries
96
+ if downsampled_area < num_queries:
97
+ warnings.warn(
98
+ "The aspect ratio of the mask does not match the aspect ratio of the output image. "
99
+ "Please update your masks or adjust the output size for optimal performance.",
100
+ UserWarning,
101
+ )
102
+ mask_downsample = F.pad(mask_downsample, (0, num_queries - mask_downsample.shape[1]), value=0.0)
103
+ # Discard last embeddings if downsampled_mask.shape[1] is bigger than num_queries
104
+ if downsampled_area > num_queries:
105
+ warnings.warn(
106
+ "The aspect ratio of the mask does not match the aspect ratio of the output image. "
107
+ "Please update your masks or adjust the output size for optimal performance.",
108
+ UserWarning,
109
+ )
110
+ mask_downsample = mask_downsample[:, :num_queries]
111
+
112
+ # Repeat last dimension to match SDPA output shape
113
+ mask_downsample = mask_downsample.view(mask_downsample.shape[0], mask_downsample.shape[1], 1).repeat(
114
+ 1, 1, value_embed_dim
115
+ )
116
+
117
+ return mask_downsample
src/utils/util.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import os
3
+ import os.path as osp
4
+ import shutil
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import torch
10
+ import torchvision
11
+ from einops import rearrange
12
+ from PIL import Image
13
+ import imageio
14
+
15
+ def seed_everything(seed):
16
+ import random
17
+ import numpy as np
18
+
19
+ torch.manual_seed(seed)
20
+ torch.cuda.manual_seed_all(seed)
21
+ np.random.seed(seed % (2**32))
22
+ random.seed(seed)
23
+
24
+
25
+ def save_videos_from_pil(pil_images, path, fps=8):
26
+ save_fmt = Path(path).suffix
27
+ os.makedirs(os.path.dirname(path), exist_ok=True)
28
+
29
+ if save_fmt == ".mp4":
30
+ with imageio.get_writer(path, fps=fps) as writer:
31
+ for img in pil_images:
32
+ img_array = np.array(img) # Convert PIL Image to numpy array
33
+ writer.append_data(img_array)
34
+
35
+ elif save_fmt == ".gif":
36
+ pil_images[0].save(
37
+ fp=path,
38
+ format="GIF",
39
+ append_images=pil_images[1:],
40
+ save_all=True,
41
+ duration=(1 / fps * 1000),
42
+ loop=0,
43
+ optimize=False,
44
+ lossless=True
45
+ )
46
+ else:
47
+ raise ValueError("Unsupported file type. Use .mp4 or .gif.")
48
+
49
+
50
+ def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=6, fps=8):
51
+ videos = rearrange(videos, "b c t h w -> t b c h w")
52
+ height, width = videos.shape[-2:]
53
+ outputs = []
54
+
55
+ for i, x in enumerate(videos):
56
+ x = torchvision.utils.make_grid(x, nrow=n_rows) # (c h w)
57
+ x = x.transpose(0, 1).transpose(1, 2).squeeze(-1) # (h w c)
58
+ if rescale:
59
+ x = (x + 1.0) / 2.0 # -1,1 -> 0,1
60
+ x = (x * 255).numpy().astype(np.uint8)
61
+ x = Image.fromarray(x)
62
+ outputs.append(x)
63
+
64
+ os.makedirs(os.path.dirname(path), exist_ok=True)
65
+
66
+ save_videos_from_pil(outputs, path, fps)
67
+