Commit
•
a8c6c0a
1
Parent(s):
4e077b8
Upload 20 files
Browse files- .gitattributes +15 -11
- .gitignore +164 -0
- LICENSE +661 -0
- README.md +6 -12
- attentions.py +344 -0
- bert_gen.py +54 -0
- commons.py +161 -0
- data_utils.py +328 -0
- losses.py +61 -0
- mel_processing.py +112 -0
- models.py +707 -0
- modules.py +452 -0
- preprocess_text.py +65 -0
- requirements.txt +130 -18
- resample.py +42 -0
- server.py +124 -0
- train_ms.py +396 -0
- transforms.py +193 -0
- utils.py +290 -0
- webui.py +136 -0
.gitattributes
CHANGED
@@ -1,35 +1,39 @@
|
|
1 |
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
*.bin filter=lfs diff=lfs merge=lfs -text
|
|
|
4 |
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
-
*.
|
35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bin.* filter=lfs diff=lfs merge=lfs -text
|
5 |
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
|
|
6 |
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
|
|
11 |
*.model filter=lfs diff=lfs merge=lfs -text
|
12 |
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
13 |
*.onnx filter=lfs diff=lfs merge=lfs -text
|
14 |
*.ot filter=lfs diff=lfs merge=lfs -text
|
15 |
*.parquet filter=lfs diff=lfs merge=lfs -text
|
16 |
*.pb filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
17 |
*.pt filter=lfs diff=lfs merge=lfs -text
|
18 |
*.pth filter=lfs diff=lfs merge=lfs -text
|
19 |
*.rar filter=lfs diff=lfs merge=lfs -text
|
|
|
20 |
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
21 |
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
|
|
22 |
*.tflite filter=lfs diff=lfs merge=lfs -text
|
23 |
*.tgz filter=lfs diff=lfs merge=lfs -text
|
|
|
24 |
*.xz filter=lfs diff=lfs merge=lfs -text
|
25 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
26 |
+
*.zstandard filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tfevents* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.db* filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.ark* filter=lfs diff=lfs merge=lfs -text
|
30 |
+
**/*ckpt*data* filter=lfs diff=lfs merge=lfs -text
|
31 |
+
**/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text
|
32 |
+
**/*ckpt*.index filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*.wav filter=lfs diff=lfs merge=lfs -text
|
36 |
+
flax_model.msgpack filter=lfs diff=lfs merge=lfs -text
|
37 |
+
pytorch_model.bin filter=lfs diff=lfs merge=lfs -text
|
38 |
+
tf_model.h5 filter=lfs diff=lfs merge=lfs -text
|
39 |
+
G_26800.pth filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
|
6 |
+
# C extensions
|
7 |
+
*.so
|
8 |
+
|
9 |
+
# Distribution / packaging
|
10 |
+
.Python
|
11 |
+
build/
|
12 |
+
develop-eggs/
|
13 |
+
dist/
|
14 |
+
downloads/
|
15 |
+
eggs/
|
16 |
+
.eggs/
|
17 |
+
lib/
|
18 |
+
lib64/
|
19 |
+
parts/
|
20 |
+
sdist/
|
21 |
+
var/
|
22 |
+
wheels/
|
23 |
+
share/python-wheels/
|
24 |
+
*.egg-info/
|
25 |
+
.installed.cfg
|
26 |
+
*.egg
|
27 |
+
MANIFEST
|
28 |
+
|
29 |
+
# PyInstaller
|
30 |
+
# Usually these files are written by a python script from a template
|
31 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
32 |
+
*.manifest
|
33 |
+
*.spec
|
34 |
+
|
35 |
+
# Installer logs
|
36 |
+
pip-log.txt
|
37 |
+
pip-delete-this-directory.txt
|
38 |
+
|
39 |
+
# Unit test / coverage reports
|
40 |
+
htmlcov/
|
41 |
+
.tox/
|
42 |
+
.nox/
|
43 |
+
.coverage
|
44 |
+
.coverage.*
|
45 |
+
.cache
|
46 |
+
nosetests.xml
|
47 |
+
coverage.xml
|
48 |
+
*.cover
|
49 |
+
*.py,cover
|
50 |
+
.hypothesis/
|
51 |
+
.pytest_cache/
|
52 |
+
cover/
|
53 |
+
|
54 |
+
# Translations
|
55 |
+
*.mo
|
56 |
+
*.pot
|
57 |
+
|
58 |
+
# Django stuff:
|
59 |
+
*.log
|
60 |
+
local_settings.py
|
61 |
+
db.sqlite3
|
62 |
+
db.sqlite3-journal
|
63 |
+
|
64 |
+
# Flask stuff:
|
65 |
+
instance/
|
66 |
+
.webassets-cache
|
67 |
+
|
68 |
+
# Scrapy stuff:
|
69 |
+
.scrapy
|
70 |
+
|
71 |
+
# Sphinx documentation
|
72 |
+
docs/_build/
|
73 |
+
|
74 |
+
# PyBuilder
|
75 |
+
.pybuilder/
|
76 |
+
target/
|
77 |
+
|
78 |
+
# Jupyter Notebook
|
79 |
+
.ipynb_checkpoints
|
80 |
+
|
81 |
+
# IPython
|
82 |
+
profile_default/
|
83 |
+
ipython_config.py
|
84 |
+
|
85 |
+
# pyenv
|
86 |
+
# For a library or package, you might want to ignore these files since the code is
|
87 |
+
# intended to run in multiple environments; otherwise, check them in:
|
88 |
+
# .python-version
|
89 |
+
|
90 |
+
# pipenv
|
91 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
92 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
93 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
94 |
+
# install all needed dependencies.
|
95 |
+
#Pipfile.lock
|
96 |
+
|
97 |
+
# poetry
|
98 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
99 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
100 |
+
# commonly ignored for libraries.
|
101 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
102 |
+
#poetry.lock
|
103 |
+
|
104 |
+
# pdm
|
105 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
106 |
+
#pdm.lock
|
107 |
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
108 |
+
# in version control.
|
109 |
+
# https://pdm.fming.dev/#use-with-ide
|
110 |
+
.pdm.toml
|
111 |
+
|
112 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
113 |
+
__pypackages__/
|
114 |
+
|
115 |
+
# Celery stuff
|
116 |
+
celerybeat-schedule
|
117 |
+
celerybeat.pid
|
118 |
+
|
119 |
+
# SageMath parsed files
|
120 |
+
*.sage.py
|
121 |
+
|
122 |
+
# Environments
|
123 |
+
.env
|
124 |
+
.venv
|
125 |
+
env/
|
126 |
+
venv/
|
127 |
+
ENV/
|
128 |
+
env.bak/
|
129 |
+
venv.bak/
|
130 |
+
|
131 |
+
# Spyder project settings
|
132 |
+
.spyderproject
|
133 |
+
.spyproject
|
134 |
+
|
135 |
+
# Rope project settings
|
136 |
+
.ropeproject
|
137 |
+
|
138 |
+
# mkdocs documentation
|
139 |
+
/site
|
140 |
+
|
141 |
+
# mypy
|
142 |
+
.mypy_cache/
|
143 |
+
.dmypy.json
|
144 |
+
dmypy.json
|
145 |
+
|
146 |
+
# Pyre type checker
|
147 |
+
.pyre/
|
148 |
+
|
149 |
+
# pytype static type analyzer
|
150 |
+
.pytype/
|
151 |
+
|
152 |
+
# Cython debug symbols
|
153 |
+
cython_debug/
|
154 |
+
|
155 |
+
# PyCharm
|
156 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
157 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
158 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
159 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
160 |
+
#.idea/
|
161 |
+
|
162 |
+
.DS_Store
|
163 |
+
/models
|
164 |
+
/logs
|
LICENSE
ADDED
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 19 November 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU Affero General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works, specifically designed to ensure
|
12 |
+
cooperation with the community in the case of network server software.
|
13 |
+
|
14 |
+
The licenses for most software and other practical works are designed
|
15 |
+
to take away your freedom to share and change the works. By contrast,
|
16 |
+
our General Public Licenses are intended to guarantee your freedom to
|
17 |
+
share and change all versions of a program--to make sure it remains free
|
18 |
+
software for all its users.
|
19 |
+
|
20 |
+
When we speak of free software, we are referring to freedom, not
|
21 |
+
price. Our General Public Licenses are designed to make sure that you
|
22 |
+
have the freedom to distribute copies of free software (and charge for
|
23 |
+
them if you wish), that you receive source code or can get it if you
|
24 |
+
want it, that you can change the software or use pieces of it in new
|
25 |
+
free programs, and that you know you can do these things.
|
26 |
+
|
27 |
+
Developers that use our General Public Licenses protect your rights
|
28 |
+
with two steps: (1) assert copyright on the software, and (2) offer
|
29 |
+
you this License which gives you legal permission to copy, distribute
|
30 |
+
and/or modify the software.
|
31 |
+
|
32 |
+
A secondary benefit of defending all users' freedom is that
|
33 |
+
improvements made in alternate versions of the program, if they
|
34 |
+
receive widespread use, become available for other developers to
|
35 |
+
incorporate. Many developers of free software are heartened and
|
36 |
+
encouraged by the resulting cooperation. However, in the case of
|
37 |
+
software used on network servers, this result may fail to come about.
|
38 |
+
The GNU General Public License permits making a modified version and
|
39 |
+
letting the public access it on a server without ever releasing its
|
40 |
+
source code to the public.
|
41 |
+
|
42 |
+
The GNU Affero General Public License is designed specifically to
|
43 |
+
ensure that, in such cases, the modified source code becomes available
|
44 |
+
to the community. It requires the operator of a network server to
|
45 |
+
provide the source code of the modified version running there to the
|
46 |
+
users of that server. Therefore, public use of a modified version, on
|
47 |
+
a publicly accessible server, gives the public access to the source
|
48 |
+
code of the modified version.
|
49 |
+
|
50 |
+
An older license, called the Affero General Public License and
|
51 |
+
published by Affero, was designed to accomplish similar goals. This is
|
52 |
+
a different license, not a version of the Affero GPL, but Affero has
|
53 |
+
released a new version of the Affero GPL which permits relicensing under
|
54 |
+
this license.
|
55 |
+
|
56 |
+
The precise terms and conditions for copying, distribution and
|
57 |
+
modification follow.
|
58 |
+
|
59 |
+
TERMS AND CONDITIONS
|
60 |
+
|
61 |
+
0. Definitions.
|
62 |
+
|
63 |
+
"This License" refers to version 3 of the GNU Affero General Public License.
|
64 |
+
|
65 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
66 |
+
works, such as semiconductor masks.
|
67 |
+
|
68 |
+
"The Program" refers to any copyrightable work licensed under this
|
69 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
70 |
+
"recipients" may be individuals or organizations.
|
71 |
+
|
72 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
73 |
+
in a fashion requiring copyright permission, other than the making of an
|
74 |
+
exact copy. The resulting work is called a "modified version" of the
|
75 |
+
earlier work or a work "based on" the earlier work.
|
76 |
+
|
77 |
+
A "covered work" means either the unmodified Program or a work based
|
78 |
+
on the Program.
|
79 |
+
|
80 |
+
To "propagate" a work means to do anything with it that, without
|
81 |
+
permission, would make you directly or secondarily liable for
|
82 |
+
infringement under applicable copyright law, except executing it on a
|
83 |
+
computer or modifying a private copy. Propagation includes copying,
|
84 |
+
distribution (with or without modification), making available to the
|
85 |
+
public, and in some countries other activities as well.
|
86 |
+
|
87 |
+
To "convey" a work means any kind of propagation that enables other
|
88 |
+
parties to make or receive copies. Mere interaction with a user through
|
89 |
+
a computer network, with no transfer of a copy, is not conveying.
|
90 |
+
|
91 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
92 |
+
to the extent that it includes a convenient and prominently visible
|
93 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
94 |
+
tells the user that there is no warranty for the work (except to the
|
95 |
+
extent that warranties are provided), that licensees may convey the
|
96 |
+
work under this License, and how to view a copy of this License. If
|
97 |
+
the interface presents a list of user commands or options, such as a
|
98 |
+
menu, a prominent item in the list meets this criterion.
|
99 |
+
|
100 |
+
1. Source Code.
|
101 |
+
|
102 |
+
The "source code" for a work means the preferred form of the work
|
103 |
+
for making modifications to it. "Object code" means any non-source
|
104 |
+
form of a work.
|
105 |
+
|
106 |
+
A "Standard Interface" means an interface that either is an official
|
107 |
+
standard defined by a recognized standards body, or, in the case of
|
108 |
+
interfaces specified for a particular programming language, one that
|
109 |
+
is widely used among developers working in that language.
|
110 |
+
|
111 |
+
The "System Libraries" of an executable work include anything, other
|
112 |
+
than the work as a whole, that (a) is included in the normal form of
|
113 |
+
packaging a Major Component, but which is not part of that Major
|
114 |
+
Component, and (b) serves only to enable use of the work with that
|
115 |
+
Major Component, or to implement a Standard Interface for which an
|
116 |
+
implementation is available to the public in source code form. A
|
117 |
+
"Major Component", in this context, means a major essential component
|
118 |
+
(kernel, window system, and so on) of the specific operating system
|
119 |
+
(if any) on which the executable work runs, or a compiler used to
|
120 |
+
produce the work, or an object code interpreter used to run it.
|
121 |
+
|
122 |
+
The "Corresponding Source" for a work in object code form means all
|
123 |
+
the source code needed to generate, install, and (for an executable
|
124 |
+
work) run the object code and to modify the work, including scripts to
|
125 |
+
control those activities. However, it does not include the work's
|
126 |
+
System Libraries, or general-purpose tools or generally available free
|
127 |
+
programs which are used unmodified in performing those activities but
|
128 |
+
which are not part of the work. For example, Corresponding Source
|
129 |
+
includes interface definition files associated with source files for
|
130 |
+
the work, and the source code for shared libraries and dynamically
|
131 |
+
linked subprograms that the work is specifically designed to require,
|
132 |
+
such as by intimate data communication or control flow between those
|
133 |
+
subprograms and other parts of the work.
|
134 |
+
|
135 |
+
The Corresponding Source need not include anything that users
|
136 |
+
can regenerate automatically from other parts of the Corresponding
|
137 |
+
Source.
|
138 |
+
|
139 |
+
The Corresponding Source for a work in source code form is that
|
140 |
+
same work.
|
141 |
+
|
142 |
+
2. Basic Permissions.
|
143 |
+
|
144 |
+
All rights granted under this License are granted for the term of
|
145 |
+
copyright on the Program, and are irrevocable provided the stated
|
146 |
+
conditions are met. This License explicitly affirms your unlimited
|
147 |
+
permission to run the unmodified Program. The output from running a
|
148 |
+
covered work is covered by this License only if the output, given its
|
149 |
+
content, constitutes a covered work. This License acknowledges your
|
150 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
151 |
+
|
152 |
+
You may make, run and propagate covered works that you do not
|
153 |
+
convey, without conditions so long as your license otherwise remains
|
154 |
+
in force. You may convey covered works to others for the sole purpose
|
155 |
+
of having them make modifications exclusively for you, or provide you
|
156 |
+
with facilities for running those works, provided that you comply with
|
157 |
+
the terms of this License in conveying all material for which you do
|
158 |
+
not control copyright. Those thus making or running the covered works
|
159 |
+
for you must do so exclusively on your behalf, under your direction
|
160 |
+
and control, on terms that prohibit them from making any copies of
|
161 |
+
your copyrighted material outside their relationship with you.
|
162 |
+
|
163 |
+
Conveying under any other circumstances is permitted solely under
|
164 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
165 |
+
makes it unnecessary.
|
166 |
+
|
167 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
168 |
+
|
169 |
+
No covered work shall be deemed part of an effective technological
|
170 |
+
measure under any applicable law fulfilling obligations under article
|
171 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
172 |
+
similar laws prohibiting or restricting circumvention of such
|
173 |
+
measures.
|
174 |
+
|
175 |
+
When you convey a covered work, you waive any legal power to forbid
|
176 |
+
circumvention of technological measures to the extent such circumvention
|
177 |
+
is effected by exercising rights under this License with respect to
|
178 |
+
the covered work, and you disclaim any intention to limit operation or
|
179 |
+
modification of the work as a means of enforcing, against the work's
|
180 |
+
users, your or third parties' legal rights to forbid circumvention of
|
181 |
+
technological measures.
|
182 |
+
|
183 |
+
4. Conveying Verbatim Copies.
|
184 |
+
|
185 |
+
You may convey verbatim copies of the Program's source code as you
|
186 |
+
receive it, in any medium, provided that you conspicuously and
|
187 |
+
appropriately publish on each copy an appropriate copyright notice;
|
188 |
+
keep intact all notices stating that this License and any
|
189 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
190 |
+
keep intact all notices of the absence of any warranty; and give all
|
191 |
+
recipients a copy of this License along with the Program.
|
192 |
+
|
193 |
+
You may charge any price or no price for each copy that you convey,
|
194 |
+
and you may offer support or warranty protection for a fee.
|
195 |
+
|
196 |
+
5. Conveying Modified Source Versions.
|
197 |
+
|
198 |
+
You may convey a work based on the Program, or the modifications to
|
199 |
+
produce it from the Program, in the form of source code under the
|
200 |
+
terms of section 4, provided that you also meet all of these conditions:
|
201 |
+
|
202 |
+
a) The work must carry prominent notices stating that you modified
|
203 |
+
it, and giving a relevant date.
|
204 |
+
|
205 |
+
b) The work must carry prominent notices stating that it is
|
206 |
+
released under this License and any conditions added under section
|
207 |
+
7. This requirement modifies the requirement in section 4 to
|
208 |
+
"keep intact all notices".
|
209 |
+
|
210 |
+
c) You must license the entire work, as a whole, under this
|
211 |
+
License to anyone who comes into possession of a copy. This
|
212 |
+
License will therefore apply, along with any applicable section 7
|
213 |
+
additional terms, to the whole of the work, and all its parts,
|
214 |
+
regardless of how they are packaged. This License gives no
|
215 |
+
permission to license the work in any other way, but it does not
|
216 |
+
invalidate such permission if you have separately received it.
|
217 |
+
|
218 |
+
d) If the work has interactive user interfaces, each must display
|
219 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
220 |
+
interfaces that do not display Appropriate Legal Notices, your
|
221 |
+
work need not make them do so.
|
222 |
+
|
223 |
+
A compilation of a covered work with other separate and independent
|
224 |
+
works, which are not by their nature extensions of the covered work,
|
225 |
+
and which are not combined with it such as to form a larger program,
|
226 |
+
in or on a volume of a storage or distribution medium, is called an
|
227 |
+
"aggregate" if the compilation and its resulting copyright are not
|
228 |
+
used to limit the access or legal rights of the compilation's users
|
229 |
+
beyond what the individual works permit. Inclusion of a covered work
|
230 |
+
in an aggregate does not cause this License to apply to the other
|
231 |
+
parts of the aggregate.
|
232 |
+
|
233 |
+
6. Conveying Non-Source Forms.
|
234 |
+
|
235 |
+
You may convey a covered work in object code form under the terms
|
236 |
+
of sections 4 and 5, provided that you also convey the
|
237 |
+
machine-readable Corresponding Source under the terms of this License,
|
238 |
+
in one of these ways:
|
239 |
+
|
240 |
+
a) Convey the object code in, or embodied in, a physical product
|
241 |
+
(including a physical distribution medium), accompanied by the
|
242 |
+
Corresponding Source fixed on a durable physical medium
|
243 |
+
customarily used for software interchange.
|
244 |
+
|
245 |
+
b) Convey the object code in, or embodied in, a physical product
|
246 |
+
(including a physical distribution medium), accompanied by a
|
247 |
+
written offer, valid for at least three years and valid for as
|
248 |
+
long as you offer spare parts or customer support for that product
|
249 |
+
model, to give anyone who possesses the object code either (1) a
|
250 |
+
copy of the Corresponding Source for all the software in the
|
251 |
+
product that is covered by this License, on a durable physical
|
252 |
+
medium customarily used for software interchange, for a price no
|
253 |
+
more than your reasonable cost of physically performing this
|
254 |
+
conveying of source, or (2) access to copy the
|
255 |
+
Corresponding Source from a network server at no charge.
|
256 |
+
|
257 |
+
c) Convey individual copies of the object code with a copy of the
|
258 |
+
written offer to provide the Corresponding Source. This
|
259 |
+
alternative is allowed only occasionally and noncommercially, and
|
260 |
+
only if you received the object code with such an offer, in accord
|
261 |
+
with subsection 6b.
|
262 |
+
|
263 |
+
d) Convey the object code by offering access from a designated
|
264 |
+
place (gratis or for a charge), and offer equivalent access to the
|
265 |
+
Corresponding Source in the same way through the same place at no
|
266 |
+
further charge. You need not require recipients to copy the
|
267 |
+
Corresponding Source along with the object code. If the place to
|
268 |
+
copy the object code is a network server, the Corresponding Source
|
269 |
+
may be on a different server (operated by you or a third party)
|
270 |
+
that supports equivalent copying facilities, provided you maintain
|
271 |
+
clear directions next to the object code saying where to find the
|
272 |
+
Corresponding Source. Regardless of what server hosts the
|
273 |
+
Corresponding Source, you remain obligated to ensure that it is
|
274 |
+
available for as long as needed to satisfy these requirements.
|
275 |
+
|
276 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
277 |
+
you inform other peers where the object code and Corresponding
|
278 |
+
Source of the work are being offered to the general public at no
|
279 |
+
charge under subsection 6d.
|
280 |
+
|
281 |
+
A separable portion of the object code, whose source code is excluded
|
282 |
+
from the Corresponding Source as a System Library, need not be
|
283 |
+
included in conveying the object code work.
|
284 |
+
|
285 |
+
A "User Product" is either (1) a "consumer product", which means any
|
286 |
+
tangible personal property which is normally used for personal, family,
|
287 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
288 |
+
into a dwelling. In determining whether a product is a consumer product,
|
289 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
290 |
+
product received by a particular user, "normally used" refers to a
|
291 |
+
typical or common use of that class of product, regardless of the status
|
292 |
+
of the particular user or of the way in which the particular user
|
293 |
+
actually uses, or expects or is expected to use, the product. A product
|
294 |
+
is a consumer product regardless of whether the product has substantial
|
295 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
296 |
+
the only significant mode of use of the product.
|
297 |
+
|
298 |
+
"Installation Information" for a User Product means any methods,
|
299 |
+
procedures, authorization keys, or other information required to install
|
300 |
+
and execute modified versions of a covered work in that User Product from
|
301 |
+
a modified version of its Corresponding Source. The information must
|
302 |
+
suffice to ensure that the continued functioning of the modified object
|
303 |
+
code is in no case prevented or interfered with solely because
|
304 |
+
modification has been made.
|
305 |
+
|
306 |
+
If you convey an object code work under this section in, or with, or
|
307 |
+
specifically for use in, a User Product, and the conveying occurs as
|
308 |
+
part of a transaction in which the right of possession and use of the
|
309 |
+
User Product is transferred to the recipient in perpetuity or for a
|
310 |
+
fixed term (regardless of how the transaction is characterized), the
|
311 |
+
Corresponding Source conveyed under this section must be accompanied
|
312 |
+
by the Installation Information. But this requirement does not apply
|
313 |
+
if neither you nor any third party retains the ability to install
|
314 |
+
modified object code on the User Product (for example, the work has
|
315 |
+
been installed in ROM).
|
316 |
+
|
317 |
+
The requirement to provide Installation Information does not include a
|
318 |
+
requirement to continue to provide support service, warranty, or updates
|
319 |
+
for a work that has been modified or installed by the recipient, or for
|
320 |
+
the User Product in which it has been modified or installed. Access to a
|
321 |
+
network may be denied when the modification itself materially and
|
322 |
+
adversely affects the operation of the network or violates the rules and
|
323 |
+
protocols for communication across the network.
|
324 |
+
|
325 |
+
Corresponding Source conveyed, and Installation Information provided,
|
326 |
+
in accord with this section must be in a format that is publicly
|
327 |
+
documented (and with an implementation available to the public in
|
328 |
+
source code form), and must require no special password or key for
|
329 |
+
unpacking, reading or copying.
|
330 |
+
|
331 |
+
7. Additional Terms.
|
332 |
+
|
333 |
+
"Additional permissions" are terms that supplement the terms of this
|
334 |
+
License by making exceptions from one or more of its conditions.
|
335 |
+
Additional permissions that are applicable to the entire Program shall
|
336 |
+
be treated as though they were included in this License, to the extent
|
337 |
+
that they are valid under applicable law. If additional permissions
|
338 |
+
apply only to part of the Program, that part may be used separately
|
339 |
+
under those permissions, but the entire Program remains governed by
|
340 |
+
this License without regard to the additional permissions.
|
341 |
+
|
342 |
+
When you convey a copy of a covered work, you may at your option
|
343 |
+
remove any additional permissions from that copy, or from any part of
|
344 |
+
it. (Additional permissions may be written to require their own
|
345 |
+
removal in certain cases when you modify the work.) You may place
|
346 |
+
additional permissions on material, added by you to a covered work,
|
347 |
+
for which you have or can give appropriate copyright permission.
|
348 |
+
|
349 |
+
Notwithstanding any other provision of this License, for material you
|
350 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
351 |
+
that material) supplement the terms of this License with terms:
|
352 |
+
|
353 |
+
a) Disclaiming warranty or limiting liability differently from the
|
354 |
+
terms of sections 15 and 16 of this License; or
|
355 |
+
|
356 |
+
b) Requiring preservation of specified reasonable legal notices or
|
357 |
+
author attributions in that material or in the Appropriate Legal
|
358 |
+
Notices displayed by works containing it; or
|
359 |
+
|
360 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
361 |
+
requiring that modified versions of such material be marked in
|
362 |
+
reasonable ways as different from the original version; or
|
363 |
+
|
364 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
365 |
+
authors of the material; or
|
366 |
+
|
367 |
+
e) Declining to grant rights under trademark law for use of some
|
368 |
+
trade names, trademarks, or service marks; or
|
369 |
+
|
370 |
+
f) Requiring indemnification of licensors and authors of that
|
371 |
+
material by anyone who conveys the material (or modified versions of
|
372 |
+
it) with contractual assumptions of liability to the recipient, for
|
373 |
+
any liability that these contractual assumptions directly impose on
|
374 |
+
those licensors and authors.
|
375 |
+
|
376 |
+
All other non-permissive additional terms are considered "further
|
377 |
+
restrictions" within the meaning of section 10. If the Program as you
|
378 |
+
received it, or any part of it, contains a notice stating that it is
|
379 |
+
governed by this License along with a term that is a further
|
380 |
+
restriction, you may remove that term. If a license document contains
|
381 |
+
a further restriction but permits relicensing or conveying under this
|
382 |
+
License, you may add to a covered work material governed by the terms
|
383 |
+
of that license document, provided that the further restriction does
|
384 |
+
not survive such relicensing or conveying.
|
385 |
+
|
386 |
+
If you add terms to a covered work in accord with this section, you
|
387 |
+
must place, in the relevant source files, a statement of the
|
388 |
+
additional terms that apply to those files, or a notice indicating
|
389 |
+
where to find the applicable terms.
|
390 |
+
|
391 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
392 |
+
form of a separately written license, or stated as exceptions;
|
393 |
+
the above requirements apply either way.
|
394 |
+
|
395 |
+
8. Termination.
|
396 |
+
|
397 |
+
You may not propagate or modify a covered work except as expressly
|
398 |
+
provided under this License. Any attempt otherwise to propagate or
|
399 |
+
modify it is void, and will automatically terminate your rights under
|
400 |
+
this License (including any patent licenses granted under the third
|
401 |
+
paragraph of section 11).
|
402 |
+
|
403 |
+
However, if you cease all violation of this License, then your
|
404 |
+
license from a particular copyright holder is reinstated (a)
|
405 |
+
provisionally, unless and until the copyright holder explicitly and
|
406 |
+
finally terminates your license, and (b) permanently, if the copyright
|
407 |
+
holder fails to notify you of the violation by some reasonable means
|
408 |
+
prior to 60 days after the cessation.
|
409 |
+
|
410 |
+
Moreover, your license from a particular copyright holder is
|
411 |
+
reinstated permanently if the copyright holder notifies you of the
|
412 |
+
violation by some reasonable means, this is the first time you have
|
413 |
+
received notice of violation of this License (for any work) from that
|
414 |
+
copyright holder, and you cure the violation prior to 30 days after
|
415 |
+
your receipt of the notice.
|
416 |
+
|
417 |
+
Termination of your rights under this section does not terminate the
|
418 |
+
licenses of parties who have received copies or rights from you under
|
419 |
+
this License. If your rights have been terminated and not permanently
|
420 |
+
reinstated, you do not qualify to receive new licenses for the same
|
421 |
+
material under section 10.
|
422 |
+
|
423 |
+
9. Acceptance Not Required for Having Copies.
|
424 |
+
|
425 |
+
You are not required to accept this License in order to receive or
|
426 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
427 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
428 |
+
to receive a copy likewise does not require acceptance. However,
|
429 |
+
nothing other than this License grants you permission to propagate or
|
430 |
+
modify any covered work. These actions infringe copyright if you do
|
431 |
+
not accept this License. Therefore, by modifying or propagating a
|
432 |
+
covered work, you indicate your acceptance of this License to do so.
|
433 |
+
|
434 |
+
10. Automatic Licensing of Downstream Recipients.
|
435 |
+
|
436 |
+
Each time you convey a covered work, the recipient automatically
|
437 |
+
receives a license from the original licensors, to run, modify and
|
438 |
+
propagate that work, subject to this License. You are not responsible
|
439 |
+
for enforcing compliance by third parties with this License.
|
440 |
+
|
441 |
+
An "entity transaction" is a transaction transferring control of an
|
442 |
+
organization, or substantially all assets of one, or subdividing an
|
443 |
+
organization, or merging organizations. If propagation of a covered
|
444 |
+
work results from an entity transaction, each party to that
|
445 |
+
transaction who receives a copy of the work also receives whatever
|
446 |
+
licenses to the work the party's predecessor in interest had or could
|
447 |
+
give under the previous paragraph, plus a right to possession of the
|
448 |
+
Corresponding Source of the work from the predecessor in interest, if
|
449 |
+
the predecessor has it or can get it with reasonable efforts.
|
450 |
+
|
451 |
+
You may not impose any further restrictions on the exercise of the
|
452 |
+
rights granted or affirmed under this License. For example, you may
|
453 |
+
not impose a license fee, royalty, or other charge for exercise of
|
454 |
+
rights granted under this License, and you may not initiate litigation
|
455 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
456 |
+
any patent claim is infringed by making, using, selling, offering for
|
457 |
+
sale, or importing the Program or any portion of it.
|
458 |
+
|
459 |
+
11. Patents.
|
460 |
+
|
461 |
+
A "contributor" is a copyright holder who authorizes use under this
|
462 |
+
License of the Program or a work on which the Program is based. The
|
463 |
+
work thus licensed is called the contributor's "contributor version".
|
464 |
+
|
465 |
+
A contributor's "essential patent claims" are all patent claims
|
466 |
+
owned or controlled by the contributor, whether already acquired or
|
467 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
468 |
+
by this License, of making, using, or selling its contributor version,
|
469 |
+
but do not include claims that would be infringed only as a
|
470 |
+
consequence of further modification of the contributor version. For
|
471 |
+
purposes of this definition, "control" includes the right to grant
|
472 |
+
patent sublicenses in a manner consistent with the requirements of
|
473 |
+
this License.
|
474 |
+
|
475 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
476 |
+
patent license under the contributor's essential patent claims, to
|
477 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
478 |
+
propagate the contents of its contributor version.
|
479 |
+
|
480 |
+
In the following three paragraphs, a "patent license" is any express
|
481 |
+
agreement or commitment, however denominated, not to enforce a patent
|
482 |
+
(such as an express permission to practice a patent or covenant not to
|
483 |
+
sue for patent infringement). To "grant" such a patent license to a
|
484 |
+
party means to make such an agreement or commitment not to enforce a
|
485 |
+
patent against the party.
|
486 |
+
|
487 |
+
If you convey a covered work, knowingly relying on a patent license,
|
488 |
+
and the Corresponding Source of the work is not available for anyone
|
489 |
+
to copy, free of charge and under the terms of this License, through a
|
490 |
+
publicly available network server or other readily accessible means,
|
491 |
+
then you must either (1) cause the Corresponding Source to be so
|
492 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
493 |
+
patent license for this particular work, or (3) arrange, in a manner
|
494 |
+
consistent with the requirements of this License, to extend the patent
|
495 |
+
license to downstream recipients. "Knowingly relying" means you have
|
496 |
+
actual knowledge that, but for the patent license, your conveying the
|
497 |
+
covered work in a country, or your recipient's use of the covered work
|
498 |
+
in a country, would infringe one or more identifiable patents in that
|
499 |
+
country that you have reason to believe are valid.
|
500 |
+
|
501 |
+
If, pursuant to or in connection with a single transaction or
|
502 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
503 |
+
covered work, and grant a patent license to some of the parties
|
504 |
+
receiving the covered work authorizing them to use, propagate, modify
|
505 |
+
or convey a specific copy of the covered work, then the patent license
|
506 |
+
you grant is automatically extended to all recipients of the covered
|
507 |
+
work and works based on it.
|
508 |
+
|
509 |
+
A patent license is "discriminatory" if it does not include within
|
510 |
+
the scope of its coverage, prohibits the exercise of, or is
|
511 |
+
conditioned on the non-exercise of one or more of the rights that are
|
512 |
+
specifically granted under this License. You may not convey a covered
|
513 |
+
work if you are a party to an arrangement with a third party that is
|
514 |
+
in the business of distributing software, under which you make payment
|
515 |
+
to the third party based on the extent of your activity of conveying
|
516 |
+
the work, and under which the third party grants, to any of the
|
517 |
+
parties who would receive the covered work from you, a discriminatory
|
518 |
+
patent license (a) in connection with copies of the covered work
|
519 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
520 |
+
for and in connection with specific products or compilations that
|
521 |
+
contain the covered work, unless you entered into that arrangement,
|
522 |
+
or that patent license was granted, prior to 28 March 2007.
|
523 |
+
|
524 |
+
Nothing in this License shall be construed as excluding or limiting
|
525 |
+
any implied license or other defenses to infringement that may
|
526 |
+
otherwise be available to you under applicable patent law.
|
527 |
+
|
528 |
+
12. No Surrender of Others' Freedom.
|
529 |
+
|
530 |
+
If conditions are imposed on you (whether by court order, agreement or
|
531 |
+
otherwise) that contradict the conditions of this License, they do not
|
532 |
+
excuse you from the conditions of this License. If you cannot convey a
|
533 |
+
covered work so as to satisfy simultaneously your obligations under this
|
534 |
+
License and any other pertinent obligations, then as a consequence you may
|
535 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
536 |
+
to collect a royalty for further conveying from those to whom you convey
|
537 |
+
the Program, the only way you could satisfy both those terms and this
|
538 |
+
License would be to refrain entirely from conveying the Program.
|
539 |
+
|
540 |
+
13. Remote Network Interaction; Use with the GNU General Public License.
|
541 |
+
|
542 |
+
Notwithstanding any other provision of this License, if you modify the
|
543 |
+
Program, your modified version must prominently offer all users
|
544 |
+
interacting with it remotely through a computer network (if your version
|
545 |
+
supports such interaction) an opportunity to receive the Corresponding
|
546 |
+
Source of your version by providing access to the Corresponding Source
|
547 |
+
from a network server at no charge, through some standard or customary
|
548 |
+
means of facilitating copying of software. This Corresponding Source
|
549 |
+
shall include the Corresponding Source for any work covered by version 3
|
550 |
+
of the GNU General Public License that is incorporated pursuant to the
|
551 |
+
following paragraph.
|
552 |
+
|
553 |
+
Notwithstanding any other provision of this License, you have
|
554 |
+
permission to link or combine any covered work with a work licensed
|
555 |
+
under version 3 of the GNU General Public License into a single
|
556 |
+
combined work, and to convey the resulting work. The terms of this
|
557 |
+
License will continue to apply to the part which is the covered work,
|
558 |
+
but the work with which it is combined will remain governed by version
|
559 |
+
3 of the GNU General Public License.
|
560 |
+
|
561 |
+
14. Revised Versions of this License.
|
562 |
+
|
563 |
+
The Free Software Foundation may publish revised and/or new versions of
|
564 |
+
the GNU Affero General Public License from time to time. Such new versions
|
565 |
+
will be similar in spirit to the present version, but may differ in detail to
|
566 |
+
address new problems or concerns.
|
567 |
+
|
568 |
+
Each version is given a distinguishing version number. If the
|
569 |
+
Program specifies that a certain numbered version of the GNU Affero General
|
570 |
+
Public License "or any later version" applies to it, you have the
|
571 |
+
option of following the terms and conditions either of that numbered
|
572 |
+
version or of any later version published by the Free Software
|
573 |
+
Foundation. If the Program does not specify a version number of the
|
574 |
+
GNU Affero General Public License, you may choose any version ever published
|
575 |
+
by the Free Software Foundation.
|
576 |
+
|
577 |
+
If the Program specifies that a proxy can decide which future
|
578 |
+
versions of the GNU Affero General Public License can be used, that proxy's
|
579 |
+
public statement of acceptance of a version permanently authorizes you
|
580 |
+
to choose that version for the Program.
|
581 |
+
|
582 |
+
Later license versions may give you additional or different
|
583 |
+
permissions. However, no additional obligations are imposed on any
|
584 |
+
author or copyright holder as a result of your choosing to follow a
|
585 |
+
later version.
|
586 |
+
|
587 |
+
15. Disclaimer of Warranty.
|
588 |
+
|
589 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
590 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
591 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
592 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
593 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
594 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
595 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
596 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
597 |
+
|
598 |
+
16. Limitation of Liability.
|
599 |
+
|
600 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
601 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
602 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
603 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
604 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
605 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
606 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
607 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
608 |
+
SUCH DAMAGES.
|
609 |
+
|
610 |
+
17. Interpretation of Sections 15 and 16.
|
611 |
+
|
612 |
+
If the disclaimer of warranty and limitation of liability provided
|
613 |
+
above cannot be given local legal effect according to their terms,
|
614 |
+
reviewing courts shall apply local law that most closely approximates
|
615 |
+
an absolute waiver of all civil liability in connection with the
|
616 |
+
Program, unless a warranty or assumption of liability accompanies a
|
617 |
+
copy of the Program in return for a fee.
|
618 |
+
|
619 |
+
END OF TERMS AND CONDITIONS
|
620 |
+
|
621 |
+
How to Apply These Terms to Your New Programs
|
622 |
+
|
623 |
+
If you develop a new program, and you want it to be of the greatest
|
624 |
+
possible use to the public, the best way to achieve this is to make it
|
625 |
+
free software which everyone can redistribute and change under these terms.
|
626 |
+
|
627 |
+
To do so, attach the following notices to the program. It is safest
|
628 |
+
to attach them to the start of each source file to most effectively
|
629 |
+
state the exclusion of warranty; and each file should have at least
|
630 |
+
the "copyright" line and a pointer to where the full notice is found.
|
631 |
+
|
632 |
+
<one line to give the program's name and a brief idea of what it does.>
|
633 |
+
Copyright (C) <year> <name of author>
|
634 |
+
|
635 |
+
This program is free software: you can redistribute it and/or modify
|
636 |
+
it under the terms of the GNU Affero General Public License as published
|
637 |
+
by the Free Software Foundation, either version 3 of the License, or
|
638 |
+
(at your option) any later version.
|
639 |
+
|
640 |
+
This program is distributed in the hope that it will be useful,
|
641 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
642 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
643 |
+
GNU Affero General Public License for more details.
|
644 |
+
|
645 |
+
You should have received a copy of the GNU Affero General Public License
|
646 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
647 |
+
|
648 |
+
Also add information on how to contact you by electronic and paper mail.
|
649 |
+
|
650 |
+
If your software can interact with users remotely through a computer
|
651 |
+
network, you should also make sure that it provides a way for users to
|
652 |
+
get its source. For example, if your program is a web application, its
|
653 |
+
interface could display a "Source" link that leads users to an archive
|
654 |
+
of the code. There are many ways you could offer source, and different
|
655 |
+
solutions will be better for different programs; see section 13 for the
|
656 |
+
specific requirements.
|
657 |
+
|
658 |
+
You should also get your employer (if you work as a programmer) or school,
|
659 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
660 |
+
For more information on this, and how to apply and follow the GNU AGPL, see
|
661 |
+
<https://www.gnu.org/licenses/>.
|
README.md
CHANGED
@@ -1,13 +1,7 @@
|
|
1 |
-
|
2 |
-
title: XuanShen Bert VITS2
|
3 |
-
emoji: 😻
|
4 |
-
colorFrom: purple
|
5 |
-
colorTo: yellow
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 3.45.2
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
license: apache-2.0
|
11 |
-
---
|
12 |
|
13 |
-
|
|
|
|
|
|
|
|
|
|
1 |
+
# Bert-VITS2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
+
VITS2 Backbone with bert
|
4 |
+
## 成熟的旅行者/开拓者/舰长/博士/sensei/猎魔人/喵喵露/V应该参阅代码自己学习如何训练。
|
5 |
+
### 严禁将此项目用于一切违反《中华人民共和国宪法》,《中华人民共和国刑法》,《中华人民共和国治安管理处罚法》和《中华人民共和国民法典》之用途。
|
6 |
+
#### Video:https://www.bilibili.com/video/BV1hp4y1K78E
|
7 |
+
#### Demo:https://www.bilibili.com/video/BV1TF411k78w
|
attentions.py
ADDED
@@ -0,0 +1,344 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import math
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
from torch.nn import functional as F
|
6 |
+
|
7 |
+
import commons
|
8 |
+
import logging
|
9 |
+
|
10 |
+
logger = logging.getLogger(__name__)
|
11 |
+
|
12 |
+
class LayerNorm(nn.Module):
|
13 |
+
def __init__(self, channels, eps=1e-5):
|
14 |
+
super().__init__()
|
15 |
+
self.channels = channels
|
16 |
+
self.eps = eps
|
17 |
+
|
18 |
+
self.gamma = nn.Parameter(torch.ones(channels))
|
19 |
+
self.beta = nn.Parameter(torch.zeros(channels))
|
20 |
+
|
21 |
+
def forward(self, x):
|
22 |
+
x = x.transpose(1, -1)
|
23 |
+
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
24 |
+
return x.transpose(1, -1)
|
25 |
+
|
26 |
+
|
27 |
+
|
28 |
+
@torch.jit.script
|
29 |
+
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
30 |
+
n_channels_int = n_channels[0]
|
31 |
+
in_act = input_a + input_b
|
32 |
+
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
33 |
+
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
34 |
+
acts = t_act * s_act
|
35 |
+
return acts
|
36 |
+
|
37 |
+
class Encoder(nn.Module):
|
38 |
+
def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, isflow = True, **kwargs):
|
39 |
+
super().__init__()
|
40 |
+
self.hidden_channels = hidden_channels
|
41 |
+
self.filter_channels = filter_channels
|
42 |
+
self.n_heads = n_heads
|
43 |
+
self.n_layers = n_layers
|
44 |
+
self.kernel_size = kernel_size
|
45 |
+
self.p_dropout = p_dropout
|
46 |
+
self.window_size = window_size
|
47 |
+
#if isflow:
|
48 |
+
# cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
|
49 |
+
# self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
|
50 |
+
# self.cond_layer = weight_norm(cond_layer, name='weight')
|
51 |
+
# self.gin_channels = 256
|
52 |
+
self.cond_layer_idx = self.n_layers
|
53 |
+
if 'gin_channels' in kwargs:
|
54 |
+
self.gin_channels = kwargs['gin_channels']
|
55 |
+
if self.gin_channels != 0:
|
56 |
+
self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
|
57 |
+
# vits2 says 3rd block, so idx is 2 by default
|
58 |
+
self.cond_layer_idx = kwargs['cond_layer_idx'] if 'cond_layer_idx' in kwargs else 2
|
59 |
+
logging.debug(self.gin_channels, self.cond_layer_idx)
|
60 |
+
assert self.cond_layer_idx < self.n_layers, 'cond_layer_idx should be less than n_layers'
|
61 |
+
self.drop = nn.Dropout(p_dropout)
|
62 |
+
self.attn_layers = nn.ModuleList()
|
63 |
+
self.norm_layers_1 = nn.ModuleList()
|
64 |
+
self.ffn_layers = nn.ModuleList()
|
65 |
+
self.norm_layers_2 = nn.ModuleList()
|
66 |
+
for i in range(self.n_layers):
|
67 |
+
self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
|
68 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
69 |
+
self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
|
70 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
71 |
+
def forward(self, x, x_mask, g=None):
|
72 |
+
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
73 |
+
x = x * x_mask
|
74 |
+
for i in range(self.n_layers):
|
75 |
+
if i == self.cond_layer_idx and g is not None:
|
76 |
+
g = self.spk_emb_linear(g.transpose(1, 2))
|
77 |
+
g = g.transpose(1, 2)
|
78 |
+
x = x + g
|
79 |
+
x = x * x_mask
|
80 |
+
y = self.attn_layers[i](x, x, attn_mask)
|
81 |
+
y = self.drop(y)
|
82 |
+
x = self.norm_layers_1[i](x + y)
|
83 |
+
|
84 |
+
y = self.ffn_layers[i](x, x_mask)
|
85 |
+
y = self.drop(y)
|
86 |
+
x = self.norm_layers_2[i](x + y)
|
87 |
+
x = x * x_mask
|
88 |
+
return x
|
89 |
+
|
90 |
+
|
91 |
+
class Decoder(nn.Module):
|
92 |
+
def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
|
93 |
+
super().__init__()
|
94 |
+
self.hidden_channels = hidden_channels
|
95 |
+
self.filter_channels = filter_channels
|
96 |
+
self.n_heads = n_heads
|
97 |
+
self.n_layers = n_layers
|
98 |
+
self.kernel_size = kernel_size
|
99 |
+
self.p_dropout = p_dropout
|
100 |
+
self.proximal_bias = proximal_bias
|
101 |
+
self.proximal_init = proximal_init
|
102 |
+
|
103 |
+
self.drop = nn.Dropout(p_dropout)
|
104 |
+
self.self_attn_layers = nn.ModuleList()
|
105 |
+
self.norm_layers_0 = nn.ModuleList()
|
106 |
+
self.encdec_attn_layers = nn.ModuleList()
|
107 |
+
self.norm_layers_1 = nn.ModuleList()
|
108 |
+
self.ffn_layers = nn.ModuleList()
|
109 |
+
self.norm_layers_2 = nn.ModuleList()
|
110 |
+
for i in range(self.n_layers):
|
111 |
+
self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
|
112 |
+
self.norm_layers_0.append(LayerNorm(hidden_channels))
|
113 |
+
self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
|
114 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
115 |
+
self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
|
116 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
117 |
+
|
118 |
+
def forward(self, x, x_mask, h, h_mask):
|
119 |
+
"""
|
120 |
+
x: decoder input
|
121 |
+
h: encoder output
|
122 |
+
"""
|
123 |
+
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
|
124 |
+
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
125 |
+
x = x * x_mask
|
126 |
+
for i in range(self.n_layers):
|
127 |
+
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
128 |
+
y = self.drop(y)
|
129 |
+
x = self.norm_layers_0[i](x + y)
|
130 |
+
|
131 |
+
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
|
132 |
+
y = self.drop(y)
|
133 |
+
x = self.norm_layers_1[i](x + y)
|
134 |
+
|
135 |
+
y = self.ffn_layers[i](x, x_mask)
|
136 |
+
y = self.drop(y)
|
137 |
+
x = self.norm_layers_2[i](x + y)
|
138 |
+
x = x * x_mask
|
139 |
+
return x
|
140 |
+
|
141 |
+
|
142 |
+
class MultiHeadAttention(nn.Module):
|
143 |
+
def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
|
144 |
+
super().__init__()
|
145 |
+
assert channels % n_heads == 0
|
146 |
+
|
147 |
+
self.channels = channels
|
148 |
+
self.out_channels = out_channels
|
149 |
+
self.n_heads = n_heads
|
150 |
+
self.p_dropout = p_dropout
|
151 |
+
self.window_size = window_size
|
152 |
+
self.heads_share = heads_share
|
153 |
+
self.block_length = block_length
|
154 |
+
self.proximal_bias = proximal_bias
|
155 |
+
self.proximal_init = proximal_init
|
156 |
+
self.attn = None
|
157 |
+
|
158 |
+
self.k_channels = channels // n_heads
|
159 |
+
self.conv_q = nn.Conv1d(channels, channels, 1)
|
160 |
+
self.conv_k = nn.Conv1d(channels, channels, 1)
|
161 |
+
self.conv_v = nn.Conv1d(channels, channels, 1)
|
162 |
+
self.conv_o = nn.Conv1d(channels, out_channels, 1)
|
163 |
+
self.drop = nn.Dropout(p_dropout)
|
164 |
+
|
165 |
+
if window_size is not None:
|
166 |
+
n_heads_rel = 1 if heads_share else n_heads
|
167 |
+
rel_stddev = self.k_channels**-0.5
|
168 |
+
self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
169 |
+
self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
170 |
+
|
171 |
+
nn.init.xavier_uniform_(self.conv_q.weight)
|
172 |
+
nn.init.xavier_uniform_(self.conv_k.weight)
|
173 |
+
nn.init.xavier_uniform_(self.conv_v.weight)
|
174 |
+
if proximal_init:
|
175 |
+
with torch.no_grad():
|
176 |
+
self.conv_k.weight.copy_(self.conv_q.weight)
|
177 |
+
self.conv_k.bias.copy_(self.conv_q.bias)
|
178 |
+
|
179 |
+
def forward(self, x, c, attn_mask=None):
|
180 |
+
q = self.conv_q(x)
|
181 |
+
k = self.conv_k(c)
|
182 |
+
v = self.conv_v(c)
|
183 |
+
|
184 |
+
x, self.attn = self.attention(q, k, v, mask=attn_mask)
|
185 |
+
|
186 |
+
x = self.conv_o(x)
|
187 |
+
return x
|
188 |
+
|
189 |
+
def attention(self, query, key, value, mask=None):
|
190 |
+
# reshape [b, d, t] -> [b, n_h, t, d_k]
|
191 |
+
b, d, t_s, t_t = (*key.size(), query.size(2))
|
192 |
+
query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
|
193 |
+
key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
194 |
+
value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
195 |
+
|
196 |
+
scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
|
197 |
+
if self.window_size is not None:
|
198 |
+
assert t_s == t_t, "Relative attention is only available for self-attention."
|
199 |
+
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
|
200 |
+
rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
|
201 |
+
scores_local = self._relative_position_to_absolute_position(rel_logits)
|
202 |
+
scores = scores + scores_local
|
203 |
+
if self.proximal_bias:
|
204 |
+
assert t_s == t_t, "Proximal bias is only available for self-attention."
|
205 |
+
scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
|
206 |
+
if mask is not None:
|
207 |
+
scores = scores.masked_fill(mask == 0, -1e4)
|
208 |
+
if self.block_length is not None:
|
209 |
+
assert t_s == t_t, "Local attention is only available for self-attention."
|
210 |
+
block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
|
211 |
+
scores = scores.masked_fill(block_mask == 0, -1e4)
|
212 |
+
p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
|
213 |
+
p_attn = self.drop(p_attn)
|
214 |
+
output = torch.matmul(p_attn, value)
|
215 |
+
if self.window_size is not None:
|
216 |
+
relative_weights = self._absolute_position_to_relative_position(p_attn)
|
217 |
+
value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
|
218 |
+
output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
|
219 |
+
output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
|
220 |
+
return output, p_attn
|
221 |
+
|
222 |
+
def _matmul_with_relative_values(self, x, y):
|
223 |
+
"""
|
224 |
+
x: [b, h, l, m]
|
225 |
+
y: [h or 1, m, d]
|
226 |
+
ret: [b, h, l, d]
|
227 |
+
"""
|
228 |
+
ret = torch.matmul(x, y.unsqueeze(0))
|
229 |
+
return ret
|
230 |
+
|
231 |
+
def _matmul_with_relative_keys(self, x, y):
|
232 |
+
"""
|
233 |
+
x: [b, h, l, d]
|
234 |
+
y: [h or 1, m, d]
|
235 |
+
ret: [b, h, l, m]
|
236 |
+
"""
|
237 |
+
ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
|
238 |
+
return ret
|
239 |
+
|
240 |
+
def _get_relative_embeddings(self, relative_embeddings, length):
|
241 |
+
max_relative_position = 2 * self.window_size + 1
|
242 |
+
# Pad first before slice to avoid using cond ops.
|
243 |
+
pad_length = max(length - (self.window_size + 1), 0)
|
244 |
+
slice_start_position = max((self.window_size + 1) - length, 0)
|
245 |
+
slice_end_position = slice_start_position + 2 * length - 1
|
246 |
+
if pad_length > 0:
|
247 |
+
padded_relative_embeddings = F.pad(
|
248 |
+
relative_embeddings,
|
249 |
+
commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
|
250 |
+
else:
|
251 |
+
padded_relative_embeddings = relative_embeddings
|
252 |
+
used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
|
253 |
+
return used_relative_embeddings
|
254 |
+
|
255 |
+
def _relative_position_to_absolute_position(self, x):
|
256 |
+
"""
|
257 |
+
x: [b, h, l, 2*l-1]
|
258 |
+
ret: [b, h, l, l]
|
259 |
+
"""
|
260 |
+
batch, heads, length, _ = x.size()
|
261 |
+
# Concat columns of pad to shift from relative to absolute indexing.
|
262 |
+
x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
|
263 |
+
|
264 |
+
# Concat extra elements so to add up to shape (len+1, 2*len-1).
|
265 |
+
x_flat = x.view([batch, heads, length * 2 * length])
|
266 |
+
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]]))
|
267 |
+
|
268 |
+
# Reshape and slice out the padded elements.
|
269 |
+
x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
|
270 |
+
return x_final
|
271 |
+
|
272 |
+
def _absolute_position_to_relative_position(self, x):
|
273 |
+
"""
|
274 |
+
x: [b, h, l, l]
|
275 |
+
ret: [b, h, l, 2*l-1]
|
276 |
+
"""
|
277 |
+
batch, heads, length, _ = x.size()
|
278 |
+
# padd along column
|
279 |
+
x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
|
280 |
+
x_flat = x.view([batch, heads, length**2 + length*(length -1)])
|
281 |
+
# add 0's in the beginning that will skew the elements after reshape
|
282 |
+
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
|
283 |
+
x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
|
284 |
+
return x_final
|
285 |
+
|
286 |
+
def _attention_bias_proximal(self, length):
|
287 |
+
"""Bias for self-attention to encourage attention to close positions.
|
288 |
+
Args:
|
289 |
+
length: an integer scalar.
|
290 |
+
Returns:
|
291 |
+
a Tensor with shape [1, 1, length, length]
|
292 |
+
"""
|
293 |
+
r = torch.arange(length, dtype=torch.float32)
|
294 |
+
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
|
295 |
+
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
|
296 |
+
|
297 |
+
|
298 |
+
class FFN(nn.Module):
|
299 |
+
def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
|
300 |
+
super().__init__()
|
301 |
+
self.in_channels = in_channels
|
302 |
+
self.out_channels = out_channels
|
303 |
+
self.filter_channels = filter_channels
|
304 |
+
self.kernel_size = kernel_size
|
305 |
+
self.p_dropout = p_dropout
|
306 |
+
self.activation = activation
|
307 |
+
self.causal = causal
|
308 |
+
|
309 |
+
if causal:
|
310 |
+
self.padding = self._causal_padding
|
311 |
+
else:
|
312 |
+
self.padding = self._same_padding
|
313 |
+
|
314 |
+
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
|
315 |
+
self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
|
316 |
+
self.drop = nn.Dropout(p_dropout)
|
317 |
+
|
318 |
+
def forward(self, x, x_mask):
|
319 |
+
x = self.conv_1(self.padding(x * x_mask))
|
320 |
+
if self.activation == "gelu":
|
321 |
+
x = x * torch.sigmoid(1.702 * x)
|
322 |
+
else:
|
323 |
+
x = torch.relu(x)
|
324 |
+
x = self.drop(x)
|
325 |
+
x = self.conv_2(self.padding(x * x_mask))
|
326 |
+
return x * x_mask
|
327 |
+
|
328 |
+
def _causal_padding(self, x):
|
329 |
+
if self.kernel_size == 1:
|
330 |
+
return x
|
331 |
+
pad_l = self.kernel_size - 1
|
332 |
+
pad_r = 0
|
333 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
334 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
335 |
+
return x
|
336 |
+
|
337 |
+
def _same_padding(self, x):
|
338 |
+
if self.kernel_size == 1:
|
339 |
+
return x
|
340 |
+
pad_l = (self.kernel_size - 1) // 2
|
341 |
+
pad_r = self.kernel_size // 2
|
342 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
343 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
344 |
+
return x
|
bert_gen.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch.utils.data import DataLoader
|
3 |
+
from multiprocessing import Pool
|
4 |
+
import commons
|
5 |
+
import utils
|
6 |
+
from data_utils import TextAudioSpeakerLoader, TextAudioSpeakerCollate
|
7 |
+
from tqdm import tqdm
|
8 |
+
import warnings
|
9 |
+
|
10 |
+
from text import cleaned_text_to_sequence, get_bert
|
11 |
+
|
12 |
+
config_path = 'configs/config.json'
|
13 |
+
hps = utils.get_hparams_from_file(config_path)
|
14 |
+
|
15 |
+
def process_line(line):
|
16 |
+
_id, spk, language_str, text, phones, tone, word2ph = line.strip().split("|")
|
17 |
+
phone = phones.split(" ")
|
18 |
+
tone = [int(i) for i in tone.split(" ")]
|
19 |
+
word2ph = [int(i) for i in word2ph.split(" ")]
|
20 |
+
w2pho = [i for i in word2ph]
|
21 |
+
word2ph = [i for i in word2ph]
|
22 |
+
phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
|
23 |
+
|
24 |
+
if hps.data.add_blank:
|
25 |
+
phone = commons.intersperse(phone, 0)
|
26 |
+
tone = commons.intersperse(tone, 0)
|
27 |
+
language = commons.intersperse(language, 0)
|
28 |
+
for i in range(len(word2ph)):
|
29 |
+
word2ph[i] = word2ph[i] * 2
|
30 |
+
word2ph[0] += 1
|
31 |
+
wav_path = f'{_id}'
|
32 |
+
|
33 |
+
bert_path = wav_path.replace(".wav", ".bert.pt")
|
34 |
+
|
35 |
+
try:
|
36 |
+
bert = torch.load(bert_path)
|
37 |
+
assert bert.shape[-1] == len(phone)
|
38 |
+
except:
|
39 |
+
bert = get_bert(text, word2ph, language_str)
|
40 |
+
assert bert.shape[-1] == len(phone)
|
41 |
+
torch.save(bert, bert_path)
|
42 |
+
|
43 |
+
|
44 |
+
if __name__ == '__main__':
|
45 |
+
lines = []
|
46 |
+
with open(hps.data.training_files, encoding='utf-8' ) as f:
|
47 |
+
lines.extend(f.readlines())
|
48 |
+
|
49 |
+
with open(hps.data.validation_files, encoding='utf-8' ) as f:
|
50 |
+
lines.extend(f.readlines())
|
51 |
+
|
52 |
+
with Pool(processes=6) as pool: #P40 24GB suitable config,if coom,please decrease the processess number.
|
53 |
+
for _ in tqdm(pool.imap_unordered(process_line, lines)):
|
54 |
+
pass
|
commons.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
from torch.nn import functional as F
|
6 |
+
|
7 |
+
|
8 |
+
def init_weights(m, mean=0.0, std=0.01):
|
9 |
+
classname = m.__class__.__name__
|
10 |
+
if classname.find("Conv") != -1:
|
11 |
+
m.weight.data.normal_(mean, std)
|
12 |
+
|
13 |
+
|
14 |
+
def get_padding(kernel_size, dilation=1):
|
15 |
+
return int((kernel_size*dilation - dilation)/2)
|
16 |
+
|
17 |
+
|
18 |
+
def convert_pad_shape(pad_shape):
|
19 |
+
l = pad_shape[::-1]
|
20 |
+
pad_shape = [item for sublist in l for item in sublist]
|
21 |
+
return pad_shape
|
22 |
+
|
23 |
+
|
24 |
+
def intersperse(lst, item):
|
25 |
+
result = [item] * (len(lst) * 2 + 1)
|
26 |
+
result[1::2] = lst
|
27 |
+
return result
|
28 |
+
|
29 |
+
|
30 |
+
def kl_divergence(m_p, logs_p, m_q, logs_q):
|
31 |
+
"""KL(P||Q)"""
|
32 |
+
kl = (logs_q - logs_p) - 0.5
|
33 |
+
kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q)
|
34 |
+
return kl
|
35 |
+
|
36 |
+
|
37 |
+
def rand_gumbel(shape):
|
38 |
+
"""Sample from the Gumbel distribution, protect from overflows."""
|
39 |
+
uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
|
40 |
+
return -torch.log(-torch.log(uniform_samples))
|
41 |
+
|
42 |
+
|
43 |
+
def rand_gumbel_like(x):
|
44 |
+
g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
|
45 |
+
return g
|
46 |
+
|
47 |
+
|
48 |
+
def slice_segments(x, ids_str, segment_size=4):
|
49 |
+
ret = torch.zeros_like(x[:, :, :segment_size])
|
50 |
+
for i in range(x.size(0)):
|
51 |
+
idx_str = ids_str[i]
|
52 |
+
idx_end = idx_str + segment_size
|
53 |
+
ret[i] = x[i, :, idx_str:idx_end]
|
54 |
+
return ret
|
55 |
+
|
56 |
+
|
57 |
+
def rand_slice_segments(x, x_lengths=None, segment_size=4):
|
58 |
+
b, d, t = x.size()
|
59 |
+
if x_lengths is None:
|
60 |
+
x_lengths = t
|
61 |
+
ids_str_max = x_lengths - segment_size + 1
|
62 |
+
ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
|
63 |
+
ret = slice_segments(x, ids_str, segment_size)
|
64 |
+
return ret, ids_str
|
65 |
+
|
66 |
+
|
67 |
+
def get_timing_signal_1d(
|
68 |
+
length, channels, min_timescale=1.0, max_timescale=1.0e4):
|
69 |
+
position = torch.arange(length, dtype=torch.float)
|
70 |
+
num_timescales = channels // 2
|
71 |
+
log_timescale_increment = (
|
72 |
+
math.log(float(max_timescale) / float(min_timescale)) /
|
73 |
+
(num_timescales - 1))
|
74 |
+
inv_timescales = min_timescale * torch.exp(
|
75 |
+
torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment)
|
76 |
+
scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
|
77 |
+
signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
|
78 |
+
signal = F.pad(signal, [0, 0, 0, channels % 2])
|
79 |
+
signal = signal.view(1, channels, length)
|
80 |
+
return signal
|
81 |
+
|
82 |
+
|
83 |
+
def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
|
84 |
+
b, channels, length = x.size()
|
85 |
+
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
|
86 |
+
return x + signal.to(dtype=x.dtype, device=x.device)
|
87 |
+
|
88 |
+
|
89 |
+
def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
|
90 |
+
b, channels, length = x.size()
|
91 |
+
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
|
92 |
+
return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
|
93 |
+
|
94 |
+
|
95 |
+
def subsequent_mask(length):
|
96 |
+
mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
|
97 |
+
return mask
|
98 |
+
|
99 |
+
|
100 |
+
@torch.jit.script
|
101 |
+
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
102 |
+
n_channels_int = n_channels[0]
|
103 |
+
in_act = input_a + input_b
|
104 |
+
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
105 |
+
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
106 |
+
acts = t_act * s_act
|
107 |
+
return acts
|
108 |
+
|
109 |
+
|
110 |
+
def convert_pad_shape(pad_shape):
|
111 |
+
l = pad_shape[::-1]
|
112 |
+
pad_shape = [item for sublist in l for item in sublist]
|
113 |
+
return pad_shape
|
114 |
+
|
115 |
+
|
116 |
+
def shift_1d(x):
|
117 |
+
x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
|
118 |
+
return x
|
119 |
+
|
120 |
+
|
121 |
+
def sequence_mask(length, max_length=None):
|
122 |
+
if max_length is None:
|
123 |
+
max_length = length.max()
|
124 |
+
x = torch.arange(max_length, dtype=length.dtype, device=length.device)
|
125 |
+
return x.unsqueeze(0) < length.unsqueeze(1)
|
126 |
+
|
127 |
+
|
128 |
+
def generate_path(duration, mask):
|
129 |
+
"""
|
130 |
+
duration: [b, 1, t_x]
|
131 |
+
mask: [b, 1, t_y, t_x]
|
132 |
+
"""
|
133 |
+
device = duration.device
|
134 |
+
|
135 |
+
b, _, t_y, t_x = mask.shape
|
136 |
+
cum_duration = torch.cumsum(duration, -1)
|
137 |
+
|
138 |
+
cum_duration_flat = cum_duration.view(b * t_x)
|
139 |
+
path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
|
140 |
+
path = path.view(b, t_x, t_y)
|
141 |
+
path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
|
142 |
+
path = path.unsqueeze(1).transpose(2,3) * mask
|
143 |
+
return path
|
144 |
+
|
145 |
+
|
146 |
+
def clip_grad_value_(parameters, clip_value, norm_type=2):
|
147 |
+
if isinstance(parameters, torch.Tensor):
|
148 |
+
parameters = [parameters]
|
149 |
+
parameters = list(filter(lambda p: p.grad is not None, parameters))
|
150 |
+
norm_type = float(norm_type)
|
151 |
+
if clip_value is not None:
|
152 |
+
clip_value = float(clip_value)
|
153 |
+
|
154 |
+
total_norm = 0
|
155 |
+
for p in parameters:
|
156 |
+
param_norm = p.grad.data.norm(norm_type)
|
157 |
+
total_norm += param_norm.item() ** norm_type
|
158 |
+
if clip_value is not None:
|
159 |
+
p.grad.data.clamp_(min=-clip_value, max=clip_value)
|
160 |
+
total_norm = total_norm ** (1. / norm_type)
|
161 |
+
return total_norm
|
data_utils.py
ADDED
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import time
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
import numpy as np
|
5 |
+
import torch
|
6 |
+
import torch.utils.data
|
7 |
+
import commons
|
8 |
+
from mel_processing import spectrogram_torch, mel_spectrogram_torch, spec_to_mel_torch
|
9 |
+
from utils import load_wav_to_torch, load_filepaths_and_text
|
10 |
+
from text import cleaned_text_to_sequence, get_bert
|
11 |
+
|
12 |
+
"""Multi speaker version"""
|
13 |
+
|
14 |
+
|
15 |
+
class TextAudioSpeakerLoader(torch.utils.data.Dataset):
|
16 |
+
"""
|
17 |
+
1) loads audio, speaker_id, text pairs
|
18 |
+
2) normalizes text and converts them to sequences of integers
|
19 |
+
3) computes spectrograms from audio files.
|
20 |
+
"""
|
21 |
+
|
22 |
+
def __init__(self, audiopaths_sid_text, hparams):
|
23 |
+
self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
|
24 |
+
self.max_wav_value = hparams.max_wav_value
|
25 |
+
self.sampling_rate = hparams.sampling_rate
|
26 |
+
self.filter_length = hparams.filter_length
|
27 |
+
self.hop_length = hparams.hop_length
|
28 |
+
self.win_length = hparams.win_length
|
29 |
+
self.sampling_rate = hparams.sampling_rate
|
30 |
+
self.spk_map = hparams.spk2id
|
31 |
+
self.hparams = hparams
|
32 |
+
|
33 |
+
self.use_mel_spec_posterior = getattr(hparams, "use_mel_posterior_encoder", False)
|
34 |
+
if self.use_mel_spec_posterior:
|
35 |
+
self.n_mel_channels = getattr(hparams, "n_mel_channels", 80)
|
36 |
+
|
37 |
+
self.cleaned_text = getattr(hparams, "cleaned_text", False)
|
38 |
+
|
39 |
+
self.add_blank = hparams.add_blank
|
40 |
+
self.min_text_len = getattr(hparams, "min_text_len", 1)
|
41 |
+
self.max_text_len = getattr(hparams, "max_text_len", 300)
|
42 |
+
|
43 |
+
random.seed(1234)
|
44 |
+
random.shuffle(self.audiopaths_sid_text)
|
45 |
+
self._filter()
|
46 |
+
|
47 |
+
def _filter(self):
|
48 |
+
"""
|
49 |
+
Filter text & store spec lengths
|
50 |
+
"""
|
51 |
+
# Store spectrogram lengths for Bucketing
|
52 |
+
# wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
|
53 |
+
# spec_length = wav_length // hop_length
|
54 |
+
|
55 |
+
audiopaths_sid_text_new = []
|
56 |
+
lengths = []
|
57 |
+
skipped = 0
|
58 |
+
for _id, spk, language, text, phones, tone, word2ph in self.audiopaths_sid_text:
|
59 |
+
audiopath = f'{_id}'
|
60 |
+
if self.min_text_len <= len(phones) and len(phones) <= self.max_text_len:
|
61 |
+
phones = phones.split(" ")
|
62 |
+
tone = [int(i) for i in tone.split(" ")]
|
63 |
+
word2ph = [int(i) for i in word2ph.split(" ")]
|
64 |
+
audiopaths_sid_text_new.append([audiopath, spk, language, text, phones, tone, word2ph])
|
65 |
+
lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
|
66 |
+
else:
|
67 |
+
skipped += 1
|
68 |
+
print("skipped: ", skipped, ", total: ", len(self.audiopaths_sid_text))
|
69 |
+
self.audiopaths_sid_text = audiopaths_sid_text_new
|
70 |
+
self.lengths = lengths
|
71 |
+
|
72 |
+
def get_audio_text_speaker_pair(self, audiopath_sid_text):
|
73 |
+
# separate filename, speaker_id and text
|
74 |
+
audiopath, sid, language, text, phones, tone, word2ph = audiopath_sid_text
|
75 |
+
|
76 |
+
bert, phones, tone, language = self.get_text(text, word2ph, phones, tone, language, audiopath)
|
77 |
+
|
78 |
+
spec, wav = self.get_audio(audiopath)
|
79 |
+
sid = torch.LongTensor([int(self.spk_map[sid])])
|
80 |
+
return (phones, spec, wav, sid, tone, language, bert)
|
81 |
+
|
82 |
+
def get_audio(self, filename):
|
83 |
+
audio, sampling_rate = load_wav_to_torch(filename)
|
84 |
+
if sampling_rate != self.sampling_rate:
|
85 |
+
raise ValueError("{} {} SR doesn't match target {} SR".format(
|
86 |
+
sampling_rate, self.sampling_rate))
|
87 |
+
audio_norm = audio / self.max_wav_value
|
88 |
+
audio_norm = audio_norm.unsqueeze(0)
|
89 |
+
spec_filename = filename.replace(".wav", ".spec.pt")
|
90 |
+
if self.use_mel_spec_posterior:
|
91 |
+
spec_filename = spec_filename.replace(".spec.pt", ".mel.pt")
|
92 |
+
try:
|
93 |
+
spec = torch.load(spec_filename)
|
94 |
+
except:
|
95 |
+
if self.use_mel_spec_posterior:
|
96 |
+
# if os.path.exists(filename.replace(".wav", ".spec.pt")):
|
97 |
+
# # spec, n_fft, num_mels, sampling_rate, fmin, fmax
|
98 |
+
# spec = spec_to_mel_torch(
|
99 |
+
# torch.load(filename.replace(".wav", ".spec.pt")),
|
100 |
+
# self.filter_length, self.n_mel_channels, self.sampling_rate,
|
101 |
+
# self.hparams.mel_fmin, self.hparams.mel_fmax)
|
102 |
+
spec = mel_spectrogram_torch(audio_norm, self.filter_length,
|
103 |
+
self.n_mel_channels, self.sampling_rate, self.hop_length,
|
104 |
+
self.win_length, self.hparams.mel_fmin, self.hparams.mel_fmax, center=False)
|
105 |
+
else:
|
106 |
+
spec = spectrogram_torch(audio_norm, self.filter_length,
|
107 |
+
self.sampling_rate, self.hop_length, self.win_length,
|
108 |
+
center=False)
|
109 |
+
spec = torch.squeeze(spec, 0)
|
110 |
+
torch.save(spec, spec_filename)
|
111 |
+
return spec, audio_norm
|
112 |
+
|
113 |
+
def get_text(self, text, word2ph, phone, tone, language_str, wav_path):
|
114 |
+
# print(text, word2ph,phone, tone, language_str)
|
115 |
+
pold = phone
|
116 |
+
w2pho = [i for i in word2ph]
|
117 |
+
word2ph = [i for i in word2ph]
|
118 |
+
phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
|
119 |
+
pold2 = phone
|
120 |
+
|
121 |
+
if self.add_blank:
|
122 |
+
p1 = len(phone)
|
123 |
+
phone = commons.intersperse(phone, 0)
|
124 |
+
p2 = len(phone)
|
125 |
+
t1 = len(tone)
|
126 |
+
tone = commons.intersperse(tone, 0)
|
127 |
+
t2 = len(tone)
|
128 |
+
language = commons.intersperse(language, 0)
|
129 |
+
for i in range(len(word2ph)):
|
130 |
+
word2ph[i] = word2ph[i] * 2
|
131 |
+
word2ph[0] += 1
|
132 |
+
bert_path = wav_path.replace(".wav", ".bert.pt")
|
133 |
+
try:
|
134 |
+
bert = torch.load(bert_path)
|
135 |
+
assert bert.shape[-1] == len(phone)
|
136 |
+
except:
|
137 |
+
bert = get_bert(text, word2ph, language_str)
|
138 |
+
torch.save(bert, bert_path)
|
139 |
+
#print(bert.shape[-1], bert_path, text, pold)
|
140 |
+
assert bert.shape[-1] == len(phone)
|
141 |
+
|
142 |
+
assert bert.shape[-1] == len(phone), (
|
143 |
+
bert.shape, len(phone), sum(word2ph), p1, p2, t1, t2, pold, pold2, word2ph, text, w2pho)
|
144 |
+
phone = torch.LongTensor(phone)
|
145 |
+
tone = torch.LongTensor(tone)
|
146 |
+
language = torch.LongTensor(language)
|
147 |
+
return bert, phone, tone, language
|
148 |
+
|
149 |
+
def get_sid(self, sid):
|
150 |
+
sid = torch.LongTensor([int(sid)])
|
151 |
+
return sid
|
152 |
+
|
153 |
+
def __getitem__(self, index):
|
154 |
+
return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
|
155 |
+
|
156 |
+
def __len__(self):
|
157 |
+
return len(self.audiopaths_sid_text)
|
158 |
+
|
159 |
+
|
160 |
+
class TextAudioSpeakerCollate():
|
161 |
+
""" Zero-pads model inputs and targets
|
162 |
+
"""
|
163 |
+
|
164 |
+
def __init__(self, return_ids=False):
|
165 |
+
self.return_ids = return_ids
|
166 |
+
|
167 |
+
def __call__(self, batch):
|
168 |
+
"""Collate's training batch from normalized text, audio and speaker identities
|
169 |
+
PARAMS
|
170 |
+
------
|
171 |
+
batch: [text_normalized, spec_normalized, wav_normalized, sid]
|
172 |
+
"""
|
173 |
+
# Right zero-pad all one-hot text sequences to max input length
|
174 |
+
_, ids_sorted_decreasing = torch.sort(
|
175 |
+
torch.LongTensor([x[1].size(1) for x in batch]),
|
176 |
+
dim=0, descending=True)
|
177 |
+
|
178 |
+
max_text_len = max([len(x[0]) for x in batch])
|
179 |
+
max_spec_len = max([x[1].size(1) for x in batch])
|
180 |
+
max_wav_len = max([x[2].size(1) for x in batch])
|
181 |
+
|
182 |
+
text_lengths = torch.LongTensor(len(batch))
|
183 |
+
spec_lengths = torch.LongTensor(len(batch))
|
184 |
+
wav_lengths = torch.LongTensor(len(batch))
|
185 |
+
sid = torch.LongTensor(len(batch))
|
186 |
+
|
187 |
+
text_padded = torch.LongTensor(len(batch), max_text_len)
|
188 |
+
tone_padded = torch.LongTensor(len(batch), max_text_len)
|
189 |
+
language_padded = torch.LongTensor(len(batch), max_text_len)
|
190 |
+
bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
|
191 |
+
|
192 |
+
spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
|
193 |
+
wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
|
194 |
+
text_padded.zero_()
|
195 |
+
tone_padded.zero_()
|
196 |
+
language_padded.zero_()
|
197 |
+
spec_padded.zero_()
|
198 |
+
wav_padded.zero_()
|
199 |
+
bert_padded.zero_()
|
200 |
+
for i in range(len(ids_sorted_decreasing)):
|
201 |
+
row = batch[ids_sorted_decreasing[i]]
|
202 |
+
|
203 |
+
text = row[0]
|
204 |
+
text_padded[i, :text.size(0)] = text
|
205 |
+
text_lengths[i] = text.size(0)
|
206 |
+
|
207 |
+
spec = row[1]
|
208 |
+
spec_padded[i, :, :spec.size(1)] = spec
|
209 |
+
spec_lengths[i] = spec.size(1)
|
210 |
+
|
211 |
+
wav = row[2]
|
212 |
+
wav_padded[i, :, :wav.size(1)] = wav
|
213 |
+
wav_lengths[i] = wav.size(1)
|
214 |
+
|
215 |
+
sid[i] = row[3]
|
216 |
+
|
217 |
+
tone = row[4]
|
218 |
+
tone_padded[i, :tone.size(0)] = tone
|
219 |
+
|
220 |
+
language = row[5]
|
221 |
+
language_padded[i, :language.size(0)] = language
|
222 |
+
|
223 |
+
bert = row[6]
|
224 |
+
bert_padded[i, :, :bert.size(1)] = bert
|
225 |
+
|
226 |
+
return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid, tone_padded, language_padded, bert_padded
|
227 |
+
|
228 |
+
|
229 |
+
class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
|
230 |
+
"""
|
231 |
+
Maintain similar input lengths in a batch.
|
232 |
+
Length groups are specified by boundaries.
|
233 |
+
Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
|
234 |
+
|
235 |
+
It removes samples which are not included in the boundaries.
|
236 |
+
Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
|
237 |
+
"""
|
238 |
+
|
239 |
+
def __init__(self, dataset, batch_size, boundaries, num_replicas=None, rank=None, shuffle=True):
|
240 |
+
super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
|
241 |
+
self.lengths = dataset.lengths
|
242 |
+
self.batch_size = batch_size
|
243 |
+
self.boundaries = boundaries
|
244 |
+
|
245 |
+
self.buckets, self.num_samples_per_bucket = self._create_buckets()
|
246 |
+
self.total_size = sum(self.num_samples_per_bucket)
|
247 |
+
self.num_samples = self.total_size // self.num_replicas
|
248 |
+
|
249 |
+
def _create_buckets(self):
|
250 |
+
buckets = [[] for _ in range(len(self.boundaries) - 1)]
|
251 |
+
for i in range(len(self.lengths)):
|
252 |
+
length = self.lengths[i]
|
253 |
+
idx_bucket = self._bisect(length)
|
254 |
+
if idx_bucket != -1:
|
255 |
+
buckets[idx_bucket].append(i)
|
256 |
+
|
257 |
+
for i in range(len(buckets) - 1, 0, -1):
|
258 |
+
if len(buckets[i]) == 0:
|
259 |
+
buckets.pop(i)
|
260 |
+
self.boundaries.pop(i + 1)
|
261 |
+
|
262 |
+
num_samples_per_bucket = []
|
263 |
+
for i in range(len(buckets)):
|
264 |
+
len_bucket = len(buckets[i])
|
265 |
+
total_batch_size = self.num_replicas * self.batch_size
|
266 |
+
rem = (total_batch_size - (len_bucket % total_batch_size)) % total_batch_size
|
267 |
+
num_samples_per_bucket.append(len_bucket + rem)
|
268 |
+
return buckets, num_samples_per_bucket
|
269 |
+
|
270 |
+
def __iter__(self):
|
271 |
+
# deterministically shuffle based on epoch
|
272 |
+
g = torch.Generator()
|
273 |
+
g.manual_seed(self.epoch)
|
274 |
+
|
275 |
+
indices = []
|
276 |
+
if self.shuffle:
|
277 |
+
for bucket in self.buckets:
|
278 |
+
indices.append(torch.randperm(len(bucket), generator=g).tolist())
|
279 |
+
else:
|
280 |
+
for bucket in self.buckets:
|
281 |
+
indices.append(list(range(len(bucket))))
|
282 |
+
|
283 |
+
batches = []
|
284 |
+
for i in range(len(self.buckets)):
|
285 |
+
bucket = self.buckets[i]
|
286 |
+
len_bucket = len(bucket)
|
287 |
+
if (len_bucket == 0):
|
288 |
+
continue
|
289 |
+
ids_bucket = indices[i]
|
290 |
+
num_samples_bucket = self.num_samples_per_bucket[i]
|
291 |
+
|
292 |
+
# add extra samples to make it evenly divisible
|
293 |
+
rem = num_samples_bucket - len_bucket
|
294 |
+
ids_bucket = ids_bucket + ids_bucket * (rem // len_bucket) + ids_bucket[:(rem % len_bucket)]
|
295 |
+
|
296 |
+
# subsample
|
297 |
+
ids_bucket = ids_bucket[self.rank::self.num_replicas]
|
298 |
+
|
299 |
+
# batching
|
300 |
+
for j in range(len(ids_bucket) // self.batch_size):
|
301 |
+
batch = [bucket[idx] for idx in ids_bucket[j * self.batch_size:(j + 1) * self.batch_size]]
|
302 |
+
batches.append(batch)
|
303 |
+
|
304 |
+
if self.shuffle:
|
305 |
+
batch_ids = torch.randperm(len(batches), generator=g).tolist()
|
306 |
+
batches = [batches[i] for i in batch_ids]
|
307 |
+
self.batches = batches
|
308 |
+
|
309 |
+
assert len(self.batches) * self.batch_size == self.num_samples
|
310 |
+
return iter(self.batches)
|
311 |
+
|
312 |
+
def _bisect(self, x, lo=0, hi=None):
|
313 |
+
if hi is None:
|
314 |
+
hi = len(self.boundaries) - 1
|
315 |
+
|
316 |
+
if hi > lo:
|
317 |
+
mid = (hi + lo) // 2
|
318 |
+
if self.boundaries[mid] < x and x <= self.boundaries[mid + 1]:
|
319 |
+
return mid
|
320 |
+
elif x <= self.boundaries[mid]:
|
321 |
+
return self._bisect(x, lo, mid)
|
322 |
+
else:
|
323 |
+
return self._bisect(x, mid + 1, hi)
|
324 |
+
else:
|
325 |
+
return -1
|
326 |
+
|
327 |
+
def __len__(self):
|
328 |
+
return self.num_samples // self.batch_size
|
losses.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch.nn import functional as F
|
3 |
+
|
4 |
+
import commons
|
5 |
+
|
6 |
+
|
7 |
+
def feature_loss(fmap_r, fmap_g):
|
8 |
+
loss = 0
|
9 |
+
for dr, dg in zip(fmap_r, fmap_g):
|
10 |
+
for rl, gl in zip(dr, dg):
|
11 |
+
rl = rl.float().detach()
|
12 |
+
gl = gl.float()
|
13 |
+
loss += torch.mean(torch.abs(rl - gl))
|
14 |
+
|
15 |
+
return loss * 2
|
16 |
+
|
17 |
+
|
18 |
+
def discriminator_loss(disc_real_outputs, disc_generated_outputs):
|
19 |
+
loss = 0
|
20 |
+
r_losses = []
|
21 |
+
g_losses = []
|
22 |
+
for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
|
23 |
+
dr = dr.float()
|
24 |
+
dg = dg.float()
|
25 |
+
r_loss = torch.mean((1-dr)**2)
|
26 |
+
g_loss = torch.mean(dg**2)
|
27 |
+
loss += (r_loss + g_loss)
|
28 |
+
r_losses.append(r_loss.item())
|
29 |
+
g_losses.append(g_loss.item())
|
30 |
+
|
31 |
+
return loss, r_losses, g_losses
|
32 |
+
|
33 |
+
|
34 |
+
def generator_loss(disc_outputs):
|
35 |
+
loss = 0
|
36 |
+
gen_losses = []
|
37 |
+
for dg in disc_outputs:
|
38 |
+
dg = dg.float()
|
39 |
+
l = torch.mean((1-dg)**2)
|
40 |
+
gen_losses.append(l)
|
41 |
+
loss += l
|
42 |
+
|
43 |
+
return loss, gen_losses
|
44 |
+
|
45 |
+
|
46 |
+
def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
|
47 |
+
"""
|
48 |
+
z_p, logs_q: [b, h, t_t]
|
49 |
+
m_p, logs_p: [b, h, t_t]
|
50 |
+
"""
|
51 |
+
z_p = z_p.float()
|
52 |
+
logs_q = logs_q.float()
|
53 |
+
m_p = m_p.float()
|
54 |
+
logs_p = logs_p.float()
|
55 |
+
z_mask = z_mask.float()
|
56 |
+
|
57 |
+
kl = logs_p - logs_q - 0.5
|
58 |
+
kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p)
|
59 |
+
kl = torch.sum(kl * z_mask)
|
60 |
+
l = kl / torch.sum(z_mask)
|
61 |
+
return l
|
mel_processing.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
import torch
|
5 |
+
from torch import nn
|
6 |
+
import torch.nn.functional as F
|
7 |
+
import torch.utils.data
|
8 |
+
import numpy as np
|
9 |
+
import librosa
|
10 |
+
import librosa.util as librosa_util
|
11 |
+
from librosa.util import normalize, pad_center, tiny
|
12 |
+
from scipy.signal import get_window
|
13 |
+
from scipy.io.wavfile import read
|
14 |
+
from librosa.filters import mel as librosa_mel_fn
|
15 |
+
|
16 |
+
MAX_WAV_VALUE = 32768.0
|
17 |
+
|
18 |
+
|
19 |
+
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
|
20 |
+
"""
|
21 |
+
PARAMS
|
22 |
+
------
|
23 |
+
C: compression factor
|
24 |
+
"""
|
25 |
+
return torch.log(torch.clamp(x, min=clip_val) * C)
|
26 |
+
|
27 |
+
|
28 |
+
def dynamic_range_decompression_torch(x, C=1):
|
29 |
+
"""
|
30 |
+
PARAMS
|
31 |
+
------
|
32 |
+
C: compression factor used to compress
|
33 |
+
"""
|
34 |
+
return torch.exp(x) / C
|
35 |
+
|
36 |
+
|
37 |
+
def spectral_normalize_torch(magnitudes):
|
38 |
+
output = dynamic_range_compression_torch(magnitudes)
|
39 |
+
return output
|
40 |
+
|
41 |
+
|
42 |
+
def spectral_de_normalize_torch(magnitudes):
|
43 |
+
output = dynamic_range_decompression_torch(magnitudes)
|
44 |
+
return output
|
45 |
+
|
46 |
+
|
47 |
+
mel_basis = {}
|
48 |
+
hann_window = {}
|
49 |
+
|
50 |
+
|
51 |
+
def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
|
52 |
+
if torch.min(y) < -1.:
|
53 |
+
print('min value is ', torch.min(y))
|
54 |
+
if torch.max(y) > 1.:
|
55 |
+
print('max value is ', torch.max(y))
|
56 |
+
|
57 |
+
global hann_window
|
58 |
+
dtype_device = str(y.dtype) + '_' + str(y.device)
|
59 |
+
wnsize_dtype_device = str(win_size) + '_' + dtype_device
|
60 |
+
if wnsize_dtype_device not in hann_window:
|
61 |
+
hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
|
62 |
+
|
63 |
+
y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
|
64 |
+
y = y.squeeze(1)
|
65 |
+
|
66 |
+
spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
|
67 |
+
center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
|
68 |
+
|
69 |
+
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
|
70 |
+
return spec
|
71 |
+
|
72 |
+
|
73 |
+
def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
|
74 |
+
global mel_basis
|
75 |
+
dtype_device = str(spec.dtype) + '_' + str(spec.device)
|
76 |
+
fmax_dtype_device = str(fmax) + '_' + dtype_device
|
77 |
+
if fmax_dtype_device not in mel_basis:
|
78 |
+
mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
|
79 |
+
mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
|
80 |
+
spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
|
81 |
+
spec = spectral_normalize_torch(spec)
|
82 |
+
return spec
|
83 |
+
|
84 |
+
|
85 |
+
def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
|
86 |
+
if torch.min(y) < -1.:
|
87 |
+
print('min value is ', torch.min(y))
|
88 |
+
if torch.max(y) > 1.:
|
89 |
+
print('max value is ', torch.max(y))
|
90 |
+
|
91 |
+
global mel_basis, hann_window
|
92 |
+
dtype_device = str(y.dtype) + '_' + str(y.device)
|
93 |
+
fmax_dtype_device = str(fmax) + '_' + dtype_device
|
94 |
+
wnsize_dtype_device = str(win_size) + '_' + dtype_device
|
95 |
+
if fmax_dtype_device not in mel_basis:
|
96 |
+
mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
|
97 |
+
mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device)
|
98 |
+
if wnsize_dtype_device not in hann_window:
|
99 |
+
hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
|
100 |
+
|
101 |
+
y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
|
102 |
+
y = y.squeeze(1)
|
103 |
+
|
104 |
+
spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
|
105 |
+
center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
|
106 |
+
|
107 |
+
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
|
108 |
+
|
109 |
+
spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
|
110 |
+
spec = spectral_normalize_torch(spec)
|
111 |
+
|
112 |
+
return spec
|
models.py
ADDED
@@ -0,0 +1,707 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import math
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
from torch.nn import functional as F
|
6 |
+
|
7 |
+
import commons
|
8 |
+
import modules
|
9 |
+
import attentions
|
10 |
+
import monotonic_align
|
11 |
+
|
12 |
+
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
|
13 |
+
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
|
14 |
+
|
15 |
+
from commons import init_weights, get_padding
|
16 |
+
from text import symbols, num_tones, num_languages
|
17 |
+
class DurationDiscriminator(nn.Module): #vits2
|
18 |
+
def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
|
19 |
+
super().__init__()
|
20 |
+
|
21 |
+
self.in_channels = in_channels
|
22 |
+
self.filter_channels = filter_channels
|
23 |
+
self.kernel_size = kernel_size
|
24 |
+
self.p_dropout = p_dropout
|
25 |
+
self.gin_channels = gin_channels
|
26 |
+
|
27 |
+
self.drop = nn.Dropout(p_dropout)
|
28 |
+
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2)
|
29 |
+
self.norm_1 = modules.LayerNorm(filter_channels)
|
30 |
+
self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
|
31 |
+
self.norm_2 = modules.LayerNorm(filter_channels)
|
32 |
+
self.dur_proj = nn.Conv1d(1, filter_channels, 1)
|
33 |
+
|
34 |
+
self.pre_out_conv_1 = nn.Conv1d(2*filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
|
35 |
+
self.pre_out_norm_1 = modules.LayerNorm(filter_channels)
|
36 |
+
self.pre_out_conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
|
37 |
+
self.pre_out_norm_2 = modules.LayerNorm(filter_channels)
|
38 |
+
|
39 |
+
if gin_channels != 0:
|
40 |
+
self.cond = nn.Conv1d(gin_channels, in_channels, 1)
|
41 |
+
|
42 |
+
self.output_layer = nn.Sequential(
|
43 |
+
nn.Linear(filter_channels, 1),
|
44 |
+
nn.Sigmoid()
|
45 |
+
)
|
46 |
+
|
47 |
+
def forward_probability(self, x, x_mask, dur, g=None):
|
48 |
+
dur = self.dur_proj(dur)
|
49 |
+
x = torch.cat([x, dur], dim=1)
|
50 |
+
x = self.pre_out_conv_1(x * x_mask)
|
51 |
+
x = torch.relu(x)
|
52 |
+
x = self.pre_out_norm_1(x)
|
53 |
+
x = self.drop(x)
|
54 |
+
x = self.pre_out_conv_2(x * x_mask)
|
55 |
+
x = torch.relu(x)
|
56 |
+
x = self.pre_out_norm_2(x)
|
57 |
+
x = self.drop(x)
|
58 |
+
x = x * x_mask
|
59 |
+
x = x.transpose(1, 2)
|
60 |
+
output_prob = self.output_layer(x)
|
61 |
+
return output_prob
|
62 |
+
|
63 |
+
def forward(self, x, x_mask, dur_r, dur_hat, g=None):
|
64 |
+
x = torch.detach(x)
|
65 |
+
if g is not None:
|
66 |
+
g = torch.detach(g)
|
67 |
+
x = x + self.cond(g)
|
68 |
+
x = self.conv_1(x * x_mask)
|
69 |
+
x = torch.relu(x)
|
70 |
+
x = self.norm_1(x)
|
71 |
+
x = self.drop(x)
|
72 |
+
x = self.conv_2(x * x_mask)
|
73 |
+
x = torch.relu(x)
|
74 |
+
x = self.norm_2(x)
|
75 |
+
x = self.drop(x)
|
76 |
+
|
77 |
+
output_probs = []
|
78 |
+
for dur in [dur_r, dur_hat]:
|
79 |
+
output_prob = self.forward_probability(x, x_mask, dur, g)
|
80 |
+
output_probs.append(output_prob)
|
81 |
+
|
82 |
+
return output_probs
|
83 |
+
|
84 |
+
class TransformerCouplingBlock(nn.Module):
|
85 |
+
def __init__(self,
|
86 |
+
channels,
|
87 |
+
hidden_channels,
|
88 |
+
filter_channels,
|
89 |
+
n_heads,
|
90 |
+
n_layers,
|
91 |
+
kernel_size,
|
92 |
+
p_dropout,
|
93 |
+
n_flows=4,
|
94 |
+
gin_channels=0,
|
95 |
+
share_parameter=False
|
96 |
+
):
|
97 |
+
|
98 |
+
super().__init__()
|
99 |
+
self.channels = channels
|
100 |
+
self.hidden_channels = hidden_channels
|
101 |
+
self.kernel_size = kernel_size
|
102 |
+
self.n_layers = n_layers
|
103 |
+
self.n_flows = n_flows
|
104 |
+
self.gin_channels = gin_channels
|
105 |
+
|
106 |
+
self.flows = nn.ModuleList()
|
107 |
+
|
108 |
+
self.wn = attentions.FFT(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, isflow = True, gin_channels = self.gin_channels) if share_parameter else None
|
109 |
+
|
110 |
+
for i in range(n_flows):
|
111 |
+
self.flows.append(
|
112 |
+
modules.TransformerCouplingLayer(channels, hidden_channels, kernel_size, n_layers, n_heads, p_dropout, filter_channels, mean_only=True, wn_sharing_parameter=self.wn, gin_channels = self.gin_channels))
|
113 |
+
self.flows.append(modules.Flip())
|
114 |
+
|
115 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
116 |
+
if not reverse:
|
117 |
+
for flow in self.flows:
|
118 |
+
x, _ = flow(x, x_mask, g=g, reverse=reverse)
|
119 |
+
else:
|
120 |
+
for flow in reversed(self.flows):
|
121 |
+
x = flow(x, x_mask, g=g, reverse=reverse)
|
122 |
+
return x
|
123 |
+
|
124 |
+
class StochasticDurationPredictor(nn.Module):
|
125 |
+
def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
|
126 |
+
super().__init__()
|
127 |
+
filter_channels = in_channels # it needs to be removed from future version.
|
128 |
+
self.in_channels = in_channels
|
129 |
+
self.filter_channels = filter_channels
|
130 |
+
self.kernel_size = kernel_size
|
131 |
+
self.p_dropout = p_dropout
|
132 |
+
self.n_flows = n_flows
|
133 |
+
self.gin_channels = gin_channels
|
134 |
+
|
135 |
+
self.log_flow = modules.Log()
|
136 |
+
self.flows = nn.ModuleList()
|
137 |
+
self.flows.append(modules.ElementwiseAffine(2))
|
138 |
+
for i in range(n_flows):
|
139 |
+
self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
|
140 |
+
self.flows.append(modules.Flip())
|
141 |
+
|
142 |
+
self.post_pre = nn.Conv1d(1, filter_channels, 1)
|
143 |
+
self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
144 |
+
self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
|
145 |
+
self.post_flows = nn.ModuleList()
|
146 |
+
self.post_flows.append(modules.ElementwiseAffine(2))
|
147 |
+
for i in range(4):
|
148 |
+
self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
|
149 |
+
self.post_flows.append(modules.Flip())
|
150 |
+
|
151 |
+
self.pre = nn.Conv1d(in_channels, filter_channels, 1)
|
152 |
+
self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
153 |
+
self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
|
154 |
+
if gin_channels != 0:
|
155 |
+
self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
|
156 |
+
|
157 |
+
def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
|
158 |
+
x = torch.detach(x)
|
159 |
+
x = self.pre(x)
|
160 |
+
if g is not None:
|
161 |
+
g = torch.detach(g)
|
162 |
+
x = x + self.cond(g)
|
163 |
+
x = self.convs(x, x_mask)
|
164 |
+
x = self.proj(x) * x_mask
|
165 |
+
|
166 |
+
if not reverse:
|
167 |
+
flows = self.flows
|
168 |
+
assert w is not None
|
169 |
+
|
170 |
+
logdet_tot_q = 0
|
171 |
+
h_w = self.post_pre(w)
|
172 |
+
h_w = self.post_convs(h_w, x_mask)
|
173 |
+
h_w = self.post_proj(h_w) * x_mask
|
174 |
+
e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
|
175 |
+
z_q = e_q
|
176 |
+
for flow in self.post_flows:
|
177 |
+
z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
|
178 |
+
logdet_tot_q += logdet_q
|
179 |
+
z_u, z1 = torch.split(z_q, [1, 1], 1)
|
180 |
+
u = torch.sigmoid(z_u) * x_mask
|
181 |
+
z0 = (w - u) * x_mask
|
182 |
+
logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2])
|
183 |
+
logq = torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q ** 2)) * x_mask, [1, 2]) - logdet_tot_q
|
184 |
+
|
185 |
+
logdet_tot = 0
|
186 |
+
z0, logdet = self.log_flow(z0, x_mask)
|
187 |
+
logdet_tot += logdet
|
188 |
+
z = torch.cat([z0, z1], 1)
|
189 |
+
for flow in flows:
|
190 |
+
z, logdet = flow(z, x_mask, g=x, reverse=reverse)
|
191 |
+
logdet_tot = logdet_tot + logdet
|
192 |
+
nll = torch.sum(0.5 * (math.log(2 * math.pi) + (z ** 2)) * x_mask, [1, 2]) - logdet_tot
|
193 |
+
return nll + logq # [b]
|
194 |
+
else:
|
195 |
+
flows = list(reversed(self.flows))
|
196 |
+
flows = flows[:-2] + [flows[-1]] # remove a useless vflow
|
197 |
+
z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
|
198 |
+
for flow in flows:
|
199 |
+
z = flow(z, x_mask, g=x, reverse=reverse)
|
200 |
+
z0, z1 = torch.split(z, [1, 1], 1)
|
201 |
+
logw = z0
|
202 |
+
return logw
|
203 |
+
|
204 |
+
|
205 |
+
class DurationPredictor(nn.Module):
|
206 |
+
def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
|
207 |
+
super().__init__()
|
208 |
+
|
209 |
+
self.in_channels = in_channels
|
210 |
+
self.filter_channels = filter_channels
|
211 |
+
self.kernel_size = kernel_size
|
212 |
+
self.p_dropout = p_dropout
|
213 |
+
self.gin_channels = gin_channels
|
214 |
+
|
215 |
+
self.drop = nn.Dropout(p_dropout)
|
216 |
+
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
|
217 |
+
self.norm_1 = modules.LayerNorm(filter_channels)
|
218 |
+
self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
|
219 |
+
self.norm_2 = modules.LayerNorm(filter_channels)
|
220 |
+
self.proj = nn.Conv1d(filter_channels, 1, 1)
|
221 |
+
|
222 |
+
if gin_channels != 0:
|
223 |
+
self.cond = nn.Conv1d(gin_channels, in_channels, 1)
|
224 |
+
|
225 |
+
def forward(self, x, x_mask, g=None):
|
226 |
+
x = torch.detach(x)
|
227 |
+
if g is not None:
|
228 |
+
g = torch.detach(g)
|
229 |
+
x = x + self.cond(g)
|
230 |
+
x = self.conv_1(x * x_mask)
|
231 |
+
x = torch.relu(x)
|
232 |
+
x = self.norm_1(x)
|
233 |
+
x = self.drop(x)
|
234 |
+
x = self.conv_2(x * x_mask)
|
235 |
+
x = torch.relu(x)
|
236 |
+
x = self.norm_2(x)
|
237 |
+
x = self.drop(x)
|
238 |
+
x = self.proj(x * x_mask)
|
239 |
+
return x * x_mask
|
240 |
+
|
241 |
+
|
242 |
+
class TextEncoder(nn.Module):
|
243 |
+
def __init__(self,
|
244 |
+
n_vocab,
|
245 |
+
out_channels,
|
246 |
+
hidden_channels,
|
247 |
+
filter_channels,
|
248 |
+
n_heads,
|
249 |
+
n_layers,
|
250 |
+
kernel_size,
|
251 |
+
p_dropout,
|
252 |
+
gin_channels=0):
|
253 |
+
super().__init__()
|
254 |
+
self.n_vocab = n_vocab
|
255 |
+
self.out_channels = out_channels
|
256 |
+
self.hidden_channels = hidden_channels
|
257 |
+
self.filter_channels = filter_channels
|
258 |
+
self.n_heads = n_heads
|
259 |
+
self.n_layers = n_layers
|
260 |
+
self.kernel_size = kernel_size
|
261 |
+
self.p_dropout = p_dropout
|
262 |
+
self.gin_channels = gin_channels
|
263 |
+
self.emb = nn.Embedding(len(symbols), hidden_channels)
|
264 |
+
nn.init.normal_(self.emb.weight, 0.0, hidden_channels ** -0.5)
|
265 |
+
self.tone_emb = nn.Embedding(num_tones, hidden_channels)
|
266 |
+
nn.init.normal_(self.tone_emb.weight, 0.0, hidden_channels ** -0.5)
|
267 |
+
self.language_emb = nn.Embedding(num_languages, hidden_channels)
|
268 |
+
nn.init.normal_(self.language_emb.weight, 0.0, hidden_channels ** -0.5)
|
269 |
+
self.bert_proj = nn.Conv1d(1024, hidden_channels, 1)
|
270 |
+
|
271 |
+
self.encoder = attentions.Encoder(
|
272 |
+
hidden_channels,
|
273 |
+
filter_channels,
|
274 |
+
n_heads,
|
275 |
+
n_layers,
|
276 |
+
kernel_size,
|
277 |
+
p_dropout,
|
278 |
+
gin_channels=self.gin_channels)
|
279 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
280 |
+
|
281 |
+
def forward(self, x, x_lengths, tone, language, bert, g=None):
|
282 |
+
x = (self.emb(x)+ self.tone_emb(tone)+ self.language_emb(language)+self.bert_proj(bert).transpose(1,2)) * math.sqrt(self.hidden_channels) # [b, t, h]
|
283 |
+
x = torch.transpose(x, 1, -1) # [b, h, t]
|
284 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
|
285 |
+
|
286 |
+
x = self.encoder(x * x_mask, x_mask, g=g)
|
287 |
+
stats = self.proj(x) * x_mask
|
288 |
+
|
289 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
290 |
+
return x, m, logs, x_mask
|
291 |
+
|
292 |
+
|
293 |
+
class ResidualCouplingBlock(nn.Module):
|
294 |
+
def __init__(self,
|
295 |
+
channels,
|
296 |
+
hidden_channels,
|
297 |
+
kernel_size,
|
298 |
+
dilation_rate,
|
299 |
+
n_layers,
|
300 |
+
n_flows=4,
|
301 |
+
gin_channels=0):
|
302 |
+
super().__init__()
|
303 |
+
self.channels = channels
|
304 |
+
self.hidden_channels = hidden_channels
|
305 |
+
self.kernel_size = kernel_size
|
306 |
+
self.dilation_rate = dilation_rate
|
307 |
+
self.n_layers = n_layers
|
308 |
+
self.n_flows = n_flows
|
309 |
+
self.gin_channels = gin_channels
|
310 |
+
|
311 |
+
self.flows = nn.ModuleList()
|
312 |
+
for i in range(n_flows):
|
313 |
+
self.flows.append(
|
314 |
+
modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers,
|
315 |
+
gin_channels=gin_channels, mean_only=True))
|
316 |
+
self.flows.append(modules.Flip())
|
317 |
+
|
318 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
319 |
+
if not reverse:
|
320 |
+
for flow in self.flows:
|
321 |
+
x, _ = flow(x, x_mask, g=g, reverse=reverse)
|
322 |
+
else:
|
323 |
+
for flow in reversed(self.flows):
|
324 |
+
x = flow(x, x_mask, g=g, reverse=reverse)
|
325 |
+
return x
|
326 |
+
|
327 |
+
|
328 |
+
class PosteriorEncoder(nn.Module):
|
329 |
+
def __init__(self,
|
330 |
+
in_channels,
|
331 |
+
out_channels,
|
332 |
+
hidden_channels,
|
333 |
+
kernel_size,
|
334 |
+
dilation_rate,
|
335 |
+
n_layers,
|
336 |
+
gin_channels=0):
|
337 |
+
super().__init__()
|
338 |
+
self.in_channels = in_channels
|
339 |
+
self.out_channels = out_channels
|
340 |
+
self.hidden_channels = hidden_channels
|
341 |
+
self.kernel_size = kernel_size
|
342 |
+
self.dilation_rate = dilation_rate
|
343 |
+
self.n_layers = n_layers
|
344 |
+
self.gin_channels = gin_channels
|
345 |
+
|
346 |
+
self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
|
347 |
+
self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
|
348 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
349 |
+
|
350 |
+
def forward(self, x, x_lengths, g=None):
|
351 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
|
352 |
+
x = self.pre(x) * x_mask
|
353 |
+
x = self.enc(x, x_mask, g=g)
|
354 |
+
stats = self.proj(x) * x_mask
|
355 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
356 |
+
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
|
357 |
+
return z, m, logs, x_mask
|
358 |
+
|
359 |
+
|
360 |
+
class Generator(torch.nn.Module):
|
361 |
+
def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
|
362 |
+
upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
|
363 |
+
super(Generator, self).__init__()
|
364 |
+
self.num_kernels = len(resblock_kernel_sizes)
|
365 |
+
self.num_upsamples = len(upsample_rates)
|
366 |
+
self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
|
367 |
+
resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
|
368 |
+
|
369 |
+
self.ups = nn.ModuleList()
|
370 |
+
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
371 |
+
self.ups.append(weight_norm(
|
372 |
+
ConvTranspose1d(upsample_initial_channel // (2 ** i), upsample_initial_channel // (2 ** (i + 1)),
|
373 |
+
k, u, padding=(k - u) // 2)))
|
374 |
+
|
375 |
+
self.resblocks = nn.ModuleList()
|
376 |
+
for i in range(len(self.ups)):
|
377 |
+
ch = upsample_initial_channel // (2 ** (i + 1))
|
378 |
+
for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
|
379 |
+
self.resblocks.append(resblock(ch, k, d))
|
380 |
+
|
381 |
+
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
|
382 |
+
self.ups.apply(init_weights)
|
383 |
+
|
384 |
+
if gin_channels != 0:
|
385 |
+
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
|
386 |
+
|
387 |
+
def forward(self, x, g=None):
|
388 |
+
x = self.conv_pre(x)
|
389 |
+
if g is not None:
|
390 |
+
x = x + self.cond(g)
|
391 |
+
|
392 |
+
for i in range(self.num_upsamples):
|
393 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
394 |
+
x = self.ups[i](x)
|
395 |
+
xs = None
|
396 |
+
for j in range(self.num_kernels):
|
397 |
+
if xs is None:
|
398 |
+
xs = self.resblocks[i * self.num_kernels + j](x)
|
399 |
+
else:
|
400 |
+
xs += self.resblocks[i * self.num_kernels + j](x)
|
401 |
+
x = xs / self.num_kernels
|
402 |
+
x = F.leaky_relu(x)
|
403 |
+
x = self.conv_post(x)
|
404 |
+
x = torch.tanh(x)
|
405 |
+
|
406 |
+
return x
|
407 |
+
|
408 |
+
def remove_weight_norm(self):
|
409 |
+
print('Removing weight norm...')
|
410 |
+
for l in self.ups:
|
411 |
+
remove_weight_norm(l)
|
412 |
+
for l in self.resblocks:
|
413 |
+
l.remove_weight_norm()
|
414 |
+
|
415 |
+
|
416 |
+
class DiscriminatorP(torch.nn.Module):
|
417 |
+
def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
|
418 |
+
super(DiscriminatorP, self).__init__()
|
419 |
+
self.period = period
|
420 |
+
self.use_spectral_norm = use_spectral_norm
|
421 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
422 |
+
self.convs = nn.ModuleList([
|
423 |
+
norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
|
424 |
+
norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
|
425 |
+
norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
|
426 |
+
norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
|
427 |
+
norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
|
428 |
+
])
|
429 |
+
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
|
430 |
+
|
431 |
+
def forward(self, x):
|
432 |
+
fmap = []
|
433 |
+
|
434 |
+
# 1d to 2d
|
435 |
+
b, c, t = x.shape
|
436 |
+
if t % self.period != 0: # pad first
|
437 |
+
n_pad = self.period - (t % self.period)
|
438 |
+
x = F.pad(x, (0, n_pad), "reflect")
|
439 |
+
t = t + n_pad
|
440 |
+
x = x.view(b, c, t // self.period, self.period)
|
441 |
+
|
442 |
+
for l in self.convs:
|
443 |
+
x = l(x)
|
444 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
445 |
+
fmap.append(x)
|
446 |
+
x = self.conv_post(x)
|
447 |
+
fmap.append(x)
|
448 |
+
x = torch.flatten(x, 1, -1)
|
449 |
+
|
450 |
+
return x, fmap
|
451 |
+
|
452 |
+
|
453 |
+
class DiscriminatorS(torch.nn.Module):
|
454 |
+
def __init__(self, use_spectral_norm=False):
|
455 |
+
super(DiscriminatorS, self).__init__()
|
456 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
457 |
+
self.convs = nn.ModuleList([
|
458 |
+
norm_f(Conv1d(1, 16, 15, 1, padding=7)),
|
459 |
+
norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
|
460 |
+
norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
|
461 |
+
norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
|
462 |
+
norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
|
463 |
+
norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
|
464 |
+
])
|
465 |
+
self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
|
466 |
+
|
467 |
+
def forward(self, x):
|
468 |
+
fmap = []
|
469 |
+
|
470 |
+
for l in self.convs:
|
471 |
+
x = l(x)
|
472 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
473 |
+
fmap.append(x)
|
474 |
+
x = self.conv_post(x)
|
475 |
+
fmap.append(x)
|
476 |
+
x = torch.flatten(x, 1, -1)
|
477 |
+
|
478 |
+
return x, fmap
|
479 |
+
|
480 |
+
|
481 |
+
class MultiPeriodDiscriminator(torch.nn.Module):
|
482 |
+
def __init__(self, use_spectral_norm=False):
|
483 |
+
super(MultiPeriodDiscriminator, self).__init__()
|
484 |
+
periods = [2, 3, 5, 7, 11]
|
485 |
+
|
486 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
487 |
+
discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
|
488 |
+
self.discriminators = nn.ModuleList(discs)
|
489 |
+
|
490 |
+
def forward(self, y, y_hat):
|
491 |
+
y_d_rs = []
|
492 |
+
y_d_gs = []
|
493 |
+
fmap_rs = []
|
494 |
+
fmap_gs = []
|
495 |
+
for i, d in enumerate(self.discriminators):
|
496 |
+
y_d_r, fmap_r = d(y)
|
497 |
+
y_d_g, fmap_g = d(y_hat)
|
498 |
+
y_d_rs.append(y_d_r)
|
499 |
+
y_d_gs.append(y_d_g)
|
500 |
+
fmap_rs.append(fmap_r)
|
501 |
+
fmap_gs.append(fmap_g)
|
502 |
+
|
503 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
504 |
+
|
505 |
+
class ReferenceEncoder(nn.Module):
|
506 |
+
'''
|
507 |
+
inputs --- [N, Ty/r, n_mels*r] mels
|
508 |
+
outputs --- [N, ref_enc_gru_size]
|
509 |
+
'''
|
510 |
+
|
511 |
+
def __init__(self, spec_channels, gin_channels=0):
|
512 |
+
|
513 |
+
super().__init__()
|
514 |
+
self.spec_channels = spec_channels
|
515 |
+
ref_enc_filters = [32, 32, 64, 64, 128, 128]
|
516 |
+
K = len(ref_enc_filters)
|
517 |
+
filters = [1] + ref_enc_filters
|
518 |
+
convs = [weight_norm(nn.Conv2d(in_channels=filters[i],
|
519 |
+
out_channels=filters[i + 1],
|
520 |
+
kernel_size=(3, 3),
|
521 |
+
stride=(2, 2),
|
522 |
+
padding=(1, 1))) for i in range(K)]
|
523 |
+
self.convs = nn.ModuleList(convs)
|
524 |
+
# self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)])
|
525 |
+
|
526 |
+
out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K)
|
527 |
+
self.gru = nn.GRU(input_size=ref_enc_filters[-1] * out_channels,
|
528 |
+
hidden_size=256 // 2,
|
529 |
+
batch_first=True)
|
530 |
+
self.proj = nn.Linear(128, gin_channels)
|
531 |
+
|
532 |
+
def forward(self, inputs, mask=None):
|
533 |
+
N = inputs.size(0)
|
534 |
+
out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs]
|
535 |
+
for conv in self.convs:
|
536 |
+
out = conv(out)
|
537 |
+
# out = wn(out)
|
538 |
+
out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K]
|
539 |
+
|
540 |
+
out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
|
541 |
+
T = out.size(1)
|
542 |
+
N = out.size(0)
|
543 |
+
out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
|
544 |
+
|
545 |
+
self.gru.flatten_parameters()
|
546 |
+
memory, out = self.gru(out) # out --- [1, N, 128]
|
547 |
+
|
548 |
+
return self.proj(out.squeeze(0))
|
549 |
+
|
550 |
+
def calculate_channels(self, L, kernel_size, stride, pad, n_convs):
|
551 |
+
for i in range(n_convs):
|
552 |
+
L = (L - kernel_size + 2 * pad) // stride + 1
|
553 |
+
return L
|
554 |
+
|
555 |
+
|
556 |
+
class SynthesizerTrn(nn.Module):
|
557 |
+
"""
|
558 |
+
Synthesizer for Training
|
559 |
+
"""
|
560 |
+
|
561 |
+
def __init__(self,
|
562 |
+
n_vocab,
|
563 |
+
spec_channels,
|
564 |
+
segment_size,
|
565 |
+
inter_channels,
|
566 |
+
hidden_channels,
|
567 |
+
filter_channels,
|
568 |
+
n_heads,
|
569 |
+
n_layers,
|
570 |
+
kernel_size,
|
571 |
+
p_dropout,
|
572 |
+
resblock,
|
573 |
+
resblock_kernel_sizes,
|
574 |
+
resblock_dilation_sizes,
|
575 |
+
upsample_rates,
|
576 |
+
upsample_initial_channel,
|
577 |
+
upsample_kernel_sizes,
|
578 |
+
n_speakers=256,
|
579 |
+
gin_channels=256,
|
580 |
+
use_sdp=True,
|
581 |
+
n_flow_layer = 4,
|
582 |
+
n_layers_trans_flow = 3,
|
583 |
+
flow_share_parameter = False,
|
584 |
+
use_transformer_flow = True,
|
585 |
+
**kwargs):
|
586 |
+
|
587 |
+
super().__init__()
|
588 |
+
self.n_vocab = n_vocab
|
589 |
+
self.spec_channels = spec_channels
|
590 |
+
self.inter_channels = inter_channels
|
591 |
+
self.hidden_channels = hidden_channels
|
592 |
+
self.filter_channels = filter_channels
|
593 |
+
self.n_heads = n_heads
|
594 |
+
self.n_layers = n_layers
|
595 |
+
self.kernel_size = kernel_size
|
596 |
+
self.p_dropout = p_dropout
|
597 |
+
self.resblock = resblock
|
598 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
599 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
600 |
+
self.upsample_rates = upsample_rates
|
601 |
+
self.upsample_initial_channel = upsample_initial_channel
|
602 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
603 |
+
self.segment_size = segment_size
|
604 |
+
self.n_speakers = n_speakers
|
605 |
+
self.gin_channels = gin_channels
|
606 |
+
self.n_layers_trans_flow = n_layers_trans_flow
|
607 |
+
self.use_spk_conditioned_encoder = kwargs.get("use_spk_conditioned_encoder", True)
|
608 |
+
self.use_sdp = use_sdp
|
609 |
+
self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False)
|
610 |
+
self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01)
|
611 |
+
self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6)
|
612 |
+
self.current_mas_noise_scale = self.mas_noise_scale_initial
|
613 |
+
if self.use_spk_conditioned_encoder and gin_channels > 0:
|
614 |
+
self.enc_gin_channels = gin_channels
|
615 |
+
self.enc_p = TextEncoder(n_vocab,
|
616 |
+
inter_channels,
|
617 |
+
hidden_channels,
|
618 |
+
filter_channels,
|
619 |
+
n_heads,
|
620 |
+
n_layers,
|
621 |
+
kernel_size,
|
622 |
+
p_dropout,
|
623 |
+
gin_channels=self.enc_gin_channels)
|
624 |
+
self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
|
625 |
+
upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
|
626 |
+
self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16,
|
627 |
+
gin_channels=gin_channels)
|
628 |
+
if use_transformer_flow:
|
629 |
+
self.flow = TransformerCouplingBlock(inter_channels, hidden_channels, filter_channels, n_heads, n_layers_trans_flow, 5, p_dropout, n_flow_layer, gin_channels=gin_channels,share_parameter= flow_share_parameter)
|
630 |
+
else:
|
631 |
+
self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, n_flow_layer, gin_channels=gin_channels)
|
632 |
+
self.sdp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels)
|
633 |
+
self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels)
|
634 |
+
|
635 |
+
if n_speakers > 1:
|
636 |
+
self.emb_g = nn.Embedding(n_speakers, gin_channels)
|
637 |
+
else:
|
638 |
+
self.ref_enc = ReferenceEncoder(spec_channels, gin_channels)
|
639 |
+
|
640 |
+
def forward(self, x, x_lengths, y, y_lengths, sid, tone, language, bert):
|
641 |
+
if self.n_speakers > 0:
|
642 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
643 |
+
else:
|
644 |
+
g = self.ref_enc(y.transpose(1,2)).unsqueeze(-1)
|
645 |
+
x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert,g=g)
|
646 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
647 |
+
z_p = self.flow(z, y_mask, g=g)
|
648 |
+
|
649 |
+
with torch.no_grad():
|
650 |
+
# negative cross-entropy
|
651 |
+
s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
|
652 |
+
neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s]
|
653 |
+
neg_cent2 = torch.matmul(-0.5 * (z_p ** 2).transpose(1, 2),
|
654 |
+
s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
|
655 |
+
neg_cent3 = torch.matmul(z_p.transpose(1, 2), (m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
|
656 |
+
neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s]
|
657 |
+
neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
|
658 |
+
if self.use_noise_scaled_mas:
|
659 |
+
epsilon = torch.std(neg_cent) * torch.randn_like(neg_cent) * self.current_mas_noise_scale
|
660 |
+
neg_cent = neg_cent + epsilon
|
661 |
+
|
662 |
+
attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
|
663 |
+
attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach()
|
664 |
+
|
665 |
+
w = attn.sum(2)
|
666 |
+
|
667 |
+
l_length_sdp = self.sdp(x, x_mask, w, g=g)
|
668 |
+
l_length_sdp = l_length_sdp / torch.sum(x_mask)
|
669 |
+
|
670 |
+
logw_ = torch.log(w + 1e-6) * x_mask
|
671 |
+
logw = self.dp(x, x_mask, g=g)
|
672 |
+
l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(x_mask) # for averaging
|
673 |
+
|
674 |
+
l_length = l_length_dp + l_length_sdp
|
675 |
+
|
676 |
+
# expand prior
|
677 |
+
m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
|
678 |
+
logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
|
679 |
+
|
680 |
+
z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
|
681 |
+
o = self.dec(z_slice, g=g)
|
682 |
+
return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q), (x, logw, logw_)
|
683 |
+
|
684 |
+
def infer(self, x, x_lengths, sid, tone, language, bert, noise_scale=.667, length_scale=1, noise_scale_w=0.8, max_len=None, sdp_ratio=0,y=None):
|
685 |
+
#x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert)
|
686 |
+
# g = self.gst(y)
|
687 |
+
if self.n_speakers > 0:
|
688 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
689 |
+
else:
|
690 |
+
g = self.ref_enc(y.transpose(1,2)).unsqueeze(-1)
|
691 |
+
x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert,g=g)
|
692 |
+
logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (sdp_ratio) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio)
|
693 |
+
w = torch.exp(logw) * x_mask * length_scale
|
694 |
+
w_ceil = torch.ceil(w)
|
695 |
+
y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
|
696 |
+
y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
|
697 |
+
attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
|
698 |
+
attn = commons.generate_path(w_ceil, attn_mask)
|
699 |
+
|
700 |
+
m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
|
701 |
+
logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1,
|
702 |
+
2) # [b, t', t], [b, t, d] -> [b, d, t']
|
703 |
+
|
704 |
+
z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
|
705 |
+
z = self.flow(z_p, y_mask, g=g, reverse=True)
|
706 |
+
o = self.dec((z * y_mask)[:, :, :max_len], g=g)
|
707 |
+
return o, attn, y_mask, (z, z_p, m_p, logs_p)
|
modules.py
ADDED
@@ -0,0 +1,452 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import math
|
3 |
+
import numpy as np
|
4 |
+
import scipy
|
5 |
+
import torch
|
6 |
+
from torch import nn
|
7 |
+
from torch.nn import functional as F
|
8 |
+
|
9 |
+
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
|
10 |
+
from torch.nn.utils import weight_norm, remove_weight_norm
|
11 |
+
|
12 |
+
import commons
|
13 |
+
from commons import init_weights, get_padding
|
14 |
+
from transforms import piecewise_rational_quadratic_transform
|
15 |
+
from attentions import Encoder
|
16 |
+
|
17 |
+
LRELU_SLOPE = 0.1
|
18 |
+
|
19 |
+
class LayerNorm(nn.Module):
|
20 |
+
def __init__(self, channels, eps=1e-5):
|
21 |
+
super().__init__()
|
22 |
+
self.channels = channels
|
23 |
+
self.eps = eps
|
24 |
+
|
25 |
+
self.gamma = nn.Parameter(torch.ones(channels))
|
26 |
+
self.beta = nn.Parameter(torch.zeros(channels))
|
27 |
+
|
28 |
+
def forward(self, x):
|
29 |
+
x = x.transpose(1, -1)
|
30 |
+
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
31 |
+
return x.transpose(1, -1)
|
32 |
+
|
33 |
+
class ConvReluNorm(nn.Module):
|
34 |
+
def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
|
35 |
+
super().__init__()
|
36 |
+
self.in_channels = in_channels
|
37 |
+
self.hidden_channels = hidden_channels
|
38 |
+
self.out_channels = out_channels
|
39 |
+
self.kernel_size = kernel_size
|
40 |
+
self.n_layers = n_layers
|
41 |
+
self.p_dropout = p_dropout
|
42 |
+
assert n_layers > 1, "Number of layers should be larger than 0."
|
43 |
+
|
44 |
+
self.conv_layers = nn.ModuleList()
|
45 |
+
self.norm_layers = nn.ModuleList()
|
46 |
+
self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
|
47 |
+
self.norm_layers.append(LayerNorm(hidden_channels))
|
48 |
+
self.relu_drop = nn.Sequential(
|
49 |
+
nn.ReLU(),
|
50 |
+
nn.Dropout(p_dropout))
|
51 |
+
for _ in range(n_layers-1):
|
52 |
+
self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
|
53 |
+
self.norm_layers.append(LayerNorm(hidden_channels))
|
54 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
|
55 |
+
self.proj.weight.data.zero_()
|
56 |
+
self.proj.bias.data.zero_()
|
57 |
+
|
58 |
+
def forward(self, x, x_mask):
|
59 |
+
x_org = x
|
60 |
+
for i in range(self.n_layers):
|
61 |
+
x = self.conv_layers[i](x * x_mask)
|
62 |
+
x = self.norm_layers[i](x)
|
63 |
+
x = self.relu_drop(x)
|
64 |
+
x = x_org + self.proj(x)
|
65 |
+
return x * x_mask
|
66 |
+
|
67 |
+
|
68 |
+
class DDSConv(nn.Module):
|
69 |
+
"""
|
70 |
+
Dialted and Depth-Separable Convolution
|
71 |
+
"""
|
72 |
+
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
|
73 |
+
super().__init__()
|
74 |
+
self.channels = channels
|
75 |
+
self.kernel_size = kernel_size
|
76 |
+
self.n_layers = n_layers
|
77 |
+
self.p_dropout = p_dropout
|
78 |
+
|
79 |
+
self.drop = nn.Dropout(p_dropout)
|
80 |
+
self.convs_sep = nn.ModuleList()
|
81 |
+
self.convs_1x1 = nn.ModuleList()
|
82 |
+
self.norms_1 = nn.ModuleList()
|
83 |
+
self.norms_2 = nn.ModuleList()
|
84 |
+
for i in range(n_layers):
|
85 |
+
dilation = kernel_size ** i
|
86 |
+
padding = (kernel_size * dilation - dilation) // 2
|
87 |
+
self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
|
88 |
+
groups=channels, dilation=dilation, padding=padding
|
89 |
+
))
|
90 |
+
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
|
91 |
+
self.norms_1.append(LayerNorm(channels))
|
92 |
+
self.norms_2.append(LayerNorm(channels))
|
93 |
+
|
94 |
+
def forward(self, x, x_mask, g=None):
|
95 |
+
if g is not None:
|
96 |
+
x = x + g
|
97 |
+
for i in range(self.n_layers):
|
98 |
+
y = self.convs_sep[i](x * x_mask)
|
99 |
+
y = self.norms_1[i](y)
|
100 |
+
y = F.gelu(y)
|
101 |
+
y = self.convs_1x1[i](y)
|
102 |
+
y = self.norms_2[i](y)
|
103 |
+
y = F.gelu(y)
|
104 |
+
y = self.drop(y)
|
105 |
+
x = x + y
|
106 |
+
return x * x_mask
|
107 |
+
|
108 |
+
|
109 |
+
class WN(torch.nn.Module):
|
110 |
+
def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
|
111 |
+
super(WN, self).__init__()
|
112 |
+
assert(kernel_size % 2 == 1)
|
113 |
+
self.hidden_channels =hidden_channels
|
114 |
+
self.kernel_size = kernel_size,
|
115 |
+
self.dilation_rate = dilation_rate
|
116 |
+
self.n_layers = n_layers
|
117 |
+
self.gin_channels = gin_channels
|
118 |
+
self.p_dropout = p_dropout
|
119 |
+
|
120 |
+
self.in_layers = torch.nn.ModuleList()
|
121 |
+
self.res_skip_layers = torch.nn.ModuleList()
|
122 |
+
self.drop = nn.Dropout(p_dropout)
|
123 |
+
|
124 |
+
if gin_channels != 0:
|
125 |
+
cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
|
126 |
+
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
|
127 |
+
|
128 |
+
for i in range(n_layers):
|
129 |
+
dilation = dilation_rate ** i
|
130 |
+
padding = int((kernel_size * dilation - dilation) / 2)
|
131 |
+
in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
|
132 |
+
dilation=dilation, padding=padding)
|
133 |
+
in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
|
134 |
+
self.in_layers.append(in_layer)
|
135 |
+
|
136 |
+
# last one is not necessary
|
137 |
+
if i < n_layers - 1:
|
138 |
+
res_skip_channels = 2 * hidden_channels
|
139 |
+
else:
|
140 |
+
res_skip_channels = hidden_channels
|
141 |
+
|
142 |
+
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
|
143 |
+
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
|
144 |
+
self.res_skip_layers.append(res_skip_layer)
|
145 |
+
|
146 |
+
def forward(self, x, x_mask, g=None, **kwargs):
|
147 |
+
output = torch.zeros_like(x)
|
148 |
+
n_channels_tensor = torch.IntTensor([self.hidden_channels])
|
149 |
+
|
150 |
+
if g is not None:
|
151 |
+
g = self.cond_layer(g)
|
152 |
+
|
153 |
+
for i in range(self.n_layers):
|
154 |
+
x_in = self.in_layers[i](x)
|
155 |
+
if g is not None:
|
156 |
+
cond_offset = i * 2 * self.hidden_channels
|
157 |
+
g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
|
158 |
+
else:
|
159 |
+
g_l = torch.zeros_like(x_in)
|
160 |
+
|
161 |
+
acts = commons.fused_add_tanh_sigmoid_multiply(
|
162 |
+
x_in,
|
163 |
+
g_l,
|
164 |
+
n_channels_tensor)
|
165 |
+
acts = self.drop(acts)
|
166 |
+
|
167 |
+
res_skip_acts = self.res_skip_layers[i](acts)
|
168 |
+
if i < self.n_layers - 1:
|
169 |
+
res_acts = res_skip_acts[:,:self.hidden_channels,:]
|
170 |
+
x = (x + res_acts) * x_mask
|
171 |
+
output = output + res_skip_acts[:,self.hidden_channels:,:]
|
172 |
+
else:
|
173 |
+
output = output + res_skip_acts
|
174 |
+
return output * x_mask
|
175 |
+
|
176 |
+
def remove_weight_norm(self):
|
177 |
+
if self.gin_channels != 0:
|
178 |
+
torch.nn.utils.remove_weight_norm(self.cond_layer)
|
179 |
+
for l in self.in_layers:
|
180 |
+
torch.nn.utils.remove_weight_norm(l)
|
181 |
+
for l in self.res_skip_layers:
|
182 |
+
torch.nn.utils.remove_weight_norm(l)
|
183 |
+
|
184 |
+
|
185 |
+
class ResBlock1(torch.nn.Module):
|
186 |
+
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
|
187 |
+
super(ResBlock1, self).__init__()
|
188 |
+
self.convs1 = nn.ModuleList([
|
189 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
|
190 |
+
padding=get_padding(kernel_size, dilation[0]))),
|
191 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
|
192 |
+
padding=get_padding(kernel_size, dilation[1]))),
|
193 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
|
194 |
+
padding=get_padding(kernel_size, dilation[2])))
|
195 |
+
])
|
196 |
+
self.convs1.apply(init_weights)
|
197 |
+
|
198 |
+
self.convs2 = nn.ModuleList([
|
199 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
200 |
+
padding=get_padding(kernel_size, 1))),
|
201 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
202 |
+
padding=get_padding(kernel_size, 1))),
|
203 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
204 |
+
padding=get_padding(kernel_size, 1)))
|
205 |
+
])
|
206 |
+
self.convs2.apply(init_weights)
|
207 |
+
|
208 |
+
def forward(self, x, x_mask=None):
|
209 |
+
for c1, c2 in zip(self.convs1, self.convs2):
|
210 |
+
xt = F.leaky_relu(x, LRELU_SLOPE)
|
211 |
+
if x_mask is not None:
|
212 |
+
xt = xt * x_mask
|
213 |
+
xt = c1(xt)
|
214 |
+
xt = F.leaky_relu(xt, LRELU_SLOPE)
|
215 |
+
if x_mask is not None:
|
216 |
+
xt = xt * x_mask
|
217 |
+
xt = c2(xt)
|
218 |
+
x = xt + x
|
219 |
+
if x_mask is not None:
|
220 |
+
x = x * x_mask
|
221 |
+
return x
|
222 |
+
|
223 |
+
def remove_weight_norm(self):
|
224 |
+
for l in self.convs1:
|
225 |
+
remove_weight_norm(l)
|
226 |
+
for l in self.convs2:
|
227 |
+
remove_weight_norm(l)
|
228 |
+
|
229 |
+
|
230 |
+
class ResBlock2(torch.nn.Module):
|
231 |
+
def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
|
232 |
+
super(ResBlock2, self).__init__()
|
233 |
+
self.convs = nn.ModuleList([
|
234 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
|
235 |
+
padding=get_padding(kernel_size, dilation[0]))),
|
236 |
+
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
|
237 |
+
padding=get_padding(kernel_size, dilation[1])))
|
238 |
+
])
|
239 |
+
self.convs.apply(init_weights)
|
240 |
+
|
241 |
+
def forward(self, x, x_mask=None):
|
242 |
+
for c in self.convs:
|
243 |
+
xt = F.leaky_relu(x, LRELU_SLOPE)
|
244 |
+
if x_mask is not None:
|
245 |
+
xt = xt * x_mask
|
246 |
+
xt = c(xt)
|
247 |
+
x = xt + x
|
248 |
+
if x_mask is not None:
|
249 |
+
x = x * x_mask
|
250 |
+
return x
|
251 |
+
|
252 |
+
def remove_weight_norm(self):
|
253 |
+
for l in self.convs:
|
254 |
+
remove_weight_norm(l)
|
255 |
+
|
256 |
+
|
257 |
+
class Log(nn.Module):
|
258 |
+
def forward(self, x, x_mask, reverse=False, **kwargs):
|
259 |
+
if not reverse:
|
260 |
+
y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
|
261 |
+
logdet = torch.sum(-y, [1, 2])
|
262 |
+
return y, logdet
|
263 |
+
else:
|
264 |
+
x = torch.exp(x) * x_mask
|
265 |
+
return x
|
266 |
+
|
267 |
+
|
268 |
+
class Flip(nn.Module):
|
269 |
+
def forward(self, x, *args, reverse=False, **kwargs):
|
270 |
+
x = torch.flip(x, [1])
|
271 |
+
if not reverse:
|
272 |
+
logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
|
273 |
+
return x, logdet
|
274 |
+
else:
|
275 |
+
return x
|
276 |
+
|
277 |
+
|
278 |
+
class ElementwiseAffine(nn.Module):
|
279 |
+
def __init__(self, channels):
|
280 |
+
super().__init__()
|
281 |
+
self.channels = channels
|
282 |
+
self.m = nn.Parameter(torch.zeros(channels,1))
|
283 |
+
self.logs = nn.Parameter(torch.zeros(channels,1))
|
284 |
+
|
285 |
+
def forward(self, x, x_mask, reverse=False, **kwargs):
|
286 |
+
if not reverse:
|
287 |
+
y = self.m + torch.exp(self.logs) * x
|
288 |
+
y = y * x_mask
|
289 |
+
logdet = torch.sum(self.logs * x_mask, [1,2])
|
290 |
+
return y, logdet
|
291 |
+
else:
|
292 |
+
x = (x - self.m) * torch.exp(-self.logs) * x_mask
|
293 |
+
return x
|
294 |
+
|
295 |
+
|
296 |
+
class ResidualCouplingLayer(nn.Module):
|
297 |
+
def __init__(self,
|
298 |
+
channels,
|
299 |
+
hidden_channels,
|
300 |
+
kernel_size,
|
301 |
+
dilation_rate,
|
302 |
+
n_layers,
|
303 |
+
p_dropout=0,
|
304 |
+
gin_channels=0,
|
305 |
+
mean_only=False):
|
306 |
+
assert channels % 2 == 0, "channels should be divisible by 2"
|
307 |
+
super().__init__()
|
308 |
+
self.channels = channels
|
309 |
+
self.hidden_channels = hidden_channels
|
310 |
+
self.kernel_size = kernel_size
|
311 |
+
self.dilation_rate = dilation_rate
|
312 |
+
self.n_layers = n_layers
|
313 |
+
self.half_channels = channels // 2
|
314 |
+
self.mean_only = mean_only
|
315 |
+
|
316 |
+
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
317 |
+
self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
|
318 |
+
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
319 |
+
self.post.weight.data.zero_()
|
320 |
+
self.post.bias.data.zero_()
|
321 |
+
|
322 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
323 |
+
x0, x1 = torch.split(x, [self.half_channels]*2, 1)
|
324 |
+
h = self.pre(x0) * x_mask
|
325 |
+
h = self.enc(h, x_mask, g=g)
|
326 |
+
stats = self.post(h) * x_mask
|
327 |
+
if not self.mean_only:
|
328 |
+
m, logs = torch.split(stats, [self.half_channels]*2, 1)
|
329 |
+
else:
|
330 |
+
m = stats
|
331 |
+
logs = torch.zeros_like(m)
|
332 |
+
|
333 |
+
if not reverse:
|
334 |
+
x1 = m + x1 * torch.exp(logs) * x_mask
|
335 |
+
x = torch.cat([x0, x1], 1)
|
336 |
+
logdet = torch.sum(logs, [1,2])
|
337 |
+
return x, logdet
|
338 |
+
else:
|
339 |
+
x1 = (x1 - m) * torch.exp(-logs) * x_mask
|
340 |
+
x = torch.cat([x0, x1], 1)
|
341 |
+
return x
|
342 |
+
|
343 |
+
|
344 |
+
class ConvFlow(nn.Module):
|
345 |
+
def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
|
346 |
+
super().__init__()
|
347 |
+
self.in_channels = in_channels
|
348 |
+
self.filter_channels = filter_channels
|
349 |
+
self.kernel_size = kernel_size
|
350 |
+
self.n_layers = n_layers
|
351 |
+
self.num_bins = num_bins
|
352 |
+
self.tail_bound = tail_bound
|
353 |
+
self.half_channels = in_channels // 2
|
354 |
+
|
355 |
+
self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
|
356 |
+
self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)
|
357 |
+
self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
|
358 |
+
self.proj.weight.data.zero_()
|
359 |
+
self.proj.bias.data.zero_()
|
360 |
+
|
361 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
362 |
+
x0, x1 = torch.split(x, [self.half_channels]*2, 1)
|
363 |
+
h = self.pre(x0)
|
364 |
+
h = self.convs(h, x_mask, g=g)
|
365 |
+
h = self.proj(h) * x_mask
|
366 |
+
|
367 |
+
b, c, t = x0.shape
|
368 |
+
h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
|
369 |
+
|
370 |
+
unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)
|
371 |
+
unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)
|
372 |
+
unnormalized_derivatives = h[..., 2 * self.num_bins:]
|
373 |
+
|
374 |
+
x1, logabsdet = piecewise_rational_quadratic_transform(x1,
|
375 |
+
unnormalized_widths,
|
376 |
+
unnormalized_heights,
|
377 |
+
unnormalized_derivatives,
|
378 |
+
inverse=reverse,
|
379 |
+
tails='linear',
|
380 |
+
tail_bound=self.tail_bound
|
381 |
+
)
|
382 |
+
|
383 |
+
x = torch.cat([x0, x1], 1) * x_mask
|
384 |
+
logdet = torch.sum(logabsdet * x_mask, [1,2])
|
385 |
+
if not reverse:
|
386 |
+
return x, logdet
|
387 |
+
else:
|
388 |
+
return x
|
389 |
+
class TransformerCouplingLayer(nn.Module):
|
390 |
+
def __init__(self,
|
391 |
+
channels,
|
392 |
+
hidden_channels,
|
393 |
+
kernel_size,
|
394 |
+
n_layers,
|
395 |
+
n_heads,
|
396 |
+
p_dropout=0,
|
397 |
+
filter_channels=0,
|
398 |
+
mean_only=False,
|
399 |
+
wn_sharing_parameter=None,
|
400 |
+
gin_channels = 0
|
401 |
+
):
|
402 |
+
assert channels % 2 == 0, "channels should be divisible by 2"
|
403 |
+
super().__init__()
|
404 |
+
self.channels = channels
|
405 |
+
self.hidden_channels = hidden_channels
|
406 |
+
self.kernel_size = kernel_size
|
407 |
+
self.n_layers = n_layers
|
408 |
+
self.half_channels = channels // 2
|
409 |
+
self.mean_only = mean_only
|
410 |
+
|
411 |
+
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
412 |
+
self.enc = Encoder(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, isflow = True, gin_channels = gin_channels) if wn_sharing_parameter is None else wn_sharing_parameter
|
413 |
+
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
414 |
+
self.post.weight.data.zero_()
|
415 |
+
self.post.bias.data.zero_()
|
416 |
+
|
417 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
418 |
+
x0, x1 = torch.split(x, [self.half_channels]*2, 1)
|
419 |
+
h = self.pre(x0) * x_mask
|
420 |
+
h = self.enc(h, x_mask, g=g)
|
421 |
+
stats = self.post(h) * x_mask
|
422 |
+
if not self.mean_only:
|
423 |
+
m, logs = torch.split(stats, [self.half_channels]*2, 1)
|
424 |
+
else:
|
425 |
+
m = stats
|
426 |
+
logs = torch.zeros_like(m)
|
427 |
+
|
428 |
+
if not reverse:
|
429 |
+
x1 = m + x1 * torch.exp(logs) * x_mask
|
430 |
+
x = torch.cat([x0, x1], 1)
|
431 |
+
logdet = torch.sum(logs, [1,2])
|
432 |
+
return x, logdet
|
433 |
+
else:
|
434 |
+
x1 = (x1 - m) * torch.exp(-logs) * x_mask
|
435 |
+
x = torch.cat([x0, x1], 1)
|
436 |
+
return x
|
437 |
+
|
438 |
+
x1, logabsdet = piecewise_rational_quadratic_transform(x1,
|
439 |
+
unnormalized_widths,
|
440 |
+
unnormalized_heights,
|
441 |
+
unnormalized_derivatives,
|
442 |
+
inverse=reverse,
|
443 |
+
tails='linear',
|
444 |
+
tail_bound=self.tail_bound
|
445 |
+
)
|
446 |
+
|
447 |
+
x = torch.cat([x0, x1], 1) * x_mask
|
448 |
+
logdet = torch.sum(logabsdet * x_mask, [1,2])
|
449 |
+
if not reverse:
|
450 |
+
return x, logdet
|
451 |
+
else:
|
452 |
+
return x
|
preprocess_text.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
from random import shuffle
|
3 |
+
|
4 |
+
import tqdm
|
5 |
+
from text.cleaner import clean_text
|
6 |
+
from collections import defaultdict
|
7 |
+
stage = [1,2,3]
|
8 |
+
|
9 |
+
transcription_path = 'filelists/xg.list'
|
10 |
+
train_path = 'filelists/train.list'
|
11 |
+
val_path = 'filelists/val.list'
|
12 |
+
config_path = "configs/config.json"
|
13 |
+
val_per_spk = 4
|
14 |
+
max_val_total = 8
|
15 |
+
|
16 |
+
if 1 in stage:
|
17 |
+
with open( transcription_path+'.cleaned', 'w', encoding='utf-8') as f:
|
18 |
+
for line in tqdm.tqdm(open(transcription_path, encoding='utf-8').readlines()):
|
19 |
+
try:
|
20 |
+
utt, spk, language, text = line.strip().split('|')
|
21 |
+
#language = "ZH"
|
22 |
+
norm_text, phones, tones, word2ph = clean_text(text, language)
|
23 |
+
f.write('{}|{}|{}|{}|{}|{}|{}\n'.format(utt, spk, language, norm_text, ' '.join(phones),
|
24 |
+
" ".join([str(i) for i in tones]),
|
25 |
+
" ".join([str(i) for i in word2ph])))
|
26 |
+
except Exception as error :
|
27 |
+
print("err!", utt, error)
|
28 |
+
|
29 |
+
if 2 in stage:
|
30 |
+
spk_utt_map = defaultdict(list)
|
31 |
+
spk_id_map = {}
|
32 |
+
current_sid = 0
|
33 |
+
|
34 |
+
with open( transcription_path+'.cleaned', encoding='utf-8') as f:
|
35 |
+
for line in f.readlines():
|
36 |
+
utt, spk, language, text, phones, tones, word2ph = line.strip().split('|')
|
37 |
+
spk_utt_map[spk].append(line)
|
38 |
+
if spk not in spk_id_map.keys():
|
39 |
+
spk_id_map[spk] = current_sid
|
40 |
+
current_sid += 1
|
41 |
+
train_list = []
|
42 |
+
val_list = []
|
43 |
+
|
44 |
+
for spk, utts in spk_utt_map.items():
|
45 |
+
shuffle(utts)
|
46 |
+
val_list+=utts[:val_per_spk]
|
47 |
+
train_list+=utts[val_per_spk:]
|
48 |
+
if len(val_list) > max_val_total:
|
49 |
+
train_list+=val_list[max_val_total:]
|
50 |
+
val_list = val_list[:max_val_total]
|
51 |
+
|
52 |
+
with open( train_path,"w", encoding='utf-8') as f:
|
53 |
+
for line in train_list:
|
54 |
+
f.write(line)
|
55 |
+
|
56 |
+
with open(val_path, "w", encoding='utf-8') as f:
|
57 |
+
for line in val_list:
|
58 |
+
f.write(line)
|
59 |
+
|
60 |
+
if 3 in stage:
|
61 |
+
assert 2 in stage
|
62 |
+
config = json.load(open(config_path, encoding='utf-8'))
|
63 |
+
config["data"]['spk2id'] = spk_id_map
|
64 |
+
with open(config_path, 'w', encoding='utf-8') as f:
|
65 |
+
json.dump(config, f, indent=2, ensure_ascii=False)
|
requirements.txt
CHANGED
@@ -1,19 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
librosa==0.9.1
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
absl-py==2.0.0
|
2 |
+
aiofiles==23.2.1
|
3 |
+
altair==5.1.1
|
4 |
+
AMFM-decompy==1.0.11
|
5 |
+
annotated-types==0.5.0
|
6 |
+
anyio==3.7.1
|
7 |
+
attrs==23.1.0
|
8 |
+
audioread==3.0.0
|
9 |
+
av==10.0.0
|
10 |
+
Babel==2.12.1
|
11 |
+
blinker==1.6.2
|
12 |
+
cachetools==5.3.1
|
13 |
+
certifi==2023.7.22
|
14 |
+
cffi==1.15.1
|
15 |
+
charset-normalizer==3.2.0
|
16 |
+
click==8.1.7
|
17 |
+
clldutils==3.20.0
|
18 |
+
cn2an==0.5.22
|
19 |
+
colorama==0.4.6
|
20 |
+
colorlog==6.7.0
|
21 |
+
contourpy==1.1.1
|
22 |
+
csvw==3.1.3
|
23 |
+
cycler==0.11.0
|
24 |
+
decorator==5.1.1
|
25 |
+
dlinfo==1.2.1
|
26 |
+
docopt==0.6.2
|
27 |
+
exceptiongroup==1.1.3
|
28 |
+
fastapi==0.103.1
|
29 |
+
ffmpy==0.3.1
|
30 |
+
filelock==3.12.4
|
31 |
+
Flask==2.3.3
|
32 |
+
fonttools==4.42.1
|
33 |
+
fsspec==2023.9.2
|
34 |
+
google-auth==2.23.0
|
35 |
+
google-auth-oauthlib==1.0.0
|
36 |
+
gradio==3.44.4
|
37 |
+
gradio_client==0.5.1
|
38 |
+
grpcio==1.58.0
|
39 |
+
h11==0.14.0
|
40 |
+
httpcore==0.18.0
|
41 |
+
httpx==0.25.0
|
42 |
+
huggingface-hub==0.17.2
|
43 |
+
idna==3.4
|
44 |
+
importlib-metadata==6.8.0
|
45 |
+
importlib-resources==6.1.0
|
46 |
+
isodate==0.6.1
|
47 |
+
itsdangerous==2.1.2
|
48 |
+
jieba==0.42.1
|
49 |
+
Jinja2==3.1.2
|
50 |
+
joblib==1.3.2
|
51 |
+
jsonschema==4.19.1
|
52 |
+
jsonschema-specifications==2023.7.1
|
53 |
+
kiwisolver==1.4.5
|
54 |
+
language-tags==1.2.0
|
55 |
librosa==0.9.1
|
56 |
+
llvmlite==0.41.0
|
57 |
+
loguru==0.7.2
|
58 |
+
lxml==4.9.3
|
59 |
+
Markdown==3.4.4
|
60 |
+
MarkupSafe==2.1.3
|
61 |
+
matplotlib==3.8.0
|
62 |
+
mecab-python3==1.0.8
|
63 |
+
mpmath==1.3.0
|
64 |
+
networkx==3.1
|
65 |
+
num2words==0.5.12
|
66 |
+
numba==0.58.0
|
67 |
+
numpy==1.25.2
|
68 |
+
oauthlib==3.2.2
|
69 |
+
orjson==3.9.7
|
70 |
+
packaging==23.1
|
71 |
+
pandas==2.1.1
|
72 |
+
phonemizer==3.2.1
|
73 |
+
Pillow==10.0.1
|
74 |
+
platformdirs==3.10.0
|
75 |
+
pooch==1.7.0
|
76 |
+
proces==0.1.7
|
77 |
+
protobuf==4.24.3
|
78 |
+
pyasn1==0.5.0
|
79 |
+
pyasn1-modules==0.3.0
|
80 |
+
pycparser==2.21
|
81 |
+
pydantic==2.3.0
|
82 |
+
pydantic_core==2.6.3
|
83 |
+
pydub==0.25.1
|
84 |
+
pylatexenc==2.10
|
85 |
+
pyparsing==3.1.1
|
86 |
+
pypinyin==0.49.0
|
87 |
+
python-dateutil==2.8.2
|
88 |
+
python-multipart==0.0.6
|
89 |
+
pytz==2023.3.post1
|
90 |
+
PyYAML==6.0.1
|
91 |
+
rdflib==7.0.0
|
92 |
+
referencing==0.30.2
|
93 |
+
regex==2023.8.8
|
94 |
+
requests==2.31.0
|
95 |
+
requests-oauthlib==1.3.1
|
96 |
+
resampy==0.4.2
|
97 |
+
rfc3986==1.5.0
|
98 |
+
rpds-py==0.10.3
|
99 |
+
rsa==4.9
|
100 |
+
safetensors==0.3.3
|
101 |
+
scikit-learn==1.3.1
|
102 |
+
scipy==1.11.2
|
103 |
+
segments==2.2.1
|
104 |
+
semantic-version==2.10.0
|
105 |
+
six==1.16.0
|
106 |
+
sniffio==1.3.0
|
107 |
+
soundfile==0.12.1
|
108 |
+
starlette==0.27.0
|
109 |
+
sympy==1.12
|
110 |
+
tabulate==0.9.0
|
111 |
+
tensorboard==2.14.0
|
112 |
+
tensorboard-data-server==0.7.1
|
113 |
+
threadpoolctl==3.2.0
|
114 |
+
tokenizers==0.13.3
|
115 |
+
toolz==0.12.0
|
116 |
+
torch==2.0.1+cu117
|
117 |
+
torchaudio==2.0.2+cu117
|
118 |
+
torchvision==0.15.2
|
119 |
+
tqdm==4.66.1
|
120 |
+
transformers==4.33.2
|
121 |
+
typing_extensions==4.8.0
|
122 |
+
tzdata==2023.3
|
123 |
+
Unidecode==1.3.6
|
124 |
+
unidic-lite==1.0.8
|
125 |
+
uritemplate==4.1.1
|
126 |
+
urllib3==1.26.16
|
127 |
+
uvicorn==0.23.2
|
128 |
+
websockets==11.0.3
|
129 |
+
Werkzeug==2.3.7
|
130 |
+
win32-setctime==1.1.0
|
131 |
+
zipp==3.17.0
|
resample.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import argparse
|
3 |
+
import librosa
|
4 |
+
import numpy as np
|
5 |
+
from multiprocessing import Pool, cpu_count
|
6 |
+
|
7 |
+
import soundfile
|
8 |
+
from scipy.io import wavfile
|
9 |
+
from tqdm import tqdm
|
10 |
+
|
11 |
+
|
12 |
+
def process(item):
|
13 |
+
spkdir, wav_name, args = item
|
14 |
+
speaker = spkdir.replace("\\", "/").split("/")[-1]
|
15 |
+
wav_path = os.path.join(args.in_dir, speaker, wav_name)
|
16 |
+
if os.path.exists(wav_path) and '.wav' in wav_path:
|
17 |
+
os.makedirs(os.path.join(args.out_dir, speaker), exist_ok=True)
|
18 |
+
wav, sr = librosa.load(wav_path, sr=args.sr)
|
19 |
+
soundfile.write(
|
20 |
+
os.path.join(args.out_dir, speaker, wav_name),
|
21 |
+
wav,
|
22 |
+
sr
|
23 |
+
)
|
24 |
+
|
25 |
+
|
26 |
+
|
27 |
+
if __name__ == "__main__":
|
28 |
+
parser = argparse.ArgumentParser()
|
29 |
+
parser.add_argument("--sr", type=int, default=44100, help="sampling rate")
|
30 |
+
parser.add_argument("--in_dir", type=str, default="./raw", help="path to source dir")
|
31 |
+
parser.add_argument("--out_dir", type=str, default="./dataset", help="path to target dir")
|
32 |
+
args = parser.parse_args()
|
33 |
+
# processs = 8
|
34 |
+
processs = cpu_count()-2 if cpu_count() >4 else 1
|
35 |
+
pool = Pool(processes=processs)
|
36 |
+
|
37 |
+
for speaker in os.listdir(args.in_dir):
|
38 |
+
spk_dir = os.path.join(args.in_dir, speaker)
|
39 |
+
if os.path.isdir(spk_dir):
|
40 |
+
print(spk_dir)
|
41 |
+
for _ in tqdm(pool.imap_unordered(process, [(spk_dir, i, args) for i in os.listdir(spk_dir) if i.endswith("wav")])):
|
42 |
+
pass
|
server.py
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, Response
|
2 |
+
from io import BytesIO
|
3 |
+
import torch
|
4 |
+
from av import open as avopen
|
5 |
+
|
6 |
+
import commons
|
7 |
+
import utils
|
8 |
+
from models import SynthesizerTrn
|
9 |
+
from text.symbols import symbols
|
10 |
+
from text import cleaned_text_to_sequence, get_bert
|
11 |
+
from text.cleaner import clean_text
|
12 |
+
from scipy.io import wavfile
|
13 |
+
|
14 |
+
# Flask Init
|
15 |
+
app = Flask(__name__)
|
16 |
+
app.config['JSON_AS_ASCII'] = False
|
17 |
+
def get_text(text, language_str, hps):
|
18 |
+
norm_text, phone, tone, word2ph = clean_text(text, language_str)
|
19 |
+
print([f"{p}{t}" for p, t in zip(phone, tone)])
|
20 |
+
phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
|
21 |
+
|
22 |
+
if hps.data.add_blank:
|
23 |
+
phone = commons.intersperse(phone, 0)
|
24 |
+
tone = commons.intersperse(tone, 0)
|
25 |
+
language = commons.intersperse(language, 0)
|
26 |
+
for i in range(len(word2ph)):
|
27 |
+
word2ph[i] = word2ph[i] * 2
|
28 |
+
word2ph[0] += 1
|
29 |
+
bert = get_bert(norm_text, word2ph, language_str)
|
30 |
+
|
31 |
+
assert bert.shape[-1] == len(phone)
|
32 |
+
|
33 |
+
phone = torch.LongTensor(phone)
|
34 |
+
tone = torch.LongTensor(tone)
|
35 |
+
language = torch.LongTensor(language)
|
36 |
+
|
37 |
+
return bert, phone, tone, language
|
38 |
+
|
39 |
+
def infer(text, sdp_ratio, noise_scale, noise_scale_w,length_scale,sid):
|
40 |
+
bert, phones, tones, lang_ids = get_text(text,"ZH", hps,)
|
41 |
+
with torch.no_grad():
|
42 |
+
x_tst=phones.to(dev).unsqueeze(0)
|
43 |
+
tones=tones.to(dev).unsqueeze(0)
|
44 |
+
lang_ids=lang_ids.to(dev).unsqueeze(0)
|
45 |
+
bert = bert.to(dev).unsqueeze(0)
|
46 |
+
x_tst_lengths = torch.LongTensor([phones.size(0)]).to(dev)
|
47 |
+
speakers = torch.LongTensor([hps.data.spk2id[sid]]).to(dev)
|
48 |
+
audio = net_g.infer(x_tst, x_tst_lengths, speakers, tones, lang_ids,bert, sdp_ratio=sdp_ratio
|
49 |
+
, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale)[0][0,0].data.cpu().float().numpy()
|
50 |
+
return audio
|
51 |
+
|
52 |
+
def replace_punctuation(text, i=2):
|
53 |
+
punctuation = ",。?!"
|
54 |
+
for char in punctuation:
|
55 |
+
text = text.replace(char, char * i)
|
56 |
+
return text
|
57 |
+
|
58 |
+
def wav2(i, o, format):
|
59 |
+
inp = avopen(i, 'rb')
|
60 |
+
out = avopen(o, 'wb', format=format)
|
61 |
+
if format == "ogg": format = "libvorbis"
|
62 |
+
|
63 |
+
ostream = out.add_stream(format)
|
64 |
+
|
65 |
+
for frame in inp.decode(audio=0):
|
66 |
+
for p in ostream.encode(frame): out.mux(p)
|
67 |
+
|
68 |
+
for p in ostream.encode(None): out.mux(p)
|
69 |
+
|
70 |
+
out.close()
|
71 |
+
inp.close()
|
72 |
+
|
73 |
+
# Load Generator
|
74 |
+
hps = utils.get_hparams_from_file("./configs/config.json")
|
75 |
+
|
76 |
+
dev='cuda'
|
77 |
+
net_g = SynthesizerTrn(
|
78 |
+
len(symbols),
|
79 |
+
hps.data.filter_length // 2 + 1,
|
80 |
+
hps.train.segment_size // hps.data.hop_length,
|
81 |
+
n_speakers=hps.data.n_speakers,
|
82 |
+
**hps.model).to(dev)
|
83 |
+
_ = net_g.eval()
|
84 |
+
|
85 |
+
# _ = utils.load_checkpoint("logs/G_649000.pth", net_g, None,skip_optimizer=True)
|
86 |
+
_ = utils.load_checkpoint("logs/dxl/G_21000.pth", net_g, None,skip_optimizer=True)
|
87 |
+
|
88 |
+
@app.route("/",methods=['GET','POST'])
|
89 |
+
def main():
|
90 |
+
if request.method == 'GET':
|
91 |
+
try:
|
92 |
+
speaker = request.args.get('speaker')
|
93 |
+
text = request.args.get('text').replace("/n","")
|
94 |
+
sdp_ratio = float(request.args.get("sdp_ratio", 0.2))
|
95 |
+
noise = float(request.args.get("noise", 0.5))
|
96 |
+
noisew = float(request.args.get("noisew", 0.6))
|
97 |
+
length = float(request.args.get("length", 1.2))
|
98 |
+
if length >= 2:
|
99 |
+
return "Too big length"
|
100 |
+
if len(text) >=200:
|
101 |
+
return "Too long text"
|
102 |
+
fmt = request.args.get("format", "wav")
|
103 |
+
if None in (speaker, text):
|
104 |
+
return "Missing Parameter"
|
105 |
+
if fmt not in ("mp3", "wav", "ogg"):
|
106 |
+
return "Invalid Format"
|
107 |
+
except:
|
108 |
+
return "Invalid Parameter"
|
109 |
+
|
110 |
+
with torch.no_grad():
|
111 |
+
audio = infer(text, sdp_ratio=sdp_ratio, noise_scale=noise, noise_scale_w=noisew, length_scale=length, sid=speaker)
|
112 |
+
|
113 |
+
with BytesIO() as wav:
|
114 |
+
wavfile.write(wav, hps.data.sampling_rate, audio)
|
115 |
+
torch.cuda.empty_cache()
|
116 |
+
if fmt == "wav":
|
117 |
+
return Response(wav.getvalue(), mimetype="audio/wav")
|
118 |
+
wav.seek(0, 0)
|
119 |
+
with BytesIO() as ofp:
|
120 |
+
wav2(wav, ofp, fmt)
|
121 |
+
return Response(
|
122 |
+
ofp.getvalue(),
|
123 |
+
mimetype="audio/mpeg" if fmt == "mp3" else "audio/ogg"
|
124 |
+
)
|
train_ms.py
ADDED
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import argparse
|
4 |
+
import itertools
|
5 |
+
import math
|
6 |
+
import torch
|
7 |
+
from torch import nn, optim
|
8 |
+
from torch.nn import functional as F
|
9 |
+
from torch.utils.data import DataLoader
|
10 |
+
from torch.utils.tensorboard import SummaryWriter
|
11 |
+
import torch.multiprocessing as mp
|
12 |
+
import torch.distributed as dist
|
13 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
14 |
+
from torch.cuda.amp import autocast, GradScaler
|
15 |
+
from tqdm import tqdm
|
16 |
+
import logging
|
17 |
+
logging.getLogger('numba').setLevel(logging.WARNING)
|
18 |
+
import commons
|
19 |
+
import utils
|
20 |
+
from data_utils import (
|
21 |
+
TextAudioSpeakerLoader,
|
22 |
+
TextAudioSpeakerCollate,
|
23 |
+
DistributedBucketSampler
|
24 |
+
)
|
25 |
+
from models import (
|
26 |
+
SynthesizerTrn,
|
27 |
+
MultiPeriodDiscriminator,
|
28 |
+
DurationDiscriminator,
|
29 |
+
)
|
30 |
+
from losses import (
|
31 |
+
generator_loss,
|
32 |
+
discriminator_loss,
|
33 |
+
feature_loss,
|
34 |
+
kl_loss
|
35 |
+
)
|
36 |
+
from mel_processing import mel_spectrogram_torch, spec_to_mel_torch
|
37 |
+
from text.symbols import symbols
|
38 |
+
|
39 |
+
torch.backends.cudnn.benchmark = True
|
40 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
41 |
+
torch.backends.cudnn.allow_tf32 = True
|
42 |
+
torch.set_float32_matmul_precision('medium')
|
43 |
+
torch.backends.cuda.sdp_kernel("flash")
|
44 |
+
torch.backends.cuda.enable_flash_sdp(True)
|
45 |
+
torch.backends.cuda.enable_mem_efficient_sdp(True)
|
46 |
+
torch.backends.cuda.enable_math_sdp(True)
|
47 |
+
global_step = 0
|
48 |
+
|
49 |
+
|
50 |
+
def main():
|
51 |
+
"""Assume Single Node Multi GPUs Training Only"""
|
52 |
+
assert torch.cuda.is_available(), "CPU training is not allowed."
|
53 |
+
|
54 |
+
n_gpus = torch.cuda.device_count()
|
55 |
+
os.environ['MASTER_ADDR'] = 'localhost'
|
56 |
+
os.environ['MASTER_PORT'] = '65280'
|
57 |
+
|
58 |
+
hps = utils.get_hparams()
|
59 |
+
mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,))
|
60 |
+
|
61 |
+
|
62 |
+
def run(rank, n_gpus, hps):
|
63 |
+
global global_step
|
64 |
+
if rank == 0:
|
65 |
+
logger = utils.get_logger(hps.model_dir)
|
66 |
+
logger.info(hps)
|
67 |
+
utils.check_git_hash(hps.model_dir)
|
68 |
+
writer = SummaryWriter(log_dir=hps.model_dir)
|
69 |
+
writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval"))
|
70 |
+
|
71 |
+
dist.init_process_group(backend='gloo', init_method='env://', world_size=n_gpus, rank=rank)
|
72 |
+
torch.manual_seed(hps.train.seed)
|
73 |
+
torch.cuda.set_device(rank)
|
74 |
+
|
75 |
+
train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data)
|
76 |
+
train_sampler = DistributedBucketSampler(
|
77 |
+
train_dataset,
|
78 |
+
hps.train.batch_size,
|
79 |
+
[32, 300, 400, 500, 600, 700, 800, 900, 1000],
|
80 |
+
num_replicas=n_gpus,
|
81 |
+
rank=rank,
|
82 |
+
shuffle=True)
|
83 |
+
collate_fn = TextAudioSpeakerCollate()
|
84 |
+
train_loader = DataLoader(train_dataset, num_workers=4, shuffle=False, pin_memory=True,
|
85 |
+
collate_fn=collate_fn, batch_sampler=train_sampler,
|
86 |
+
persistent_workers=True,prefetch_factor=4) #256G Memory suitable loader.
|
87 |
+
if rank == 0:
|
88 |
+
eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data)
|
89 |
+
eval_loader = DataLoader(eval_dataset, num_workers=0, shuffle=False,
|
90 |
+
batch_size=1, pin_memory=True,
|
91 |
+
drop_last=False, collate_fn=collate_fn)
|
92 |
+
if "use_noise_scaled_mas" in hps.model.keys() and hps.model.use_noise_scaled_mas == True:
|
93 |
+
print("Using noise scaled MAS for VITS2")
|
94 |
+
use_noise_scaled_mas = True
|
95 |
+
mas_noise_scale_initial = 0.01
|
96 |
+
noise_scale_delta = 2e-6
|
97 |
+
else:
|
98 |
+
print("Using normal MAS for VITS1")
|
99 |
+
use_noise_scaled_mas = False
|
100 |
+
mas_noise_scale_initial = 0.0
|
101 |
+
noise_scale_delta = 0.0
|
102 |
+
if "use_duration_discriminator" in hps.model.keys() and hps.model.use_duration_discriminator == True:
|
103 |
+
print("Using duration discriminator for VITS2")
|
104 |
+
use_duration_discriminator = True
|
105 |
+
net_dur_disc = DurationDiscriminator(
|
106 |
+
hps.model.hidden_channels,
|
107 |
+
hps.model.hidden_channels,
|
108 |
+
3,
|
109 |
+
0.1,
|
110 |
+
gin_channels=hps.model.gin_channels if hps.data.n_speakers != 0 else 0,
|
111 |
+
).cuda(rank)
|
112 |
+
if "use_spk_conditioned_encoder" in hps.model.keys() and hps.model.use_spk_conditioned_encoder == True:
|
113 |
+
if hps.data.n_speakers == 0:
|
114 |
+
raise ValueError("n_speakers must be > 0 when using spk conditioned encoder to train multi-speaker model")
|
115 |
+
use_spk_conditioned_encoder = True
|
116 |
+
else:
|
117 |
+
print("Using normal encoder for VITS1")
|
118 |
+
use_spk_conditioned_encoder = False
|
119 |
+
|
120 |
+
net_g = SynthesizerTrn(
|
121 |
+
len(symbols),
|
122 |
+
hps.data.filter_length // 2 + 1,
|
123 |
+
hps.train.segment_size // hps.data.hop_length,
|
124 |
+
n_speakers=hps.data.n_speakers,
|
125 |
+
mas_noise_scale_initial = mas_noise_scale_initial,
|
126 |
+
noise_scale_delta = noise_scale_delta,
|
127 |
+
**hps.model).cuda(rank)
|
128 |
+
|
129 |
+
freeze_enc = getattr(hps.model, "freeze_enc", False)
|
130 |
+
if freeze_enc:
|
131 |
+
print("freeze encoder !!!")
|
132 |
+
for param in net_g.enc_p.parameters():
|
133 |
+
param.requires_grad = False
|
134 |
+
|
135 |
+
net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank)
|
136 |
+
optim_g = torch.optim.AdamW(
|
137 |
+
filter(lambda p: p.requires_grad, net_g.parameters()),
|
138 |
+
hps.train.learning_rate,
|
139 |
+
betas=hps.train.betas,
|
140 |
+
eps=hps.train.eps)
|
141 |
+
optim_d = torch.optim.AdamW(
|
142 |
+
net_d.parameters(),
|
143 |
+
hps.train.learning_rate,
|
144 |
+
betas=hps.train.betas,
|
145 |
+
eps=hps.train.eps)
|
146 |
+
if net_dur_disc is not None:
|
147 |
+
optim_dur_disc = torch.optim.AdamW(
|
148 |
+
net_dur_disc.parameters(),
|
149 |
+
hps.train.learning_rate,
|
150 |
+
betas=hps.train.betas,
|
151 |
+
eps=hps.train.eps)
|
152 |
+
else:
|
153 |
+
optim_dur_disc = None
|
154 |
+
net_g = DDP(net_g, device_ids=[rank], find_unused_parameters=True)
|
155 |
+
net_d = DDP(net_d, device_ids=[rank], find_unused_parameters=True)
|
156 |
+
if net_dur_disc is not None:
|
157 |
+
net_dur_disc = DDP(net_dur_disc, device_ids=[rank], find_unused_parameters=True)
|
158 |
+
try:
|
159 |
+
if net_dur_disc is not None:
|
160 |
+
_, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "DUR_*.pth"), net_dur_disc, optim_dur_disc, skip_optimizer=True)
|
161 |
+
_, optim_g, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g,
|
162 |
+
optim_g, skip_optimizer=True)
|
163 |
+
_, optim_d, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d,
|
164 |
+
optim_d, skip_optimizer=True)
|
165 |
+
|
166 |
+
epoch_str = max(epoch_str, 1)
|
167 |
+
global_step = (epoch_str - 1) * len(train_loader)
|
168 |
+
except Exception as e:
|
169 |
+
print(e)
|
170 |
+
epoch_str = 1
|
171 |
+
global_step = 0
|
172 |
+
|
173 |
+
|
174 |
+
scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay)
|
175 |
+
scheduler_g.last_epoch = epoch_str - 2
|
176 |
+
scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay)
|
177 |
+
scheduler_d.last_epoch = epoch_str - 2
|
178 |
+
if net_dur_disc is not None:
|
179 |
+
scheduler_dur_disc = torch.optim.lr_scheduler.ExponentialLR(optim_dur_disc, gamma=hps.train.lr_decay)
|
180 |
+
scheduler_dur_disc.last_epoch = epoch_str - 2
|
181 |
+
else:
|
182 |
+
scheduler_dur_disc = None
|
183 |
+
scaler = GradScaler(enabled=hps.train.fp16_run)
|
184 |
+
|
185 |
+
for epoch in range(epoch_str, hps.train.epochs + 1):
|
186 |
+
if rank == 0:
|
187 |
+
train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, eval_loader], logger, [writer, writer_eval])
|
188 |
+
else:
|
189 |
+
train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, None], None, None)
|
190 |
+
scheduler_g.step()
|
191 |
+
scheduler_d.step()
|
192 |
+
if net_dur_disc is not None:
|
193 |
+
scheduler_dur_disc.step()
|
194 |
+
|
195 |
+
|
196 |
+
def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers):
|
197 |
+
net_g, net_d, net_dur_disc = nets
|
198 |
+
optim_g, optim_d, optim_dur_disc = optims
|
199 |
+
scheduler_g, scheduler_d, scheduler_dur_disc = schedulers
|
200 |
+
train_loader, eval_loader = loaders
|
201 |
+
if writers is not None:
|
202 |
+
writer, writer_eval = writers
|
203 |
+
|
204 |
+
train_loader.batch_sampler.set_epoch(epoch)
|
205 |
+
global global_step
|
206 |
+
|
207 |
+
net_g.train()
|
208 |
+
net_d.train()
|
209 |
+
if net_dur_disc is not None:
|
210 |
+
net_dur_disc.train()
|
211 |
+
for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert) in tqdm(enumerate(train_loader)):
|
212 |
+
if net_g.module.use_noise_scaled_mas:
|
213 |
+
current_mas_noise_scale = net_g.module.mas_noise_scale_initial - net_g.module.noise_scale_delta * global_step
|
214 |
+
net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0)
|
215 |
+
x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True)
|
216 |
+
spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(rank, non_blocking=True)
|
217 |
+
y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True)
|
218 |
+
speakers = speakers.cuda(rank, non_blocking=True)
|
219 |
+
tone = tone.cuda(rank, non_blocking=True)
|
220 |
+
language = language.cuda(rank, non_blocking=True)
|
221 |
+
bert = bert.cuda(rank, non_blocking=True)
|
222 |
+
|
223 |
+
with autocast(enabled=hps.train.fp16_run):
|
224 |
+
y_hat, l_length, attn, ids_slice, x_mask, z_mask, \
|
225 |
+
(z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_) = net_g(x, x_lengths, spec, spec_lengths, speakers, tone, language, bert)
|
226 |
+
mel = spec_to_mel_torch(
|
227 |
+
spec,
|
228 |
+
hps.data.filter_length,
|
229 |
+
hps.data.n_mel_channels,
|
230 |
+
hps.data.sampling_rate,
|
231 |
+
hps.data.mel_fmin,
|
232 |
+
hps.data.mel_fmax)
|
233 |
+
y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length)
|
234 |
+
y_hat_mel = mel_spectrogram_torch(
|
235 |
+
y_hat.squeeze(1),
|
236 |
+
hps.data.filter_length,
|
237 |
+
hps.data.n_mel_channels,
|
238 |
+
hps.data.sampling_rate,
|
239 |
+
hps.data.hop_length,
|
240 |
+
hps.data.win_length,
|
241 |
+
hps.data.mel_fmin,
|
242 |
+
hps.data.mel_fmax
|
243 |
+
)
|
244 |
+
|
245 |
+
y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice
|
246 |
+
|
247 |
+
# Discriminator
|
248 |
+
y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach())
|
249 |
+
with autocast(enabled=False):
|
250 |
+
loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g)
|
251 |
+
loss_disc_all = loss_disc
|
252 |
+
if net_dur_disc is not None:
|
253 |
+
y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x.detach(), x_mask.detach(), logw.detach(), logw_.detach())
|
254 |
+
with autocast(enabled=False):
|
255 |
+
# TODO: I think need to mean using the mask, but for now, just mean all
|
256 |
+
loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g = discriminator_loss(y_dur_hat_r, y_dur_hat_g)
|
257 |
+
loss_dur_disc_all = loss_dur_disc
|
258 |
+
optim_dur_disc.zero_grad()
|
259 |
+
scaler.scale(loss_dur_disc_all).backward()
|
260 |
+
scaler.unscale_(optim_dur_disc)
|
261 |
+
grad_norm_dur_disc = commons.clip_grad_value_(net_dur_disc.parameters(), None)
|
262 |
+
scaler.step(optim_dur_disc)
|
263 |
+
|
264 |
+
optim_d.zero_grad()
|
265 |
+
scaler.scale(loss_disc_all).backward()
|
266 |
+
scaler.unscale_(optim_d)
|
267 |
+
grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None)
|
268 |
+
scaler.step(optim_d)
|
269 |
+
|
270 |
+
with autocast(enabled=hps.train.fp16_run):
|
271 |
+
# Generator
|
272 |
+
y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat)
|
273 |
+
if net_dur_disc is not None:
|
274 |
+
y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw, logw_)
|
275 |
+
with autocast(enabled=False):
|
276 |
+
loss_dur = torch.sum(l_length.float())
|
277 |
+
loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel
|
278 |
+
loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
|
279 |
+
|
280 |
+
loss_fm = feature_loss(fmap_r, fmap_g)
|
281 |
+
loss_gen, losses_gen = generator_loss(y_d_hat_g)
|
282 |
+
loss_gen_all = loss_gen + loss_fm + loss_mel + loss_dur + loss_kl
|
283 |
+
if net_dur_disc is not None:
|
284 |
+
loss_dur_gen, losses_dur_gen = generator_loss(y_dur_hat_g)
|
285 |
+
loss_gen_all += loss_dur_gen
|
286 |
+
optim_g.zero_grad()
|
287 |
+
scaler.scale(loss_gen_all).backward()
|
288 |
+
scaler.unscale_(optim_g)
|
289 |
+
grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None)
|
290 |
+
scaler.step(optim_g)
|
291 |
+
scaler.update()
|
292 |
+
|
293 |
+
if rank == 0:
|
294 |
+
if global_step % hps.train.log_interval == 0:
|
295 |
+
lr = optim_g.param_groups[0]['lr']
|
296 |
+
losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_dur, loss_kl]
|
297 |
+
logger.info('Train Epoch: {} [{:.0f}%]'.format(
|
298 |
+
epoch,
|
299 |
+
100. * batch_idx / len(train_loader)))
|
300 |
+
logger.info([x.item() for x in losses] + [global_step, lr])
|
301 |
+
|
302 |
+
scalar_dict = {"loss/g/total": loss_gen_all, "loss/d/total": loss_disc_all, "learning_rate": lr,
|
303 |
+
"grad_norm_d": grad_norm_d, "grad_norm_g": grad_norm_g}
|
304 |
+
scalar_dict.update(
|
305 |
+
{"loss/g/fm": loss_fm, "loss/g/mel": loss_mel, "loss/g/dur": loss_dur, "loss/g/kl": loss_kl})
|
306 |
+
scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)})
|
307 |
+
scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)})
|
308 |
+
scalar_dict.update({"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)})
|
309 |
+
|
310 |
+
image_dict = {
|
311 |
+
"slice/mel_org": utils.plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()),
|
312 |
+
"slice/mel_gen": utils.plot_spectrogram_to_numpy(y_hat_mel[0].data.cpu().numpy()),
|
313 |
+
"all/mel": utils.plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()),
|
314 |
+
"all/attn": utils.plot_alignment_to_numpy(attn[0, 0].data.cpu().numpy())
|
315 |
+
}
|
316 |
+
utils.summarize(
|
317 |
+
writer=writer,
|
318 |
+
global_step=global_step,
|
319 |
+
images=image_dict,
|
320 |
+
scalars=scalar_dict)
|
321 |
+
|
322 |
+
if global_step % hps.train.eval_interval == 0:
|
323 |
+
evaluate(hps, net_g, eval_loader, writer_eval)
|
324 |
+
utils.save_checkpoint(net_g, optim_g, hps.train.learning_rate, epoch,
|
325 |
+
os.path.join(hps.model_dir, "G_{}.pth".format(global_step)))
|
326 |
+
utils.save_checkpoint(net_d, optim_d, hps.train.learning_rate, epoch,
|
327 |
+
os.path.join(hps.model_dir, "D_{}.pth".format(global_step)))
|
328 |
+
if net_dur_disc is not None:
|
329 |
+
utils.save_checkpoint(net_dur_disc, optim_dur_disc, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, "DUR_{}.pth".format(global_step)))
|
330 |
+
keep_ckpts = getattr(hps.train, 'keep_ckpts', 5)
|
331 |
+
if keep_ckpts > 0:
|
332 |
+
utils.clean_checkpoints(path_to_models=hps.model_dir, n_ckpts_to_keep=keep_ckpts, sort_by_time=True)
|
333 |
+
|
334 |
+
|
335 |
+
global_step += 1
|
336 |
+
|
337 |
+
if rank == 0:
|
338 |
+
logger.info('====> Epoch: {}'.format(epoch))
|
339 |
+
|
340 |
+
|
341 |
+
|
342 |
+
def evaluate(hps, generator, eval_loader, writer_eval):
|
343 |
+
generator.eval()
|
344 |
+
image_dict = {}
|
345 |
+
audio_dict = {}
|
346 |
+
print("Evaluating ...")
|
347 |
+
with torch.no_grad():
|
348 |
+
for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert) in enumerate(eval_loader):
|
349 |
+
x, x_lengths = x.cuda(), x_lengths.cuda()
|
350 |
+
spec, spec_lengths = spec.cuda(), spec_lengths.cuda()
|
351 |
+
y, y_lengths = y.cuda(), y_lengths.cuda()
|
352 |
+
speakers = speakers.cuda()
|
353 |
+
bert = bert.cuda()
|
354 |
+
tone = tone.cuda()
|
355 |
+
language = language.cuda()
|
356 |
+
for use_sdp in [True, False]:
|
357 |
+
y_hat, attn, mask, *_ = generator.module.infer(x, x_lengths, speakers, tone, language, bert, y=spec, max_len=1000, sdp_ratio=0.0 if not use_sdp else 1.0)
|
358 |
+
y_hat_lengths = mask.sum([1, 2]).long() * hps.data.hop_length
|
359 |
+
|
360 |
+
mel = spec_to_mel_torch(
|
361 |
+
spec,
|
362 |
+
hps.data.filter_length,
|
363 |
+
hps.data.n_mel_channels,
|
364 |
+
hps.data.sampling_rate,
|
365 |
+
hps.data.mel_fmin,
|
366 |
+
hps.data.mel_fmax)
|
367 |
+
y_hat_mel = mel_spectrogram_torch(
|
368 |
+
y_hat.squeeze(1).float(),
|
369 |
+
hps.data.filter_length,
|
370 |
+
hps.data.n_mel_channels,
|
371 |
+
hps.data.sampling_rate,
|
372 |
+
hps.data.hop_length,
|
373 |
+
hps.data.win_length,
|
374 |
+
hps.data.mel_fmin,
|
375 |
+
hps.data.mel_fmax
|
376 |
+
)
|
377 |
+
image_dict.update({
|
378 |
+
f"gen/mel_{batch_idx}": utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy())
|
379 |
+
})
|
380 |
+
audio_dict.update({
|
381 |
+
f"gen/audio_{batch_idx}_{use_sdp}": y_hat[0, :, :y_hat_lengths[0]]
|
382 |
+
})
|
383 |
+
image_dict.update({f"gt/mel_{batch_idx}": utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy())})
|
384 |
+
audio_dict.update({f"gt/audio_{batch_idx}": y[0, :, :y_lengths[0]]})
|
385 |
+
|
386 |
+
utils.summarize(
|
387 |
+
writer=writer_eval,
|
388 |
+
global_step=global_step,
|
389 |
+
images=image_dict,
|
390 |
+
audios=audio_dict,
|
391 |
+
audio_sampling_rate=hps.data.sampling_rate
|
392 |
+
)
|
393 |
+
generator.train()
|
394 |
+
|
395 |
+
if __name__ == "__main__":
|
396 |
+
main()
|
transforms.py
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch.nn import functional as F
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
|
7 |
+
DEFAULT_MIN_BIN_WIDTH = 1e-3
|
8 |
+
DEFAULT_MIN_BIN_HEIGHT = 1e-3
|
9 |
+
DEFAULT_MIN_DERIVATIVE = 1e-3
|
10 |
+
|
11 |
+
|
12 |
+
def piecewise_rational_quadratic_transform(inputs,
|
13 |
+
unnormalized_widths,
|
14 |
+
unnormalized_heights,
|
15 |
+
unnormalized_derivatives,
|
16 |
+
inverse=False,
|
17 |
+
tails=None,
|
18 |
+
tail_bound=1.,
|
19 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
20 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
21 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE):
|
22 |
+
|
23 |
+
if tails is None:
|
24 |
+
spline_fn = rational_quadratic_spline
|
25 |
+
spline_kwargs = {}
|
26 |
+
else:
|
27 |
+
spline_fn = unconstrained_rational_quadratic_spline
|
28 |
+
spline_kwargs = {
|
29 |
+
'tails': tails,
|
30 |
+
'tail_bound': tail_bound
|
31 |
+
}
|
32 |
+
|
33 |
+
outputs, logabsdet = spline_fn(
|
34 |
+
inputs=inputs,
|
35 |
+
unnormalized_widths=unnormalized_widths,
|
36 |
+
unnormalized_heights=unnormalized_heights,
|
37 |
+
unnormalized_derivatives=unnormalized_derivatives,
|
38 |
+
inverse=inverse,
|
39 |
+
min_bin_width=min_bin_width,
|
40 |
+
min_bin_height=min_bin_height,
|
41 |
+
min_derivative=min_derivative,
|
42 |
+
**spline_kwargs
|
43 |
+
)
|
44 |
+
return outputs, logabsdet
|
45 |
+
|
46 |
+
|
47 |
+
def searchsorted(bin_locations, inputs, eps=1e-6):
|
48 |
+
bin_locations[..., -1] += eps
|
49 |
+
return torch.sum(
|
50 |
+
inputs[..., None] >= bin_locations,
|
51 |
+
dim=-1
|
52 |
+
) - 1
|
53 |
+
|
54 |
+
|
55 |
+
def unconstrained_rational_quadratic_spline(inputs,
|
56 |
+
unnormalized_widths,
|
57 |
+
unnormalized_heights,
|
58 |
+
unnormalized_derivatives,
|
59 |
+
inverse=False,
|
60 |
+
tails='linear',
|
61 |
+
tail_bound=1.,
|
62 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
63 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
64 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE):
|
65 |
+
inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
|
66 |
+
outside_interval_mask = ~inside_interval_mask
|
67 |
+
|
68 |
+
outputs = torch.zeros_like(inputs)
|
69 |
+
logabsdet = torch.zeros_like(inputs)
|
70 |
+
|
71 |
+
if tails == 'linear':
|
72 |
+
unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
|
73 |
+
constant = np.log(np.exp(1 - min_derivative) - 1)
|
74 |
+
unnormalized_derivatives[..., 0] = constant
|
75 |
+
unnormalized_derivatives[..., -1] = constant
|
76 |
+
|
77 |
+
outputs[outside_interval_mask] = inputs[outside_interval_mask]
|
78 |
+
logabsdet[outside_interval_mask] = 0
|
79 |
+
else:
|
80 |
+
raise RuntimeError('{} tails are not implemented.'.format(tails))
|
81 |
+
|
82 |
+
outputs[inside_interval_mask], logabsdet[inside_interval_mask] = rational_quadratic_spline(
|
83 |
+
inputs=inputs[inside_interval_mask],
|
84 |
+
unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
|
85 |
+
unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
|
86 |
+
unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
|
87 |
+
inverse=inverse,
|
88 |
+
left=-tail_bound, right=tail_bound, bottom=-tail_bound, top=tail_bound,
|
89 |
+
min_bin_width=min_bin_width,
|
90 |
+
min_bin_height=min_bin_height,
|
91 |
+
min_derivative=min_derivative
|
92 |
+
)
|
93 |
+
|
94 |
+
return outputs, logabsdet
|
95 |
+
|
96 |
+
def rational_quadratic_spline(inputs,
|
97 |
+
unnormalized_widths,
|
98 |
+
unnormalized_heights,
|
99 |
+
unnormalized_derivatives,
|
100 |
+
inverse=False,
|
101 |
+
left=0., right=1., bottom=0., top=1.,
|
102 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
103 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
104 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE):
|
105 |
+
if torch.min(inputs) < left or torch.max(inputs) > right:
|
106 |
+
raise ValueError('Input to a transform is not within its domain')
|
107 |
+
|
108 |
+
num_bins = unnormalized_widths.shape[-1]
|
109 |
+
|
110 |
+
if min_bin_width * num_bins > 1.0:
|
111 |
+
raise ValueError('Minimal bin width too large for the number of bins')
|
112 |
+
if min_bin_height * num_bins > 1.0:
|
113 |
+
raise ValueError('Minimal bin height too large for the number of bins')
|
114 |
+
|
115 |
+
widths = F.softmax(unnormalized_widths, dim=-1)
|
116 |
+
widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
|
117 |
+
cumwidths = torch.cumsum(widths, dim=-1)
|
118 |
+
cumwidths = F.pad(cumwidths, pad=(1, 0), mode='constant', value=0.0)
|
119 |
+
cumwidths = (right - left) * cumwidths + left
|
120 |
+
cumwidths[..., 0] = left
|
121 |
+
cumwidths[..., -1] = right
|
122 |
+
widths = cumwidths[..., 1:] - cumwidths[..., :-1]
|
123 |
+
|
124 |
+
derivatives = min_derivative + F.softplus(unnormalized_derivatives)
|
125 |
+
|
126 |
+
heights = F.softmax(unnormalized_heights, dim=-1)
|
127 |
+
heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
|
128 |
+
cumheights = torch.cumsum(heights, dim=-1)
|
129 |
+
cumheights = F.pad(cumheights, pad=(1, 0), mode='constant', value=0.0)
|
130 |
+
cumheights = (top - bottom) * cumheights + bottom
|
131 |
+
cumheights[..., 0] = bottom
|
132 |
+
cumheights[..., -1] = top
|
133 |
+
heights = cumheights[..., 1:] - cumheights[..., :-1]
|
134 |
+
|
135 |
+
if inverse:
|
136 |
+
bin_idx = searchsorted(cumheights, inputs)[..., None]
|
137 |
+
else:
|
138 |
+
bin_idx = searchsorted(cumwidths, inputs)[..., None]
|
139 |
+
|
140 |
+
input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
|
141 |
+
input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
|
142 |
+
|
143 |
+
input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
|
144 |
+
delta = heights / widths
|
145 |
+
input_delta = delta.gather(-1, bin_idx)[..., 0]
|
146 |
+
|
147 |
+
input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
|
148 |
+
input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
|
149 |
+
|
150 |
+
input_heights = heights.gather(-1, bin_idx)[..., 0]
|
151 |
+
|
152 |
+
if inverse:
|
153 |
+
a = (((inputs - input_cumheights) * (input_derivatives
|
154 |
+
+ input_derivatives_plus_one
|
155 |
+
- 2 * input_delta)
|
156 |
+
+ input_heights * (input_delta - input_derivatives)))
|
157 |
+
b = (input_heights * input_derivatives
|
158 |
+
- (inputs - input_cumheights) * (input_derivatives
|
159 |
+
+ input_derivatives_plus_one
|
160 |
+
- 2 * input_delta))
|
161 |
+
c = - input_delta * (inputs - input_cumheights)
|
162 |
+
|
163 |
+
discriminant = b.pow(2) - 4 * a * c
|
164 |
+
assert (discriminant >= 0).all()
|
165 |
+
|
166 |
+
root = (2 * c) / (-b - torch.sqrt(discriminant))
|
167 |
+
outputs = root * input_bin_widths + input_cumwidths
|
168 |
+
|
169 |
+
theta_one_minus_theta = root * (1 - root)
|
170 |
+
denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
|
171 |
+
* theta_one_minus_theta)
|
172 |
+
derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * root.pow(2)
|
173 |
+
+ 2 * input_delta * theta_one_minus_theta
|
174 |
+
+ input_derivatives * (1 - root).pow(2))
|
175 |
+
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
176 |
+
|
177 |
+
return outputs, -logabsdet
|
178 |
+
else:
|
179 |
+
theta = (inputs - input_cumwidths) / input_bin_widths
|
180 |
+
theta_one_minus_theta = theta * (1 - theta)
|
181 |
+
|
182 |
+
numerator = input_heights * (input_delta * theta.pow(2)
|
183 |
+
+ input_derivatives * theta_one_minus_theta)
|
184 |
+
denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
|
185 |
+
* theta_one_minus_theta)
|
186 |
+
outputs = input_cumheights + numerator / denominator
|
187 |
+
|
188 |
+
derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * theta.pow(2)
|
189 |
+
+ 2 * input_delta * theta_one_minus_theta
|
190 |
+
+ input_derivatives * (1 - theta).pow(2))
|
191 |
+
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
192 |
+
|
193 |
+
return outputs, logabsdet
|
utils.py
ADDED
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import glob
|
3 |
+
import sys
|
4 |
+
import argparse
|
5 |
+
import logging
|
6 |
+
import json
|
7 |
+
import subprocess
|
8 |
+
import numpy as np
|
9 |
+
from scipy.io.wavfile import read
|
10 |
+
import torch
|
11 |
+
|
12 |
+
MATPLOTLIB_FLAG = False
|
13 |
+
|
14 |
+
logger = logging.getLogger(__name__)
|
15 |
+
|
16 |
+
|
17 |
+
def load_checkpoint(checkpoint_path, model, optimizer=None, skip_optimizer=False):
|
18 |
+
assert os.path.isfile(checkpoint_path)
|
19 |
+
checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
|
20 |
+
iteration = checkpoint_dict['iteration']
|
21 |
+
learning_rate = checkpoint_dict['learning_rate']
|
22 |
+
if optimizer is not None and not skip_optimizer and checkpoint_dict['optimizer'] is not None:
|
23 |
+
optimizer.load_state_dict(checkpoint_dict['optimizer'])
|
24 |
+
elif optimizer is None and not skip_optimizer:
|
25 |
+
#else: Disable this line if Infer and resume checkpoint,then enable the line upper
|
26 |
+
new_opt_dict = optimizer.state_dict()
|
27 |
+
new_opt_dict_params = new_opt_dict['param_groups'][0]['params']
|
28 |
+
new_opt_dict['param_groups'] = checkpoint_dict['optimizer']['param_groups']
|
29 |
+
new_opt_dict['param_groups'][0]['params'] = new_opt_dict_params
|
30 |
+
optimizer.load_state_dict(new_opt_dict)
|
31 |
+
saved_state_dict = checkpoint_dict['model']
|
32 |
+
if hasattr(model, 'module'):
|
33 |
+
state_dict = model.module.state_dict()
|
34 |
+
else:
|
35 |
+
state_dict = model.state_dict()
|
36 |
+
new_state_dict = {}
|
37 |
+
for k, v in state_dict.items():
|
38 |
+
try:
|
39 |
+
#assert "emb_g" not in k
|
40 |
+
# print("load", k)
|
41 |
+
new_state_dict[k] = saved_state_dict[k]
|
42 |
+
assert saved_state_dict[k].shape == v.shape, (saved_state_dict[k].shape, v.shape)
|
43 |
+
except:
|
44 |
+
logger.error("%s is not in the checkpoint" % k)
|
45 |
+
new_state_dict[k] = v
|
46 |
+
if hasattr(model, 'module'):
|
47 |
+
model.module.load_state_dict(new_state_dict, strict=False)
|
48 |
+
else:
|
49 |
+
model.load_state_dict(new_state_dict, strict=False)
|
50 |
+
logger.info("Loaded checkpoint '{}' (iteration {})".format(
|
51 |
+
checkpoint_path, iteration))
|
52 |
+
return model, optimizer, learning_rate, iteration
|
53 |
+
|
54 |
+
|
55 |
+
def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
|
56 |
+
logger.info("Saving model and optimizer state at iteration {} to {}".format(
|
57 |
+
iteration, checkpoint_path))
|
58 |
+
if hasattr(model, 'module'):
|
59 |
+
state_dict = model.module.state_dict()
|
60 |
+
else:
|
61 |
+
state_dict = model.state_dict()
|
62 |
+
torch.save({'model': state_dict,
|
63 |
+
'iteration': iteration,
|
64 |
+
'optimizer': optimizer.state_dict(),
|
65 |
+
'learning_rate': learning_rate}, checkpoint_path)
|
66 |
+
|
67 |
+
|
68 |
+
def summarize(writer, global_step, scalars={}, histograms={}, images={}, audios={}, audio_sampling_rate=22050):
|
69 |
+
for k, v in scalars.items():
|
70 |
+
writer.add_scalar(k, v, global_step)
|
71 |
+
for k, v in histograms.items():
|
72 |
+
writer.add_histogram(k, v, global_step)
|
73 |
+
for k, v in images.items():
|
74 |
+
writer.add_image(k, v, global_step, dataformats='HWC')
|
75 |
+
for k, v in audios.items():
|
76 |
+
writer.add_audio(k, v, global_step, audio_sampling_rate)
|
77 |
+
|
78 |
+
|
79 |
+
def latest_checkpoint_path(dir_path, regex="G_*.pth"):
|
80 |
+
f_list = glob.glob(os.path.join(dir_path, regex))
|
81 |
+
f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
|
82 |
+
x = f_list[-1]
|
83 |
+
print(x)
|
84 |
+
return x
|
85 |
+
|
86 |
+
|
87 |
+
def plot_spectrogram_to_numpy(spectrogram):
|
88 |
+
global MATPLOTLIB_FLAG
|
89 |
+
if not MATPLOTLIB_FLAG:
|
90 |
+
import matplotlib
|
91 |
+
matplotlib.use("Agg")
|
92 |
+
MATPLOTLIB_FLAG = True
|
93 |
+
mpl_logger = logging.getLogger('matplotlib')
|
94 |
+
mpl_logger.setLevel(logging.WARNING)
|
95 |
+
import matplotlib.pylab as plt
|
96 |
+
import numpy as np
|
97 |
+
|
98 |
+
fig, ax = plt.subplots(figsize=(10, 2))
|
99 |
+
im = ax.imshow(spectrogram, aspect="auto", origin="lower",
|
100 |
+
interpolation='none')
|
101 |
+
plt.colorbar(im, ax=ax)
|
102 |
+
plt.xlabel("Frames")
|
103 |
+
plt.ylabel("Channels")
|
104 |
+
plt.tight_layout()
|
105 |
+
|
106 |
+
fig.canvas.draw()
|
107 |
+
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
|
108 |
+
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
109 |
+
plt.close()
|
110 |
+
return data
|
111 |
+
|
112 |
+
|
113 |
+
def plot_alignment_to_numpy(alignment, info=None):
|
114 |
+
global MATPLOTLIB_FLAG
|
115 |
+
if not MATPLOTLIB_FLAG:
|
116 |
+
import matplotlib
|
117 |
+
matplotlib.use("Agg")
|
118 |
+
MATPLOTLIB_FLAG = True
|
119 |
+
mpl_logger = logging.getLogger('matplotlib')
|
120 |
+
mpl_logger.setLevel(logging.WARNING)
|
121 |
+
import matplotlib.pylab as plt
|
122 |
+
import numpy as np
|
123 |
+
|
124 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
125 |
+
im = ax.imshow(alignment.transpose(), aspect='auto', origin='lower',
|
126 |
+
interpolation='none')
|
127 |
+
fig.colorbar(im, ax=ax)
|
128 |
+
xlabel = 'Decoder timestep'
|
129 |
+
if info is not None:
|
130 |
+
xlabel += '\n\n' + info
|
131 |
+
plt.xlabel(xlabel)
|
132 |
+
plt.ylabel('Encoder timestep')
|
133 |
+
plt.tight_layout()
|
134 |
+
|
135 |
+
fig.canvas.draw()
|
136 |
+
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
|
137 |
+
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
138 |
+
plt.close()
|
139 |
+
return data
|
140 |
+
|
141 |
+
|
142 |
+
def load_wav_to_torch(full_path):
|
143 |
+
sampling_rate, data = read(full_path)
|
144 |
+
return torch.FloatTensor(data.astype(np.float32)), sampling_rate
|
145 |
+
|
146 |
+
|
147 |
+
def load_filepaths_and_text(filename, split="|"):
|
148 |
+
with open(filename, encoding='utf-8') as f:
|
149 |
+
filepaths_and_text = [line.strip().split(split) for line in f]
|
150 |
+
return filepaths_and_text
|
151 |
+
|
152 |
+
|
153 |
+
def get_hparams(init=True):
|
154 |
+
parser = argparse.ArgumentParser()
|
155 |
+
parser.add_argument('-c', '--config', type=str, default="./configs/base.json",
|
156 |
+
help='JSON file for configuration')
|
157 |
+
parser.add_argument('-m', '--model', type=str, required=True,
|
158 |
+
help='Model name')
|
159 |
+
|
160 |
+
args = parser.parse_args()
|
161 |
+
# model_dir = os.path.join("./logs", args.model)
|
162 |
+
model_dir = "./logs/" + args.model
|
163 |
+
|
164 |
+
if not os.path.exists(model_dir):
|
165 |
+
os.makedirs(model_dir)
|
166 |
+
|
167 |
+
config_path = args.config
|
168 |
+
config_save_path = os.path.join(model_dir, "config.json")
|
169 |
+
if init:
|
170 |
+
with open(config_path, "r" ,encoding='utf-8') as f:
|
171 |
+
data = f.read()
|
172 |
+
with open(config_save_path, "w" ,encoding='utf-8') as f:
|
173 |
+
f.write(data)
|
174 |
+
else:
|
175 |
+
with open(config_save_path, "r" ,encoding='utf-8') as f:
|
176 |
+
data = f.read()
|
177 |
+
config = json.loads(data)
|
178 |
+
|
179 |
+
hparams = HParams(**config)
|
180 |
+
hparams.model_dir = model_dir
|
181 |
+
return hparams
|
182 |
+
|
183 |
+
|
184 |
+
def clean_checkpoints(path_to_models='logs/44k/', n_ckpts_to_keep=2, sort_by_time=True):
|
185 |
+
"""Freeing up space by deleting saved ckpts
|
186 |
+
|
187 |
+
Arguments:
|
188 |
+
path_to_models -- Path to the model directory
|
189 |
+
n_ckpts_to_keep -- Number of ckpts to keep, excluding G_0.pth and D_0.pth
|
190 |
+
sort_by_time -- True -> chronologically delete ckpts
|
191 |
+
False -> lexicographically delete ckpts
|
192 |
+
"""
|
193 |
+
import re
|
194 |
+
ckpts_files = [f for f in os.listdir(path_to_models) if os.path.isfile(os.path.join(path_to_models, f))]
|
195 |
+
name_key = (lambda _f: int(re.compile('._(\d+)\.pth').match(_f).group(1)))
|
196 |
+
time_key = (lambda _f: os.path.getmtime(os.path.join(path_to_models, _f)))
|
197 |
+
sort_key = time_key if sort_by_time else name_key
|
198 |
+
x_sorted = lambda _x: sorted([f for f in ckpts_files if f.startswith(_x) and not f.endswith('_0.pth')],
|
199 |
+
key=sort_key)
|
200 |
+
to_del = [os.path.join(path_to_models, fn) for fn in
|
201 |
+
(x_sorted('G')[:-n_ckpts_to_keep] + x_sorted('D')[:-n_ckpts_to_keep])]
|
202 |
+
del_info = lambda fn: logger.info(f".. Free up space by deleting ckpt {fn}")
|
203 |
+
del_routine = lambda x: [os.remove(x), del_info(x)]
|
204 |
+
rs = [del_routine(fn) for fn in to_del]
|
205 |
+
|
206 |
+
def get_hparams_from_dir(model_dir):
|
207 |
+
config_save_path = os.path.join(model_dir, "config.json")
|
208 |
+
with open(config_save_path, "r", encoding='utf-8') as f:
|
209 |
+
data = f.read()
|
210 |
+
config = json.loads(data)
|
211 |
+
|
212 |
+
hparams = HParams(**config)
|
213 |
+
hparams.model_dir = model_dir
|
214 |
+
return hparams
|
215 |
+
|
216 |
+
|
217 |
+
def get_hparams_from_file(config_path):
|
218 |
+
with open(config_path, "r", encoding='utf-8') as f:
|
219 |
+
data = f.read()
|
220 |
+
config = json.loads(data)
|
221 |
+
|
222 |
+
hparams = HParams(**config)
|
223 |
+
return hparams
|
224 |
+
|
225 |
+
|
226 |
+
def check_git_hash(model_dir):
|
227 |
+
source_dir = os.path.dirname(os.path.realpath(__file__))
|
228 |
+
if not os.path.exists(os.path.join(source_dir, ".git")):
|
229 |
+
logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format(
|
230 |
+
source_dir
|
231 |
+
))
|
232 |
+
return
|
233 |
+
|
234 |
+
cur_hash = subprocess.getoutput("git rev-parse HEAD")
|
235 |
+
|
236 |
+
path = os.path.join(model_dir, "githash")
|
237 |
+
if os.path.exists(path):
|
238 |
+
saved_hash = open(path).read()
|
239 |
+
if saved_hash != cur_hash:
|
240 |
+
logger.warn("git hash values are different. {}(saved) != {}(current)".format(
|
241 |
+
saved_hash[:8], cur_hash[:8]))
|
242 |
+
else:
|
243 |
+
open(path, "w").write(cur_hash)
|
244 |
+
|
245 |
+
|
246 |
+
def get_logger(model_dir, filename="train.log"):
|
247 |
+
global logger
|
248 |
+
logger = logging.getLogger(os.path.basename(model_dir))
|
249 |
+
logger.setLevel(logging.DEBUG)
|
250 |
+
|
251 |
+
formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
|
252 |
+
if not os.path.exists(model_dir):
|
253 |
+
os.makedirs(model_dir)
|
254 |
+
h = logging.FileHandler(os.path.join(model_dir, filename))
|
255 |
+
h.setLevel(logging.DEBUG)
|
256 |
+
h.setFormatter(formatter)
|
257 |
+
logger.addHandler(h)
|
258 |
+
return logger
|
259 |
+
|
260 |
+
|
261 |
+
class HParams():
|
262 |
+
def __init__(self, **kwargs):
|
263 |
+
for k, v in kwargs.items():
|
264 |
+
if type(v) == dict:
|
265 |
+
v = HParams(**v)
|
266 |
+
self[k] = v
|
267 |
+
|
268 |
+
def keys(self):
|
269 |
+
return self.__dict__.keys()
|
270 |
+
|
271 |
+
def items(self):
|
272 |
+
return self.__dict__.items()
|
273 |
+
|
274 |
+
def values(self):
|
275 |
+
return self.__dict__.values()
|
276 |
+
|
277 |
+
def __len__(self):
|
278 |
+
return len(self.__dict__)
|
279 |
+
|
280 |
+
def __getitem__(self, key):
|
281 |
+
return getattr(self, key)
|
282 |
+
|
283 |
+
def __setitem__(self, key, value):
|
284 |
+
return setattr(self, key, value)
|
285 |
+
|
286 |
+
def __contains__(self, key):
|
287 |
+
return key in self.__dict__
|
288 |
+
|
289 |
+
def __repr__(self):
|
290 |
+
return self.__dict__.__repr__()
|
webui.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys, os
|
2 |
+
|
3 |
+
if sys.platform == "darwin":
|
4 |
+
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
|
5 |
+
|
6 |
+
import logging
|
7 |
+
|
8 |
+
logging.getLogger("numba").setLevel(logging.WARNING)
|
9 |
+
logging.getLogger("markdown_it").setLevel(logging.WARNING)
|
10 |
+
logging.getLogger("urllib3").setLevel(logging.WARNING)
|
11 |
+
logging.getLogger("matplotlib").setLevel(logging.WARNING)
|
12 |
+
|
13 |
+
logging.basicConfig(level=logging.INFO, format="| %(name)s | %(levelname)s | %(message)s")
|
14 |
+
|
15 |
+
logger = logging.getLogger(__name__)
|
16 |
+
|
17 |
+
import torch
|
18 |
+
import argparse
|
19 |
+
import commons
|
20 |
+
import utils
|
21 |
+
from models import SynthesizerTrn
|
22 |
+
from text.symbols import symbols
|
23 |
+
from text import cleaned_text_to_sequence, get_bert
|
24 |
+
from text.cleaner import clean_text
|
25 |
+
import gradio as gr
|
26 |
+
import webbrowser
|
27 |
+
|
28 |
+
|
29 |
+
net_g = None
|
30 |
+
|
31 |
+
|
32 |
+
def get_text(text, language_str, hps):
|
33 |
+
norm_text, phone, tone, word2ph = clean_text(text, language_str)
|
34 |
+
phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
|
35 |
+
|
36 |
+
if hps.data.add_blank:
|
37 |
+
phone = commons.intersperse(phone, 0)
|
38 |
+
tone = commons.intersperse(tone, 0)
|
39 |
+
language = commons.intersperse(language, 0)
|
40 |
+
for i in range(len(word2ph)):
|
41 |
+
word2ph[i] = word2ph[i] * 2
|
42 |
+
word2ph[0] += 1
|
43 |
+
bert = get_bert(norm_text, word2ph, language_str)
|
44 |
+
del word2ph
|
45 |
+
|
46 |
+
assert bert.shape[-1] == len(phone)
|
47 |
+
|
48 |
+
phone = torch.LongTensor(phone)
|
49 |
+
tone = torch.LongTensor(tone)
|
50 |
+
language = torch.LongTensor(language)
|
51 |
+
|
52 |
+
return bert, phone, tone, language
|
53 |
+
|
54 |
+
def infer(text, sdp_ratio, noise_scale, noise_scale_w, length_scale, sid):
|
55 |
+
global net_g
|
56 |
+
bert, phones, tones, lang_ids = get_text(text, "ZH", hps)
|
57 |
+
with torch.no_grad():
|
58 |
+
x_tst=phones.to(device).unsqueeze(0)
|
59 |
+
tones=tones.to(device).unsqueeze(0)
|
60 |
+
lang_ids=lang_ids.to(device).unsqueeze(0)
|
61 |
+
bert = bert.to(device).unsqueeze(0)
|
62 |
+
x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device)
|
63 |
+
del phones
|
64 |
+
speakers = torch.LongTensor([hps.data.spk2id[sid]]).to(device)
|
65 |
+
audio = net_g.infer(x_tst, x_tst_lengths, speakers, tones, lang_ids, bert, sdp_ratio=sdp_ratio
|
66 |
+
, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale)[0][0,0].data.cpu().float().numpy()
|
67 |
+
del x_tst, tones, lang_ids, bert, x_tst_lengths, speakers
|
68 |
+
return audio
|
69 |
+
|
70 |
+
def tts_fn(text, speaker, sdp_ratio, noise_scale, noise_scale_w, length_scale):
|
71 |
+
with torch.no_grad():
|
72 |
+
audio = infer(text, sdp_ratio=sdp_ratio, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale, sid=speaker)
|
73 |
+
return "Success", (hps.data.sampling_rate, audio)
|
74 |
+
|
75 |
+
|
76 |
+
if __name__ == "__main__":
|
77 |
+
parser = argparse.ArgumentParser()
|
78 |
+
# parser.add_argument("-m", "--model", default="./logs/dxl/G21200.pth", help="path of your model")
|
79 |
+
parser.add_argument("-mn", "--model_name", default="dxl", help="path of your model")
|
80 |
+
parser.add_argument("-m", "--model", default="null", help="path of your model")
|
81 |
+
parser.add_argument("-c", "--config", default="./configs/config.json", help="path of your config file")
|
82 |
+
parser.add_argument("--share", default=True, help="make link public")
|
83 |
+
parser.add_argument("-d", "--debug", action="store_true", help="enable DEBUG-LEVEL log")
|
84 |
+
|
85 |
+
args = parser.parse_args()
|
86 |
+
if args.debug:
|
87 |
+
logger.info("Enable DEBUG-LEVEL log")
|
88 |
+
logging.basicConfig(level=logging.DEBUG)
|
89 |
+
hps = utils.get_hparams_from_file(args.config)
|
90 |
+
|
91 |
+
device = (
|
92 |
+
"cuda:0"
|
93 |
+
if torch.cuda.is_available()
|
94 |
+
else (
|
95 |
+
"mps"
|
96 |
+
if sys.platform == "darwin" and torch.backends.mps.is_available()
|
97 |
+
else "cpu"
|
98 |
+
)
|
99 |
+
)
|
100 |
+
net_g = SynthesizerTrn(
|
101 |
+
len(symbols),
|
102 |
+
hps.data.filter_length // 2 + 1,
|
103 |
+
hps.train.segment_size // hps.data.hop_length,
|
104 |
+
n_speakers=hps.data.n_speakers,
|
105 |
+
**hps.model).to(device)
|
106 |
+
_ = net_g.eval()
|
107 |
+
|
108 |
+
model_path = args.model
|
109 |
+
if not os.path.exists(model_path) or model_path == "null":
|
110 |
+
model_path = utils.latest_checkpoint_path(os.path.join("./logs/",args.model_name), "G_*.pth")
|
111 |
+
|
112 |
+
_ = utils.load_checkpoint(model_path, net_g, None, skip_optimizer=True)
|
113 |
+
|
114 |
+
speaker_ids = hps.data.spk2id
|
115 |
+
speakers = list(speaker_ids.keys())
|
116 |
+
with gr.Blocks() as app:
|
117 |
+
with gr.Row():
|
118 |
+
with gr.Column():
|
119 |
+
text = gr.TextArea(label="Text", placeholder="Input Text Here",
|
120 |
+
value="吃葡萄不吐葡萄皮,不吃葡萄倒吐葡萄皮。")
|
121 |
+
speaker = gr.Dropdown(choices=speakers, value=speakers[0], label='Speaker')
|
122 |
+
sdp_ratio = gr.Slider(minimum=0, maximum=1, value=0.2, step=0.1, label='SDP Ratio')
|
123 |
+
noise_scale = gr.Slider(minimum=0.1, maximum=2, value=0.6, step=0.1, label='Noise Scale')
|
124 |
+
noise_scale_w = gr.Slider(minimum=0.1, maximum=2, value=0.8, step=0.1, label='Noise Scale W')
|
125 |
+
length_scale = gr.Slider(minimum=0.1, maximum=2, value=1, step=0.1, label='Length Scale')
|
126 |
+
btn = gr.Button("Generate!", variant="primary")
|
127 |
+
with gr.Column():
|
128 |
+
text_output = gr.Textbox(label="Message")
|
129 |
+
audio_output = gr.Audio(label="Output Audio")
|
130 |
+
|
131 |
+
btn.click(tts_fn,
|
132 |
+
inputs=[text, speaker, sdp_ratio, noise_scale, noise_scale_w, length_scale],
|
133 |
+
outputs=[text_output, audio_output])
|
134 |
+
|
135 |
+
webbrowser.open("http://127.0.0.1:7860")
|
136 |
+
app.launch(share=args.share)
|