Spaces:
Configuration error
Configuration error
Upload 13 files
Browse files- LICENSE.txt +201 -0
- README.md +387 -14
- app.py +819 -0
- generate_infinitetalk.py +663 -0
- kokoro/__init__.py +23 -0
- kokoro/__main__.py +148 -0
- kokoro/custom_stft.py +197 -0
- kokoro/istftnet.py +421 -0
- kokoro/model.py +155 -0
- kokoro/modules.py +183 -0
- kokoro/pipeline.py +445 -0
- requirements.txt +21 -0
- setup.sh +28 -0
LICENSE.txt
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
README.md
CHANGED
|
@@ -1,14 +1,387 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
| 1 |
+
<div align="center">
|
| 2 |
+
|
| 3 |
+
<p align="center">
|
| 4 |
+
<img src="assets/logo2.jpg" alt="InfinteTalk" width="440"/>
|
| 5 |
+
</p>
|
| 6 |
+
|
| 7 |
+
<h1>InfiniteTalk: Audio-driven Video Generation for Sparse-Frame Video Dubbing</h1>
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
[Shaoshu Yang*](https://scholar.google.com/citations?user=JrdZbTsAAAAJ&hl=en) · [Zhe Kong*](https://scholar.google.com/citations?user=4X3yLwsAAAAJ&hl=zh-CN) · [Feng Gao*](https://scholar.google.com/citations?user=lFkCeoYAAAAJ) · [Meng Cheng*]() · [Xiangyu Liu*]() · [Yong Zhang](https://yzhang2016.github.io/)<sup>✉</sup> · [Zhuoliang Kang](https://scholar.google.com/citations?user=W1ZXjMkAAAAJ&hl=en)
|
| 11 |
+
|
| 12 |
+
[Wenhan Luo](https://whluo.github.io/) · [Xunliang Cai](https://openreview.net/profile?id=~Xunliang_Cai1) · [Ran He](https://scholar.google.com/citations?user=ayrg9AUAAAAJ&hl=en)· [Xiaoming Wei](https://scholar.google.com/citations?user=JXV5yrZxj5MC&hl=zh-CN)
|
| 13 |
+
|
| 14 |
+
<sup>*</sup>Equal Contribution
|
| 15 |
+
<sup>✉</sup>Corresponding Authors
|
| 16 |
+
|
| 17 |
+
<a href='https://meigen-ai.github.io/InfiniteTalk/'><img src='https://img.shields.io/badge/Project-Page-green'></a>
|
| 18 |
+
<a href='https://arxiv.org/abs/2508.14033'><img src='https://img.shields.io/badge/Technique-Report-red'></a>
|
| 19 |
+
<a href='https://huggingface.co/MeiGen-AI/InfiniteTalk'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Model-blue'></a>
|
| 20 |
+
</div>
|
| 21 |
+
|
| 22 |
+
> **TL; DR:** InfiniteTalk is an unlimited-length talking video generation model that supports both audio-driven video-to-video and image-to-video generation
|
| 23 |
+
|
| 24 |
+
<p align="center">
|
| 25 |
+
<img src="assets/pipeline.png">
|
| 26 |
+
</p>
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
## 🔥 Latest News
|
| 35 |
+
|
| 36 |
+
* August 19, 2025: We release the [Technique-Report](https://arxiv.org/abs/2508.14033) , weights, and code of **InfiniteTalk**. The Gradio and the [ComfyUI](https://github.com/MeiGen-AI/InfiniteTalk/tree/comfyui) branch have been released.
|
| 37 |
+
* August 19, 2025: We release the [project page](https://meigen-ai.github.io/InfiniteTalk/) of **InfiniteTalk**
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
## ✨ Key Features
|
| 41 |
+
We propose **InfiniteTalk**, a novel sparse-frame video dubbing framework. Given an input video and audio track, InfiniteTalk synthesizes a new video with accurate lip synchronization while simultaneously aligning head movements, body posture, and facial expressions with the audio. Unlike traditional dubbing methods that focus solely on lips, InfiniteTalk enables infinite-length video generation with accurate lip synchronization and consistent identity preservation. Beside, InfiniteTalk can also be used as an image-audio-to-video model with an image and an audio as input.
|
| 42 |
+
- 💬 Sparse-frame Video Dubbing – Synchronizes not only lips, but aslo head, body, and expressions
|
| 43 |
+
- ⏱️ Infinite-Length Generation – Supports unlimited video duration
|
| 44 |
+
- ✨ Stability – Reduces hand/body distortions compared to MultiTalk
|
| 45 |
+
- 🚀 Lip Accuracy – Achieves superior lip synchronization to MultiTalk
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
## 🌐 Community Works
|
| 50 |
+
- [Wan2GP](https://github.com/deepbeepmeep/Wan2GP/): Thanks [deepbeepmeep](https://github.com/deepbeepmeep) for integrating InfiniteTalk in Wan2GP that is optimized for low VRAM and offers many video edtiting option and other models (MMaudio support, Qwen Image Edit, ...).
|
| 51 |
+
- [ComfyUI](https://github.com/kijai/ComfyUI-WanVideoWrapper): Thanks for the comfyui support of [kijai](https://github.com/kijai).
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
## 📑 Todo List
|
| 56 |
+
|
| 57 |
+
- [x] Release the technical report
|
| 58 |
+
- [x] Inference
|
| 59 |
+
- [x] Checkpoints
|
| 60 |
+
- [x] Multi-GPU Inference
|
| 61 |
+
- [ ] Inference acceleration
|
| 62 |
+
- [x] TeaCache
|
| 63 |
+
- [x] int8 quantization
|
| 64 |
+
- [ ] LCM distillation
|
| 65 |
+
- [ ] Sparse Attention
|
| 66 |
+
- [x] Run with very low VRAM
|
| 67 |
+
- [x] Gradio demo
|
| 68 |
+
- [x] ComfyUI
|
| 69 |
+
|
| 70 |
+
## Video Demos
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
### Video-to-video (HQ videos can be found on [Google Drive](https://drive.google.com/drive/folders/1BNrH6GJZ2Wt5gBuNLmfXZ6kpqb9xFPjU?usp=sharing) )
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
<table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
|
| 77 |
+
<tr>
|
| 78 |
+
<td>
|
| 79 |
+
<video src="https://github.com/user-attachments/assets/04f15986-8de7-4bb4-8cde-7f7f38244f9f" width="320" controls loop></video>
|
| 80 |
+
</td>
|
| 81 |
+
<td>
|
| 82 |
+
<video src="https://github.com/user-attachments/assets/1500f72e-a096-42e5-8b44-f887fa8ae7cb" width="320" controls loop></video>
|
| 83 |
+
</td>
|
| 84 |
+
<td>
|
| 85 |
+
<video src="https://github.com/user-attachments/assets/28f484c2-87dc-4828-a9e7-cb963da92d14" width="320" controls loop></video>
|
| 86 |
+
</td>
|
| 87 |
+
<td>
|
| 88 |
+
<video src="https://github.com/user-attachments/assets/665fabe4-3e24-4008-a0a2-a66e2e57c38b" width="320" controls loop></video>
|
| 89 |
+
</td>
|
| 90 |
+
</tr>
|
| 91 |
+
</table>
|
| 92 |
+
|
| 93 |
+
### Image-to-video
|
| 94 |
+
|
| 95 |
+
<table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
|
| 96 |
+
<tr>
|
| 97 |
+
<td>
|
| 98 |
+
<video src="https://github.com/user-attachments/assets/7e4a4dad-9666-4896-8684-2acb36aead59" width="320" controls loop></video>
|
| 99 |
+
</td>
|
| 100 |
+
<td>
|
| 101 |
+
<video src="https://github.com/user-attachments/assets/bd6da665-f34d-4634-ae94-b4978f92ad3a" width="320" controls loop></video>
|
| 102 |
+
</td>
|
| 103 |
+
<td>
|
| 104 |
+
<video src="https://github.com/user-attachments/assets/510e2648-82db-4648-aaf3-6542303dbe22" width="320" controls loop></video>
|
| 105 |
+
</td>
|
| 106 |
+
<td>
|
| 107 |
+
<video src="https://github.com/user-attachments/assets/27bb087b-866a-4300-8a03-3bbb4ce3ddf9" width="320" controls loop></video>
|
| 108 |
+
</td>
|
| 109 |
+
|
| 110 |
+
</tr>
|
| 111 |
+
<tr>
|
| 112 |
+
<td>
|
| 113 |
+
<video src="https://github.com/user-attachments/assets/3263c5e1-9f98-4b9b-8688-b3e497460a76" width="320" controls loop></video>
|
| 114 |
+
</td>
|
| 115 |
+
<td>
|
| 116 |
+
<video src="https://github.com/user-attachments/assets/5ff3607f-90ec-4eee-b964-9d5ee3028005" width="320" controls loop></video>
|
| 117 |
+
</td>
|
| 118 |
+
<td>
|
| 119 |
+
<video src="https://github.com/user-attachments/assets/e504417b-c8c7-4cf0-9afa-da0f3cbf3726" width="320" controls loop></video>
|
| 120 |
+
</td>
|
| 121 |
+
<td>
|
| 122 |
+
<video src="https://github.com/user-attachments/assets/56aac91e-c51f-4d44-b80d-7d115e94ead7" width="320" controls loop></video>
|
| 123 |
+
</td>
|
| 124 |
+
|
| 125 |
+
</tr>
|
| 126 |
+
</table>
|
| 127 |
+
|
| 128 |
+
## Quick Start
|
| 129 |
+
|
| 130 |
+
### 🛠️Installation
|
| 131 |
+
|
| 132 |
+
#### 1. Create a conda environment and install pytorch, xformers
|
| 133 |
+
```
|
| 134 |
+
conda create -n multitalk python=3.10
|
| 135 |
+
conda activate multitalk
|
| 136 |
+
pip install torch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 --index-url https://download.pytorch.org/whl/cu121
|
| 137 |
+
pip install -U xformers==0.0.28 --index-url https://download.pytorch.org/whl/cu121
|
| 138 |
+
```
|
| 139 |
+
#### 2. Flash-attn installation:
|
| 140 |
+
```
|
| 141 |
+
pip install misaki[en]
|
| 142 |
+
pip install ninja
|
| 143 |
+
pip install psutil
|
| 144 |
+
pip install packaging
|
| 145 |
+
pip install wheel
|
| 146 |
+
pip install flash_attn==2.7.4.post1
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
#### 3. Other dependencies
|
| 150 |
+
```
|
| 151 |
+
pip install -r requirements.txt
|
| 152 |
+
conda install -c conda-forge librosa
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
#### 4. FFmeg installation
|
| 156 |
+
```
|
| 157 |
+
conda install -c conda-forge ffmpeg
|
| 158 |
+
```
|
| 159 |
+
or
|
| 160 |
+
```
|
| 161 |
+
sudo yum install ffmpeg ffmpeg-devel
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
### 🧱Model Preparation
|
| 165 |
+
|
| 166 |
+
#### 1. Model Download
|
| 167 |
+
|
| 168 |
+
| Models | Download Link | Notes |
|
| 169 |
+
| --------------|-------------------------------------------------------------------------------|-------------------------------|
|
| 170 |
+
| Wan2.1-I2V-14B-480P | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.1-I2V-14B-480P) | Base model
|
| 171 |
+
| chinese-wav2vec2-base | 🤗 [Huggingface](https://huggingface.co/TencentGameMate/chinese-wav2vec2-base) | Audio encoder
|
| 172 |
+
| MeiGen-InfiniteTalk | 🤗 [Huggingface](https://huggingface.co/MeiGen-AI/InfiniteTalk) | Our audio condition weights
|
| 173 |
+
|
| 174 |
+
Download models using huggingface-cli:
|
| 175 |
+
``` sh
|
| 176 |
+
huggingface-cli download Wan-AI/Wan2.1-I2V-14B-480P --local-dir ./weights/Wan2.1-I2V-14B-480P
|
| 177 |
+
huggingface-cli download TencentGameMate/chinese-wav2vec2-base --local-dir ./weights/chinese-wav2vec2-base
|
| 178 |
+
huggingface-cli download TencentGameMate/chinese-wav2vec2-base model.safetensors --revision refs/pr/1 --local-dir ./weights/chinese-wav2vec2-base
|
| 179 |
+
huggingface-cli download MeiGen-AI/InfiniteTalk --local-dir ./weights/InfiniteTalk
|
| 180 |
+
|
| 181 |
+
```
|
| 182 |
+
|
| 183 |
+
### 🔑 Quick Inference
|
| 184 |
+
|
| 185 |
+
Our model is compatible with both 480P and 720P resolutions.
|
| 186 |
+
> Some tips
|
| 187 |
+
> - Lip synchronization accuracy: Audio CFG works optimally between 3–5. Increase the audio CFG value for better synchronization.
|
| 188 |
+
> - FusionX: While it enables faster inference and higher quality, FusionX LoRA exacerbates color shift over 1 minute and reduces ID preservation in videos.
|
| 189 |
+
> - V2V generation: Enables unlimited length generation. The model mimics the original video's camera movement, though not identically. Using SDEdit improves camera movement accuracy significantly but introduces color shift and is best suited for short clips. Improvements for long video camera control are planned.
|
| 190 |
+
> - I2V generation: Generates good results from a single image for up to 1 minute. Beyond 1 minute, color shifts become more pronounced. One trick for the high-quailty generation beyond 1 min is to copy the image to a video by translating or zooming in the image. Here is a script to [convert image to video](https://github.com/MeiGen-AI/InfiniteTalk/blob/main/tools/convert_img_to_video.py).
|
| 191 |
+
> - Quantization model: If your inference process is killed due to insufficient memory, we suggest using the quantization model, which can help **reduce memory usage**.
|
| 192 |
+
|
| 193 |
+
#### Usage of InfiniteTalk
|
| 194 |
+
```
|
| 195 |
+
--mode streaming: long video generation.
|
| 196 |
+
--mode clip: generate short video with one chunk.
|
| 197 |
+
--use_teacache: run with TeaCache.
|
| 198 |
+
--size infinitetalk-480: generate 480P video.
|
| 199 |
+
--size infinitetalk-720: generate 720P video.
|
| 200 |
+
--use_apg: run with APG.
|
| 201 |
+
--teacache_thresh: A coefficient used for TeaCache acceleration
|
| 202 |
+
—-sample_text_guide_scale: When not using LoRA, the optimal value is 5. After applying LoRA, the recommended value is 1.
|
| 203 |
+
—-sample_audio_guide_scale: When not using LoRA, the optimal value is 4. After applying LoRA, the recommended value is 2.
|
| 204 |
+
—-sample_audio_guide_scale: When not using LoRA, the optimal value is 4. After applying LoRA, the recommended value is 2.
|
| 205 |
+
--max_frame_num: The max frame length of the generated video, the default is 40 seconds(1000 frames).
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
#### 1. Inference
|
| 209 |
+
|
| 210 |
+
##### 1) Run with single GPU
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
```
|
| 214 |
+
python generate_infinitetalk.py \
|
| 215 |
+
--ckpt_dir weights/Wan2.1-I2V-14B-480P \
|
| 216 |
+
--wav2vec_dir 'weights/chinese-wav2vec2-base' \
|
| 217 |
+
--infinitetalk_dir weights/InfiniteTalk/single/infinitetalk.safetensors \
|
| 218 |
+
--input_json examples/single_example_image.json \
|
| 219 |
+
--size infinitetalk-480 \
|
| 220 |
+
--sample_steps 40 \
|
| 221 |
+
--mode streaming \
|
| 222 |
+
--motion_frame 9 \
|
| 223 |
+
--save_file infinitetalk_res
|
| 224 |
+
|
| 225 |
+
```
|
| 226 |
+
|
| 227 |
+
##### 2) Run with 720P
|
| 228 |
+
|
| 229 |
+
If you want run with 720P, set `--size infinitetalk-720`:
|
| 230 |
+
|
| 231 |
+
```
|
| 232 |
+
python generate_infinitetalk.py \
|
| 233 |
+
--ckpt_dir weights/Wan2.1-I2V-14B-480P \
|
| 234 |
+
--wav2vec_dir 'weights/chinese-wav2vec2-base' \
|
| 235 |
+
--infinitetalk_dir weights/InfiniteTalk/single/infinitetalk.safetensors \
|
| 236 |
+
--input_json examples/single_example_image.json \
|
| 237 |
+
--size infinitetalk-720 \
|
| 238 |
+
--sample_steps 40 \
|
| 239 |
+
--mode streaming \
|
| 240 |
+
--motion_frame 9 \
|
| 241 |
+
--save_file infinitetalk_res_720p
|
| 242 |
+
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
##### 3) Run with very low VRAM
|
| 246 |
+
|
| 247 |
+
If you want run with very low VRAM, set `--num_persistent_param_in_dit 0`:
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
```
|
| 251 |
+
python generate_infinitetalk.py \
|
| 252 |
+
--ckpt_dir weights/Wan2.1-I2V-14B-480P \
|
| 253 |
+
--wav2vec_dir 'weights/chinese-wav2vec2-base' \
|
| 254 |
+
--infinitetalk_dir weights/InfiniteTalk/single/infinitetalk.safetensors \
|
| 255 |
+
--input_json examples/single_example_image.json \
|
| 256 |
+
--size infinitetalk-480 \
|
| 257 |
+
--sample_steps 40 \
|
| 258 |
+
--num_persistent_param_in_dit 0 \
|
| 259 |
+
--mode streaming \
|
| 260 |
+
--motion_frame 9 \
|
| 261 |
+
--save_file infinitetalk_res_lowvram
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
##### 4) Multi-GPU inference
|
| 265 |
+
|
| 266 |
+
```
|
| 267 |
+
GPU_NUM=8
|
| 268 |
+
torchrun --nproc_per_node=$GPU_NUM --standalone generate_infinitetalk.py \
|
| 269 |
+
--ckpt_dir weights/Wan2.1-I2V-14B-480P \
|
| 270 |
+
--wav2vec_dir 'weights/chinese-wav2vec2-base' \
|
| 271 |
+
--infinitetalk_dir weights/InfiniteTalk/single/infinitetalk.safetensors \
|
| 272 |
+
--dit_fsdp --t5_fsdp \
|
| 273 |
+
--ulysses_size=$GPU_NUM \
|
| 274 |
+
--input_json examples/single_example_image.json \
|
| 275 |
+
--size infinitetalk-480 \
|
| 276 |
+
--sample_steps 40 \
|
| 277 |
+
--mode streaming \
|
| 278 |
+
--motion_frame 9 \
|
| 279 |
+
--save_file infinitetalk_res_multigpu
|
| 280 |
+
```
|
| 281 |
+
|
| 282 |
+
##### 5) Multi-Person animation
|
| 283 |
+
|
| 284 |
+
```
|
| 285 |
+
python generate_infinitetalk.py \
|
| 286 |
+
--ckpt_dir weights/Wan2.1-I2V-14B-480P \
|
| 287 |
+
--wav2vec_dir 'weights/chinese-wav2vec2-base' \
|
| 288 |
+
--infinitetalk_dir weights/InfiniteTalk/multi/infinitetalk.safetensors \
|
| 289 |
+
--input_json examples/multi_example_image.json \
|
| 290 |
+
--size infinitetalk-480 \
|
| 291 |
+
--sample_steps 40 \
|
| 292 |
+
--num_persistent_param_in_dit 0 \
|
| 293 |
+
--mode streaming \
|
| 294 |
+
--motion_frame 9 \
|
| 295 |
+
--save_file infinitetalk_res_multiperson
|
| 296 |
+
```
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
#### 2. Run with FusioniX or Lightx2v(Require only 4~8 steps)
|
| 300 |
+
|
| 301 |
+
[FusioniX](https://huggingface.co/vrgamedevgirl84/Wan14BT2VFusioniX/blob/main/FusionX_LoRa/Wan2.1_I2V_14B_FusionX_LoRA.safetensors) require 8 steps and [lightx2v](https://huggingface.co/Kijai/WanVideo_comfy/blob/main/Wan21_T2V_14B_lightx2v_cfg_step_distill_lora_rank32.safetensors) requires only 4 steps.
|
| 302 |
+
|
| 303 |
+
```
|
| 304 |
+
python generate_infinitetalk.py \
|
| 305 |
+
--ckpt_dir weights/Wan2.1-I2V-14B-480P \
|
| 306 |
+
--wav2vec_dir 'weights/chinese-wav2vec2-base' \
|
| 307 |
+
--infinitetalk_dir weights/InfiniteTalk/single/infinitetalk.safetensors \
|
| 308 |
+
--lora_dir weights/Wan2.1_I2V_14B_FusionX_LoRA.safetensors \
|
| 309 |
+
--input_json examples/single_example_image.json \
|
| 310 |
+
--lora_scale 1.0 \
|
| 311 |
+
--size infinitetalk-480 \
|
| 312 |
+
--sample_text_guide_scale 1.0 \
|
| 313 |
+
--sample_audio_guide_scale 2.0 \
|
| 314 |
+
--sample_steps 8 \
|
| 315 |
+
--mode streaming \
|
| 316 |
+
--motion_frame 9 \
|
| 317 |
+
--sample_shift 2 \
|
| 318 |
+
--num_persistent_param_in_dit 0 \
|
| 319 |
+
--save_file infinitetalk_res_lora
|
| 320 |
+
```
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
#### 3. Run with the quantization model (Only support run with single gpu)
|
| 325 |
+
|
| 326 |
+
```
|
| 327 |
+
python generate_infinitetalk.py \
|
| 328 |
+
--ckpt_dir weights/Wan2.1-I2V-14B-480P \
|
| 329 |
+
--wav2vec_dir 'weights/chinese-wav2vec2-base' \
|
| 330 |
+
--infinitetalk_dir weights/InfiniteTalk/single/infinitetalk.safetensors \
|
| 331 |
+
--input_json examples/single_example_image.json \
|
| 332 |
+
--size infinitetalk-480 \
|
| 333 |
+
--sample_steps 40 \
|
| 334 |
+
--mode streaming \
|
| 335 |
+
--quant fp8 \
|
| 336 |
+
--quant_dir weights/InfiniteTalk/quant_models/infinitetalk_single_fp8.safetensors \
|
| 337 |
+
--motion_frame 9 \
|
| 338 |
+
--num_persistent_param_in_dit 0 \
|
| 339 |
+
--save_file infinitetalk_res_quant
|
| 340 |
+
```
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
#### 4. Run with Gradio
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
```
|
| 348 |
+
python app.py \
|
| 349 |
+
--ckpt_dir weights/Wan2.1-I2V-14B-480P \
|
| 350 |
+
--wav2vec_dir 'weights/chinese-wav2vec2-base' \
|
| 351 |
+
--infinitetalk_dir weights/InfiniteTalk/single/infinitetalk.safetensors \
|
| 352 |
+
--num_persistent_param_in_dit 0 \
|
| 353 |
+
--motion_frame 9
|
| 354 |
+
```
|
| 355 |
+
or
|
| 356 |
+
```
|
| 357 |
+
python app.py \
|
| 358 |
+
--ckpt_dir weights/Wan2.1-I2V-14B-480P \
|
| 359 |
+
--wav2vec_dir 'weights/chinese-wav2vec2-base' \
|
| 360 |
+
--infinitetalk_dir weights/InfiniteTalk/multi/infinitetalk.safetensors \
|
| 361 |
+
--num_persistent_param_in_dit 0 \
|
| 362 |
+
--motion_frame 9
|
| 363 |
+
```
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
## 📚 Citation
|
| 367 |
+
|
| 368 |
+
If you find our work useful in your research, please consider citing:
|
| 369 |
+
|
| 370 |
+
```
|
| 371 |
+
@misc{yang2025infinitetalkaudiodrivenvideogeneration,
|
| 372 |
+
title={InfiniteTalk: Audio-driven Video Generation for Sparse-Frame Video Dubbing},
|
| 373 |
+
author={Shaoshu Yang and Zhe Kong and Feng Gao and Meng Cheng and Xiangyu Liu and Yong Zhang and Zhuoliang Kang and Wenhan Luo and Xunliang Cai and Ran He and Xiaoming Wei},
|
| 374 |
+
year={2025},
|
| 375 |
+
eprint={2508.14033},
|
| 376 |
+
archivePrefix={arXiv},
|
| 377 |
+
primaryClass={cs.CV},
|
| 378 |
+
url={https://arxiv.org/abs/2508.14033},
|
| 379 |
+
}
|
| 380 |
+
```
|
| 381 |
+
|
| 382 |
+
## 📜 License
|
| 383 |
+
The models in this repository are licensed under the Apache 2.0 License. We claim no rights over the your generated contents,
|
| 384 |
+
granting you the freedom to use them while ensuring that your usage complies with the provisions of this license.
|
| 385 |
+
You are fully accountable for your use of the models, which must not involve sharing any content that violates applicable laws,
|
| 386 |
+
causes harm to individuals or groups, disseminates personal information intended for harm, spreads misinformation, or targets vulnerable populations.
|
| 387 |
+
|
app.py
ADDED
|
@@ -0,0 +1,819 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
os.environ["no_proxy"] = "localhost,127.0.0.1,::1"
|
| 6 |
+
import sys
|
| 7 |
+
import json
|
| 8 |
+
import warnings
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
|
| 11 |
+
import gradio as gr
|
| 12 |
+
warnings.filterwarnings('ignore')
|
| 13 |
+
|
| 14 |
+
import random
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.distributed as dist
|
| 18 |
+
from PIL import Image
|
| 19 |
+
import subprocess
|
| 20 |
+
|
| 21 |
+
import wan
|
| 22 |
+
from wan.configs import SIZE_CONFIGS, SUPPORTED_SIZES, WAN_CONFIGS
|
| 23 |
+
from wan.utils.utils import cache_image, cache_video, str2bool
|
| 24 |
+
from wan.utils.multitalk_utils import save_video_ffmpeg
|
| 25 |
+
from kokoro import KPipeline
|
| 26 |
+
from transformers import Wav2Vec2FeatureExtractor
|
| 27 |
+
from src.audio_analysis.wav2vec2 import Wav2Vec2Model
|
| 28 |
+
|
| 29 |
+
import librosa
|
| 30 |
+
import pyloudnorm as pyln
|
| 31 |
+
import numpy as np
|
| 32 |
+
from einops import rearrange
|
| 33 |
+
import soundfile as sf
|
| 34 |
+
import re
|
| 35 |
+
|
| 36 |
+
def _validate_args(args):
|
| 37 |
+
# Basic check
|
| 38 |
+
assert args.ckpt_dir is not None, "Please specify the checkpoint directory."
|
| 39 |
+
assert args.task in WAN_CONFIGS, f"Unsupport task: {args.task}"
|
| 40 |
+
|
| 41 |
+
# The default sampling steps are 40 for image-to-video tasks and 50 for text-to-video tasks.
|
| 42 |
+
if args.sample_steps is None:
|
| 43 |
+
args.sample_steps = 40
|
| 44 |
+
|
| 45 |
+
if args.sample_shift is None:
|
| 46 |
+
if args.size == 'infinitetalk-480':
|
| 47 |
+
args.sample_shift = 7
|
| 48 |
+
elif args.size == 'infinitetalk-720':
|
| 49 |
+
args.sample_shift = 11
|
| 50 |
+
else:
|
| 51 |
+
raise NotImplementedError(f'Not supported size')
|
| 52 |
+
|
| 53 |
+
args.base_seed = args.base_seed if args.base_seed >= 0 else random.randint(
|
| 54 |
+
0, 99999999)
|
| 55 |
+
# Size check
|
| 56 |
+
assert args.size in SUPPORTED_SIZES[
|
| 57 |
+
args.
|
| 58 |
+
task], f"Unsupport size {args.size} for task {args.task}, supported sizes are: {', '.join(SUPPORTED_SIZES[args.task])}"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _parse_args():
|
| 62 |
+
parser = argparse.ArgumentParser(
|
| 63 |
+
description="Generate a image or video from a text prompt or image using Wan"
|
| 64 |
+
)
|
| 65 |
+
parser.add_argument(
|
| 66 |
+
"--task",
|
| 67 |
+
type=str,
|
| 68 |
+
default="infinitetalk-14B",
|
| 69 |
+
choices=list(WAN_CONFIGS.keys()),
|
| 70 |
+
help="The task to run.")
|
| 71 |
+
parser.add_argument(
|
| 72 |
+
"--size",
|
| 73 |
+
type=str,
|
| 74 |
+
default="infinitetalk-480",
|
| 75 |
+
choices=list(SIZE_CONFIGS.keys()),
|
| 76 |
+
help="The buckget size of the generated video. The aspect ratio of the output video will follow that of the input image."
|
| 77 |
+
)
|
| 78 |
+
parser.add_argument(
|
| 79 |
+
"--frame_num",
|
| 80 |
+
type=int,
|
| 81 |
+
default=81,
|
| 82 |
+
help="How many frames to be generated in one clip. The number should be 4n+1"
|
| 83 |
+
)
|
| 84 |
+
parser.add_argument(
|
| 85 |
+
"--ckpt_dir",
|
| 86 |
+
type=str,
|
| 87 |
+
default='./weights/Wan2.1-I2V-14B-480P',
|
| 88 |
+
help="The path to the Wan checkpoint directory.")
|
| 89 |
+
parser.add_argument(
|
| 90 |
+
"--quant_dir",
|
| 91 |
+
type=str,
|
| 92 |
+
default=None,
|
| 93 |
+
help="The path to the Wan quant checkpoint directory.")
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--infinitetalk_dir",
|
| 96 |
+
type=str,
|
| 97 |
+
default='weights/InfiniteTalk/single/infinitetalk.safetensors',
|
| 98 |
+
help="The path to the InfiniteTalk checkpoint directory.")
|
| 99 |
+
parser.add_argument(
|
| 100 |
+
"--wav2vec_dir",
|
| 101 |
+
type=str,
|
| 102 |
+
default='./weights/chinese-wav2vec2-base',
|
| 103 |
+
help="The path to the wav2vec checkpoint directory.")
|
| 104 |
+
parser.add_argument(
|
| 105 |
+
"--dit_path",
|
| 106 |
+
type=str,
|
| 107 |
+
default=None,
|
| 108 |
+
help="The path to the Wan checkpoint directory.")
|
| 109 |
+
parser.add_argument(
|
| 110 |
+
"--lora_dir",
|
| 111 |
+
type=str,
|
| 112 |
+
nargs='+',
|
| 113 |
+
default=None,
|
| 114 |
+
help="The path to the LoRA checkpoint directory.")
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
"--lora_scale",
|
| 117 |
+
type=float,
|
| 118 |
+
nargs='+',
|
| 119 |
+
default=[1.2],
|
| 120 |
+
help="Controls how much to influence the outputs with the LoRA parameters. Accepts multiple float values."
|
| 121 |
+
)
|
| 122 |
+
parser.add_argument(
|
| 123 |
+
"--offload_model",
|
| 124 |
+
type=str2bool,
|
| 125 |
+
default=None,
|
| 126 |
+
help="Whether to offload the model to CPU after each model forward, reducing GPU memory usage."
|
| 127 |
+
)
|
| 128 |
+
parser.add_argument(
|
| 129 |
+
"--ulysses_size",
|
| 130 |
+
type=int,
|
| 131 |
+
default=1,
|
| 132 |
+
help="The size of the ulysses parallelism in DiT.")
|
| 133 |
+
parser.add_argument(
|
| 134 |
+
"--ring_size",
|
| 135 |
+
type=int,
|
| 136 |
+
default=1,
|
| 137 |
+
help="The size of the ring attention parallelism in DiT.")
|
| 138 |
+
parser.add_argument(
|
| 139 |
+
"--t5_fsdp",
|
| 140 |
+
action="store_true",
|
| 141 |
+
default=False,
|
| 142 |
+
help="Whether to use FSDP for T5.")
|
| 143 |
+
parser.add_argument(
|
| 144 |
+
"--t5_cpu",
|
| 145 |
+
action="store_true",
|
| 146 |
+
default=False,
|
| 147 |
+
help="Whether to place T5 model on CPU.")
|
| 148 |
+
parser.add_argument(
|
| 149 |
+
"--dit_fsdp",
|
| 150 |
+
action="store_true",
|
| 151 |
+
default=False,
|
| 152 |
+
help="Whether to use FSDP for DiT.")
|
| 153 |
+
parser.add_argument(
|
| 154 |
+
"--save_file",
|
| 155 |
+
type=str,
|
| 156 |
+
default=None,
|
| 157 |
+
help="The file to save the generated image or video to.")
|
| 158 |
+
parser.add_argument(
|
| 159 |
+
"--audio_save_dir",
|
| 160 |
+
type=str,
|
| 161 |
+
default='save_audio/gradio',
|
| 162 |
+
help="The path to save the audio embedding.")
|
| 163 |
+
parser.add_argument(
|
| 164 |
+
"--base_seed",
|
| 165 |
+
type=int,
|
| 166 |
+
default=42,
|
| 167 |
+
help="The seed to use for generating the image or video.")
|
| 168 |
+
parser.add_argument(
|
| 169 |
+
"--input_json",
|
| 170 |
+
type=str,
|
| 171 |
+
default='examples.json',
|
| 172 |
+
help="[meta file] The condition path to generate the video.")
|
| 173 |
+
parser.add_argument(
|
| 174 |
+
"--motion_frame",
|
| 175 |
+
type=int,
|
| 176 |
+
default=9,
|
| 177 |
+
help="Driven frame length used in the mode of long video genration.")
|
| 178 |
+
parser.add_argument(
|
| 179 |
+
"--mode",
|
| 180 |
+
type=str,
|
| 181 |
+
default="streaming",
|
| 182 |
+
choices=['clip', 'streaming'],
|
| 183 |
+
help="clip: generate one video chunk, streaming: long video generation")
|
| 184 |
+
parser.add_argument(
|
| 185 |
+
"--sample_steps", type=int, default=None, help="The sampling steps.")
|
| 186 |
+
parser.add_argument(
|
| 187 |
+
"--sample_shift",
|
| 188 |
+
type=float,
|
| 189 |
+
default=None,
|
| 190 |
+
help="Sampling shift factor for flow matching schedulers.")
|
| 191 |
+
parser.add_argument(
|
| 192 |
+
"--sample_text_guide_scale",
|
| 193 |
+
type=float,
|
| 194 |
+
default=5.0,
|
| 195 |
+
help="Classifier free guidance scale for text control.")
|
| 196 |
+
parser.add_argument(
|
| 197 |
+
"--sample_audio_guide_scale",
|
| 198 |
+
type=float,
|
| 199 |
+
default=4.0,
|
| 200 |
+
help="Classifier free guidance scale for audio control.")
|
| 201 |
+
parser.add_argument(
|
| 202 |
+
"--num_persistent_param_in_dit",
|
| 203 |
+
type=int,
|
| 204 |
+
default=None,
|
| 205 |
+
required=False,
|
| 206 |
+
help="Maximum parameter quantity retained in video memory, small number to reduce VRAM required",
|
| 207 |
+
)
|
| 208 |
+
parser.add_argument(
|
| 209 |
+
"--use_teacache",
|
| 210 |
+
action="store_true",
|
| 211 |
+
default=False,
|
| 212 |
+
help="Enable teacache for video generation."
|
| 213 |
+
)
|
| 214 |
+
parser.add_argument(
|
| 215 |
+
"--teacache_thresh",
|
| 216 |
+
type=float,
|
| 217 |
+
default=0.2,
|
| 218 |
+
help="Threshold for teacache."
|
| 219 |
+
)
|
| 220 |
+
parser.add_argument(
|
| 221 |
+
"--use_apg",
|
| 222 |
+
action="store_true",
|
| 223 |
+
default=False,
|
| 224 |
+
help="Enable adaptive projected guidance for video generation (APG)."
|
| 225 |
+
)
|
| 226 |
+
parser.add_argument(
|
| 227 |
+
"--apg_momentum",
|
| 228 |
+
type=float,
|
| 229 |
+
default=-0.75,
|
| 230 |
+
help="Momentum used in adaptive projected guidance (APG)."
|
| 231 |
+
)
|
| 232 |
+
parser.add_argument(
|
| 233 |
+
"--apg_norm_threshold",
|
| 234 |
+
type=float,
|
| 235 |
+
default=55,
|
| 236 |
+
help="Norm threshold used in adaptive projected guidance (APG)."
|
| 237 |
+
)
|
| 238 |
+
parser.add_argument(
|
| 239 |
+
"--color_correction_strength",
|
| 240 |
+
type=float,
|
| 241 |
+
default=1.0,
|
| 242 |
+
help="strength for color correction [0.0 -- 1.0]."
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
parser.add_argument(
|
| 246 |
+
"--quant",
|
| 247 |
+
type=str,
|
| 248 |
+
default=None,
|
| 249 |
+
help="Quantization type, must be 'int8' or 'fp8'."
|
| 250 |
+
)
|
| 251 |
+
args = parser.parse_args()
|
| 252 |
+
_validate_args(args)
|
| 253 |
+
return args
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def custom_init(device, wav2vec):
|
| 257 |
+
audio_encoder = Wav2Vec2Model.from_pretrained(wav2vec, local_files_only=True).to(device)
|
| 258 |
+
audio_encoder.feature_extractor._freeze_parameters()
|
| 259 |
+
wav2vec_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(wav2vec, local_files_only=True)
|
| 260 |
+
return wav2vec_feature_extractor, audio_encoder
|
| 261 |
+
|
| 262 |
+
def loudness_norm(audio_array, sr=16000, lufs=-23):
|
| 263 |
+
meter = pyln.Meter(sr)
|
| 264 |
+
loudness = meter.integrated_loudness(audio_array)
|
| 265 |
+
if abs(loudness) > 100:
|
| 266 |
+
return audio_array
|
| 267 |
+
normalized_audio = pyln.normalize.loudness(audio_array, loudness, lufs)
|
| 268 |
+
return normalized_audio
|
| 269 |
+
|
| 270 |
+
def audio_prepare_multi(left_path, right_path, audio_type, sample_rate=16000):
|
| 271 |
+
if not (left_path=='None' or right_path=='None'):
|
| 272 |
+
human_speech_array1 = audio_prepare_single(left_path)
|
| 273 |
+
human_speech_array2 = audio_prepare_single(right_path)
|
| 274 |
+
elif left_path=='None':
|
| 275 |
+
human_speech_array2 = audio_prepare_single(right_path)
|
| 276 |
+
human_speech_array1 = np.zeros(human_speech_array2.shape[0])
|
| 277 |
+
elif right_path=='None':
|
| 278 |
+
human_speech_array1 = audio_prepare_single(left_path)
|
| 279 |
+
human_speech_array2 = np.zeros(human_speech_array1.shape[0])
|
| 280 |
+
|
| 281 |
+
if audio_type=='para':
|
| 282 |
+
new_human_speech1 = human_speech_array1
|
| 283 |
+
new_human_speech2 = human_speech_array2
|
| 284 |
+
elif audio_type=='add':
|
| 285 |
+
new_human_speech1 = np.concatenate([human_speech_array1[: human_speech_array1.shape[0]], np.zeros(human_speech_array2.shape[0])])
|
| 286 |
+
new_human_speech2 = np.concatenate([np.zeros(human_speech_array1.shape[0]), human_speech_array2[:human_speech_array2.shape[0]]])
|
| 287 |
+
sum_human_speechs = new_human_speech1 + new_human_speech2
|
| 288 |
+
return new_human_speech1, new_human_speech2, sum_human_speechs
|
| 289 |
+
|
| 290 |
+
def _init_logging(rank):
|
| 291 |
+
# logging
|
| 292 |
+
if rank == 0:
|
| 293 |
+
# set format
|
| 294 |
+
logging.basicConfig(
|
| 295 |
+
level=logging.INFO,
|
| 296 |
+
format="[%(asctime)s] %(levelname)s: %(message)s",
|
| 297 |
+
handlers=[logging.StreamHandler(stream=sys.stdout)])
|
| 298 |
+
else:
|
| 299 |
+
logging.basicConfig(level=logging.ERROR)
|
| 300 |
+
|
| 301 |
+
def get_embedding(speech_array, wav2vec_feature_extractor, audio_encoder, sr=16000, device='cpu'):
|
| 302 |
+
audio_duration = len(speech_array) / sr
|
| 303 |
+
video_length = audio_duration * 25 # Assume the video fps is 25
|
| 304 |
+
|
| 305 |
+
# wav2vec_feature_extractor
|
| 306 |
+
audio_feature = np.squeeze(
|
| 307 |
+
wav2vec_feature_extractor(speech_array, sampling_rate=sr).input_values
|
| 308 |
+
)
|
| 309 |
+
audio_feature = torch.from_numpy(audio_feature).float().to(device=device)
|
| 310 |
+
audio_feature = audio_feature.unsqueeze(0)
|
| 311 |
+
|
| 312 |
+
# audio encoder
|
| 313 |
+
with torch.no_grad():
|
| 314 |
+
embeddings = audio_encoder(audio_feature, seq_len=int(video_length), output_hidden_states=True)
|
| 315 |
+
|
| 316 |
+
if len(embeddings) == 0:
|
| 317 |
+
print("Fail to extract audio embedding")
|
| 318 |
+
return None
|
| 319 |
+
|
| 320 |
+
audio_emb = torch.stack(embeddings.hidden_states[1:], dim=1).squeeze(0)
|
| 321 |
+
audio_emb = rearrange(audio_emb, "b s d -> s b d")
|
| 322 |
+
|
| 323 |
+
audio_emb = audio_emb.cpu().detach()
|
| 324 |
+
return audio_emb
|
| 325 |
+
|
| 326 |
+
def extract_audio_from_video(filename, sample_rate):
|
| 327 |
+
raw_audio_path = filename.split('/')[-1].split('.')[0]+'.wav'
|
| 328 |
+
ffmpeg_command = [
|
| 329 |
+
"ffmpeg",
|
| 330 |
+
"-y",
|
| 331 |
+
"-i",
|
| 332 |
+
str(filename),
|
| 333 |
+
"-vn",
|
| 334 |
+
"-acodec",
|
| 335 |
+
"pcm_s16le",
|
| 336 |
+
"-ar",
|
| 337 |
+
"16000",
|
| 338 |
+
"-ac",
|
| 339 |
+
"2",
|
| 340 |
+
str(raw_audio_path),
|
| 341 |
+
]
|
| 342 |
+
subprocess.run(ffmpeg_command, check=True)
|
| 343 |
+
human_speech_array, sr = librosa.load(raw_audio_path, sr=sample_rate)
|
| 344 |
+
human_speech_array = loudness_norm(human_speech_array, sr)
|
| 345 |
+
os.remove(raw_audio_path)
|
| 346 |
+
|
| 347 |
+
return human_speech_array
|
| 348 |
+
|
| 349 |
+
def audio_prepare_single(audio_path, sample_rate=16000):
|
| 350 |
+
ext = os.path.splitext(audio_path)[1].lower()
|
| 351 |
+
if ext in ['.mp4', '.mov', '.avi', '.mkv']:
|
| 352 |
+
human_speech_array = extract_audio_from_video(audio_path, sample_rate)
|
| 353 |
+
return human_speech_array
|
| 354 |
+
else:
|
| 355 |
+
human_speech_array, sr = librosa.load(audio_path, sr=sample_rate)
|
| 356 |
+
human_speech_array = loudness_norm(human_speech_array, sr)
|
| 357 |
+
return human_speech_array
|
| 358 |
+
|
| 359 |
+
def process_tts_single(text, save_dir, voice1):
|
| 360 |
+
s1_sentences = []
|
| 361 |
+
|
| 362 |
+
pipeline = KPipeline(lang_code='a', repo_id='weights/Kokoro-82M')
|
| 363 |
+
|
| 364 |
+
voice_tensor = torch.load(voice1, weights_only=True)
|
| 365 |
+
generator = pipeline(
|
| 366 |
+
text, voice=voice_tensor, # <= change voice here
|
| 367 |
+
speed=1, split_pattern=r'\n+'
|
| 368 |
+
)
|
| 369 |
+
audios = []
|
| 370 |
+
for i, (gs, ps, audio) in enumerate(generator):
|
| 371 |
+
audios.append(audio)
|
| 372 |
+
audios = torch.concat(audios, dim=0)
|
| 373 |
+
s1_sentences.append(audios)
|
| 374 |
+
s1_sentences = torch.concat(s1_sentences, dim=0)
|
| 375 |
+
save_path1 =f'{save_dir}/s1.wav'
|
| 376 |
+
sf.write(save_path1, s1_sentences, 24000) # save each audio file
|
| 377 |
+
s1, _ = librosa.load(save_path1, sr=16000)
|
| 378 |
+
return s1, save_path1
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def process_tts_multi(text, save_dir, voice1, voice2):
|
| 383 |
+
pattern = r'\(s(\d+)\)\s*(.*?)(?=\s*\(s\d+\)|$)'
|
| 384 |
+
matches = re.findall(pattern, text, re.DOTALL)
|
| 385 |
+
|
| 386 |
+
s1_sentences = []
|
| 387 |
+
s2_sentences = []
|
| 388 |
+
|
| 389 |
+
pipeline = KPipeline(lang_code='a', repo_id='weights/Kokoro-82M')
|
| 390 |
+
for idx, (speaker, content) in enumerate(matches):
|
| 391 |
+
if speaker == '1':
|
| 392 |
+
voice_tensor = torch.load(voice1, weights_only=True)
|
| 393 |
+
generator = pipeline(
|
| 394 |
+
content, voice=voice_tensor, # <= change voice here
|
| 395 |
+
speed=1, split_pattern=r'\n+'
|
| 396 |
+
)
|
| 397 |
+
audios = []
|
| 398 |
+
for i, (gs, ps, audio) in enumerate(generator):
|
| 399 |
+
audios.append(audio)
|
| 400 |
+
audios = torch.concat(audios, dim=0)
|
| 401 |
+
s1_sentences.append(audios)
|
| 402 |
+
s2_sentences.append(torch.zeros_like(audios))
|
| 403 |
+
elif speaker == '2':
|
| 404 |
+
voice_tensor = torch.load(voice2, weights_only=True)
|
| 405 |
+
generator = pipeline(
|
| 406 |
+
content, voice=voice_tensor, # <= change voice here
|
| 407 |
+
speed=1, split_pattern=r'\n+'
|
| 408 |
+
)
|
| 409 |
+
audios = []
|
| 410 |
+
for i, (gs, ps, audio) in enumerate(generator):
|
| 411 |
+
audios.append(audio)
|
| 412 |
+
audios = torch.concat(audios, dim=0)
|
| 413 |
+
s2_sentences.append(audios)
|
| 414 |
+
s1_sentences.append(torch.zeros_like(audios))
|
| 415 |
+
|
| 416 |
+
s1_sentences = torch.concat(s1_sentences, dim=0)
|
| 417 |
+
s2_sentences = torch.concat(s2_sentences, dim=0)
|
| 418 |
+
sum_sentences = s1_sentences + s2_sentences
|
| 419 |
+
save_path1 =f'{save_dir}/s1.wav'
|
| 420 |
+
save_path2 =f'{save_dir}/s2.wav'
|
| 421 |
+
save_path_sum = f'{save_dir}/sum.wav'
|
| 422 |
+
sf.write(save_path1, s1_sentences, 24000) # save each audio file
|
| 423 |
+
sf.write(save_path2, s2_sentences, 24000)
|
| 424 |
+
sf.write(save_path_sum, sum_sentences, 24000)
|
| 425 |
+
|
| 426 |
+
s1, _ = librosa.load(save_path1, sr=16000)
|
| 427 |
+
s2, _ = librosa.load(save_path2, sr=16000)
|
| 428 |
+
# sum, _ = librosa.load(save_path_sum, sr=16000)
|
| 429 |
+
return s1, s2, save_path_sum
|
| 430 |
+
|
| 431 |
+
def run_graio_demo(args):
|
| 432 |
+
rank = int(os.getenv("RANK", 0))
|
| 433 |
+
world_size = int(os.getenv("WORLD_SIZE", 1))
|
| 434 |
+
local_rank = int(os.getenv("LOCAL_RANK", 0))
|
| 435 |
+
device = local_rank
|
| 436 |
+
_init_logging(rank)
|
| 437 |
+
|
| 438 |
+
if args.offload_model is None:
|
| 439 |
+
args.offload_model = False if world_size > 1 else True
|
| 440 |
+
logging.info(
|
| 441 |
+
f"offload_model is not specified, set to {args.offload_model}.")
|
| 442 |
+
if world_size > 1:
|
| 443 |
+
torch.cuda.set_device(local_rank)
|
| 444 |
+
dist.init_process_group(
|
| 445 |
+
backend="nccl",
|
| 446 |
+
init_method="env://",
|
| 447 |
+
rank=rank,
|
| 448 |
+
world_size=world_size)
|
| 449 |
+
else:
|
| 450 |
+
assert not (
|
| 451 |
+
args.t5_fsdp or args.dit_fsdp
|
| 452 |
+
), f"t5_fsdp and dit_fsdp are not supported in non-distributed environments."
|
| 453 |
+
assert not (
|
| 454 |
+
args.ulysses_size > 1 or args.ring_size > 1
|
| 455 |
+
), f"context parallel are not supported in non-distributed environments."
|
| 456 |
+
|
| 457 |
+
if args.ulysses_size > 1 or args.ring_size > 1:
|
| 458 |
+
assert args.ulysses_size * args.ring_size == world_size, f"The number of ulysses_size and ring_size should be equal to the world size."
|
| 459 |
+
from xfuser.core.distributed import (
|
| 460 |
+
init_distributed_environment,
|
| 461 |
+
initialize_model_parallel,
|
| 462 |
+
)
|
| 463 |
+
init_distributed_environment(
|
| 464 |
+
rank=dist.get_rank(), world_size=dist.get_world_size())
|
| 465 |
+
|
| 466 |
+
initialize_model_parallel(
|
| 467 |
+
sequence_parallel_degree=dist.get_world_size(),
|
| 468 |
+
ring_degree=args.ring_size,
|
| 469 |
+
ulysses_degree=args.ulysses_size,
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
cfg = WAN_CONFIGS[args.task]
|
| 474 |
+
if args.ulysses_size > 1:
|
| 475 |
+
assert cfg.num_heads % args.ulysses_size == 0, f"`{cfg.num_heads=}` cannot be divided evenly by `{args.ulysses_size=}`."
|
| 476 |
+
|
| 477 |
+
logging.info(f"Generation job args: {args}")
|
| 478 |
+
logging.info(f"Generation model config: {cfg}")
|
| 479 |
+
|
| 480 |
+
if dist.is_initialized():
|
| 481 |
+
base_seed = [args.base_seed] if rank == 0 else [None]
|
| 482 |
+
dist.broadcast_object_list(base_seed, src=0)
|
| 483 |
+
args.base_seed = base_seed[0]
|
| 484 |
+
|
| 485 |
+
assert args.task == "infinitetalk-14B", 'You should choose multitalk in args.task.'
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
wav2vec_feature_extractor, audio_encoder= custom_init('cpu', args.wav2vec_dir)
|
| 490 |
+
os.makedirs(args.audio_save_dir,exist_ok=True)
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
logging.info("Creating MultiTalk pipeline.")
|
| 494 |
+
wan_i2v = wan.InfiniteTalkPipeline(
|
| 495 |
+
config=cfg,
|
| 496 |
+
checkpoint_dir=args.ckpt_dir,
|
| 497 |
+
quant_dir=args.quant_dir,
|
| 498 |
+
device_id=device,
|
| 499 |
+
rank=rank,
|
| 500 |
+
t5_fsdp=args.t5_fsdp,
|
| 501 |
+
dit_fsdp=args.dit_fsdp,
|
| 502 |
+
use_usp=(args.ulysses_size > 1 or args.ring_size > 1),
|
| 503 |
+
t5_cpu=args.t5_cpu,
|
| 504 |
+
lora_dir=args.lora_dir,
|
| 505 |
+
lora_scales=args.lora_scale,
|
| 506 |
+
quant=args.quant,
|
| 507 |
+
dit_path=args.dit_path,
|
| 508 |
+
infinitetalk_dir=args.infinitetalk_dir
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
if args.num_persistent_param_in_dit is not None:
|
| 512 |
+
wan_i2v.vram_management = True
|
| 513 |
+
wan_i2v.enable_vram_management(
|
| 514 |
+
num_persistent_param_in_dit=args.num_persistent_param_in_dit
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def generate_video(img2vid_image, vid2vid_vid, task_mode, img2vid_prompt, n_prompt, img2vid_audio_1, img2vid_audio_2,
|
| 520 |
+
sd_steps, seed, text_guide_scale, audio_guide_scale, mode_selector, tts_text, resolution_select, human1_voice, human2_voice):
|
| 521 |
+
input_data = {}
|
| 522 |
+
input_data["prompt"] = img2vid_prompt
|
| 523 |
+
if task_mode=='VideoDubbing':
|
| 524 |
+
input_data["cond_video"] = vid2vid_vid
|
| 525 |
+
else:
|
| 526 |
+
input_data["cond_video"] = img2vid_image
|
| 527 |
+
person = {}
|
| 528 |
+
if mode_selector == "Single Person(Local File)":
|
| 529 |
+
person['person1'] = img2vid_audio_1
|
| 530 |
+
elif mode_selector == "Single Person(TTS)":
|
| 531 |
+
tts_audio = {}
|
| 532 |
+
tts_audio['text'] = tts_text
|
| 533 |
+
tts_audio['human1_voice'] = human1_voice
|
| 534 |
+
input_data["tts_audio"] = tts_audio
|
| 535 |
+
elif mode_selector == "Multi Person(Local File, audio add)":
|
| 536 |
+
person['person1'] = img2vid_audio_1
|
| 537 |
+
person['person2'] = img2vid_audio_2
|
| 538 |
+
input_data["audio_type"] = 'add'
|
| 539 |
+
elif mode_selector == "Multi Person(Local File, audio parallel)":
|
| 540 |
+
person['person1'] = img2vid_audio_1
|
| 541 |
+
person['person2'] = img2vid_audio_2
|
| 542 |
+
input_data["audio_type"] = 'para'
|
| 543 |
+
else:
|
| 544 |
+
tts_audio = {}
|
| 545 |
+
tts_audio['text'] = tts_text
|
| 546 |
+
tts_audio['human1_voice'] = human1_voice
|
| 547 |
+
tts_audio['human2_voice'] = human2_voice
|
| 548 |
+
input_data["tts_audio"] = tts_audio
|
| 549 |
+
|
| 550 |
+
input_data["cond_audio"] = person
|
| 551 |
+
|
| 552 |
+
if 'Local File' in mode_selector:
|
| 553 |
+
if len(input_data['cond_audio'])==2:
|
| 554 |
+
new_human_speech1, new_human_speech2, sum_human_speechs = audio_prepare_multi(input_data['cond_audio']['person1'], input_data['cond_audio']['person2'], input_data['audio_type'])
|
| 555 |
+
audio_embedding_1 = get_embedding(new_human_speech1, wav2vec_feature_extractor, audio_encoder)
|
| 556 |
+
audio_embedding_2 = get_embedding(new_human_speech2, wav2vec_feature_extractor, audio_encoder)
|
| 557 |
+
emb1_path = os.path.join(args.audio_save_dir, '1.pt')
|
| 558 |
+
emb2_path = os.path.join(args.audio_save_dir, '2.pt')
|
| 559 |
+
sum_audio = os.path.join(args.audio_save_dir, 'sum.wav')
|
| 560 |
+
sf.write(sum_audio, sum_human_speechs, 16000)
|
| 561 |
+
torch.save(audio_embedding_1, emb1_path)
|
| 562 |
+
torch.save(audio_embedding_2, emb2_path)
|
| 563 |
+
input_data['cond_audio']['person1'] = emb1_path
|
| 564 |
+
input_data['cond_audio']['person2'] = emb2_path
|
| 565 |
+
input_data['video_audio'] = sum_audio
|
| 566 |
+
elif len(input_data['cond_audio'])==1:
|
| 567 |
+
human_speech = audio_prepare_single(input_data['cond_audio']['person1'])
|
| 568 |
+
audio_embedding = get_embedding(human_speech, wav2vec_feature_extractor, audio_encoder)
|
| 569 |
+
emb_path = os.path.join(args.audio_save_dir, '1.pt')
|
| 570 |
+
sum_audio = os.path.join(args.audio_save_dir, 'sum.wav')
|
| 571 |
+
sf.write(sum_audio, human_speech, 16000)
|
| 572 |
+
torch.save(audio_embedding, emb_path)
|
| 573 |
+
input_data['cond_audio']['person1'] = emb_path
|
| 574 |
+
input_data['video_audio'] = sum_audio
|
| 575 |
+
elif 'TTS' in mode_selector:
|
| 576 |
+
if 'human2_voice' not in input_data['tts_audio'].keys():
|
| 577 |
+
new_human_speech1, sum_audio = process_tts_single(input_data['tts_audio']['text'], args.audio_save_dir, input_data['tts_audio']['human1_voice'])
|
| 578 |
+
audio_embedding_1 = get_embedding(new_human_speech1, wav2vec_feature_extractor, audio_encoder)
|
| 579 |
+
emb1_path = os.path.join(args.audio_save_dir, '1.pt')
|
| 580 |
+
torch.save(audio_embedding_1, emb1_path)
|
| 581 |
+
input_data['cond_audio']['person1'] = emb1_path
|
| 582 |
+
input_data['video_audio'] = sum_audio
|
| 583 |
+
else:
|
| 584 |
+
new_human_speech1, new_human_speech2, sum_audio = process_tts_multi(input_data['tts_audio']['text'], args.audio_save_dir, input_data['tts_audio']['human1_voice'], input_data['tts_audio']['human2_voice'])
|
| 585 |
+
audio_embedding_1 = get_embedding(new_human_speech1, wav2vec_feature_extractor, audio_encoder)
|
| 586 |
+
audio_embedding_2 = get_embedding(new_human_speech2, wav2vec_feature_extractor, audio_encoder)
|
| 587 |
+
emb1_path = os.path.join(args.audio_save_dir, '1.pt')
|
| 588 |
+
emb2_path = os.path.join(args.audio_save_dir, '2.pt')
|
| 589 |
+
torch.save(audio_embedding_1, emb1_path)
|
| 590 |
+
torch.save(audio_embedding_2, emb2_path)
|
| 591 |
+
input_data['cond_audio']['person1'] = emb1_path
|
| 592 |
+
input_data['cond_audio']['person2'] = emb2_path
|
| 593 |
+
input_data['video_audio'] = sum_audio
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
# if len(input_data['cond_audio'])==2:
|
| 597 |
+
# new_human_speech1, new_human_speech2, sum_human_speechs = audio_prepare_multi(input_data['cond_audio']['person1'], input_data['cond_audio']['person2'], input_data['audio_type'])
|
| 598 |
+
# audio_embedding_1 = get_embedding(new_human_speech1, wav2vec_feature_extractor, audio_encoder)
|
| 599 |
+
# audio_embedding_2 = get_embedding(new_human_speech2, wav2vec_feature_extractor, audio_encoder)
|
| 600 |
+
# emb1_path = os.path.join(args.audio_save_dir, '1.pt')
|
| 601 |
+
# emb2_path = os.path.join(args.audio_save_dir, '2.pt')
|
| 602 |
+
# sum_audio = os.path.join(args.audio_save_dir, 'sum.wav')
|
| 603 |
+
# sf.write(sum_audio, sum_human_speechs, 16000)
|
| 604 |
+
# torch.save(audio_embedding_1, emb1_path)
|
| 605 |
+
# torch.save(audio_embedding_2, emb2_path)
|
| 606 |
+
# input_data['cond_audio']['person1'] = emb1_path
|
| 607 |
+
# input_data['cond_audio']['person2'] = emb2_path
|
| 608 |
+
# input_data['video_audio'] = sum_audio
|
| 609 |
+
# elif len(input_data['cond_audio'])==1:
|
| 610 |
+
# human_speech = audio_prepare_single(input_data['cond_audio']['person1'])
|
| 611 |
+
# audio_embedding = get_embedding(human_speech, wav2vec_feature_extractor, audio_encoder)
|
| 612 |
+
# emb_path = os.path.join(args.audio_save_dir, '1.pt')
|
| 613 |
+
# sum_audio = os.path.join(args.audio_save_dir, 'sum.wav')
|
| 614 |
+
# sf.write(sum_audio, human_speech, 16000)
|
| 615 |
+
# torch.save(audio_embedding, emb_path)
|
| 616 |
+
# input_data['cond_audio']['person1'] = emb_path
|
| 617 |
+
# input_data['video_audio'] = sum_audio
|
| 618 |
+
|
| 619 |
+
logging.info("Generating video ...")
|
| 620 |
+
video = wan_i2v.generate_infinitetalk(
|
| 621 |
+
input_data,
|
| 622 |
+
size_buckget=resolution_select,
|
| 623 |
+
motion_frame=args.motion_frame,
|
| 624 |
+
frame_num=args.frame_num,
|
| 625 |
+
shift=args.sample_shift,
|
| 626 |
+
sampling_steps=sd_steps,
|
| 627 |
+
text_guide_scale=text_guide_scale,
|
| 628 |
+
audio_guide_scale=audio_guide_scale,
|
| 629 |
+
seed=seed,
|
| 630 |
+
n_prompt=n_prompt,
|
| 631 |
+
offload_model=args.offload_model,
|
| 632 |
+
max_frames_num=args.frame_num if args.mode == 'clip' else 1000,
|
| 633 |
+
color_correction_strength = args.color_correction_strength,
|
| 634 |
+
extra_args=args,
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
if args.save_file is None:
|
| 639 |
+
formatted_time = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 640 |
+
formatted_prompt = input_data['prompt'].replace(" ", "_").replace("/",
|
| 641 |
+
"_")[:50]
|
| 642 |
+
args.save_file = f"{args.task}_{args.size.replace('*','x') if sys.platform=='win32' else args.size}_{args.ulysses_size}_{args.ring_size}_{formatted_prompt}_{formatted_time}"
|
| 643 |
+
|
| 644 |
+
logging.info(f"Saving generated video to {args.save_file}.mp4")
|
| 645 |
+
save_video_ffmpeg(video, args.save_file, [input_data['video_audio']], high_quality_save=False)
|
| 646 |
+
logging.info("Finished.")
|
| 647 |
+
|
| 648 |
+
return args.save_file + '.mp4'
|
| 649 |
+
|
| 650 |
+
def toggle_audio_mode(mode):
|
| 651 |
+
if 'TTS' in mode:
|
| 652 |
+
return [
|
| 653 |
+
gr.Audio(visible=False, interactive=False),
|
| 654 |
+
gr.Audio(visible=False, interactive=False),
|
| 655 |
+
gr.Textbox(visible=True, interactive=True)
|
| 656 |
+
]
|
| 657 |
+
elif 'Single' in mode:
|
| 658 |
+
return [
|
| 659 |
+
gr.Audio(visible=True, interactive=True),
|
| 660 |
+
gr.Audio(visible=False, interactive=False),
|
| 661 |
+
gr.Textbox(visible=False, interactive=False)
|
| 662 |
+
]
|
| 663 |
+
else:
|
| 664 |
+
return [
|
| 665 |
+
gr.Audio(visible=True, interactive=True),
|
| 666 |
+
gr.Audio(visible=True, interactive=True),
|
| 667 |
+
gr.Textbox(visible=False, interactive=False)
|
| 668 |
+
]
|
| 669 |
+
|
| 670 |
+
def show_upload(mode):
|
| 671 |
+
if mode == "SingleImageDriven":
|
| 672 |
+
return gr.update(visible=True), gr.update(visible=False)
|
| 673 |
+
else:
|
| 674 |
+
return gr.update(visible=False), gr.update(visible=True)
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
with gr.Blocks() as demo:
|
| 678 |
+
|
| 679 |
+
gr.Markdown("""
|
| 680 |
+
<div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
|
| 681 |
+
MeiGen-InfiniteTalk
|
| 682 |
+
</div>
|
| 683 |
+
<div style="text-align: center; font-size: 16px; font-weight: normal; margin-bottom: 20px;">
|
| 684 |
+
InfiniteTalk: Audio-driven Video Generation for Spare-Frame Video Dubbing.
|
| 685 |
+
</div>
|
| 686 |
+
<div style="display: flex; justify-content: center; gap: 10px; flex-wrap: wrap;">
|
| 687 |
+
<a href=''><img src='https://img.shields.io/badge/Project-Page-blue'></a>
|
| 688 |
+
<a href=''><img src='https://img.shields.io/badge/%F0%9F%A4%97%20HuggingFace-Model-yellow'></a>
|
| 689 |
+
<a href=''><img src='https://img.shields.io/badge/Paper-Arxiv-red'></a>
|
| 690 |
+
</div>
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
""")
|
| 694 |
+
|
| 695 |
+
with gr.Row():
|
| 696 |
+
with gr.Column(scale=1):
|
| 697 |
+
task_mode = gr.Radio(
|
| 698 |
+
choices=["SingleImageDriven", "VideoDubbing"],
|
| 699 |
+
label="Choose SingleImageDriven task or VideoDubbing task",
|
| 700 |
+
value="VideoDubbing"
|
| 701 |
+
)
|
| 702 |
+
vid2vid_vid = gr.Video(
|
| 703 |
+
label="Upload Input Video",
|
| 704 |
+
visible=True)
|
| 705 |
+
img2vid_image = gr.Image(
|
| 706 |
+
type="filepath",
|
| 707 |
+
label="Upload Input Image",
|
| 708 |
+
elem_id="image_upload",
|
| 709 |
+
visible=False
|
| 710 |
+
)
|
| 711 |
+
img2vid_prompt = gr.Textbox(
|
| 712 |
+
label="Prompt",
|
| 713 |
+
placeholder="Describe the video you want to generate",
|
| 714 |
+
)
|
| 715 |
+
task_mode.change(
|
| 716 |
+
fn=show_upload,
|
| 717 |
+
inputs=task_mode,
|
| 718 |
+
outputs=[img2vid_image, vid2vid_vid]
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
with gr.Accordion("Audio Options", open=True):
|
| 723 |
+
mode_selector = gr.Radio(
|
| 724 |
+
choices=["Single Person(Local File)", "Single Person(TTS)", "Multi Person(Local File, audio add)", "Multi Person(Local File, audio parallel)", "Multi Person(TTS)"],
|
| 725 |
+
label="Select person and audio mode.",
|
| 726 |
+
value="Single Person(Local File)"
|
| 727 |
+
)
|
| 728 |
+
resolution_select = gr.Radio(
|
| 729 |
+
choices=["infinitetalk-480", "infinitetalk-720"],
|
| 730 |
+
label="Select resolution.",
|
| 731 |
+
value="infinitetalk-480"
|
| 732 |
+
)
|
| 733 |
+
img2vid_audio_1 = gr.Audio(label="Conditioning Audio for speaker 1", type="filepath", visible=True)
|
| 734 |
+
img2vid_audio_2 = gr.Audio(label="Conditioning Audio for speaker 2", type="filepath", visible=False)
|
| 735 |
+
tts_text = gr.Textbox(
|
| 736 |
+
label="Text for TTS",
|
| 737 |
+
placeholder="Refer to the format in the examples",
|
| 738 |
+
visible=False,
|
| 739 |
+
interactive=False
|
| 740 |
+
)
|
| 741 |
+
mode_selector.change(
|
| 742 |
+
fn=toggle_audio_mode,
|
| 743 |
+
inputs=mode_selector,
|
| 744 |
+
outputs=[img2vid_audio_1, img2vid_audio_2, tts_text]
|
| 745 |
+
)
|
| 746 |
+
|
| 747 |
+
with gr.Accordion("Advanced Options", open=False):
|
| 748 |
+
with gr.Row():
|
| 749 |
+
sd_steps = gr.Slider(
|
| 750 |
+
label="Diffusion steps",
|
| 751 |
+
minimum=1,
|
| 752 |
+
maximum=1000,
|
| 753 |
+
value=8,
|
| 754 |
+
step=1)
|
| 755 |
+
seed = gr.Slider(
|
| 756 |
+
label="Seed",
|
| 757 |
+
minimum=-1,
|
| 758 |
+
maximum=2147483647,
|
| 759 |
+
step=1,
|
| 760 |
+
value=42)
|
| 761 |
+
with gr.Row():
|
| 762 |
+
text_guide_scale = gr.Slider(
|
| 763 |
+
label="Text Guide scale",
|
| 764 |
+
minimum=0,
|
| 765 |
+
maximum=20,
|
| 766 |
+
value=1.0,
|
| 767 |
+
step=1)
|
| 768 |
+
audio_guide_scale = gr.Slider(
|
| 769 |
+
label="Audio Guide scale",
|
| 770 |
+
minimum=0,
|
| 771 |
+
maximum=20,
|
| 772 |
+
value=2.0,
|
| 773 |
+
step=1)
|
| 774 |
+
with gr.Row():
|
| 775 |
+
human1_voice = gr.Textbox(
|
| 776 |
+
label="Voice for the left person",
|
| 777 |
+
value="weights/Kokoro-82M/voices/am_adam.pt",
|
| 778 |
+
)
|
| 779 |
+
human2_voice = gr.Textbox(
|
| 780 |
+
label="Voice for right person",
|
| 781 |
+
value="weights/Kokoro-82M/voices/af_heart.pt"
|
| 782 |
+
)
|
| 783 |
+
# with gr.Row():
|
| 784 |
+
n_prompt = gr.Textbox(
|
| 785 |
+
label="Negative Prompt",
|
| 786 |
+
placeholder="Describe the negative prompt you want to add",
|
| 787 |
+
value="bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
run_i2v_button = gr.Button("Generate Video")
|
| 791 |
+
|
| 792 |
+
with gr.Column(scale=2):
|
| 793 |
+
result_gallery = gr.Video(
|
| 794 |
+
label='Generated Video', interactive=False, height=600, )
|
| 795 |
+
|
| 796 |
+
gr.Examples(
|
| 797 |
+
examples = [
|
| 798 |
+
['SingleImageDriven', 'examples/single/ref_image.png', None, "A woman is passionately singing into a professional microphone in a recording studio. She wears large black headphones and a dark cardigan over a gray top. Her long, wavy brown hair frames her face as she looks slightly upwards, her mouth open mid-song. The studio is equipped with various audio equipment, including a mixing console and a keyboard, with soundproofing panels on the walls. The lighting is warm and focused on her, creating a professional and intimate atmosphere. A close-up shot captures her expressive performance.", "Single Person(Local File)", "examples/single/1.wav", None, None],
|
| 799 |
+
['VideoDubbing', None, 'examples/single/ref_video.mp4', "A man is talking", "Single Person(Local File)", "examples/single/1.wav", None, None],
|
| 800 |
+
|
| 801 |
+
],
|
| 802 |
+
inputs = [task_mode, img2vid_image, vid2vid_vid, img2vid_prompt, mode_selector, img2vid_audio_1, img2vid_audio_2, tts_text],
|
| 803 |
+
)
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
run_i2v_button.click(
|
| 807 |
+
fn=generate_video,
|
| 808 |
+
inputs=[img2vid_image, vid2vid_vid, task_mode, img2vid_prompt, n_prompt, img2vid_audio_1, img2vid_audio_2,sd_steps, seed, text_guide_scale, audio_guide_scale, mode_selector, tts_text, resolution_select, human1_voice, human2_voice],
|
| 809 |
+
outputs=[result_gallery],
|
| 810 |
+
)
|
| 811 |
+
demo.launch(server_name="0.0.0.0", debug=True, server_port=8418)
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
if __name__ == "__main__":
|
| 817 |
+
args = _parse_args()
|
| 818 |
+
run_graio_demo(args)
|
| 819 |
+
|
generate_infinitetalk.py
ADDED
|
@@ -0,0 +1,663 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import json
|
| 7 |
+
import warnings
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
|
| 10 |
+
warnings.filterwarnings('ignore')
|
| 11 |
+
|
| 12 |
+
import random
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.distributed as dist
|
| 16 |
+
from PIL import Image
|
| 17 |
+
import subprocess
|
| 18 |
+
|
| 19 |
+
import wan
|
| 20 |
+
from wan.configs import SIZE_CONFIGS, SUPPORTED_SIZES, WAN_CONFIGS
|
| 21 |
+
from wan.utils.utils import str2bool, is_video, split_wav_librosa
|
| 22 |
+
from wan.utils.multitalk_utils import save_video_ffmpeg
|
| 23 |
+
from kokoro import KPipeline
|
| 24 |
+
from transformers import Wav2Vec2FeatureExtractor
|
| 25 |
+
from src.audio_analysis.wav2vec2 import Wav2Vec2Model
|
| 26 |
+
from wan.utils.segvideo import shot_detect
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
import librosa
|
| 30 |
+
import pyloudnorm as pyln
|
| 31 |
+
import numpy as np
|
| 32 |
+
from einops import rearrange
|
| 33 |
+
import soundfile as sf
|
| 34 |
+
import re
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _validate_args(args):
|
| 38 |
+
# Basic check
|
| 39 |
+
assert args.ckpt_dir is not None, "Please specify the checkpoint directory."
|
| 40 |
+
assert args.task in WAN_CONFIGS, f"Unsupport task: {args.task}"
|
| 41 |
+
|
| 42 |
+
# The default sampling steps are 40 for image-to-video tasks and 50 for text-to-video tasks.
|
| 43 |
+
if args.sample_steps is None:
|
| 44 |
+
args.sample_steps = 40
|
| 45 |
+
|
| 46 |
+
if args.sample_shift is None:
|
| 47 |
+
if args.size == 'infinitetalk-480':
|
| 48 |
+
args.sample_shift = 7
|
| 49 |
+
elif args.size == 'infinitetalk-720':
|
| 50 |
+
args.sample_shift = 11
|
| 51 |
+
else:
|
| 52 |
+
raise NotImplementedError(f'Not supported size')
|
| 53 |
+
|
| 54 |
+
args.base_seed = args.base_seed if args.base_seed >= 0 else random.randint(
|
| 55 |
+
0, 99999999)
|
| 56 |
+
# Size check
|
| 57 |
+
assert args.size in SUPPORTED_SIZES[
|
| 58 |
+
args.
|
| 59 |
+
task], f"Unsupport size {args.size} for task {args.task}, supported sizes are: {', '.join(SUPPORTED_SIZES[args.task])}"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _parse_args():
|
| 63 |
+
parser = argparse.ArgumentParser(
|
| 64 |
+
description="Generate a image or video from a text prompt or image using Wan"
|
| 65 |
+
)
|
| 66 |
+
parser.add_argument(
|
| 67 |
+
"--task",
|
| 68 |
+
type=str,
|
| 69 |
+
default="infinitetalk-14B",
|
| 70 |
+
choices=list(WAN_CONFIGS.keys()),
|
| 71 |
+
help="The task to run.")
|
| 72 |
+
parser.add_argument(
|
| 73 |
+
"--size",
|
| 74 |
+
type=str,
|
| 75 |
+
default="infinitetalk-480",
|
| 76 |
+
choices=list(SIZE_CONFIGS.keys()),
|
| 77 |
+
help="The buckget size of the generated video. The aspect ratio of the output video will follow that of the input image."
|
| 78 |
+
)
|
| 79 |
+
parser.add_argument(
|
| 80 |
+
"--frame_num",
|
| 81 |
+
type=int,
|
| 82 |
+
default=81,
|
| 83 |
+
help="How many frames to be generated in one clip. The number should be 4n+1"
|
| 84 |
+
)
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--max_frame_num",
|
| 87 |
+
type=int,
|
| 88 |
+
default=1000,
|
| 89 |
+
help="The max frame lenght of the generated video."
|
| 90 |
+
)
|
| 91 |
+
parser.add_argument(
|
| 92 |
+
"--ckpt_dir",
|
| 93 |
+
type=str,
|
| 94 |
+
default=None,
|
| 95 |
+
help="The path to the Wan checkpoint directory.")
|
| 96 |
+
parser.add_argument(
|
| 97 |
+
"--infinitetalk_dir",
|
| 98 |
+
type=str,
|
| 99 |
+
default=None,
|
| 100 |
+
help="The path to the InfiniteTalk checkpoint directory.")
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--quant_dir",
|
| 103 |
+
type=str,
|
| 104 |
+
default=None,
|
| 105 |
+
help="The path to the Wan quant checkpoint directory.")
|
| 106 |
+
parser.add_argument(
|
| 107 |
+
"--wav2vec_dir",
|
| 108 |
+
type=str,
|
| 109 |
+
default=None,
|
| 110 |
+
help="The path to the wav2vec checkpoint directory.")
|
| 111 |
+
parser.add_argument(
|
| 112 |
+
"--dit_path",
|
| 113 |
+
type=str,
|
| 114 |
+
default=None,
|
| 115 |
+
help="The path to the Wan checkpoint directory.")
|
| 116 |
+
parser.add_argument(
|
| 117 |
+
"--lora_dir",
|
| 118 |
+
type=str,
|
| 119 |
+
nargs='+',
|
| 120 |
+
default=None,
|
| 121 |
+
help="The paths to the LoRA checkpoint files."
|
| 122 |
+
)
|
| 123 |
+
parser.add_argument(
|
| 124 |
+
"--lora_scale",
|
| 125 |
+
type=float,
|
| 126 |
+
nargs='+',
|
| 127 |
+
default=[1.2],
|
| 128 |
+
help="Controls how much to influence the outputs with the LoRA parameters. Accepts multiple float values."
|
| 129 |
+
)
|
| 130 |
+
parser.add_argument(
|
| 131 |
+
"--offload_model",
|
| 132 |
+
type=str2bool,
|
| 133 |
+
default=None,
|
| 134 |
+
help="Whether to offload the model to CPU after each model forward, reducing GPU memory usage."
|
| 135 |
+
)
|
| 136 |
+
parser.add_argument(
|
| 137 |
+
"--ulysses_size",
|
| 138 |
+
type=int,
|
| 139 |
+
default=1,
|
| 140 |
+
help="The size of the ulysses parallelism in DiT.")
|
| 141 |
+
parser.add_argument(
|
| 142 |
+
"--ring_size",
|
| 143 |
+
type=int,
|
| 144 |
+
default=1,
|
| 145 |
+
help="The size of the ring attention parallelism in DiT.")
|
| 146 |
+
parser.add_argument(
|
| 147 |
+
"--t5_fsdp",
|
| 148 |
+
action="store_true",
|
| 149 |
+
default=False,
|
| 150 |
+
help="Whether to use FSDP for T5.")
|
| 151 |
+
parser.add_argument(
|
| 152 |
+
"--t5_cpu",
|
| 153 |
+
action="store_true",
|
| 154 |
+
default=False,
|
| 155 |
+
help="Whether to place T5 model on CPU.")
|
| 156 |
+
parser.add_argument(
|
| 157 |
+
"--dit_fsdp",
|
| 158 |
+
action="store_true",
|
| 159 |
+
default=False,
|
| 160 |
+
help="Whether to use FSDP for DiT.")
|
| 161 |
+
parser.add_argument(
|
| 162 |
+
"--save_file",
|
| 163 |
+
type=str,
|
| 164 |
+
default=None,
|
| 165 |
+
help="The file to save the generated image or video to.")
|
| 166 |
+
parser.add_argument(
|
| 167 |
+
"--audio_save_dir",
|
| 168 |
+
type=str,
|
| 169 |
+
default='save_audio',
|
| 170 |
+
help="The path to save the audio embedding.")
|
| 171 |
+
parser.add_argument(
|
| 172 |
+
"--base_seed",
|
| 173 |
+
type=int,
|
| 174 |
+
default=42,
|
| 175 |
+
help="The seed to use for generating the image or video.")
|
| 176 |
+
parser.add_argument(
|
| 177 |
+
"--input_json",
|
| 178 |
+
type=str,
|
| 179 |
+
default='examples.json',
|
| 180 |
+
help="[meta file] The condition path to generate the video.")
|
| 181 |
+
parser.add_argument(
|
| 182 |
+
"--motion_frame",
|
| 183 |
+
type=int,
|
| 184 |
+
default=9,
|
| 185 |
+
help="Driven frame length used in the mode of long video genration.")
|
| 186 |
+
parser.add_argument(
|
| 187 |
+
"--mode",
|
| 188 |
+
type=str,
|
| 189 |
+
default="clip",
|
| 190 |
+
choices=['clip', 'streaming'],
|
| 191 |
+
help="clip: generate one video chunk, streaming: long video generation")
|
| 192 |
+
parser.add_argument(
|
| 193 |
+
"--sample_steps", type=int, default=None, help="The sampling steps.")
|
| 194 |
+
parser.add_argument(
|
| 195 |
+
"--sample_shift",
|
| 196 |
+
type=float,
|
| 197 |
+
default=None,
|
| 198 |
+
help="Sampling shift factor for flow matching schedulers.")
|
| 199 |
+
parser.add_argument(
|
| 200 |
+
"--sample_text_guide_scale",
|
| 201 |
+
type=float,
|
| 202 |
+
default=5.0,
|
| 203 |
+
help="Classifier free guidance scale for text control.")
|
| 204 |
+
parser.add_argument(
|
| 205 |
+
"--sample_audio_guide_scale",
|
| 206 |
+
type=float,
|
| 207 |
+
default=4.0,
|
| 208 |
+
help="Classifier free guidance scale for audio control.")
|
| 209 |
+
parser.add_argument(
|
| 210 |
+
"--num_persistent_param_in_dit",
|
| 211 |
+
type=int,
|
| 212 |
+
default=None,
|
| 213 |
+
required=False,
|
| 214 |
+
help="Maximum parameter quantity retained in video memory, small number to reduce VRAM required",
|
| 215 |
+
)
|
| 216 |
+
parser.add_argument(
|
| 217 |
+
"--audio_mode",
|
| 218 |
+
type=str,
|
| 219 |
+
default="localfile",
|
| 220 |
+
choices=['localfile', 'tts'],
|
| 221 |
+
help="localfile: audio from local wav file, tts: audio from TTS")
|
| 222 |
+
parser.add_argument(
|
| 223 |
+
"--use_teacache",
|
| 224 |
+
action="store_true",
|
| 225 |
+
default=False,
|
| 226 |
+
help="Enable teacache for video generation."
|
| 227 |
+
)
|
| 228 |
+
parser.add_argument(
|
| 229 |
+
"--teacache_thresh",
|
| 230 |
+
type=float,
|
| 231 |
+
default=0.2,
|
| 232 |
+
help="Threshold for teacache."
|
| 233 |
+
)
|
| 234 |
+
parser.add_argument(
|
| 235 |
+
"--use_apg",
|
| 236 |
+
action="store_true",
|
| 237 |
+
default=False,
|
| 238 |
+
help="Enable adaptive projected guidance for video generation (APG)."
|
| 239 |
+
)
|
| 240 |
+
parser.add_argument(
|
| 241 |
+
"--apg_momentum",
|
| 242 |
+
type=float,
|
| 243 |
+
default=-0.75,
|
| 244 |
+
help="Momentum used in adaptive projected guidance (APG)."
|
| 245 |
+
)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--apg_norm_threshold",
|
| 248 |
+
type=float,
|
| 249 |
+
default=55,
|
| 250 |
+
help="Norm threshold used in adaptive projected guidance (APG)."
|
| 251 |
+
)
|
| 252 |
+
parser.add_argument(
|
| 253 |
+
"--color_correction_strength",
|
| 254 |
+
type=float,
|
| 255 |
+
default=1.0,
|
| 256 |
+
help="strength for color correction [0.0 -- 1.0]."
|
| 257 |
+
)
|
| 258 |
+
parser.add_argument(
|
| 259 |
+
"--scene_seg",
|
| 260 |
+
action="store_true",
|
| 261 |
+
default=False,
|
| 262 |
+
help="Enable scene segmentation for input video."
|
| 263 |
+
)
|
| 264 |
+
parser.add_argument(
|
| 265 |
+
"--quant",
|
| 266 |
+
type=str,
|
| 267 |
+
default=None,
|
| 268 |
+
help="Quantization type, must be 'int8' or 'fp8'."
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
args = parser.parse_args()
|
| 272 |
+
|
| 273 |
+
_validate_args(args)
|
| 274 |
+
|
| 275 |
+
return args
|
| 276 |
+
|
| 277 |
+
def custom_init(device, wav2vec):
|
| 278 |
+
audio_encoder = Wav2Vec2Model.from_pretrained(wav2vec, local_files_only=True).to(device)
|
| 279 |
+
audio_encoder.feature_extractor._freeze_parameters()
|
| 280 |
+
wav2vec_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(wav2vec, local_files_only=True)
|
| 281 |
+
return wav2vec_feature_extractor, audio_encoder
|
| 282 |
+
|
| 283 |
+
def loudness_norm(audio_array, sr=16000, lufs=-23):
|
| 284 |
+
meter = pyln.Meter(sr)
|
| 285 |
+
loudness = meter.integrated_loudness(audio_array)
|
| 286 |
+
if abs(loudness) > 100:
|
| 287 |
+
return audio_array
|
| 288 |
+
normalized_audio = pyln.normalize.loudness(audio_array, loudness, lufs)
|
| 289 |
+
return normalized_audio
|
| 290 |
+
|
| 291 |
+
def audio_prepare_multi(left_path, right_path, audio_type, sample_rate=16000):
|
| 292 |
+
|
| 293 |
+
if not (left_path=='None' or right_path=='None'):
|
| 294 |
+
human_speech_array1 = audio_prepare_single(left_path)
|
| 295 |
+
human_speech_array2 = audio_prepare_single(right_path)
|
| 296 |
+
elif left_path=='None':
|
| 297 |
+
human_speech_array2 = audio_prepare_single(right_path)
|
| 298 |
+
human_speech_array1 = np.zeros(human_speech_array2.shape[0])
|
| 299 |
+
elif right_path=='None':
|
| 300 |
+
human_speech_array1 = audio_prepare_single(left_path)
|
| 301 |
+
human_speech_array2 = np.zeros(human_speech_array1.shape[0])
|
| 302 |
+
|
| 303 |
+
if audio_type=='para':
|
| 304 |
+
new_human_speech1 = human_speech_array1
|
| 305 |
+
new_human_speech2 = human_speech_array2
|
| 306 |
+
elif audio_type=='add':
|
| 307 |
+
new_human_speech1 = np.concatenate([human_speech_array1[: human_speech_array1.shape[0]], np.zeros(human_speech_array2.shape[0])])
|
| 308 |
+
new_human_speech2 = np.concatenate([np.zeros(human_speech_array1.shape[0]), human_speech_array2[:human_speech_array2.shape[0]]])
|
| 309 |
+
sum_human_speechs = new_human_speech1 + new_human_speech2
|
| 310 |
+
return new_human_speech1, new_human_speech2, sum_human_speechs
|
| 311 |
+
|
| 312 |
+
def _init_logging(rank):
|
| 313 |
+
# logging
|
| 314 |
+
if rank == 0:
|
| 315 |
+
# set format
|
| 316 |
+
logging.basicConfig(
|
| 317 |
+
level=logging.INFO,
|
| 318 |
+
format="[%(asctime)s] %(levelname)s: %(message)s",
|
| 319 |
+
handlers=[logging.StreamHandler(stream=sys.stdout)])
|
| 320 |
+
else:
|
| 321 |
+
logging.basicConfig(level=logging.ERROR)
|
| 322 |
+
|
| 323 |
+
def get_embedding(speech_array, wav2vec_feature_extractor, audio_encoder, sr=16000, device='cpu'):
|
| 324 |
+
audio_duration = len(speech_array) / sr
|
| 325 |
+
video_length = audio_duration * 25 # Assume the video fps is 25
|
| 326 |
+
|
| 327 |
+
# wav2vec_feature_extractor
|
| 328 |
+
audio_feature = np.squeeze(
|
| 329 |
+
wav2vec_feature_extractor(speech_array, sampling_rate=sr).input_values
|
| 330 |
+
)
|
| 331 |
+
audio_feature = torch.from_numpy(audio_feature).float().to(device=device)
|
| 332 |
+
audio_feature = audio_feature.unsqueeze(0)
|
| 333 |
+
|
| 334 |
+
# audio encoder
|
| 335 |
+
with torch.no_grad():
|
| 336 |
+
embeddings = audio_encoder(audio_feature, seq_len=int(video_length), output_hidden_states=True)
|
| 337 |
+
|
| 338 |
+
if len(embeddings) == 0:
|
| 339 |
+
print("Fail to extract audio embedding")
|
| 340 |
+
return None
|
| 341 |
+
|
| 342 |
+
audio_emb = torch.stack(embeddings.hidden_states[1:], dim=1).squeeze(0)
|
| 343 |
+
audio_emb = rearrange(audio_emb, "b s d -> s b d")
|
| 344 |
+
|
| 345 |
+
audio_emb = audio_emb.cpu().detach()
|
| 346 |
+
return audio_emb
|
| 347 |
+
|
| 348 |
+
def extract_audio_from_video(filename, sample_rate):
|
| 349 |
+
raw_audio_path = filename.split('/')[-1].split('.')[0]+'.wav'
|
| 350 |
+
ffmpeg_command = [
|
| 351 |
+
"ffmpeg",
|
| 352 |
+
"-y",
|
| 353 |
+
"-i",
|
| 354 |
+
str(filename),
|
| 355 |
+
"-vn",
|
| 356 |
+
"-acodec",
|
| 357 |
+
"pcm_s16le",
|
| 358 |
+
"-ar",
|
| 359 |
+
"16000",
|
| 360 |
+
"-ac",
|
| 361 |
+
"2",
|
| 362 |
+
str(raw_audio_path),
|
| 363 |
+
]
|
| 364 |
+
subprocess.run(ffmpeg_command, check=True)
|
| 365 |
+
human_speech_array, sr = librosa.load(raw_audio_path, sr=sample_rate)
|
| 366 |
+
human_speech_array = loudness_norm(human_speech_array, sr)
|
| 367 |
+
os.remove(raw_audio_path)
|
| 368 |
+
|
| 369 |
+
return human_speech_array
|
| 370 |
+
|
| 371 |
+
def audio_prepare_single(audio_path, sample_rate=16000):
|
| 372 |
+
ext = os.path.splitext(audio_path)[1].lower()
|
| 373 |
+
if ext in ['.mp4', '.mov', '.avi', '.mkv']:
|
| 374 |
+
human_speech_array = extract_audio_from_video(audio_path, sample_rate)
|
| 375 |
+
return human_speech_array
|
| 376 |
+
else:
|
| 377 |
+
human_speech_array, sr = librosa.load(audio_path, sr=sample_rate)
|
| 378 |
+
human_speech_array = loudness_norm(human_speech_array, sr)
|
| 379 |
+
return human_speech_array
|
| 380 |
+
|
| 381 |
+
def process_tts_single(text, save_dir, voice1):
|
| 382 |
+
s1_sentences = []
|
| 383 |
+
|
| 384 |
+
pipeline = KPipeline(lang_code='a', repo_id='weights/Kokoro-82M')
|
| 385 |
+
|
| 386 |
+
voice_tensor = torch.load(voice1, weights_only=True)
|
| 387 |
+
generator = pipeline(
|
| 388 |
+
text, voice=voice_tensor, # <= change voice here
|
| 389 |
+
speed=1, split_pattern=r'\n+'
|
| 390 |
+
)
|
| 391 |
+
audios = []
|
| 392 |
+
for i, (gs, ps, audio) in enumerate(generator):
|
| 393 |
+
audios.append(audio)
|
| 394 |
+
audios = torch.concat(audios, dim=0)
|
| 395 |
+
s1_sentences.append(audios)
|
| 396 |
+
s1_sentences = torch.concat(s1_sentences, dim=0)
|
| 397 |
+
save_path1 =f'{save_dir}/s1.wav'
|
| 398 |
+
sf.write(save_path1, s1_sentences, 24000) # save each audio file
|
| 399 |
+
s1, _ = librosa.load(save_path1, sr=16000)
|
| 400 |
+
return s1, save_path1
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def process_tts_multi(text, save_dir, voice1, voice2):
|
| 405 |
+
pattern = r'\(s(\d+)\)\s*(.*?)(?=\s*\(s\d+\)|$)'
|
| 406 |
+
matches = re.findall(pattern, text, re.DOTALL)
|
| 407 |
+
|
| 408 |
+
s1_sentences = []
|
| 409 |
+
s2_sentences = []
|
| 410 |
+
|
| 411 |
+
pipeline = KPipeline(lang_code='a', repo_id='weights/Kokoro-82M')
|
| 412 |
+
for idx, (speaker, content) in enumerate(matches):
|
| 413 |
+
if speaker == '1':
|
| 414 |
+
voice_tensor = torch.load(voice1, weights_only=True)
|
| 415 |
+
generator = pipeline(
|
| 416 |
+
content, voice=voice_tensor, # <= change voice here
|
| 417 |
+
speed=1, split_pattern=r'\n+'
|
| 418 |
+
)
|
| 419 |
+
audios = []
|
| 420 |
+
for i, (gs, ps, audio) in enumerate(generator):
|
| 421 |
+
audios.append(audio)
|
| 422 |
+
audios = torch.concat(audios, dim=0)
|
| 423 |
+
s1_sentences.append(audios)
|
| 424 |
+
s2_sentences.append(torch.zeros_like(audios))
|
| 425 |
+
elif speaker == '2':
|
| 426 |
+
voice_tensor = torch.load(voice2, weights_only=True)
|
| 427 |
+
generator = pipeline(
|
| 428 |
+
content, voice=voice_tensor, # <= change voice here
|
| 429 |
+
speed=1, split_pattern=r'\n+'
|
| 430 |
+
)
|
| 431 |
+
audios = []
|
| 432 |
+
for i, (gs, ps, audio) in enumerate(generator):
|
| 433 |
+
audios.append(audio)
|
| 434 |
+
audios = torch.concat(audios, dim=0)
|
| 435 |
+
s2_sentences.append(audios)
|
| 436 |
+
s1_sentences.append(torch.zeros_like(audios))
|
| 437 |
+
|
| 438 |
+
s1_sentences = torch.concat(s1_sentences, dim=0)
|
| 439 |
+
s2_sentences = torch.concat(s2_sentences, dim=0)
|
| 440 |
+
sum_sentences = s1_sentences + s2_sentences
|
| 441 |
+
save_path1 =f'{save_dir}/s1.wav'
|
| 442 |
+
save_path2 =f'{save_dir}/s2.wav'
|
| 443 |
+
save_path_sum = f'{save_dir}/sum.wav'
|
| 444 |
+
sf.write(save_path1, s1_sentences, 24000) # save each audio file
|
| 445 |
+
sf.write(save_path2, s2_sentences, 24000)
|
| 446 |
+
sf.write(save_path_sum, sum_sentences, 24000)
|
| 447 |
+
|
| 448 |
+
s1, _ = librosa.load(save_path1, sr=16000)
|
| 449 |
+
s2, _ = librosa.load(save_path2, sr=16000)
|
| 450 |
+
# sum, _ = librosa.load(save_path_sum, sr=16000)
|
| 451 |
+
return s1, s2, save_path_sum
|
| 452 |
+
|
| 453 |
+
def generate(args):
|
| 454 |
+
rank = int(os.getenv("RANK", 0))
|
| 455 |
+
world_size = int(os.getenv("WORLD_SIZE", 1))
|
| 456 |
+
local_rank = int(os.getenv("LOCAL_RANK", 0))
|
| 457 |
+
device = local_rank
|
| 458 |
+
_init_logging(rank)
|
| 459 |
+
|
| 460 |
+
if args.offload_model is None:
|
| 461 |
+
args.offload_model = False if world_size > 1 else True
|
| 462 |
+
logging.info(
|
| 463 |
+
f"offload_model is not specified, set to {args.offload_model}.")
|
| 464 |
+
if world_size > 1:
|
| 465 |
+
torch.cuda.set_device(local_rank)
|
| 466 |
+
dist.init_process_group(
|
| 467 |
+
backend="nccl",
|
| 468 |
+
init_method="env://",
|
| 469 |
+
rank=rank,
|
| 470 |
+
world_size=world_size)
|
| 471 |
+
else:
|
| 472 |
+
assert not (
|
| 473 |
+
args.t5_fsdp or args.dit_fsdp
|
| 474 |
+
), f"t5_fsdp and dit_fsdp are not supported in non-distributed environments."
|
| 475 |
+
assert not (
|
| 476 |
+
args.ulysses_size > 1 or args.ring_size > 1
|
| 477 |
+
), f"context parallel are not supported in non-distributed environments."
|
| 478 |
+
|
| 479 |
+
if args.ulysses_size > 1 or args.ring_size > 1:
|
| 480 |
+
assert args.ulysses_size * args.ring_size == world_size, f"The number of ulysses_size and ring_size should be equal to the world size."
|
| 481 |
+
from xfuser.core.distributed import (
|
| 482 |
+
init_distributed_environment,
|
| 483 |
+
initialize_model_parallel,
|
| 484 |
+
)
|
| 485 |
+
init_distributed_environment(
|
| 486 |
+
rank=dist.get_rank(), world_size=dist.get_world_size())
|
| 487 |
+
|
| 488 |
+
initialize_model_parallel(
|
| 489 |
+
sequence_parallel_degree=dist.get_world_size(),
|
| 490 |
+
ring_degree=args.ring_size,
|
| 491 |
+
ulysses_degree=args.ulysses_size,
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
# TODO: use prompt refine
|
| 495 |
+
# if args.use_prompt_extend:
|
| 496 |
+
# if args.prompt_extend_method == "dashscope":
|
| 497 |
+
# prompt_expander = DashScopePromptExpander(
|
| 498 |
+
# model_name=args.prompt_extend_model,
|
| 499 |
+
# is_vl="i2v" in args.task or "flf2v" in args.task)
|
| 500 |
+
# elif args.prompt_extend_method == "local_qwen":
|
| 501 |
+
# prompt_expander = QwenPromptExpander(
|
| 502 |
+
# model_name=args.prompt_extend_model,
|
| 503 |
+
# is_vl="i2v" in args.task,
|
| 504 |
+
# device=rank)
|
| 505 |
+
# else:
|
| 506 |
+
# raise NotImplementedError(
|
| 507 |
+
# f"Unsupport prompt_extend_method: {args.prompt_extend_method}")
|
| 508 |
+
|
| 509 |
+
cfg = WAN_CONFIGS[args.task]
|
| 510 |
+
if args.ulysses_size > 1:
|
| 511 |
+
assert cfg.num_heads % args.ulysses_size == 0, f"`{cfg.num_heads=}` cannot be divided evenly by `{args.ulysses_size=}`."
|
| 512 |
+
|
| 513 |
+
logging.info(f"Generation job args: {args}")
|
| 514 |
+
logging.info(f"Generation model config: {cfg}")
|
| 515 |
+
|
| 516 |
+
if dist.is_initialized():
|
| 517 |
+
base_seed = [args.base_seed] if rank == 0 else [None]
|
| 518 |
+
dist.broadcast_object_list(base_seed, src=0)
|
| 519 |
+
args.base_seed = base_seed[0]
|
| 520 |
+
|
| 521 |
+
assert args.task == "infinitetalk-14B", 'You should choose infinitetalk in args.task.'
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
logging.info("Creating infinitetalk pipeline.")
|
| 525 |
+
wan_i2v = wan.InfiniteTalkPipeline(
|
| 526 |
+
config=cfg,
|
| 527 |
+
checkpoint_dir=args.ckpt_dir,
|
| 528 |
+
quant_dir=args.quant_dir,
|
| 529 |
+
device_id=device,
|
| 530 |
+
rank=rank,
|
| 531 |
+
t5_fsdp=args.t5_fsdp,
|
| 532 |
+
dit_fsdp=args.dit_fsdp,
|
| 533 |
+
use_usp=(args.ulysses_size > 1 or args.ring_size > 1),
|
| 534 |
+
t5_cpu=args.t5_cpu,
|
| 535 |
+
lora_dir=args.lora_dir,
|
| 536 |
+
lora_scales=args.lora_scale,
|
| 537 |
+
quant=args.quant,
|
| 538 |
+
dit_path=args.dit_path,
|
| 539 |
+
infinitetalk_dir=args.infinitetalk_dir
|
| 540 |
+
)
|
| 541 |
+
if args.num_persistent_param_in_dit is not None:
|
| 542 |
+
wan_i2v.vram_management = True
|
| 543 |
+
wan_i2v.enable_vram_management(
|
| 544 |
+
num_persistent_param_in_dit=args.num_persistent_param_in_dit
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
generated_list = []
|
| 548 |
+
with open(args.input_json, 'r', encoding='utf-8') as f:
|
| 549 |
+
input_data = json.load(f)
|
| 550 |
+
|
| 551 |
+
wav2vec_feature_extractor, audio_encoder= custom_init('cpu', args.wav2vec_dir)
|
| 552 |
+
args.audio_save_dir = os.path.join(args.audio_save_dir, input_data['cond_video'].split('/')[-1].split('.')[0])
|
| 553 |
+
os.makedirs(args.audio_save_dir,exist_ok=True)
|
| 554 |
+
|
| 555 |
+
conds_list = []
|
| 556 |
+
|
| 557 |
+
if args.scene_seg and is_video(input_data['cond_video']):
|
| 558 |
+
time_list, cond_list = shot_detect(input_data['cond_video'], args.audio_save_dir)
|
| 559 |
+
if len(time_list)==0:
|
| 560 |
+
conds_list.append([input_data['cond_video']])
|
| 561 |
+
conds_list.append([input_data['cond_audio']['person1']])
|
| 562 |
+
if len(input_data['cond_audio'])==2:
|
| 563 |
+
conds_list.append([input_data['cond_audio']['person2']])
|
| 564 |
+
else:
|
| 565 |
+
audio1_list = split_wav_librosa(input_data['cond_audio']['person1'], time_list, args.audio_save_dir)
|
| 566 |
+
conds_list.append(cond_list)
|
| 567 |
+
conds_list.append(audio1_list)
|
| 568 |
+
if len(input_data['cond_audio'])==2:
|
| 569 |
+
audio2_list = split_wav_librosa(input_data['cond_audio']['person2'], time_list, args.audio_save_dir)
|
| 570 |
+
conds_list.append(audio2_list)
|
| 571 |
+
else:
|
| 572 |
+
conds_list.append([input_data['cond_video']])
|
| 573 |
+
conds_list.append([input_data['cond_audio']['person1']])
|
| 574 |
+
if len(input_data['cond_audio'])==2:
|
| 575 |
+
conds_list.append([input_data['cond_audio']['person2']])
|
| 576 |
+
|
| 577 |
+
if len(input_data['cond_audio'])==2:
|
| 578 |
+
new_human_speech1, new_human_speech2, sum_human_speechs = audio_prepare_multi(input_data['cond_audio']['person1'], input_data['cond_audio']['person2'], input_data['audio_type'])
|
| 579 |
+
sum_audio = os.path.join(args.audio_save_dir, 'sum_all.wav')
|
| 580 |
+
sf.write(sum_audio, sum_human_speechs, 16000)
|
| 581 |
+
input_data['video_audio'] = sum_audio
|
| 582 |
+
else:
|
| 583 |
+
human_speech = audio_prepare_single(input_data['cond_audio']['person1'])
|
| 584 |
+
sum_audio = os.path.join(args.audio_save_dir, 'sum_all.wav')
|
| 585 |
+
sf.write(sum_audio, human_speech, 16000)
|
| 586 |
+
input_data['video_audio'] = sum_audio
|
| 587 |
+
logging.info("Generating video ...")
|
| 588 |
+
|
| 589 |
+
for idx, items in enumerate(zip(*conds_list)):
|
| 590 |
+
print(items)
|
| 591 |
+
input_clip = {}
|
| 592 |
+
input_clip['prompt'] = input_data['prompt']
|
| 593 |
+
input_clip['cond_video'] = items[0]
|
| 594 |
+
|
| 595 |
+
if 'audio_type' in input_data:
|
| 596 |
+
input_clip['audio_type'] = input_data['audio_type']
|
| 597 |
+
if 'bbox' in input_data:
|
| 598 |
+
input_clip['bbox'] = input_data['bbox']
|
| 599 |
+
cond_audio = {}
|
| 600 |
+
if args.audio_mode=='localfile':
|
| 601 |
+
if len(input_data['cond_audio'])==2:
|
| 602 |
+
new_human_speech1, new_human_speech2, sum_human_speechs = audio_prepare_multi(items[1], items[2], input_data['audio_type'])
|
| 603 |
+
audio_embedding_1 = get_embedding(new_human_speech1, wav2vec_feature_extractor, audio_encoder)
|
| 604 |
+
audio_embedding_2 = get_embedding(new_human_speech2, wav2vec_feature_extractor, audio_encoder)
|
| 605 |
+
emb1_path = os.path.join(args.audio_save_dir, '1.pt')
|
| 606 |
+
emb2_path = os.path.join(args.audio_save_dir, '2.pt')
|
| 607 |
+
sum_audio = os.path.join(args.audio_save_dir, 'sum.wav')
|
| 608 |
+
sf.write(sum_audio, sum_human_speechs, 16000)
|
| 609 |
+
torch.save(audio_embedding_1, emb1_path)
|
| 610 |
+
torch.save(audio_embedding_2, emb2_path)
|
| 611 |
+
cond_audio['person1'] = emb1_path
|
| 612 |
+
cond_audio['person2'] = emb2_path
|
| 613 |
+
input_clip['video_audio'] = sum_audio
|
| 614 |
+
v_length = audio_embedding_1.shape[0]
|
| 615 |
+
elif len(input_data['cond_audio'])==1:
|
| 616 |
+
human_speech = audio_prepare_single(items[1])
|
| 617 |
+
audio_embedding = get_embedding(human_speech, wav2vec_feature_extractor, audio_encoder)
|
| 618 |
+
emb_path = os.path.join(args.audio_save_dir, '1.pt')
|
| 619 |
+
sum_audio = os.path.join(args.audio_save_dir, 'sum.wav')
|
| 620 |
+
sf.write(sum_audio, human_speech, 16000)
|
| 621 |
+
torch.save(audio_embedding, emb_path)
|
| 622 |
+
cond_audio['person1'] = emb_path
|
| 623 |
+
input_clip['video_audio'] = sum_audio
|
| 624 |
+
v_length = audio_embedding.shape[0]
|
| 625 |
+
|
| 626 |
+
input_clip['cond_audio'] = cond_audio
|
| 627 |
+
|
| 628 |
+
video = wan_i2v.generate_infinitetalk(
|
| 629 |
+
input_clip,
|
| 630 |
+
size_buckget=args.size,
|
| 631 |
+
motion_frame=args.motion_frame,
|
| 632 |
+
frame_num=args.frame_num,
|
| 633 |
+
shift=args.sample_shift,
|
| 634 |
+
sampling_steps=args.sample_steps,
|
| 635 |
+
text_guide_scale=args.sample_text_guide_scale,
|
| 636 |
+
audio_guide_scale=args.sample_audio_guide_scale,
|
| 637 |
+
seed=args.base_seed,
|
| 638 |
+
offload_model=args.offload_model,
|
| 639 |
+
max_frames_num=args.frame_num if args.mode == 'clip' else args.max_frame_num,
|
| 640 |
+
color_correction_strength = args.color_correction_strength,
|
| 641 |
+
extra_args=args,
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
generated_list.append(video)
|
| 645 |
+
|
| 646 |
+
if rank == 0:
|
| 647 |
+
|
| 648 |
+
if args.save_file is None:
|
| 649 |
+
formatted_time = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 650 |
+
formatted_prompt = input_clip['prompt'].replace(" ", "_").replace("/",
|
| 651 |
+
"_")[:50]
|
| 652 |
+
args.save_file = f"{args.task}_{args.size.replace('*','x') if sys.platform=='win32' else args.size}_{args.ulysses_size}_{args.ring_size}_{formatted_prompt}_{formatted_time}"
|
| 653 |
+
|
| 654 |
+
sum_video = torch.cat(generated_list, dim=1)
|
| 655 |
+
save_video_ffmpeg(sum_video, args.save_file, [input_data['video_audio']], high_quality_save=False)
|
| 656 |
+
|
| 657 |
+
logging.info(f"Saving generated video to {args.save_file}.mp4")
|
| 658 |
+
logging.info("Finished.")
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
if __name__ == "__main__":
|
| 662 |
+
args = _parse_args()
|
| 663 |
+
generate(args)
|
kokoro/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__version__ = '0.9.4'
|
| 2 |
+
|
| 3 |
+
from loguru import logger
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
# Remove default handler
|
| 7 |
+
logger.remove()
|
| 8 |
+
|
| 9 |
+
# Add custom handler with clean format including module and line number
|
| 10 |
+
logger.add(
|
| 11 |
+
sys.stderr,
|
| 12 |
+
format="<green>{time:HH:mm:ss}</green> | <cyan>{module:>16}:{line}</cyan> | <level>{level: >8}</level> | <level>{message}</level>",
|
| 13 |
+
colorize=True,
|
| 14 |
+
level="INFO" # "DEBUG" to enable logger.debug("message") and up prints
|
| 15 |
+
# "ERROR" to enable only logger.error("message") prints
|
| 16 |
+
# etc
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
# Disable before release or as needed
|
| 20 |
+
logger.disable("kokoro")
|
| 21 |
+
|
| 22 |
+
from .model import KModel
|
| 23 |
+
from .pipeline import KPipeline
|
kokoro/__main__.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Kokoro TTS CLI
|
| 2 |
+
Example usage:
|
| 3 |
+
python3 -m kokoro --text "The sky above the port was the color of television, tuned to a dead channel." -o file.wav --debug
|
| 4 |
+
|
| 5 |
+
echo "Bom dia mundo, como vão vocês" > text.txt
|
| 6 |
+
python3 -m kokoro -i text.txt -l p --voice pm_alex > audio.wav
|
| 7 |
+
|
| 8 |
+
Common issues:
|
| 9 |
+
pip not installed: `uv pip install pip`
|
| 10 |
+
(Temporary workaround while https://github.com/explosion/spaCy/issues/13747 is not fixed)
|
| 11 |
+
|
| 12 |
+
espeak not installed: `apt-get install espeak-ng`
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import wave
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Generator, TYPE_CHECKING
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
from loguru import logger
|
| 22 |
+
|
| 23 |
+
languages = [
|
| 24 |
+
"a", # American English
|
| 25 |
+
"b", # British English
|
| 26 |
+
"h", # Hindi
|
| 27 |
+
"e", # Spanish
|
| 28 |
+
"f", # French
|
| 29 |
+
"i", # Italian
|
| 30 |
+
"p", # Brazilian Portuguese
|
| 31 |
+
"j", # Japanese
|
| 32 |
+
"z", # Mandarin Chinese
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
if TYPE_CHECKING:
|
| 36 |
+
from kokoro import KPipeline
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def generate_audio(
|
| 40 |
+
text: str, kokoro_language: str, voice: str, speed=1
|
| 41 |
+
) -> Generator["KPipeline.Result", None, None]:
|
| 42 |
+
from kokoro import KPipeline
|
| 43 |
+
|
| 44 |
+
if not voice.startswith(kokoro_language):
|
| 45 |
+
logger.warning(f"Voice {voice} is not made for language {kokoro_language}")
|
| 46 |
+
pipeline = KPipeline(lang_code=kokoro_language)
|
| 47 |
+
yield from pipeline(text, voice=voice, speed=speed, split_pattern=r"\n+")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def generate_and_save_audio(
|
| 51 |
+
output_file: Path, text: str, kokoro_language: str, voice: str, speed=1
|
| 52 |
+
) -> None:
|
| 53 |
+
with wave.open(str(output_file.resolve()), "wb") as wav_file:
|
| 54 |
+
wav_file.setnchannels(1) # Mono audio
|
| 55 |
+
wav_file.setsampwidth(2) # 2 bytes per sample (16-bit audio)
|
| 56 |
+
wav_file.setframerate(24000) # Sample rate
|
| 57 |
+
|
| 58 |
+
for result in generate_audio(
|
| 59 |
+
text, kokoro_language=kokoro_language, voice=voice, speed=speed
|
| 60 |
+
):
|
| 61 |
+
logger.debug(result.phonemes)
|
| 62 |
+
if result.audio is None:
|
| 63 |
+
continue
|
| 64 |
+
audio_bytes = (result.audio.numpy() * 32767).astype(np.int16).tobytes()
|
| 65 |
+
wav_file.writeframes(audio_bytes)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def main() -> None:
|
| 69 |
+
parser = argparse.ArgumentParser()
|
| 70 |
+
parser.add_argument(
|
| 71 |
+
"-m",
|
| 72 |
+
"--voice",
|
| 73 |
+
default="af_heart",
|
| 74 |
+
help="Voice to use",
|
| 75 |
+
)
|
| 76 |
+
parser.add_argument(
|
| 77 |
+
"-l",
|
| 78 |
+
"--language",
|
| 79 |
+
help="Language to use (defaults to the one corresponding to the voice)",
|
| 80 |
+
choices=languages,
|
| 81 |
+
)
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"-o",
|
| 84 |
+
"--output-file",
|
| 85 |
+
"--output_file",
|
| 86 |
+
type=Path,
|
| 87 |
+
help="Path to output WAV file",
|
| 88 |
+
required=True,
|
| 89 |
+
)
|
| 90 |
+
parser.add_argument(
|
| 91 |
+
"-i",
|
| 92 |
+
"--input-file",
|
| 93 |
+
"--input_file",
|
| 94 |
+
type=Path,
|
| 95 |
+
help="Path to input text file (default: stdin)",
|
| 96 |
+
)
|
| 97 |
+
parser.add_argument(
|
| 98 |
+
"-t",
|
| 99 |
+
"--text",
|
| 100 |
+
help="Text to use instead of reading from stdin",
|
| 101 |
+
)
|
| 102 |
+
parser.add_argument(
|
| 103 |
+
"-s",
|
| 104 |
+
"--speed",
|
| 105 |
+
type=float,
|
| 106 |
+
default=1.0,
|
| 107 |
+
help="Speech speed",
|
| 108 |
+
)
|
| 109 |
+
parser.add_argument(
|
| 110 |
+
"--debug",
|
| 111 |
+
action="store_true",
|
| 112 |
+
help="Print DEBUG messages to console",
|
| 113 |
+
)
|
| 114 |
+
args = parser.parse_args()
|
| 115 |
+
if args.debug:
|
| 116 |
+
logger.level("DEBUG")
|
| 117 |
+
logger.debug(args)
|
| 118 |
+
|
| 119 |
+
lang = args.language or args.voice[0]
|
| 120 |
+
|
| 121 |
+
if args.text is not None and args.input_file is not None:
|
| 122 |
+
raise Exception("You cannot specify both 'text' and 'input_file'")
|
| 123 |
+
elif args.text:
|
| 124 |
+
text = args.text
|
| 125 |
+
elif args.input_file:
|
| 126 |
+
file: Path = args.input_file
|
| 127 |
+
text = file.read_text()
|
| 128 |
+
else:
|
| 129 |
+
import sys
|
| 130 |
+
print("Press Ctrl+D to stop reading input and start generating", flush=True)
|
| 131 |
+
text = '\n'.join(sys.stdin)
|
| 132 |
+
|
| 133 |
+
logger.debug(f"Input text: {text!r}")
|
| 134 |
+
|
| 135 |
+
out_file: Path = args.output_file
|
| 136 |
+
if not out_file.suffix == ".wav":
|
| 137 |
+
logger.warning("The output file name should end with .wav")
|
| 138 |
+
generate_and_save_audio(
|
| 139 |
+
output_file=out_file,
|
| 140 |
+
text=text,
|
| 141 |
+
kokoro_language=lang,
|
| 142 |
+
voice=args.voice,
|
| 143 |
+
speed=args.speed,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from attr import attr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
class CustomSTFT(nn.Module):
|
| 8 |
+
"""
|
| 9 |
+
STFT/iSTFT without unfold/complex ops, using conv1d and conv_transpose1d.
|
| 10 |
+
|
| 11 |
+
- forward STFT => Real-part conv1d + Imag-part conv1d
|
| 12 |
+
- inverse STFT => Real-part conv_transpose1d + Imag-part conv_transpose1d + sum
|
| 13 |
+
- avoids F.unfold, so easier to export to ONNX
|
| 14 |
+
- uses replicate or constant padding for 'center=True' to approximate 'reflect'
|
| 15 |
+
(reflect is not supported for dynamic shapes in ONNX)
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
filter_length=800,
|
| 21 |
+
hop_length=200,
|
| 22 |
+
win_length=800,
|
| 23 |
+
window="hann",
|
| 24 |
+
center=True,
|
| 25 |
+
pad_mode="replicate", # or 'constant'
|
| 26 |
+
):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.filter_length = filter_length
|
| 29 |
+
self.hop_length = hop_length
|
| 30 |
+
self.win_length = win_length
|
| 31 |
+
self.n_fft = filter_length
|
| 32 |
+
self.center = center
|
| 33 |
+
self.pad_mode = pad_mode
|
| 34 |
+
|
| 35 |
+
# Number of frequency bins for real-valued STFT with onesided=True
|
| 36 |
+
self.freq_bins = self.n_fft // 2 + 1
|
| 37 |
+
|
| 38 |
+
# Build window
|
| 39 |
+
assert window == 'hann', window
|
| 40 |
+
window_tensor = torch.hann_window(win_length, periodic=True, dtype=torch.float32)
|
| 41 |
+
if self.win_length < self.n_fft:
|
| 42 |
+
# Zero-pad up to n_fft
|
| 43 |
+
extra = self.n_fft - self.win_length
|
| 44 |
+
window_tensor = F.pad(window_tensor, (0, extra))
|
| 45 |
+
elif self.win_length > self.n_fft:
|
| 46 |
+
window_tensor = window_tensor[: self.n_fft]
|
| 47 |
+
self.register_buffer("window", window_tensor)
|
| 48 |
+
|
| 49 |
+
# Precompute forward DFT (real, imag)
|
| 50 |
+
# PyTorch stft uses e^{-j 2 pi k n / N} => real=cos(...), imag=-sin(...)
|
| 51 |
+
n = np.arange(self.n_fft)
|
| 52 |
+
k = np.arange(self.freq_bins)
|
| 53 |
+
angle = 2 * np.pi * np.outer(k, n) / self.n_fft # shape (freq_bins, n_fft)
|
| 54 |
+
dft_real = np.cos(angle)
|
| 55 |
+
dft_imag = -np.sin(angle) # note negative sign
|
| 56 |
+
|
| 57 |
+
# Combine window and dft => shape (freq_bins, filter_length)
|
| 58 |
+
# We'll make 2 conv weight tensors of shape (freq_bins, 1, filter_length).
|
| 59 |
+
forward_window = window_tensor.numpy() # shape (n_fft,)
|
| 60 |
+
forward_real = dft_real * forward_window # (freq_bins, n_fft)
|
| 61 |
+
forward_imag = dft_imag * forward_window
|
| 62 |
+
|
| 63 |
+
# Convert to PyTorch
|
| 64 |
+
forward_real_torch = torch.from_numpy(forward_real).float()
|
| 65 |
+
forward_imag_torch = torch.from_numpy(forward_imag).float()
|
| 66 |
+
|
| 67 |
+
# Register as Conv1d weight => (out_channels, in_channels, kernel_size)
|
| 68 |
+
# out_channels = freq_bins, in_channels=1, kernel_size=n_fft
|
| 69 |
+
self.register_buffer(
|
| 70 |
+
"weight_forward_real", forward_real_torch.unsqueeze(1)
|
| 71 |
+
)
|
| 72 |
+
self.register_buffer(
|
| 73 |
+
"weight_forward_imag", forward_imag_torch.unsqueeze(1)
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# Precompute inverse DFT
|
| 77 |
+
# Real iFFT formula => scale = 1/n_fft, doubling for bins 1..freq_bins-2 if n_fft even, etc.
|
| 78 |
+
# For simplicity, we won't do the "DC/nyquist not doubled" approach here.
|
| 79 |
+
# If you want perfect real iSTFT, you can add that logic.
|
| 80 |
+
# This version just yields good approximate reconstruction with Hann + typical overlap.
|
| 81 |
+
inv_scale = 1.0 / self.n_fft
|
| 82 |
+
n = np.arange(self.n_fft)
|
| 83 |
+
angle_t = 2 * np.pi * np.outer(n, k) / self.n_fft # shape (n_fft, freq_bins)
|
| 84 |
+
idft_cos = np.cos(angle_t).T # => (freq_bins, n_fft)
|
| 85 |
+
idft_sin = np.sin(angle_t).T # => (freq_bins, n_fft)
|
| 86 |
+
|
| 87 |
+
# Multiply by window again for typical overlap-add
|
| 88 |
+
# We also incorporate the scale factor 1/n_fft
|
| 89 |
+
inv_window = window_tensor.numpy() * inv_scale
|
| 90 |
+
backward_real = idft_cos * inv_window # (freq_bins, n_fft)
|
| 91 |
+
backward_imag = idft_sin * inv_window
|
| 92 |
+
|
| 93 |
+
# We'll implement iSTFT as real+imag conv_transpose with stride=hop.
|
| 94 |
+
self.register_buffer(
|
| 95 |
+
"weight_backward_real", torch.from_numpy(backward_real).float().unsqueeze(1)
|
| 96 |
+
)
|
| 97 |
+
self.register_buffer(
|
| 98 |
+
"weight_backward_imag", torch.from_numpy(backward_imag).float().unsqueeze(1)
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def transform(self, waveform: torch.Tensor):
|
| 104 |
+
"""
|
| 105 |
+
Forward STFT => returns magnitude, phase
|
| 106 |
+
Output shape => (batch, freq_bins, frames)
|
| 107 |
+
"""
|
| 108 |
+
# waveform shape => (B, T). conv1d expects (B, 1, T).
|
| 109 |
+
# Optional center pad
|
| 110 |
+
if self.center:
|
| 111 |
+
pad_len = self.n_fft // 2
|
| 112 |
+
waveform = F.pad(waveform, (pad_len, pad_len), mode=self.pad_mode)
|
| 113 |
+
|
| 114 |
+
x = waveform.unsqueeze(1) # => (B, 1, T)
|
| 115 |
+
# Convolution to get real part => shape (B, freq_bins, frames)
|
| 116 |
+
real_out = F.conv1d(
|
| 117 |
+
x,
|
| 118 |
+
self.weight_forward_real,
|
| 119 |
+
bias=None,
|
| 120 |
+
stride=self.hop_length,
|
| 121 |
+
padding=0,
|
| 122 |
+
)
|
| 123 |
+
# Imag part
|
| 124 |
+
imag_out = F.conv1d(
|
| 125 |
+
x,
|
| 126 |
+
self.weight_forward_imag,
|
| 127 |
+
bias=None,
|
| 128 |
+
stride=self.hop_length,
|
| 129 |
+
padding=0,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# magnitude, phase
|
| 133 |
+
magnitude = torch.sqrt(real_out**2 + imag_out**2 + 1e-14)
|
| 134 |
+
phase = torch.atan2(imag_out, real_out)
|
| 135 |
+
# Handle the case where imag_out is 0 and real_out is negative to correct ONNX atan2 to match PyTorch
|
| 136 |
+
# In this case, PyTorch returns pi, ONNX returns -pi
|
| 137 |
+
correction_mask = (imag_out == 0) & (real_out < 0)
|
| 138 |
+
phase[correction_mask] = torch.pi
|
| 139 |
+
return magnitude, phase
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def inverse(self, magnitude: torch.Tensor, phase: torch.Tensor, length=None):
|
| 143 |
+
"""
|
| 144 |
+
Inverse STFT => returns waveform shape (B, T).
|
| 145 |
+
"""
|
| 146 |
+
# magnitude, phase => (B, freq_bins, frames)
|
| 147 |
+
# Re-create real/imag => shape (B, freq_bins, frames)
|
| 148 |
+
real_part = magnitude * torch.cos(phase)
|
| 149 |
+
imag_part = magnitude * torch.sin(phase)
|
| 150 |
+
|
| 151 |
+
# conv_transpose wants shape (B, freq_bins, frames). We'll treat "frames" as time dimension
|
| 152 |
+
# so we do (B, freq_bins, frames) => (B, freq_bins, frames)
|
| 153 |
+
# But PyTorch conv_transpose1d expects (B, in_channels, input_length)
|
| 154 |
+
real_part = real_part # (B, freq_bins, frames)
|
| 155 |
+
imag_part = imag_part
|
| 156 |
+
|
| 157 |
+
# real iSTFT => convolve with "backward_real", "backward_imag", and sum
|
| 158 |
+
# We'll do 2 conv_transpose calls, each giving (B, 1, time),
|
| 159 |
+
# then add them => (B, 1, time).
|
| 160 |
+
real_rec = F.conv_transpose1d(
|
| 161 |
+
real_part,
|
| 162 |
+
self.weight_backward_real, # shape (freq_bins, 1, filter_length)
|
| 163 |
+
bias=None,
|
| 164 |
+
stride=self.hop_length,
|
| 165 |
+
padding=0,
|
| 166 |
+
)
|
| 167 |
+
imag_rec = F.conv_transpose1d(
|
| 168 |
+
imag_part,
|
| 169 |
+
self.weight_backward_imag,
|
| 170 |
+
bias=None,
|
| 171 |
+
stride=self.hop_length,
|
| 172 |
+
padding=0,
|
| 173 |
+
)
|
| 174 |
+
# sum => (B, 1, time)
|
| 175 |
+
waveform = real_rec - imag_rec # typical real iFFT has minus for imaginary part
|
| 176 |
+
|
| 177 |
+
# If we used "center=True" in forward, we should remove pad
|
| 178 |
+
if self.center:
|
| 179 |
+
pad_len = self.n_fft // 2
|
| 180 |
+
# Because of transposed convolution, total length might have extra samples
|
| 181 |
+
# We remove `pad_len` from start & end if possible
|
| 182 |
+
waveform = waveform[..., pad_len:-pad_len]
|
| 183 |
+
|
| 184 |
+
# If a specific length is desired, clamp
|
| 185 |
+
if length is not None:
|
| 186 |
+
waveform = waveform[..., :length]
|
| 187 |
+
|
| 188 |
+
# shape => (B, T)
|
| 189 |
+
return waveform
|
| 190 |
+
|
| 191 |
+
def forward(self, x: torch.Tensor):
|
| 192 |
+
"""
|
| 193 |
+
Full STFT -> iSTFT pass: returns time-domain reconstruction.
|
| 194 |
+
Same interface as your original code.
|
| 195 |
+
"""
|
| 196 |
+
mag, phase = self.transform(x)
|
| 197 |
+
return self.inverse(mag, phase, length=x.shape[-1])
|
kokoro/istftnet.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ADAPTED from https://github.com/yl4579/StyleTTS2/blob/main/Modules/istftnet.py
|
| 2 |
+
from kokoro.custom_stft import CustomSTFT
|
| 3 |
+
from torch.nn.utils import weight_norm
|
| 4 |
+
import math
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# https://github.com/yl4579/StyleTTS2/blob/main/Modules/utils.py
|
| 11 |
+
def init_weights(m, mean=0.0, std=0.01):
|
| 12 |
+
classname = m.__class__.__name__
|
| 13 |
+
if classname.find("Conv") != -1:
|
| 14 |
+
m.weight.data.normal_(mean, std)
|
| 15 |
+
|
| 16 |
+
def get_padding(kernel_size, dilation=1):
|
| 17 |
+
return int((kernel_size*dilation - dilation)/2)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class AdaIN1d(nn.Module):
|
| 21 |
+
def __init__(self, style_dim, num_features):
|
| 22 |
+
super().__init__()
|
| 23 |
+
# affine should be False, however there's a bug in the old torch.onnx.export (not newer dynamo) that causes the channel dimension to be lost if affine=False. When affine is true, there's additional learnably parameters. This shouldn't really matter setting it to True, since we're in inference mode
|
| 24 |
+
self.norm = nn.InstanceNorm1d(num_features, affine=True)
|
| 25 |
+
self.fc = nn.Linear(style_dim, num_features*2)
|
| 26 |
+
|
| 27 |
+
def forward(self, x, s):
|
| 28 |
+
h = self.fc(s)
|
| 29 |
+
h = h.view(h.size(0), h.size(1), 1)
|
| 30 |
+
gamma, beta = torch.chunk(h, chunks=2, dim=1)
|
| 31 |
+
return (1 + gamma) * self.norm(x) + beta
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class AdaINResBlock1(nn.Module):
|
| 35 |
+
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5), style_dim=64):
|
| 36 |
+
super(AdaINResBlock1, self).__init__()
|
| 37 |
+
self.convs1 = nn.ModuleList([
|
| 38 |
+
weight_norm(nn.Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
|
| 39 |
+
padding=get_padding(kernel_size, dilation[0]))),
|
| 40 |
+
weight_norm(nn.Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
|
| 41 |
+
padding=get_padding(kernel_size, dilation[1]))),
|
| 42 |
+
weight_norm(nn.Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
|
| 43 |
+
padding=get_padding(kernel_size, dilation[2])))
|
| 44 |
+
])
|
| 45 |
+
self.convs1.apply(init_weights)
|
| 46 |
+
self.convs2 = nn.ModuleList([
|
| 47 |
+
weight_norm(nn.Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
| 48 |
+
padding=get_padding(kernel_size, 1))),
|
| 49 |
+
weight_norm(nn.Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
| 50 |
+
padding=get_padding(kernel_size, 1))),
|
| 51 |
+
weight_norm(nn.Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
| 52 |
+
padding=get_padding(kernel_size, 1)))
|
| 53 |
+
])
|
| 54 |
+
self.convs2.apply(init_weights)
|
| 55 |
+
self.adain1 = nn.ModuleList([
|
| 56 |
+
AdaIN1d(style_dim, channels),
|
| 57 |
+
AdaIN1d(style_dim, channels),
|
| 58 |
+
AdaIN1d(style_dim, channels),
|
| 59 |
+
])
|
| 60 |
+
self.adain2 = nn.ModuleList([
|
| 61 |
+
AdaIN1d(style_dim, channels),
|
| 62 |
+
AdaIN1d(style_dim, channels),
|
| 63 |
+
AdaIN1d(style_dim, channels),
|
| 64 |
+
])
|
| 65 |
+
self.alpha1 = nn.ParameterList([nn.Parameter(torch.ones(1, channels, 1)) for i in range(len(self.convs1))])
|
| 66 |
+
self.alpha2 = nn.ParameterList([nn.Parameter(torch.ones(1, channels, 1)) for i in range(len(self.convs2))])
|
| 67 |
+
|
| 68 |
+
def forward(self, x, s):
|
| 69 |
+
for c1, c2, n1, n2, a1, a2 in zip(self.convs1, self.convs2, self.adain1, self.adain2, self.alpha1, self.alpha2):
|
| 70 |
+
xt = n1(x, s)
|
| 71 |
+
xt = xt + (1 / a1) * (torch.sin(a1 * xt) ** 2) # Snake1D
|
| 72 |
+
xt = c1(xt)
|
| 73 |
+
xt = n2(xt, s)
|
| 74 |
+
xt = xt + (1 / a2) * (torch.sin(a2 * xt) ** 2) # Snake1D
|
| 75 |
+
xt = c2(xt)
|
| 76 |
+
x = xt + x
|
| 77 |
+
return x
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class TorchSTFT(nn.Module):
|
| 81 |
+
def __init__(self, filter_length=800, hop_length=200, win_length=800, window='hann'):
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.filter_length = filter_length
|
| 84 |
+
self.hop_length = hop_length
|
| 85 |
+
self.win_length = win_length
|
| 86 |
+
assert window == 'hann', window
|
| 87 |
+
self.window = torch.hann_window(win_length, periodic=True, dtype=torch.float32)
|
| 88 |
+
|
| 89 |
+
def transform(self, input_data):
|
| 90 |
+
forward_transform = torch.stft(
|
| 91 |
+
input_data,
|
| 92 |
+
self.filter_length, self.hop_length, self.win_length, window=self.window.to(input_data.device),
|
| 93 |
+
return_complex=True)
|
| 94 |
+
return torch.abs(forward_transform), torch.angle(forward_transform)
|
| 95 |
+
|
| 96 |
+
def inverse(self, magnitude, phase):
|
| 97 |
+
inverse_transform = torch.istft(
|
| 98 |
+
magnitude * torch.exp(phase * 1j),
|
| 99 |
+
self.filter_length, self.hop_length, self.win_length, window=self.window.to(magnitude.device))
|
| 100 |
+
return inverse_transform.unsqueeze(-2) # unsqueeze to stay consistent with conv_transpose1d implementation
|
| 101 |
+
|
| 102 |
+
def forward(self, input_data):
|
| 103 |
+
self.magnitude, self.phase = self.transform(input_data)
|
| 104 |
+
reconstruction = self.inverse(self.magnitude, self.phase)
|
| 105 |
+
return reconstruction
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class SineGen(nn.Module):
|
| 109 |
+
""" Definition of sine generator
|
| 110 |
+
SineGen(samp_rate, harmonic_num = 0,
|
| 111 |
+
sine_amp = 0.1, noise_std = 0.003,
|
| 112 |
+
voiced_threshold = 0,
|
| 113 |
+
flag_for_pulse=False)
|
| 114 |
+
samp_rate: sampling rate in Hz
|
| 115 |
+
harmonic_num: number of harmonic overtones (default 0)
|
| 116 |
+
sine_amp: amplitude of sine-wavefrom (default 0.1)
|
| 117 |
+
noise_std: std of Gaussian noise (default 0.003)
|
| 118 |
+
voiced_thoreshold: F0 threshold for U/V classification (default 0)
|
| 119 |
+
flag_for_pulse: this SinGen is used inside PulseGen (default False)
|
| 120 |
+
Note: when flag_for_pulse is True, the first time step of a voiced
|
| 121 |
+
segment is always sin(torch.pi) or cos(0)
|
| 122 |
+
"""
|
| 123 |
+
def __init__(self, samp_rate, upsample_scale, harmonic_num=0,
|
| 124 |
+
sine_amp=0.1, noise_std=0.003,
|
| 125 |
+
voiced_threshold=0,
|
| 126 |
+
flag_for_pulse=False):
|
| 127 |
+
super(SineGen, self).__init__()
|
| 128 |
+
self.sine_amp = sine_amp
|
| 129 |
+
self.noise_std = noise_std
|
| 130 |
+
self.harmonic_num = harmonic_num
|
| 131 |
+
self.dim = self.harmonic_num + 1
|
| 132 |
+
self.sampling_rate = samp_rate
|
| 133 |
+
self.voiced_threshold = voiced_threshold
|
| 134 |
+
self.flag_for_pulse = flag_for_pulse
|
| 135 |
+
self.upsample_scale = upsample_scale
|
| 136 |
+
|
| 137 |
+
def _f02uv(self, f0):
|
| 138 |
+
# generate uv signal
|
| 139 |
+
uv = (f0 > self.voiced_threshold).type(torch.float32)
|
| 140 |
+
return uv
|
| 141 |
+
|
| 142 |
+
def _f02sine(self, f0_values):
|
| 143 |
+
""" f0_values: (batchsize, length, dim)
|
| 144 |
+
where dim indicates fundamental tone and overtones
|
| 145 |
+
"""
|
| 146 |
+
# convert to F0 in rad. The interger part n can be ignored
|
| 147 |
+
# because 2 * torch.pi * n doesn't affect phase
|
| 148 |
+
rad_values = (f0_values / self.sampling_rate) % 1
|
| 149 |
+
# initial phase noise (no noise for fundamental component)
|
| 150 |
+
rand_ini = torch.rand(f0_values.shape[0], f0_values.shape[2], device=f0_values.device)
|
| 151 |
+
rand_ini[:, 0] = 0
|
| 152 |
+
rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
|
| 153 |
+
# instantanouse phase sine[t] = sin(2*pi \sum_i=1 ^{t} rad)
|
| 154 |
+
if not self.flag_for_pulse:
|
| 155 |
+
rad_values = F.interpolate(rad_values.transpose(1, 2), scale_factor=1/self.upsample_scale, mode="linear").transpose(1, 2)
|
| 156 |
+
phase = torch.cumsum(rad_values, dim=1) * 2 * torch.pi
|
| 157 |
+
phase = F.interpolate(phase.transpose(1, 2) * self.upsample_scale, scale_factor=self.upsample_scale, mode="linear").transpose(1, 2)
|
| 158 |
+
sines = torch.sin(phase)
|
| 159 |
+
else:
|
| 160 |
+
# If necessary, make sure that the first time step of every
|
| 161 |
+
# voiced segments is sin(pi) or cos(0)
|
| 162 |
+
# This is used for pulse-train generation
|
| 163 |
+
# identify the last time step in unvoiced segments
|
| 164 |
+
uv = self._f02uv(f0_values)
|
| 165 |
+
uv_1 = torch.roll(uv, shifts=-1, dims=1)
|
| 166 |
+
uv_1[:, -1, :] = 1
|
| 167 |
+
u_loc = (uv < 1) * (uv_1 > 0)
|
| 168 |
+
# get the instantanouse phase
|
| 169 |
+
tmp_cumsum = torch.cumsum(rad_values, dim=1)
|
| 170 |
+
# different batch needs to be processed differently
|
| 171 |
+
for idx in range(f0_values.shape[0]):
|
| 172 |
+
temp_sum = tmp_cumsum[idx, u_loc[idx, :, 0], :]
|
| 173 |
+
temp_sum[1:, :] = temp_sum[1:, :] - temp_sum[0:-1, :]
|
| 174 |
+
# stores the accumulation of i.phase within
|
| 175 |
+
# each voiced segments
|
| 176 |
+
tmp_cumsum[idx, :, :] = 0
|
| 177 |
+
tmp_cumsum[idx, u_loc[idx, :, 0], :] = temp_sum
|
| 178 |
+
# rad_values - tmp_cumsum: remove the accumulation of i.phase
|
| 179 |
+
# within the previous voiced segment.
|
| 180 |
+
i_phase = torch.cumsum(rad_values - tmp_cumsum, dim=1)
|
| 181 |
+
# get the sines
|
| 182 |
+
sines = torch.cos(i_phase * 2 * torch.pi)
|
| 183 |
+
return sines
|
| 184 |
+
|
| 185 |
+
def forward(self, f0):
|
| 186 |
+
""" sine_tensor, uv = forward(f0)
|
| 187 |
+
input F0: tensor(batchsize=1, length, dim=1)
|
| 188 |
+
f0 for unvoiced steps should be 0
|
| 189 |
+
output sine_tensor: tensor(batchsize=1, length, dim)
|
| 190 |
+
output uv: tensor(batchsize=1, length, 1)
|
| 191 |
+
"""
|
| 192 |
+
f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device)
|
| 193 |
+
# fundamental component
|
| 194 |
+
fn = torch.multiply(f0, torch.FloatTensor([[range(1, self.harmonic_num + 2)]]).to(f0.device))
|
| 195 |
+
# generate sine waveforms
|
| 196 |
+
sine_waves = self._f02sine(fn) * self.sine_amp
|
| 197 |
+
# generate uv signal
|
| 198 |
+
# uv = torch.ones(f0.shape)
|
| 199 |
+
# uv = uv * (f0 > self.voiced_threshold)
|
| 200 |
+
uv = self._f02uv(f0)
|
| 201 |
+
# noise: for unvoiced should be similar to sine_amp
|
| 202 |
+
# std = self.sine_amp/3 -> max value ~ self.sine_amp
|
| 203 |
+
# for voiced regions is self.noise_std
|
| 204 |
+
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
|
| 205 |
+
noise = noise_amp * torch.randn_like(sine_waves)
|
| 206 |
+
# first: set the unvoiced part to 0 by uv
|
| 207 |
+
# then: additive noise
|
| 208 |
+
sine_waves = sine_waves * uv + noise
|
| 209 |
+
return sine_waves, uv, noise
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class SourceModuleHnNSF(nn.Module):
|
| 213 |
+
""" SourceModule for hn-nsf
|
| 214 |
+
SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
|
| 215 |
+
add_noise_std=0.003, voiced_threshod=0)
|
| 216 |
+
sampling_rate: sampling_rate in Hz
|
| 217 |
+
harmonic_num: number of harmonic above F0 (default: 0)
|
| 218 |
+
sine_amp: amplitude of sine source signal (default: 0.1)
|
| 219 |
+
add_noise_std: std of additive Gaussian noise (default: 0.003)
|
| 220 |
+
note that amplitude of noise in unvoiced is decided
|
| 221 |
+
by sine_amp
|
| 222 |
+
voiced_threshold: threhold to set U/V given F0 (default: 0)
|
| 223 |
+
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
|
| 224 |
+
F0_sampled (batchsize, length, 1)
|
| 225 |
+
Sine_source (batchsize, length, 1)
|
| 226 |
+
noise_source (batchsize, length 1)
|
| 227 |
+
uv (batchsize, length, 1)
|
| 228 |
+
"""
|
| 229 |
+
def __init__(self, sampling_rate, upsample_scale, harmonic_num=0, sine_amp=0.1,
|
| 230 |
+
add_noise_std=0.003, voiced_threshod=0):
|
| 231 |
+
super(SourceModuleHnNSF, self).__init__()
|
| 232 |
+
self.sine_amp = sine_amp
|
| 233 |
+
self.noise_std = add_noise_std
|
| 234 |
+
# to produce sine waveforms
|
| 235 |
+
self.l_sin_gen = SineGen(sampling_rate, upsample_scale, harmonic_num,
|
| 236 |
+
sine_amp, add_noise_std, voiced_threshod)
|
| 237 |
+
# to merge source harmonics into a single excitation
|
| 238 |
+
self.l_linear = nn.Linear(harmonic_num + 1, 1)
|
| 239 |
+
self.l_tanh = nn.Tanh()
|
| 240 |
+
|
| 241 |
+
def forward(self, x):
|
| 242 |
+
"""
|
| 243 |
+
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
|
| 244 |
+
F0_sampled (batchsize, length, 1)
|
| 245 |
+
Sine_source (batchsize, length, 1)
|
| 246 |
+
noise_source (batchsize, length 1)
|
| 247 |
+
"""
|
| 248 |
+
# source for harmonic branch
|
| 249 |
+
with torch.no_grad():
|
| 250 |
+
sine_wavs, uv, _ = self.l_sin_gen(x)
|
| 251 |
+
sine_merge = self.l_tanh(self.l_linear(sine_wavs))
|
| 252 |
+
# source for noise branch, in the same shape as uv
|
| 253 |
+
noise = torch.randn_like(uv) * self.sine_amp / 3
|
| 254 |
+
return sine_merge, noise, uv
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class Generator(nn.Module):
|
| 258 |
+
def __init__(self, style_dim, resblock_kernel_sizes, upsample_rates, upsample_initial_channel, resblock_dilation_sizes, upsample_kernel_sizes, gen_istft_n_fft, gen_istft_hop_size, disable_complex=False):
|
| 259 |
+
super(Generator, self).__init__()
|
| 260 |
+
self.num_kernels = len(resblock_kernel_sizes)
|
| 261 |
+
self.num_upsamples = len(upsample_rates)
|
| 262 |
+
self.m_source = SourceModuleHnNSF(
|
| 263 |
+
sampling_rate=24000,
|
| 264 |
+
upsample_scale=math.prod(upsample_rates) * gen_istft_hop_size,
|
| 265 |
+
harmonic_num=8, voiced_threshod=10)
|
| 266 |
+
self.f0_upsamp = nn.Upsample(scale_factor=math.prod(upsample_rates) * gen_istft_hop_size)
|
| 267 |
+
self.noise_convs = nn.ModuleList()
|
| 268 |
+
self.noise_res = nn.ModuleList()
|
| 269 |
+
self.ups = nn.ModuleList()
|
| 270 |
+
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
| 271 |
+
self.ups.append(weight_norm(
|
| 272 |
+
nn.ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
|
| 273 |
+
k, u, padding=(k-u)//2)))
|
| 274 |
+
self.resblocks = nn.ModuleList()
|
| 275 |
+
for i in range(len(self.ups)):
|
| 276 |
+
ch = upsample_initial_channel//(2**(i+1))
|
| 277 |
+
for j, (k, d) in enumerate(zip(resblock_kernel_sizes,resblock_dilation_sizes)):
|
| 278 |
+
self.resblocks.append(AdaINResBlock1(ch, k, d, style_dim))
|
| 279 |
+
c_cur = upsample_initial_channel // (2 ** (i + 1))
|
| 280 |
+
if i + 1 < len(upsample_rates):
|
| 281 |
+
stride_f0 = math.prod(upsample_rates[i + 1:])
|
| 282 |
+
self.noise_convs.append(nn.Conv1d(
|
| 283 |
+
gen_istft_n_fft + 2, c_cur, kernel_size=stride_f0 * 2, stride=stride_f0, padding=(stride_f0+1) // 2))
|
| 284 |
+
self.noise_res.append(AdaINResBlock1(c_cur, 7, [1,3,5], style_dim))
|
| 285 |
+
else:
|
| 286 |
+
self.noise_convs.append(nn.Conv1d(gen_istft_n_fft + 2, c_cur, kernel_size=1))
|
| 287 |
+
self.noise_res.append(AdaINResBlock1(c_cur, 11, [1,3,5], style_dim))
|
| 288 |
+
self.post_n_fft = gen_istft_n_fft
|
| 289 |
+
self.conv_post = weight_norm(nn.Conv1d(ch, self.post_n_fft + 2, 7, 1, padding=3))
|
| 290 |
+
self.ups.apply(init_weights)
|
| 291 |
+
self.conv_post.apply(init_weights)
|
| 292 |
+
self.reflection_pad = nn.ReflectionPad1d((1, 0))
|
| 293 |
+
self.stft = (
|
| 294 |
+
CustomSTFT(filter_length=gen_istft_n_fft, hop_length=gen_istft_hop_size, win_length=gen_istft_n_fft)
|
| 295 |
+
if disable_complex
|
| 296 |
+
else TorchSTFT(filter_length=gen_istft_n_fft, hop_length=gen_istft_hop_size, win_length=gen_istft_n_fft)
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
def forward(self, x, s, f0):
|
| 300 |
+
with torch.no_grad():
|
| 301 |
+
f0 = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
|
| 302 |
+
har_source, noi_source, uv = self.m_source(f0)
|
| 303 |
+
har_source = har_source.transpose(1, 2).squeeze(1)
|
| 304 |
+
har_spec, har_phase = self.stft.transform(har_source)
|
| 305 |
+
har = torch.cat([har_spec, har_phase], dim=1)
|
| 306 |
+
for i in range(self.num_upsamples):
|
| 307 |
+
x = F.leaky_relu(x, negative_slope=0.1)
|
| 308 |
+
x_source = self.noise_convs[i](har)
|
| 309 |
+
x_source = self.noise_res[i](x_source, s)
|
| 310 |
+
x = self.ups[i](x)
|
| 311 |
+
if i == self.num_upsamples - 1:
|
| 312 |
+
x = self.reflection_pad(x)
|
| 313 |
+
x = x + x_source
|
| 314 |
+
xs = None
|
| 315 |
+
for j in range(self.num_kernels):
|
| 316 |
+
if xs is None:
|
| 317 |
+
xs = self.resblocks[i*self.num_kernels+j](x, s)
|
| 318 |
+
else:
|
| 319 |
+
xs += self.resblocks[i*self.num_kernels+j](x, s)
|
| 320 |
+
x = xs / self.num_kernels
|
| 321 |
+
x = F.leaky_relu(x)
|
| 322 |
+
x = self.conv_post(x)
|
| 323 |
+
spec = torch.exp(x[:,:self.post_n_fft // 2 + 1, :])
|
| 324 |
+
phase = torch.sin(x[:, self.post_n_fft // 2 + 1:, :])
|
| 325 |
+
return self.stft.inverse(spec, phase)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class UpSample1d(nn.Module):
|
| 329 |
+
def __init__(self, layer_type):
|
| 330 |
+
super().__init__()
|
| 331 |
+
self.layer_type = layer_type
|
| 332 |
+
|
| 333 |
+
def forward(self, x):
|
| 334 |
+
if self.layer_type == 'none':
|
| 335 |
+
return x
|
| 336 |
+
else:
|
| 337 |
+
return F.interpolate(x, scale_factor=2, mode='nearest')
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
class AdainResBlk1d(nn.Module):
|
| 341 |
+
def __init__(self, dim_in, dim_out, style_dim=64, actv=nn.LeakyReLU(0.2), upsample='none', dropout_p=0.0):
|
| 342 |
+
super().__init__()
|
| 343 |
+
self.actv = actv
|
| 344 |
+
self.upsample_type = upsample
|
| 345 |
+
self.upsample = UpSample1d(upsample)
|
| 346 |
+
self.learned_sc = dim_in != dim_out
|
| 347 |
+
self._build_weights(dim_in, dim_out, style_dim)
|
| 348 |
+
self.dropout = nn.Dropout(dropout_p)
|
| 349 |
+
if upsample == 'none':
|
| 350 |
+
self.pool = nn.Identity()
|
| 351 |
+
else:
|
| 352 |
+
self.pool = weight_norm(nn.ConvTranspose1d(dim_in, dim_in, kernel_size=3, stride=2, groups=dim_in, padding=1, output_padding=1))
|
| 353 |
+
|
| 354 |
+
def _build_weights(self, dim_in, dim_out, style_dim):
|
| 355 |
+
self.conv1 = weight_norm(nn.Conv1d(dim_in, dim_out, 3, 1, 1))
|
| 356 |
+
self.conv2 = weight_norm(nn.Conv1d(dim_out, dim_out, 3, 1, 1))
|
| 357 |
+
self.norm1 = AdaIN1d(style_dim, dim_in)
|
| 358 |
+
self.norm2 = AdaIN1d(style_dim, dim_out)
|
| 359 |
+
if self.learned_sc:
|
| 360 |
+
self.conv1x1 = weight_norm(nn.Conv1d(dim_in, dim_out, 1, 1, 0, bias=False))
|
| 361 |
+
|
| 362 |
+
def _shortcut(self, x):
|
| 363 |
+
x = self.upsample(x)
|
| 364 |
+
if self.learned_sc:
|
| 365 |
+
x = self.conv1x1(x)
|
| 366 |
+
return x
|
| 367 |
+
|
| 368 |
+
def _residual(self, x, s):
|
| 369 |
+
x = self.norm1(x, s)
|
| 370 |
+
x = self.actv(x)
|
| 371 |
+
x = self.pool(x)
|
| 372 |
+
x = self.conv1(self.dropout(x))
|
| 373 |
+
x = self.norm2(x, s)
|
| 374 |
+
x = self.actv(x)
|
| 375 |
+
x = self.conv2(self.dropout(x))
|
| 376 |
+
return x
|
| 377 |
+
|
| 378 |
+
def forward(self, x, s):
|
| 379 |
+
out = self._residual(x, s)
|
| 380 |
+
out = (out + self._shortcut(x)) * torch.rsqrt(torch.tensor(2))
|
| 381 |
+
return out
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class Decoder(nn.Module):
|
| 385 |
+
def __init__(self, dim_in, style_dim, dim_out,
|
| 386 |
+
resblock_kernel_sizes,
|
| 387 |
+
upsample_rates,
|
| 388 |
+
upsample_initial_channel,
|
| 389 |
+
resblock_dilation_sizes,
|
| 390 |
+
upsample_kernel_sizes,
|
| 391 |
+
gen_istft_n_fft, gen_istft_hop_size,
|
| 392 |
+
disable_complex=False):
|
| 393 |
+
super().__init__()
|
| 394 |
+
self.encode = AdainResBlk1d(dim_in + 2, 1024, style_dim)
|
| 395 |
+
self.decode = nn.ModuleList()
|
| 396 |
+
self.decode.append(AdainResBlk1d(1024 + 2 + 64, 1024, style_dim))
|
| 397 |
+
self.decode.append(AdainResBlk1d(1024 + 2 + 64, 1024, style_dim))
|
| 398 |
+
self.decode.append(AdainResBlk1d(1024 + 2 + 64, 1024, style_dim))
|
| 399 |
+
self.decode.append(AdainResBlk1d(1024 + 2 + 64, 512, style_dim, upsample=True))
|
| 400 |
+
self.F0_conv = weight_norm(nn.Conv1d(1, 1, kernel_size=3, stride=2, groups=1, padding=1))
|
| 401 |
+
self.N_conv = weight_norm(nn.Conv1d(1, 1, kernel_size=3, stride=2, groups=1, padding=1))
|
| 402 |
+
self.asr_res = nn.Sequential(weight_norm(nn.Conv1d(512, 64, kernel_size=1)))
|
| 403 |
+
self.generator = Generator(style_dim, resblock_kernel_sizes, upsample_rates,
|
| 404 |
+
upsample_initial_channel, resblock_dilation_sizes,
|
| 405 |
+
upsample_kernel_sizes, gen_istft_n_fft, gen_istft_hop_size, disable_complex=disable_complex)
|
| 406 |
+
|
| 407 |
+
def forward(self, asr, F0_curve, N, s):
|
| 408 |
+
F0 = self.F0_conv(F0_curve.unsqueeze(1))
|
| 409 |
+
N = self.N_conv(N.unsqueeze(1))
|
| 410 |
+
x = torch.cat([asr, F0, N], axis=1)
|
| 411 |
+
x = self.encode(x, s)
|
| 412 |
+
asr_res = self.asr_res(asr)
|
| 413 |
+
res = True
|
| 414 |
+
for block in self.decode:
|
| 415 |
+
if res:
|
| 416 |
+
x = torch.cat([x, asr_res, F0, N], axis=1)
|
| 417 |
+
x = block(x, s)
|
| 418 |
+
if block.upsample_type != "none":
|
| 419 |
+
res = False
|
| 420 |
+
x = self.generator(x, s, F0_curve)
|
| 421 |
+
return x
|
kokoro/model.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .istftnet import Decoder
|
| 2 |
+
from .modules import CustomAlbert, ProsodyPredictor, TextEncoder
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from huggingface_hub import hf_hub_download
|
| 5 |
+
from loguru import logger
|
| 6 |
+
from transformers import AlbertConfig
|
| 7 |
+
from typing import Dict, Optional, Union
|
| 8 |
+
import json
|
| 9 |
+
import torch
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
class KModel(torch.nn.Module):
|
| 13 |
+
'''
|
| 14 |
+
KModel is a torch.nn.Module with 2 main responsibilities:
|
| 15 |
+
1. Init weights, downloading config.json + model.pth from HF if needed
|
| 16 |
+
2. forward(phonemes: str, ref_s: FloatTensor) -> (audio: FloatTensor)
|
| 17 |
+
|
| 18 |
+
You likely only need one KModel instance, and it can be reused across
|
| 19 |
+
multiple KPipelines to avoid redundant memory allocation.
|
| 20 |
+
|
| 21 |
+
Unlike KPipeline, KModel is language-blind.
|
| 22 |
+
|
| 23 |
+
KModel stores self.vocab and thus knows how to map phonemes -> input_ids,
|
| 24 |
+
so there is no need to repeatedly download config.json outside of KModel.
|
| 25 |
+
'''
|
| 26 |
+
|
| 27 |
+
MODEL_NAMES = {
|
| 28 |
+
'hexgrad/Kokoro-82M': 'kokoro-v1_0.pth',
|
| 29 |
+
'hexgrad/Kokoro-82M-v1.1-zh': 'kokoro-v1_1-zh.pth',
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
def __init__(
|
| 33 |
+
self,
|
| 34 |
+
repo_id: Optional[str] = None,
|
| 35 |
+
config: Union[Dict, str, None] = None,
|
| 36 |
+
model: Optional[str] = None,
|
| 37 |
+
disable_complex: bool = False
|
| 38 |
+
):
|
| 39 |
+
super().__init__()
|
| 40 |
+
if repo_id is None:
|
| 41 |
+
repo_id = 'hexgrad/Kokoro-82M'
|
| 42 |
+
print(f"WARNING: Defaulting repo_id to {repo_id}. Pass repo_id='{repo_id}' to suppress this warning.")
|
| 43 |
+
self.repo_id = repo_id
|
| 44 |
+
if not isinstance(config, dict):
|
| 45 |
+
if not config:
|
| 46 |
+
logger.debug("No config provided, downloading from HF")
|
| 47 |
+
config = hf_hub_download(repo_id=repo_id, filename='config.json')
|
| 48 |
+
with open(config, 'r', encoding='utf-8') as r:
|
| 49 |
+
config = json.load(r)
|
| 50 |
+
logger.debug(f"Loaded config: {config}")
|
| 51 |
+
self.vocab = config['vocab']
|
| 52 |
+
self.bert = CustomAlbert(AlbertConfig(vocab_size=config['n_token'], **config['plbert']))
|
| 53 |
+
self.bert_encoder = torch.nn.Linear(self.bert.config.hidden_size, config['hidden_dim'])
|
| 54 |
+
self.context_length = self.bert.config.max_position_embeddings
|
| 55 |
+
self.predictor = ProsodyPredictor(
|
| 56 |
+
style_dim=config['style_dim'], d_hid=config['hidden_dim'],
|
| 57 |
+
nlayers=config['n_layer'], max_dur=config['max_dur'], dropout=config['dropout']
|
| 58 |
+
)
|
| 59 |
+
self.text_encoder = TextEncoder(
|
| 60 |
+
channels=config['hidden_dim'], kernel_size=config['text_encoder_kernel_size'],
|
| 61 |
+
depth=config['n_layer'], n_symbols=config['n_token']
|
| 62 |
+
)
|
| 63 |
+
self.decoder = Decoder(
|
| 64 |
+
dim_in=config['hidden_dim'], style_dim=config['style_dim'],
|
| 65 |
+
dim_out=config['n_mels'], disable_complex=disable_complex, **config['istftnet']
|
| 66 |
+
)
|
| 67 |
+
if not model:
|
| 68 |
+
try:
|
| 69 |
+
model = hf_hub_download(repo_id=repo_id, filename=KModel.MODEL_NAMES[repo_id])
|
| 70 |
+
except:
|
| 71 |
+
model = os.path.join(repo_id, 'kokoro-v1_0.pth')
|
| 72 |
+
for key, state_dict in torch.load(model, map_location='cpu', weights_only=True).items():
|
| 73 |
+
assert hasattr(self, key), key
|
| 74 |
+
try:
|
| 75 |
+
getattr(self, key).load_state_dict(state_dict)
|
| 76 |
+
except:
|
| 77 |
+
logger.debug(f"Did not load {key} from state_dict")
|
| 78 |
+
state_dict = {k[7:]: v for k, v in state_dict.items()}
|
| 79 |
+
getattr(self, key).load_state_dict(state_dict, strict=False)
|
| 80 |
+
|
| 81 |
+
@property
|
| 82 |
+
def device(self):
|
| 83 |
+
return self.bert.device
|
| 84 |
+
|
| 85 |
+
@dataclass
|
| 86 |
+
class Output:
|
| 87 |
+
audio: torch.FloatTensor
|
| 88 |
+
pred_dur: Optional[torch.LongTensor] = None
|
| 89 |
+
|
| 90 |
+
@torch.no_grad()
|
| 91 |
+
def forward_with_tokens(
|
| 92 |
+
self,
|
| 93 |
+
input_ids: torch.LongTensor,
|
| 94 |
+
ref_s: torch.FloatTensor,
|
| 95 |
+
speed: float = 1
|
| 96 |
+
) -> tuple[torch.FloatTensor, torch.LongTensor]:
|
| 97 |
+
input_lengths = torch.full(
|
| 98 |
+
(input_ids.shape[0],),
|
| 99 |
+
input_ids.shape[-1],
|
| 100 |
+
device=input_ids.device,
|
| 101 |
+
dtype=torch.long
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
text_mask = torch.arange(input_lengths.max()).unsqueeze(0).expand(input_lengths.shape[0], -1).type_as(input_lengths)
|
| 105 |
+
text_mask = torch.gt(text_mask+1, input_lengths.unsqueeze(1)).to(self.device)
|
| 106 |
+
bert_dur = self.bert(input_ids, attention_mask=(~text_mask).int())
|
| 107 |
+
d_en = self.bert_encoder(bert_dur).transpose(-1, -2)
|
| 108 |
+
s = ref_s[:, 128:]
|
| 109 |
+
d = self.predictor.text_encoder(d_en, s, input_lengths, text_mask)
|
| 110 |
+
x, _ = self.predictor.lstm(d)
|
| 111 |
+
duration = self.predictor.duration_proj(x)
|
| 112 |
+
duration = torch.sigmoid(duration).sum(axis=-1) / speed
|
| 113 |
+
pred_dur = torch.round(duration).clamp(min=1).long().squeeze()
|
| 114 |
+
indices = torch.repeat_interleave(torch.arange(input_ids.shape[1], device=self.device), pred_dur)
|
| 115 |
+
pred_aln_trg = torch.zeros((input_ids.shape[1], indices.shape[0]), device=self.device)
|
| 116 |
+
pred_aln_trg[indices, torch.arange(indices.shape[0])] = 1
|
| 117 |
+
pred_aln_trg = pred_aln_trg.unsqueeze(0).to(self.device)
|
| 118 |
+
en = d.transpose(-1, -2) @ pred_aln_trg
|
| 119 |
+
F0_pred, N_pred = self.predictor.F0Ntrain(en, s)
|
| 120 |
+
t_en = self.text_encoder(input_ids, input_lengths, text_mask)
|
| 121 |
+
asr = t_en @ pred_aln_trg
|
| 122 |
+
audio = self.decoder(asr, F0_pred, N_pred, ref_s[:, :128]).squeeze()
|
| 123 |
+
return audio, pred_dur
|
| 124 |
+
|
| 125 |
+
def forward(
|
| 126 |
+
self,
|
| 127 |
+
phonemes: str,
|
| 128 |
+
ref_s: torch.FloatTensor,
|
| 129 |
+
speed: float = 1,
|
| 130 |
+
return_output: bool = False
|
| 131 |
+
) -> Union['KModel.Output', torch.FloatTensor]:
|
| 132 |
+
input_ids = list(filter(lambda i: i is not None, map(lambda p: self.vocab.get(p), phonemes)))
|
| 133 |
+
logger.debug(f"phonemes: {phonemes} -> input_ids: {input_ids}")
|
| 134 |
+
assert len(input_ids)+2 <= self.context_length, (len(input_ids)+2, self.context_length)
|
| 135 |
+
input_ids = torch.LongTensor([[0, *input_ids, 0]]).to(self.device)
|
| 136 |
+
ref_s = ref_s.to(self.device)
|
| 137 |
+
audio, pred_dur = self.forward_with_tokens(input_ids, ref_s, speed)
|
| 138 |
+
audio = audio.squeeze().cpu()
|
| 139 |
+
pred_dur = pred_dur.cpu() if pred_dur is not None else None
|
| 140 |
+
logger.debug(f"pred_dur: {pred_dur}")
|
| 141 |
+
return self.Output(audio=audio, pred_dur=pred_dur) if return_output else audio
|
| 142 |
+
|
| 143 |
+
class KModelForONNX(torch.nn.Module):
|
| 144 |
+
def __init__(self, kmodel: KModel):
|
| 145 |
+
super().__init__()
|
| 146 |
+
self.kmodel = kmodel
|
| 147 |
+
|
| 148 |
+
def forward(
|
| 149 |
+
self,
|
| 150 |
+
input_ids: torch.LongTensor,
|
| 151 |
+
ref_s: torch.FloatTensor,
|
| 152 |
+
speed: float = 1
|
| 153 |
+
) -> tuple[torch.FloatTensor, torch.LongTensor]:
|
| 154 |
+
waveform, duration = self.kmodel.forward_with_tokens(input_ids, ref_s, speed)
|
| 155 |
+
return waveform, duration
|
kokoro/modules.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# https://github.com/yl4579/StyleTTS2/blob/main/models.py
|
| 2 |
+
from .istftnet import AdainResBlk1d
|
| 3 |
+
from torch.nn.utils import weight_norm
|
| 4 |
+
from transformers import AlbertModel
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class LinearNorm(nn.Module):
|
| 12 |
+
def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
|
| 13 |
+
super(LinearNorm, self).__init__()
|
| 14 |
+
self.linear_layer = nn.Linear(in_dim, out_dim, bias=bias)
|
| 15 |
+
nn.init.xavier_uniform_(self.linear_layer.weight, gain=nn.init.calculate_gain(w_init_gain))
|
| 16 |
+
|
| 17 |
+
def forward(self, x):
|
| 18 |
+
return self.linear_layer(x)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class LayerNorm(nn.Module):
|
| 22 |
+
def __init__(self, channels, eps=1e-5):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.channels = channels
|
| 25 |
+
self.eps = eps
|
| 26 |
+
self.gamma = nn.Parameter(torch.ones(channels))
|
| 27 |
+
self.beta = nn.Parameter(torch.zeros(channels))
|
| 28 |
+
|
| 29 |
+
def forward(self, x):
|
| 30 |
+
x = x.transpose(1, -1)
|
| 31 |
+
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
| 32 |
+
return x.transpose(1, -1)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class TextEncoder(nn.Module):
|
| 36 |
+
def __init__(self, channels, kernel_size, depth, n_symbols, actv=nn.LeakyReLU(0.2)):
|
| 37 |
+
super().__init__()
|
| 38 |
+
self.embedding = nn.Embedding(n_symbols, channels)
|
| 39 |
+
padding = (kernel_size - 1) // 2
|
| 40 |
+
self.cnn = nn.ModuleList()
|
| 41 |
+
for _ in range(depth):
|
| 42 |
+
self.cnn.append(nn.Sequential(
|
| 43 |
+
weight_norm(nn.Conv1d(channels, channels, kernel_size=kernel_size, padding=padding)),
|
| 44 |
+
LayerNorm(channels),
|
| 45 |
+
actv,
|
| 46 |
+
nn.Dropout(0.2),
|
| 47 |
+
))
|
| 48 |
+
self.lstm = nn.LSTM(channels, channels//2, 1, batch_first=True, bidirectional=True)
|
| 49 |
+
|
| 50 |
+
def forward(self, x, input_lengths, m):
|
| 51 |
+
x = self.embedding(x) # [B, T, emb]
|
| 52 |
+
x = x.transpose(1, 2) # [B, emb, T]
|
| 53 |
+
m = m.unsqueeze(1)
|
| 54 |
+
x.masked_fill_(m, 0.0)
|
| 55 |
+
for c in self.cnn:
|
| 56 |
+
x = c(x)
|
| 57 |
+
x.masked_fill_(m, 0.0)
|
| 58 |
+
x = x.transpose(1, 2) # [B, T, chn]
|
| 59 |
+
lengths = input_lengths if input_lengths.device == torch.device('cpu') else input_lengths.to('cpu')
|
| 60 |
+
x = nn.utils.rnn.pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False)
|
| 61 |
+
self.lstm.flatten_parameters()
|
| 62 |
+
x, _ = self.lstm(x)
|
| 63 |
+
x, _ = nn.utils.rnn.pad_packed_sequence(x, batch_first=True)
|
| 64 |
+
x = x.transpose(-1, -2)
|
| 65 |
+
x_pad = torch.zeros([x.shape[0], x.shape[1], m.shape[-1]], device=x.device)
|
| 66 |
+
x_pad[:, :, :x.shape[-1]] = x
|
| 67 |
+
x = x_pad
|
| 68 |
+
x.masked_fill_(m, 0.0)
|
| 69 |
+
return x
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class AdaLayerNorm(nn.Module):
|
| 73 |
+
def __init__(self, style_dim, channels, eps=1e-5):
|
| 74 |
+
super().__init__()
|
| 75 |
+
self.channels = channels
|
| 76 |
+
self.eps = eps
|
| 77 |
+
self.fc = nn.Linear(style_dim, channels*2)
|
| 78 |
+
|
| 79 |
+
def forward(self, x, s):
|
| 80 |
+
x = x.transpose(-1, -2)
|
| 81 |
+
x = x.transpose(1, -1)
|
| 82 |
+
h = self.fc(s)
|
| 83 |
+
h = h.view(h.size(0), h.size(1), 1)
|
| 84 |
+
gamma, beta = torch.chunk(h, chunks=2, dim=1)
|
| 85 |
+
gamma, beta = gamma.transpose(1, -1), beta.transpose(1, -1)
|
| 86 |
+
x = F.layer_norm(x, (self.channels,), eps=self.eps)
|
| 87 |
+
x = (1 + gamma) * x + beta
|
| 88 |
+
return x.transpose(1, -1).transpose(-1, -2)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class ProsodyPredictor(nn.Module):
|
| 92 |
+
def __init__(self, style_dim, d_hid, nlayers, max_dur=50, dropout=0.1):
|
| 93 |
+
super().__init__()
|
| 94 |
+
self.text_encoder = DurationEncoder(sty_dim=style_dim, d_model=d_hid,nlayers=nlayers, dropout=dropout)
|
| 95 |
+
self.lstm = nn.LSTM(d_hid + style_dim, d_hid // 2, 1, batch_first=True, bidirectional=True)
|
| 96 |
+
self.duration_proj = LinearNorm(d_hid, max_dur)
|
| 97 |
+
self.shared = nn.LSTM(d_hid + style_dim, d_hid // 2, 1, batch_first=True, bidirectional=True)
|
| 98 |
+
self.F0 = nn.ModuleList()
|
| 99 |
+
self.F0.append(AdainResBlk1d(d_hid, d_hid, style_dim, dropout_p=dropout))
|
| 100 |
+
self.F0.append(AdainResBlk1d(d_hid, d_hid // 2, style_dim, upsample=True, dropout_p=dropout))
|
| 101 |
+
self.F0.append(AdainResBlk1d(d_hid // 2, d_hid // 2, style_dim, dropout_p=dropout))
|
| 102 |
+
self.N = nn.ModuleList()
|
| 103 |
+
self.N.append(AdainResBlk1d(d_hid, d_hid, style_dim, dropout_p=dropout))
|
| 104 |
+
self.N.append(AdainResBlk1d(d_hid, d_hid // 2, style_dim, upsample=True, dropout_p=dropout))
|
| 105 |
+
self.N.append(AdainResBlk1d(d_hid // 2, d_hid // 2, style_dim, dropout_p=dropout))
|
| 106 |
+
self.F0_proj = nn.Conv1d(d_hid // 2, 1, 1, 1, 0)
|
| 107 |
+
self.N_proj = nn.Conv1d(d_hid // 2, 1, 1, 1, 0)
|
| 108 |
+
|
| 109 |
+
def forward(self, texts, style, text_lengths, alignment, m):
|
| 110 |
+
d = self.text_encoder(texts, style, text_lengths, m)
|
| 111 |
+
m = m.unsqueeze(1)
|
| 112 |
+
lengths = text_lengths if text_lengths.device == torch.device('cpu') else text_lengths.to('cpu')
|
| 113 |
+
x = nn.utils.rnn.pack_padded_sequence(d, lengths, batch_first=True, enforce_sorted=False)
|
| 114 |
+
self.lstm.flatten_parameters()
|
| 115 |
+
x, _ = self.lstm(x)
|
| 116 |
+
x, _ = nn.utils.rnn.pad_packed_sequence(x, batch_first=True)
|
| 117 |
+
x_pad = torch.zeros([x.shape[0], m.shape[-1], x.shape[-1]], device=x.device)
|
| 118 |
+
x_pad[:, :x.shape[1], :] = x
|
| 119 |
+
x = x_pad
|
| 120 |
+
duration = self.duration_proj(nn.functional.dropout(x, 0.5, training=False))
|
| 121 |
+
en = (d.transpose(-1, -2) @ alignment)
|
| 122 |
+
return duration.squeeze(-1), en
|
| 123 |
+
|
| 124 |
+
def F0Ntrain(self, x, s):
|
| 125 |
+
x, _ = self.shared(x.transpose(-1, -2))
|
| 126 |
+
F0 = x.transpose(-1, -2)
|
| 127 |
+
for block in self.F0:
|
| 128 |
+
F0 = block(F0, s)
|
| 129 |
+
F0 = self.F0_proj(F0)
|
| 130 |
+
N = x.transpose(-1, -2)
|
| 131 |
+
for block in self.N:
|
| 132 |
+
N = block(N, s)
|
| 133 |
+
N = self.N_proj(N)
|
| 134 |
+
return F0.squeeze(1), N.squeeze(1)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class DurationEncoder(nn.Module):
|
| 138 |
+
def __init__(self, sty_dim, d_model, nlayers, dropout=0.1):
|
| 139 |
+
super().__init__()
|
| 140 |
+
self.lstms = nn.ModuleList()
|
| 141 |
+
for _ in range(nlayers):
|
| 142 |
+
self.lstms.append(nn.LSTM(d_model + sty_dim, d_model // 2, num_layers=1, batch_first=True, bidirectional=True, dropout=dropout))
|
| 143 |
+
self.lstms.append(AdaLayerNorm(sty_dim, d_model))
|
| 144 |
+
self.dropout = dropout
|
| 145 |
+
self.d_model = d_model
|
| 146 |
+
self.sty_dim = sty_dim
|
| 147 |
+
|
| 148 |
+
def forward(self, x, style, text_lengths, m):
|
| 149 |
+
masks = m
|
| 150 |
+
x = x.permute(2, 0, 1)
|
| 151 |
+
s = style.expand(x.shape[0], x.shape[1], -1)
|
| 152 |
+
x = torch.cat([x, s], axis=-1)
|
| 153 |
+
x.masked_fill_(masks.unsqueeze(-1).transpose(0, 1), 0.0)
|
| 154 |
+
x = x.transpose(0, 1)
|
| 155 |
+
x = x.transpose(-1, -2)
|
| 156 |
+
for block in self.lstms:
|
| 157 |
+
if isinstance(block, AdaLayerNorm):
|
| 158 |
+
x = block(x.transpose(-1, -2), style).transpose(-1, -2)
|
| 159 |
+
x = torch.cat([x, s.permute(1, 2, 0)], axis=1)
|
| 160 |
+
x.masked_fill_(masks.unsqueeze(-1).transpose(-1, -2), 0.0)
|
| 161 |
+
else:
|
| 162 |
+
lengths = text_lengths if text_lengths.device == torch.device('cpu') else text_lengths.to('cpu')
|
| 163 |
+
x = x.transpose(-1, -2)
|
| 164 |
+
x = nn.utils.rnn.pack_padded_sequence(
|
| 165 |
+
x, lengths, batch_first=True, enforce_sorted=False)
|
| 166 |
+
block.flatten_parameters()
|
| 167 |
+
x, _ = block(x)
|
| 168 |
+
x, _ = nn.utils.rnn.pad_packed_sequence(
|
| 169 |
+
x, batch_first=True)
|
| 170 |
+
x = F.dropout(x, p=self.dropout, training=False)
|
| 171 |
+
x = x.transpose(-1, -2)
|
| 172 |
+
x_pad = torch.zeros([x.shape[0], x.shape[1], m.shape[-1]], device=x.device)
|
| 173 |
+
x_pad[:, :, :x.shape[-1]] = x
|
| 174 |
+
x = x_pad
|
| 175 |
+
|
| 176 |
+
return x.transpose(-1, -2)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# https://github.com/yl4579/StyleTTS2/blob/main/Utils/PLBERT/util.py
|
| 180 |
+
class CustomAlbert(AlbertModel):
|
| 181 |
+
def forward(self, *args, **kwargs):
|
| 182 |
+
outputs = super().forward(*args, **kwargs)
|
| 183 |
+
return outputs.last_hidden_state
|
kokoro/pipeline.py
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .model import KModel
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from huggingface_hub import hf_hub_download
|
| 4 |
+
from loguru import logger
|
| 5 |
+
from misaki import en, espeak
|
| 6 |
+
from typing import Callable, Generator, List, Optional, Tuple, Union
|
| 7 |
+
import re
|
| 8 |
+
import torch
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
ALIASES = {
|
| 12 |
+
'en-us': 'a',
|
| 13 |
+
'en-gb': 'b',
|
| 14 |
+
'es': 'e',
|
| 15 |
+
'fr-fr': 'f',
|
| 16 |
+
'hi': 'h',
|
| 17 |
+
'it': 'i',
|
| 18 |
+
'pt-br': 'p',
|
| 19 |
+
'ja': 'j',
|
| 20 |
+
'zh': 'z',
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
LANG_CODES = dict(
|
| 24 |
+
# pip install misaki[en]
|
| 25 |
+
a='American English',
|
| 26 |
+
b='British English',
|
| 27 |
+
|
| 28 |
+
# espeak-ng
|
| 29 |
+
e='es',
|
| 30 |
+
f='fr-fr',
|
| 31 |
+
h='hi',
|
| 32 |
+
i='it',
|
| 33 |
+
p='pt-br',
|
| 34 |
+
|
| 35 |
+
# pip install misaki[ja]
|
| 36 |
+
j='Japanese',
|
| 37 |
+
|
| 38 |
+
# pip install misaki[zh]
|
| 39 |
+
z='Mandarin Chinese',
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
class KPipeline:
|
| 43 |
+
'''
|
| 44 |
+
KPipeline is a language-aware support class with 2 main responsibilities:
|
| 45 |
+
1. Perform language-specific G2P, mapping (and chunking) text -> phonemes
|
| 46 |
+
2. Manage and store voices, lazily downloaded from HF if needed
|
| 47 |
+
|
| 48 |
+
You are expected to have one KPipeline per language. If you have multiple
|
| 49 |
+
KPipelines, you should reuse one KModel instance across all of them.
|
| 50 |
+
|
| 51 |
+
KPipeline is designed to work with a KModel, but this is not required.
|
| 52 |
+
There are 2 ways to pass an existing model into a pipeline:
|
| 53 |
+
1. On init: us_pipeline = KPipeline(lang_code='a', model=model)
|
| 54 |
+
2. On call: us_pipeline(text, voice, model=model)
|
| 55 |
+
|
| 56 |
+
By default, KPipeline will automatically initialize its own KModel. To
|
| 57 |
+
suppress this, construct a "quiet" KPipeline with model=False.
|
| 58 |
+
|
| 59 |
+
A "quiet" KPipeline yields (graphemes, phonemes, None) without generating
|
| 60 |
+
any audio. You can use this to phonemize and chunk your text in advance.
|
| 61 |
+
|
| 62 |
+
A "loud" KPipeline _with_ a model yields (graphemes, phonemes, audio).
|
| 63 |
+
'''
|
| 64 |
+
def __init__(
|
| 65 |
+
self,
|
| 66 |
+
lang_code: str,
|
| 67 |
+
repo_id: Optional[str] = None,
|
| 68 |
+
model: Union[KModel, bool] = True,
|
| 69 |
+
trf: bool = False,
|
| 70 |
+
en_callable: Optional[Callable[[str], str]] = None,
|
| 71 |
+
device: Optional[str] = None
|
| 72 |
+
):
|
| 73 |
+
"""Initialize a KPipeline.
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
lang_code: Language code for G2P processing
|
| 77 |
+
model: KModel instance, True to create new model, False for no model
|
| 78 |
+
trf: Whether to use transformer-based G2P
|
| 79 |
+
device: Override default device selection ('cuda' or 'cpu', or None for auto)
|
| 80 |
+
If None, will auto-select cuda if available
|
| 81 |
+
If 'cuda' and not available, will explicitly raise an error
|
| 82 |
+
"""
|
| 83 |
+
if repo_id is None:
|
| 84 |
+
repo_id = 'hexgrad/Kokoro-82M'
|
| 85 |
+
print(f"WARNING: Defaulting repo_id to {repo_id}. Pass repo_id='{repo_id}' to suppress this warning.")
|
| 86 |
+
config=None
|
| 87 |
+
else:
|
| 88 |
+
config = os.path.join(repo_id, 'config.json')
|
| 89 |
+
self.repo_id = repo_id
|
| 90 |
+
lang_code = lang_code.lower()
|
| 91 |
+
lang_code = ALIASES.get(lang_code, lang_code)
|
| 92 |
+
assert lang_code in LANG_CODES, (lang_code, LANG_CODES)
|
| 93 |
+
self.lang_code = lang_code
|
| 94 |
+
self.model = None
|
| 95 |
+
if isinstance(model, KModel):
|
| 96 |
+
self.model = model
|
| 97 |
+
elif model:
|
| 98 |
+
if device == 'cuda' and not torch.cuda.is_available():
|
| 99 |
+
raise RuntimeError("CUDA requested but not available")
|
| 100 |
+
if device == 'mps' and not torch.backends.mps.is_available():
|
| 101 |
+
raise RuntimeError("MPS requested but not available")
|
| 102 |
+
if device == 'mps' and os.environ.get('PYTORCH_ENABLE_MPS_FALLBACK') != '1':
|
| 103 |
+
raise RuntimeError("MPS requested but fallback not enabled")
|
| 104 |
+
if device is None:
|
| 105 |
+
if torch.cuda.is_available():
|
| 106 |
+
device = 'cuda'
|
| 107 |
+
elif os.environ.get('PYTORCH_ENABLE_MPS_FALLBACK') == '1' and torch.backends.mps.is_available():
|
| 108 |
+
device = 'mps'
|
| 109 |
+
else:
|
| 110 |
+
device = 'cpu'
|
| 111 |
+
try:
|
| 112 |
+
self.model = KModel(repo_id=repo_id, config=config).to(device).eval()
|
| 113 |
+
except RuntimeError as e:
|
| 114 |
+
if device == 'cuda':
|
| 115 |
+
raise RuntimeError(f"""Failed to initialize model on CUDA: {e}.
|
| 116 |
+
Try setting device='cpu' or check CUDA installation.""")
|
| 117 |
+
raise
|
| 118 |
+
self.voices = {}
|
| 119 |
+
if lang_code in 'ab':
|
| 120 |
+
try:
|
| 121 |
+
fallback = espeak.EspeakFallback(british=lang_code=='b')
|
| 122 |
+
except Exception as e:
|
| 123 |
+
logger.warning("EspeakFallback not Enabled: OOD words will be skipped")
|
| 124 |
+
logger.warning({str(e)})
|
| 125 |
+
fallback = None
|
| 126 |
+
self.g2p = en.G2P(trf=trf, british=lang_code=='b', fallback=fallback, unk='')
|
| 127 |
+
elif lang_code == 'j':
|
| 128 |
+
try:
|
| 129 |
+
from misaki import ja
|
| 130 |
+
self.g2p = ja.JAG2P()
|
| 131 |
+
except ImportError:
|
| 132 |
+
logger.error("You need to `pip install misaki[ja]` to use lang_code='j'")
|
| 133 |
+
raise
|
| 134 |
+
elif lang_code == 'z':
|
| 135 |
+
try:
|
| 136 |
+
from misaki import zh
|
| 137 |
+
self.g2p = zh.ZHG2P(
|
| 138 |
+
version=None if repo_id.endswith('/Kokoro-82M') else '1.1',
|
| 139 |
+
en_callable=en_callable
|
| 140 |
+
)
|
| 141 |
+
except ImportError:
|
| 142 |
+
logger.error("You need to `pip install misaki[zh]` to use lang_code='z'")
|
| 143 |
+
raise
|
| 144 |
+
else:
|
| 145 |
+
language = LANG_CODES[lang_code]
|
| 146 |
+
logger.warning(f"Using EspeakG2P(language='{language}'). Chunking logic not yet implemented, so long texts may be truncated unless you split them with '\\n'.")
|
| 147 |
+
self.g2p = espeak.EspeakG2P(language=language)
|
| 148 |
+
|
| 149 |
+
def load_single_voice(self, voice: str):
|
| 150 |
+
if voice in self.voices:
|
| 151 |
+
return self.voices[voice]
|
| 152 |
+
if voice.endswith('.pt'):
|
| 153 |
+
f = voice
|
| 154 |
+
else:
|
| 155 |
+
f = hf_hub_download(repo_id=self.repo_id, filename=f'voices/{voice}.pt')
|
| 156 |
+
if not voice.startswith(self.lang_code):
|
| 157 |
+
v = LANG_CODES.get(voice, voice)
|
| 158 |
+
p = LANG_CODES.get(self.lang_code, self.lang_code)
|
| 159 |
+
logger.warning(f'Language mismatch, loading {v} voice into {p} pipeline.')
|
| 160 |
+
pack = torch.load(f, weights_only=True)
|
| 161 |
+
self.voices[voice] = pack
|
| 162 |
+
return pack
|
| 163 |
+
|
| 164 |
+
"""
|
| 165 |
+
load_voice is a helper function that lazily downloads and loads a voice:
|
| 166 |
+
Single voice can be requested (e.g. 'af_bella') or multiple voices (e.g. 'af_bella,af_jessica').
|
| 167 |
+
If multiple voices are requested, they are averaged.
|
| 168 |
+
Delimiter is optional and defaults to ','.
|
| 169 |
+
"""
|
| 170 |
+
def load_voice(self, voice: Union[str, torch.FloatTensor], delimiter: str = ",") -> torch.FloatTensor:
|
| 171 |
+
if isinstance(voice, torch.FloatTensor):
|
| 172 |
+
return voice
|
| 173 |
+
if voice in self.voices:
|
| 174 |
+
return self.voices[voice]
|
| 175 |
+
logger.debug(f"Loading voice: {voice}")
|
| 176 |
+
packs = [self.load_single_voice(v) for v in voice.split(delimiter)]
|
| 177 |
+
if len(packs) == 1:
|
| 178 |
+
return packs[0]
|
| 179 |
+
self.voices[voice] = torch.mean(torch.stack(packs), dim=0)
|
| 180 |
+
return self.voices[voice]
|
| 181 |
+
|
| 182 |
+
@staticmethod
|
| 183 |
+
def tokens_to_ps(tokens: List[en.MToken]) -> str:
|
| 184 |
+
return ''.join(t.phonemes + (' ' if t.whitespace else '') for t in tokens).strip()
|
| 185 |
+
|
| 186 |
+
@staticmethod
|
| 187 |
+
def waterfall_last(
|
| 188 |
+
tokens: List[en.MToken],
|
| 189 |
+
next_count: int,
|
| 190 |
+
waterfall: List[str] = ['!.?…', ':;', ',—'],
|
| 191 |
+
bumps: List[str] = [')', '”']
|
| 192 |
+
) -> int:
|
| 193 |
+
for w in waterfall:
|
| 194 |
+
z = next((i for i, t in reversed(list(enumerate(tokens))) if t.phonemes in set(w)), None)
|
| 195 |
+
if z is None:
|
| 196 |
+
continue
|
| 197 |
+
z += 1
|
| 198 |
+
if z < len(tokens) and tokens[z].phonemes in bumps:
|
| 199 |
+
z += 1
|
| 200 |
+
if next_count - len(KPipeline.tokens_to_ps(tokens[:z])) <= 510:
|
| 201 |
+
return z
|
| 202 |
+
return len(tokens)
|
| 203 |
+
|
| 204 |
+
@staticmethod
|
| 205 |
+
def tokens_to_text(tokens: List[en.MToken]) -> str:
|
| 206 |
+
return ''.join(t.text + t.whitespace for t in tokens).strip()
|
| 207 |
+
|
| 208 |
+
def en_tokenize(
|
| 209 |
+
self,
|
| 210 |
+
tokens: List[en.MToken]
|
| 211 |
+
) -> Generator[Tuple[str, str, List[en.MToken]], None, None]:
|
| 212 |
+
tks = []
|
| 213 |
+
pcount = 0
|
| 214 |
+
for t in tokens:
|
| 215 |
+
# American English: ɾ => T
|
| 216 |
+
t.phonemes = '' if t.phonemes is None else t.phonemes#.replace('ɾ', 'T')
|
| 217 |
+
next_ps = t.phonemes + (' ' if t.whitespace else '')
|
| 218 |
+
next_pcount = pcount + len(next_ps.rstrip())
|
| 219 |
+
if next_pcount > 510:
|
| 220 |
+
z = KPipeline.waterfall_last(tks, next_pcount)
|
| 221 |
+
text = KPipeline.tokens_to_text(tks[:z])
|
| 222 |
+
logger.debug(f"Chunking text at {z}: '{text[:30]}{'...' if len(text) > 30 else ''}'")
|
| 223 |
+
ps = KPipeline.tokens_to_ps(tks[:z])
|
| 224 |
+
yield text, ps, tks[:z]
|
| 225 |
+
tks = tks[z:]
|
| 226 |
+
pcount = len(KPipeline.tokens_to_ps(tks))
|
| 227 |
+
if not tks:
|
| 228 |
+
next_ps = next_ps.lstrip()
|
| 229 |
+
tks.append(t)
|
| 230 |
+
pcount += len(next_ps)
|
| 231 |
+
if tks:
|
| 232 |
+
text = KPipeline.tokens_to_text(tks)
|
| 233 |
+
ps = KPipeline.tokens_to_ps(tks)
|
| 234 |
+
yield ''.join(text).strip(), ''.join(ps).strip(), tks
|
| 235 |
+
|
| 236 |
+
@staticmethod
|
| 237 |
+
def infer(
|
| 238 |
+
model: KModel,
|
| 239 |
+
ps: str,
|
| 240 |
+
pack: torch.FloatTensor,
|
| 241 |
+
speed: Union[float, Callable[[int], float]] = 1
|
| 242 |
+
) -> KModel.Output:
|
| 243 |
+
if callable(speed):
|
| 244 |
+
speed = speed(len(ps))
|
| 245 |
+
return model(ps, pack[len(ps)-1], speed, return_output=True)
|
| 246 |
+
|
| 247 |
+
def generate_from_tokens(
|
| 248 |
+
self,
|
| 249 |
+
tokens: Union[str, List[en.MToken]],
|
| 250 |
+
voice: str,
|
| 251 |
+
speed: float = 1,
|
| 252 |
+
model: Optional[KModel] = None
|
| 253 |
+
) -> Generator['KPipeline.Result', None, None]:
|
| 254 |
+
"""Generate audio from either raw phonemes or pre-processed tokens.
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
tokens: Either a phoneme string or list of pre-processed MTokens
|
| 258 |
+
voice: The voice to use for synthesis
|
| 259 |
+
speed: Speech speed modifier (default: 1)
|
| 260 |
+
model: Optional KModel instance (uses pipeline's model if not provided)
|
| 261 |
+
|
| 262 |
+
Yields:
|
| 263 |
+
KPipeline.Result containing the input tokens and generated audio
|
| 264 |
+
|
| 265 |
+
Raises:
|
| 266 |
+
ValueError: If no voice is provided or token sequence exceeds model limits
|
| 267 |
+
"""
|
| 268 |
+
model = model or self.model
|
| 269 |
+
if model and voice is None:
|
| 270 |
+
raise ValueError('Specify a voice: pipeline.generate_from_tokens(..., voice="af_heart")')
|
| 271 |
+
|
| 272 |
+
pack = self.load_voice(voice).to(model.device) if model else None
|
| 273 |
+
|
| 274 |
+
# Handle raw phoneme string
|
| 275 |
+
if isinstance(tokens, str):
|
| 276 |
+
logger.debug("Processing phonemes from raw string")
|
| 277 |
+
if len(tokens) > 510:
|
| 278 |
+
raise ValueError(f'Phoneme string too long: {len(tokens)} > 510')
|
| 279 |
+
output = KPipeline.infer(model, tokens, pack, speed) if model else None
|
| 280 |
+
yield self.Result(graphemes='', phonemes=tokens, output=output)
|
| 281 |
+
return
|
| 282 |
+
|
| 283 |
+
logger.debug("Processing MTokens")
|
| 284 |
+
# Handle pre-processed tokens
|
| 285 |
+
for gs, ps, tks in self.en_tokenize(tokens):
|
| 286 |
+
if not ps:
|
| 287 |
+
continue
|
| 288 |
+
elif len(ps) > 510:
|
| 289 |
+
logger.warning(f"Unexpected len(ps) == {len(ps)} > 510 and ps == '{ps}'")
|
| 290 |
+
logger.warning("Truncating to 510 characters")
|
| 291 |
+
ps = ps[:510]
|
| 292 |
+
output = KPipeline.infer(model, ps, pack, speed) if model else None
|
| 293 |
+
if output is not None and output.pred_dur is not None:
|
| 294 |
+
KPipeline.join_timestamps(tks, output.pred_dur)
|
| 295 |
+
yield self.Result(graphemes=gs, phonemes=ps, tokens=tks, output=output)
|
| 296 |
+
|
| 297 |
+
@staticmethod
|
| 298 |
+
def join_timestamps(tokens: List[en.MToken], pred_dur: torch.LongTensor):
|
| 299 |
+
# Multiply by 600 to go from pred_dur frames to sample_rate 24000
|
| 300 |
+
# Equivalent to dividing pred_dur frames by 40 to get timestamp in seconds
|
| 301 |
+
# We will count nice round half-frames, so the divisor is 80
|
| 302 |
+
MAGIC_DIVISOR = 80
|
| 303 |
+
if not tokens or len(pred_dur) < 3:
|
| 304 |
+
# We expect at least 3: <bos>, token, <eos>
|
| 305 |
+
return
|
| 306 |
+
# We track 2 counts, measured in half-frames: (left, right)
|
| 307 |
+
# This way we can cut space characters in half
|
| 308 |
+
# TODO: Is -3 an appropriate offset?
|
| 309 |
+
left = right = 2 * max(0, pred_dur[0].item() - 3)
|
| 310 |
+
# Updates:
|
| 311 |
+
# left = right + (2 * token_dur) + space_dur
|
| 312 |
+
# right = left + space_dur
|
| 313 |
+
i = 1
|
| 314 |
+
for t in tokens:
|
| 315 |
+
if i >= len(pred_dur)-1:
|
| 316 |
+
break
|
| 317 |
+
if not t.phonemes:
|
| 318 |
+
if t.whitespace:
|
| 319 |
+
i += 1
|
| 320 |
+
left = right + pred_dur[i].item()
|
| 321 |
+
right = left + pred_dur[i].item()
|
| 322 |
+
i += 1
|
| 323 |
+
continue
|
| 324 |
+
j = i + len(t.phonemes)
|
| 325 |
+
if j >= len(pred_dur):
|
| 326 |
+
break
|
| 327 |
+
t.start_ts = left / MAGIC_DIVISOR
|
| 328 |
+
token_dur = pred_dur[i: j].sum().item()
|
| 329 |
+
space_dur = pred_dur[j].item() if t.whitespace else 0
|
| 330 |
+
left = right + (2 * token_dur) + space_dur
|
| 331 |
+
t.end_ts = left / MAGIC_DIVISOR
|
| 332 |
+
right = left + space_dur
|
| 333 |
+
i = j + (1 if t.whitespace else 0)
|
| 334 |
+
|
| 335 |
+
@dataclass
|
| 336 |
+
class Result:
|
| 337 |
+
graphemes: str
|
| 338 |
+
phonemes: str
|
| 339 |
+
tokens: Optional[List[en.MToken]] = None
|
| 340 |
+
output: Optional[KModel.Output] = None
|
| 341 |
+
text_index: Optional[int] = None
|
| 342 |
+
|
| 343 |
+
@property
|
| 344 |
+
def audio(self) -> Optional[torch.FloatTensor]:
|
| 345 |
+
return None if self.output is None else self.output.audio
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def pred_dur(self) -> Optional[torch.LongTensor]:
|
| 349 |
+
return None if self.output is None else self.output.pred_dur
|
| 350 |
+
|
| 351 |
+
### MARK: BEGIN BACKWARD COMPAT ###
|
| 352 |
+
def __iter__(self):
|
| 353 |
+
yield self.graphemes
|
| 354 |
+
yield self.phonemes
|
| 355 |
+
yield self.audio
|
| 356 |
+
|
| 357 |
+
def __getitem__(self, index):
|
| 358 |
+
return [self.graphemes, self.phonemes, self.audio][index]
|
| 359 |
+
|
| 360 |
+
def __len__(self):
|
| 361 |
+
return 3
|
| 362 |
+
#### MARK: END BACKWARD COMPAT ####
|
| 363 |
+
|
| 364 |
+
def __call__(
|
| 365 |
+
self,
|
| 366 |
+
text: Union[str, List[str]],
|
| 367 |
+
voice: Optional[str] = None,
|
| 368 |
+
speed: Union[float, Callable[[int], float]] = 1,
|
| 369 |
+
split_pattern: Optional[str] = r'\n+',
|
| 370 |
+
model: Optional[KModel] = None
|
| 371 |
+
) -> Generator['KPipeline.Result', None, None]:
|
| 372 |
+
model = model or self.model
|
| 373 |
+
if model and voice is None:
|
| 374 |
+
raise ValueError('Specify a voice: en_us_pipeline(text="Hello world!", voice="af_heart")')
|
| 375 |
+
pack = self.load_voice(voice).to(model.device) if model else None
|
| 376 |
+
|
| 377 |
+
# Convert input to list of segments
|
| 378 |
+
if isinstance(text, str):
|
| 379 |
+
text = re.split(split_pattern, text.strip()) if split_pattern else [text]
|
| 380 |
+
|
| 381 |
+
# Process each segment
|
| 382 |
+
for graphemes_index, graphemes in enumerate(text):
|
| 383 |
+
if not graphemes.strip(): # Skip empty segments
|
| 384 |
+
continue
|
| 385 |
+
|
| 386 |
+
# English processing (unchanged)
|
| 387 |
+
if self.lang_code in 'ab':
|
| 388 |
+
logger.debug(f"Processing English text: {graphemes[:50]}{'...' if len(graphemes) > 50 else ''}")
|
| 389 |
+
_, tokens = self.g2p(graphemes)
|
| 390 |
+
for gs, ps, tks in self.en_tokenize(tokens):
|
| 391 |
+
if not ps:
|
| 392 |
+
continue
|
| 393 |
+
elif len(ps) > 510:
|
| 394 |
+
logger.warning(f"Unexpected len(ps) == {len(ps)} > 510 and ps == '{ps}'")
|
| 395 |
+
ps = ps[:510]
|
| 396 |
+
output = KPipeline.infer(model, ps, pack, speed) if model else None
|
| 397 |
+
if output is not None and output.pred_dur is not None:
|
| 398 |
+
KPipeline.join_timestamps(tks, output.pred_dur)
|
| 399 |
+
yield self.Result(graphemes=gs, phonemes=ps, tokens=tks, output=output, text_index=graphemes_index)
|
| 400 |
+
|
| 401 |
+
# Non-English processing with chunking
|
| 402 |
+
else:
|
| 403 |
+
# Split long text into smaller chunks (roughly 400 characters each)
|
| 404 |
+
# Using sentence boundaries when possible
|
| 405 |
+
chunk_size = 400
|
| 406 |
+
chunks = []
|
| 407 |
+
|
| 408 |
+
# Try to split on sentence boundaries first
|
| 409 |
+
sentences = re.split(r'([.!?]+)', graphemes)
|
| 410 |
+
current_chunk = ""
|
| 411 |
+
|
| 412 |
+
for i in range(0, len(sentences), 2):
|
| 413 |
+
sentence = sentences[i]
|
| 414 |
+
# Add the punctuation back if it exists
|
| 415 |
+
if i + 1 < len(sentences):
|
| 416 |
+
sentence += sentences[i + 1]
|
| 417 |
+
|
| 418 |
+
if len(current_chunk) + len(sentence) <= chunk_size:
|
| 419 |
+
current_chunk += sentence
|
| 420 |
+
else:
|
| 421 |
+
if current_chunk:
|
| 422 |
+
chunks.append(current_chunk.strip())
|
| 423 |
+
current_chunk = sentence
|
| 424 |
+
|
| 425 |
+
if current_chunk:
|
| 426 |
+
chunks.append(current_chunk.strip())
|
| 427 |
+
|
| 428 |
+
# If no chunks were created (no sentence boundaries), fall back to character-based chunking
|
| 429 |
+
if not chunks:
|
| 430 |
+
chunks = [graphemes[i:i+chunk_size] for i in range(0, len(graphemes), chunk_size)]
|
| 431 |
+
|
| 432 |
+
# Process each chunk
|
| 433 |
+
for chunk in chunks:
|
| 434 |
+
if not chunk.strip():
|
| 435 |
+
continue
|
| 436 |
+
|
| 437 |
+
ps, _ = self.g2p(chunk)
|
| 438 |
+
if not ps:
|
| 439 |
+
continue
|
| 440 |
+
elif len(ps) > 510:
|
| 441 |
+
logger.warning(f'Truncating len(ps) == {len(ps)} > 510')
|
| 442 |
+
ps = ps[:510]
|
| 443 |
+
|
| 444 |
+
output = KPipeline.infer(model, ps, pack, speed) if model else None
|
| 445 |
+
yield self.Result(graphemes=chunk, phonemes=ps, output=output, text_index=graphemes_index)
|
requirements.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
opencv-python>=4.9.0.80
|
| 2 |
+
diffusers>=0.31.0
|
| 3 |
+
transformers>=4.49.0
|
| 4 |
+
tokenizers>=0.20.3
|
| 5 |
+
accelerate>=1.1.1
|
| 6 |
+
tqdm
|
| 7 |
+
imageio
|
| 8 |
+
easydict
|
| 9 |
+
ftfy
|
| 10 |
+
dashscope
|
| 11 |
+
imageio-ffmpeg
|
| 12 |
+
scikit-image
|
| 13 |
+
loguru
|
| 14 |
+
gradio>=5.0.0
|
| 15 |
+
numpy>=1.23.5,<2
|
| 16 |
+
xfuser>=0.4.1
|
| 17 |
+
pyloudnorm
|
| 18 |
+
optimum-quanto==0.2.6
|
| 19 |
+
scenedetect
|
| 20 |
+
moviepy==1.0.3
|
| 21 |
+
decord
|
setup.sh
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -e
|
| 3 |
+
|
| 4 |
+
echo "=== Setting up InfiniteTalk ==="
|
| 5 |
+
|
| 6 |
+
echo "Repository structure:"
|
| 7 |
+
ls -la InfiniteTalk/
|
| 8 |
+
|
| 9 |
+
# Add to Python path
|
| 10 |
+
export PYTHONPATH="/home/user/app/InfiniteTalk:$PYTHONPATH"
|
| 11 |
+
|
| 12 |
+
# Install requirements using pip3
|
| 13 |
+
echo "Installing Python requirements..."
|
| 14 |
+
pip3 install -r requirements.txt
|
| 15 |
+
|
| 16 |
+
# Test imports
|
| 17 |
+
echo "Testing imports..."
|
| 18 |
+
python3 -c "
|
| 19 |
+
import sys
|
| 20 |
+
sys.path.append('./InfiniteTalk')
|
| 21 |
+
try:
|
| 22 |
+
from wan.configs import SIZE_CONFIGS, SUPPORTED_SIZES, WAN_CONFIGS
|
| 23 |
+
print('✓ SUCCESS: All wan imports work!')
|
| 24 |
+
except ImportError as e:
|
| 25 |
+
print(f'✗ FAILED: {e}')
|
| 26 |
+
"
|
| 27 |
+
|
| 28 |
+
echo "=== Setup completed ==="
|