Julius8888 commited on
Commit
b58aba6
1 Parent(s): f84c9ca

Upload 40 files

Browse files
Files changed (40) hide show
  1. .gitattributes +0 -2
  2. .gitignore +162 -0
  3. .gitmodules +0 -0
  4. .pre-commit-config.yaml +25 -0
  5. Dockerfile +61 -0
  6. LICENSE +661 -0
  7. README.md +6 -6
  8. app.py +555 -0
  9. attentions.py +464 -0
  10. author_and_voice_data.json +4 -0
  11. bert_gen.py +81 -0
  12. clap_gen.py +64 -0
  13. clap_wrapper.py +49 -0
  14. commons.py +158 -0
  15. compress_model.py +89 -0
  16. config.py +248 -0
  17. config.yml +177 -0
  18. data_utils.py +405 -0
  19. default_config.yml +177 -0
  20. empty_emo.npy +0 -0
  21. export_onnx.py +14 -0
  22. infer.py +411 -0
  23. losses.py +153 -0
  24. mel_processing.py +142 -0
  25. models.py +1076 -0
  26. modules.py +597 -0
  27. onnx_infer.py +68 -0
  28. preprocess_text.py +141 -0
  29. re_matching.py +81 -0
  30. requirements.txt +32 -0
  31. resample.py +75 -0
  32. resample_legacy.py +71 -0
  33. run_MnodesAndMgpus.sh +31 -0
  34. server_fastapi.py +680 -0
  35. spec_gen.py +87 -0
  36. train_ms.py +840 -0
  37. transforms.py +209 -0
  38. update_status.py +89 -0
  39. utils.py +461 -0
  40. webui_preprocess.py +166 -0
.gitattributes CHANGED
@@ -11,13 +11,11 @@
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
 
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
  *.npz filter=lfs diff=lfs merge=lfs -text
15
  *.onnx filter=lfs diff=lfs merge=lfs -text
16
  *.ot filter=lfs diff=lfs merge=lfs -text
17
  *.parquet filter=lfs diff=lfs merge=lfs -text
18
  *.pb filter=lfs diff=lfs merge=lfs -text
 
19
  *.pkl filter=lfs diff=lfs merge=lfs -text
20
  *.pt filter=lfs diff=lfs merge=lfs -text
21
  *.pth filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
.gitmodules ADDED
File without changes
.pre-commit-config.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v4.5.0
4
+ hooks:
5
+ - id: check-yaml
6
+ - id: end-of-file-fixer
7
+ - id: trailing-whitespace
8
+
9
+ - repo: https://github.com/astral-sh/ruff-pre-commit
10
+ rev: v0.1.8
11
+ hooks:
12
+ - id: ruff
13
+ args: [ --fix ]
14
+
15
+ - repo: https://github.com/psf/black
16
+ rev: 23.12.0
17
+ hooks:
18
+ - id: black
19
+
20
+ - repo: https://github.com/codespell-project/codespell
21
+ rev: v2.2.6
22
+ hooks:
23
+ - id: codespell
24
+ files: ^.*\.(py|md|rst|yml)$
25
+ args: [-L=fro]
Dockerfile ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dockerfile
2
+ FROM python:3.10.12
3
+
4
+ ## Set working directory
5
+ WORKDIR /app
6
+
7
+ ## Set the timezone
8
+ ENV TZ=Asia/Taipei
9
+ RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
10
+
11
+ # Copy files
12
+ COPY . .
13
+
14
+ RUN cd bert && ls && pwd
15
+
16
+ # Clone the Bert repository
17
+ RUN wget https://huggingface.co/microsoft/wavlm-base-plus/resolve/main/pytorch_model.bin?download=true -O slm/wavlm-base-plus/pytorch_model.bin && \
18
+ wget https://huggingface.co/ku-nlp/deberta-v2-large-japanese-char-wwm/resolve/main/pytorch_model.bin?download=true -O bert/deberta-v2-large-japanese-char-wwm/pytorch_model.bin && \
19
+ wget https://huggingface.co/hfl/chinese-roberta-wwm-ext-large/resolve/main/pytorch_model.bin?download=true -O bert/chinese-roberta-wwm-ext-large/pytorch_model.bin && \
20
+ wget https://huggingface.co/microsoft/deberta-v3-large/resolve/main/pytorch_model.bin?download=true -O bert/deberta-v3-large/pytorch_model.bin && \
21
+ wget https://huggingface.co/microsoft/deberta-v3-large/resolve/main/spm.model?download=true -O bert/deberta-v3-large/spm.model && \
22
+ git clone --depth 1 https://huggingface.co/laion/clap-htsat-fused emotional/clap-htsat-fused && \
23
+ git clone --depth 1 https://huggingface.co/audeering/wav2vec2-large-robust-12-ft-emotion-msp-dim emotional/wav2vec2-large-robust-12-ft-emotion-msp-dim
24
+
25
+ RUN cd bert && ls
26
+
27
+ RUN cd bert/deberta-v3-large && ls -lh
28
+
29
+ # Install Python requirements
30
+ RUN pip install -r requirements.txt
31
+
32
+
33
+ # Set Gradio server name
34
+ ENV GRADIO_SERVER_NAME=0.0.0.0
35
+
36
+ RUN chmod 777 /usr
37
+ RUN chmod 777 /app
38
+
39
+ RUN wget https://github.com/r9y9/open_jtalk/releases/download/v1.11.1/open_jtalk_dic_utf_8-1.11.tar.gz -O /usr/local/lib/python3.10/site-packages/pyopenjtalk/dic.tar.gz
40
+ RUN chmod 777 /usr/local/lib/python3.10/site-packages/pyopenjtalk/dic.tar.gz
41
+ RUN chmod 777 /usr/local/lib/python3.10/site-packages/pyopenjtalk
42
+
43
+
44
+ RUN mkdir /nltk_data && \
45
+ chmod 777 /nltk_data && \
46
+ mkdir /temp && \
47
+ chmod 777 /temp && \
48
+ mkdir /temp/matplotlib && \
49
+ mkdir /temp/huggingface && \
50
+ mkdir /temp/numba
51
+
52
+ ENV NUMBA_CACHE_DIR=/temp/numba
53
+ ENV MPLCONFIGDIR=/temp/matplotlib
54
+ ENV HF_HOME=/temp/huggingface
55
+ ENV HOME=/app
56
+
57
+ # Expose port
58
+ EXPOSE 7860
59
+
60
+ # Run the application
61
+ CMD ["python", "app.py"]
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,10 +1,10 @@
1
  ---
2
- title: XJP Voice
3
- emoji: 🐢
4
- colorFrom: gray
5
- colorTo: green
6
  sdk: docker
7
  pinned: false
8
  ---
9
-
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Bert VITS2 Docker Template
3
+ emoji: 📊
4
+ colorFrom: green
5
+ colorTo: red
6
  sdk: docker
7
  pinned: false
8
  ---
9
+ # Bert-VITS2-Docker-template
10
+ 此儲存庫提供一個無須上傳一堆Bert模型,便可以快速部署HuggingFace Spaces的方法。僅需修改config.yml以及上傳Bert-VITS的模型本體即可,大大縮短LFS的上傳時間。(順便提供 [Bert-VITS2-Colab](https://github.com/ADT109119/Bert-VITS2-Colab) 一鍵部署到 HF 的模板)
app.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: E402
2
+ import os
3
+ import logging
4
+ import re_matching
5
+ from tools.sentence import split_by_language
6
+
7
+ logging.getLogger("numba").setLevel(logging.WARNING)
8
+ logging.getLogger("markdown_it").setLevel(logging.WARNING)
9
+ logging.getLogger("urllib3").setLevel(logging.WARNING)
10
+ logging.getLogger("matplotlib").setLevel(logging.WARNING)
11
+
12
+ logging.basicConfig(
13
+ level=logging.INFO, format="| %(name)s | %(levelname)s | %(message)s"
14
+ )
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ import torch
19
+ import ssl
20
+ ssl._create_default_https_context = ssl._create_unverified_context
21
+ import nltk
22
+ nltk.download('cmudict')
23
+ import utils
24
+ from infer import infer, latest_version, get_net_g, infer_multilang
25
+ import gradio as gr
26
+ import webbrowser
27
+ import numpy as np
28
+ from config import config
29
+ from tools.translate import translate
30
+ import librosa
31
+
32
+ net_g = None
33
+
34
+ device = config.webui_config.device
35
+ if device == "mps":
36
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
37
+
38
+
39
+ def generate_audio(
40
+ slices,
41
+ sdp_ratio,
42
+ noise_scale,
43
+ noise_scale_w,
44
+ length_scale,
45
+ speaker,
46
+ language,
47
+ reference_audio,
48
+ emotion,
49
+ style_text,
50
+ style_weight,
51
+ skip_start=False,
52
+ skip_end=False,
53
+ ):
54
+ audio_list = []
55
+ # silence = np.zeros(hps.data.sampling_rate // 2, dtype=np.int16)
56
+ with torch.no_grad():
57
+ for idx, piece in enumerate(slices):
58
+ skip_start = idx != 0
59
+ skip_end = idx != len(slices) - 1
60
+ audio = infer(
61
+ piece,
62
+ reference_audio=reference_audio,
63
+ emotion=emotion,
64
+ sdp_ratio=sdp_ratio,
65
+ noise_scale=noise_scale,
66
+ noise_scale_w=noise_scale_w,
67
+ length_scale=length_scale,
68
+ sid=speaker,
69
+ language=language,
70
+ hps=hps,
71
+ net_g=net_g,
72
+ device=device,
73
+ skip_start=skip_start,
74
+ skip_end=skip_end,
75
+ style_text=style_text,
76
+ style_weight=style_weight,
77
+ )
78
+ audio16bit = gr.processing_utils.convert_to_16_bit_wav(audio)
79
+ audio_list.append(audio16bit)
80
+ return audio_list
81
+
82
+
83
+ def generate_audio_multilang(
84
+ slices,
85
+ sdp_ratio,
86
+ noise_scale,
87
+ noise_scale_w,
88
+ length_scale,
89
+ speaker,
90
+ language,
91
+ reference_audio,
92
+ emotion,
93
+ skip_start=False,
94
+ skip_end=False,
95
+ ):
96
+ audio_list = []
97
+ # silence = np.zeros(hps.data.sampling_rate // 2, dtype=np.int16)
98
+ with torch.no_grad():
99
+ for idx, piece in enumerate(slices):
100
+ skip_start = idx != 0
101
+ skip_end = idx != len(slices) - 1
102
+ audio = infer_multilang(
103
+ piece,
104
+ reference_audio=reference_audio,
105
+ emotion=emotion,
106
+ sdp_ratio=sdp_ratio,
107
+ noise_scale=noise_scale,
108
+ noise_scale_w=noise_scale_w,
109
+ length_scale=length_scale,
110
+ sid=speaker,
111
+ language=language[idx],
112
+ hps=hps,
113
+ net_g=net_g,
114
+ device=device,
115
+ skip_start=skip_start,
116
+ skip_end=skip_end,
117
+ )
118
+ audio16bit = gr.processing_utils.convert_to_16_bit_wav(audio)
119
+ audio_list.append(audio16bit)
120
+ return audio_list
121
+
122
+
123
+ def tts_split(
124
+ text: str,
125
+ speaker,
126
+ sdp_ratio,
127
+ noise_scale,
128
+ noise_scale_w,
129
+ length_scale,
130
+ language,
131
+ cut_by_sent,
132
+ interval_between_para,
133
+ interval_between_sent,
134
+ reference_audio,
135
+ emotion,
136
+ style_text,
137
+ style_weight,
138
+ ):
139
+ while text.find("\n\n") != -1:
140
+ text = text.replace("\n\n", "\n")
141
+ text = text.replace("|", "")
142
+ para_list = re_matching.cut_para(text)
143
+ para_list = [p for p in para_list if p != ""]
144
+ audio_list = []
145
+ for p in para_list:
146
+ if not cut_by_sent:
147
+ audio_list += process_text(
148
+ p,
149
+ speaker,
150
+ sdp_ratio,
151
+ noise_scale,
152
+ noise_scale_w,
153
+ length_scale,
154
+ language,
155
+ reference_audio,
156
+ emotion,
157
+ style_text,
158
+ style_weight,
159
+ )
160
+ silence = np.zeros((int)(44100 * interval_between_para), dtype=np.int16)
161
+ audio_list.append(silence)
162
+ else:
163
+ audio_list_sent = []
164
+ sent_list = re_matching.cut_sent(p)
165
+ sent_list = [s for s in sent_list if s != ""]
166
+ for s in sent_list:
167
+ audio_list_sent += process_text(
168
+ s,
169
+ speaker,
170
+ sdp_ratio,
171
+ noise_scale,
172
+ noise_scale_w,
173
+ length_scale,
174
+ language,
175
+ reference_audio,
176
+ emotion,
177
+ style_text,
178
+ style_weight,
179
+ )
180
+ silence = np.zeros((int)(44100 * interval_between_sent))
181
+ audio_list_sent.append(silence)
182
+ if (interval_between_para - interval_between_sent) > 0:
183
+ silence = np.zeros(
184
+ (int)(44100 * (interval_between_para - interval_between_sent))
185
+ )
186
+ audio_list_sent.append(silence)
187
+ audio16bit = gr.processing_utils.convert_to_16_bit_wav(
188
+ np.concatenate(audio_list_sent)
189
+ ) # 对完整句子做音量归一
190
+ audio_list.append(audio16bit)
191
+ audio_concat = np.concatenate(audio_list)
192
+ return ("Success", (hps.data.sampling_rate, audio_concat))
193
+
194
+
195
+ def process_mix(slice):
196
+ _speaker = slice.pop()
197
+ _text, _lang = [], []
198
+ for lang, content in slice:
199
+ content = content.split("|")
200
+ content = [part for part in content if part != ""]
201
+ if len(content) == 0:
202
+ continue
203
+ if len(_text) == 0:
204
+ _text = [[part] for part in content]
205
+ _lang = [[lang] for part in content]
206
+ else:
207
+ _text[-1].append(content[0])
208
+ _lang[-1].append(lang)
209
+ if len(content) > 1:
210
+ _text += [[part] for part in content[1:]]
211
+ _lang += [[lang] for part in content[1:]]
212
+ return _text, _lang, _speaker
213
+
214
+
215
+ def process_auto(text):
216
+ _text, _lang = [], []
217
+ for slice in text.split("|"):
218
+ if slice == "":
219
+ continue
220
+ temp_text, temp_lang = [], []
221
+ sentences_list = split_by_language(slice, target_languages=["zh", "ja", "en"])
222
+ for sentence, lang in sentences_list:
223
+ if sentence == "":
224
+ continue
225
+ temp_text.append(sentence)
226
+ temp_lang.append(lang.upper())
227
+ _text.append(temp_text)
228
+ _lang.append(temp_lang)
229
+ return _text, _lang
230
+
231
+
232
+ def process_text(
233
+ text: str,
234
+ speaker,
235
+ sdp_ratio,
236
+ noise_scale,
237
+ noise_scale_w,
238
+ length_scale,
239
+ language,
240
+ reference_audio,
241
+ emotion,
242
+ style_text=None,
243
+ style_weight=0,
244
+ ):
245
+ audio_list = []
246
+ if language == "mix":
247
+ bool_valid, str_valid = re_matching.validate_text(text)
248
+ if not bool_valid:
249
+ return str_valid, (
250
+ hps.data.sampling_rate,
251
+ np.concatenate([np.zeros(hps.data.sampling_rate // 2)]),
252
+ )
253
+ for slice in re_matching.text_matching(text):
254
+ _text, _lang, _speaker = process_mix(slice)
255
+ if _speaker is None:
256
+ continue
257
+ print(f"Text: {_text}\nLang: {_lang}")
258
+ audio_list.extend(
259
+ generate_audio_multilang(
260
+ _text,
261
+ sdp_ratio,
262
+ noise_scale,
263
+ noise_scale_w,
264
+ length_scale,
265
+ _speaker,
266
+ _lang,
267
+ reference_audio,
268
+ emotion,
269
+ )
270
+ )
271
+ elif language.lower() == "auto":
272
+ _text, _lang = process_auto(text)
273
+ print(f"Text: {_text}\nLang: {_lang}")
274
+ _lang = [[lang.replace("JA", "JP") for lang in lang_list] for lang_list in _lang]
275
+ audio_list.extend(
276
+ generate_audio_multilang(
277
+ _text,
278
+ sdp_ratio,
279
+ noise_scale,
280
+ noise_scale_w,
281
+ length_scale,
282
+ speaker,
283
+ _lang,
284
+ reference_audio,
285
+ emotion,
286
+ )
287
+ )
288
+ else:
289
+ audio_list.extend(
290
+ generate_audio(
291
+ text.split("|"),
292
+ sdp_ratio,
293
+ noise_scale,
294
+ noise_scale_w,
295
+ length_scale,
296
+ speaker,
297
+ language,
298
+ reference_audio,
299
+ emotion,
300
+ style_text,
301
+ style_weight,
302
+ )
303
+ )
304
+ return audio_list
305
+
306
+
307
+ def tts_fn(
308
+ text: str,
309
+ speaker,
310
+ sdp_ratio,
311
+ noise_scale,
312
+ noise_scale_w,
313
+ length_scale,
314
+ language,
315
+ reference_audio,
316
+ emotion,
317
+ prompt_mode,
318
+ style_text=None,
319
+ style_weight=0,
320
+ ):
321
+ if style_text == "":
322
+ style_text = None
323
+ if prompt_mode == "Audio prompt":
324
+ if reference_audio == None:
325
+ return ("Invalid audio prompt", None)
326
+ else:
327
+ reference_audio = load_audio(reference_audio)[1]
328
+ else:
329
+ reference_audio = None
330
+
331
+ audio_list = process_text(
332
+ text,
333
+ speaker,
334
+ sdp_ratio,
335
+ noise_scale,
336
+ noise_scale_w,
337
+ length_scale,
338
+ language,
339
+ reference_audio,
340
+ emotion,
341
+ style_text,
342
+ style_weight,
343
+ )
344
+
345
+ audio_concat = np.concatenate(audio_list)
346
+ return "Success", (hps.data.sampling_rate, audio_concat)
347
+
348
+
349
+ def format_utils(text, speaker):
350
+ _text, _lang = process_auto(text)
351
+ res = f"[{speaker}]"
352
+ for lang_s, content_s in zip(_lang, _text):
353
+ for lang, content in zip(lang_s, content_s):
354
+ res += f"<{lang.lower()}>{content}"
355
+ res += "|"
356
+ return "mix", res[:-1]
357
+
358
+
359
+ def load_audio(path):
360
+ audio, sr = librosa.load(path, 48000)
361
+ # audio = librosa.resample(audio, 44100, 48000)
362
+ return sr, audio
363
+
364
+
365
+ def gr_util(item):
366
+ if item == "Text prompt":
367
+ return {"visible": True, "__type__": "update"}, {
368
+ "visible": False,
369
+ "__type__": "update",
370
+ }
371
+ else:
372
+ return {"visible": False, "__type__": "update"}, {
373
+ "visible": True,
374
+ "__type__": "update",
375
+ }
376
+
377
+ import json
378
+
379
+ def load_json(file_path):
380
+ with open(file_path, 'r', encoding="utf-8") as file:
381
+ data = json.load(file)
382
+ return data
383
+
384
+ if __name__ == "__main__":
385
+ if config.webui_config.debug:
386
+ logger.info("Enable DEBUG-LEVEL log")
387
+ logging.basicConfig(level=logging.DEBUG)
388
+ hps = utils.get_hparams_from_file(config.webui_config.config_path)
389
+ # 若config.json中未指定版本则默认为最新版本
390
+ version = hps.version if hasattr(hps, "version") else latest_version
391
+ net_g = get_net_g(
392
+ model_path=config.webui_config.model, version=version, device=device, hps=hps
393
+ )
394
+ speaker_ids = hps.data.spk2id
395
+ speakers = list(speaker_ids.keys())
396
+ languages = ["ZH", "JP", "EN", "auto", "mix"]
397
+
398
+ author_and_voice_data = load_json('author_and_voice_data.json')
399
+
400
+ with gr.Blocks() as app:
401
+ with gr.Row():
402
+ with gr.Column():
403
+ gr.Markdown(value=f"""
404
+ 作者:{author_and_voice_data["author"]}\n
405
+ 聲音歸屬:{author_and_voice_data["voice"]}\n
406
+ Bert-VITS2項目:https://github.com/fishaudio/Bert-VITS2\n
407
+ Bert-VITS2-Colab:https://github.com/ADT109119/Bert-VITS2-Colab\n
408
+ 使用本模型請嚴格遵守法規! \n
409
+ 發布二創作品請標註本計畫作者及連結、作品使用Bert-VITS2 AI生成! \n
410
+ 【提示】手機端容易誤觸調節,請刷新恢復預設! 每次產生的結果都不一樣,效果不好請嘗試多次產生與調節,選擇最佳結果! \n """)
411
+ text = gr.TextArea(
412
+ label="輸入文本內容",
413
+ placeholder="""
414
+ 推薦不同語言分開推理,因為無法連貫且可能影響最終效果!
415
+ 若選擇語言為\'mix\',必須依照格式輸入,否則報錯:
416
+ 格式舉例(zh是中文,jp是日語,en是英語;不區分大小寫):
417
+ [說話者]<zh>你好 <jp>こんにちは <en>Hello
418
+ 另外,所有的語言選項都可以用'|'分割長段實現分句生成。
419
+ """, )
420
+ speaker = gr.Dropdown(
421
+ choices=speakers, value=speakers[0], label="Speaker"
422
+ )
423
+ _ = gr.Markdown(
424
+ value="提示模式(Prompt mode):可選文字提示或音訊提示,用於產生文字或音訊指定風格的聲音。\n",
425
+ visible=False,
426
+ )
427
+ prompt_mode = gr.Radio(
428
+ ["Text prompt", "Audio prompt"],
429
+ label="Prompt Mode",
430
+ value="Text prompt",
431
+ visible=False,
432
+ )
433
+ text_prompt = gr.Textbox(
434
+ label="Text prompt",
435
+ placeholder="用文字描述生成風格。如:Happy",
436
+ value="Happy",
437
+ visible=False,
438
+ )
439
+ audio_prompt = gr.Audio(
440
+ label="Audio prompt", type="filepath", visible=False
441
+ )
442
+ sdp_ratio = gr.Slider(
443
+ minimum=0, maximum=1, value=0.5, step=0.01, label="SDP Ratio"
444
+ )
445
+ noise_scale = gr.Slider(
446
+ minimum=0.1, maximum=2, value=0.5, step=0.01, label="Noise"
447
+ )
448
+ noise_scale_w = gr.Slider(
449
+ minimum=0.1, maximum=2, value=0.9, step=0.01, label="Noise_W"
450
+ )
451
+ length_scale = gr.Slider(
452
+ minimum=0.1, maximum=2, value=1.0, step=0.01, label="Length"
453
+ )
454
+ language = gr.Dropdown(
455
+ choices=languages, value=languages[0], label="Language"
456
+ )
457
+ btn = gr.Button("點擊生成", variant="primary")
458
+ with gr.Column():
459
+ with gr.Accordion("融合文本語義", open=False):
460
+ gr.Markdown(
461
+ value="使用輔助文本的語意來輔助生成對話(語言保持與主文本相同)\n\n"
462
+ "**注意**:不要使用**指令式文字**(如:開心),要使用**帶有強烈情感的文本**(如���我好快樂!!!)\n\n"
463
+ "效果較不明確,留空即為不使用該功能"
464
+ )
465
+ style_text = gr.Textbox(label="輔助文本")
466
+ style_weight = gr.Slider(
467
+ minimum=0,
468
+ maximum=1,
469
+ value=0.7,
470
+ step=0.1,
471
+ label="Weight",
472
+ info="主文本和輔助文本的bert混合比率,0表示僅主文本,1表示僅輔助文本",
473
+ )
474
+ with gr.Row():
475
+ with gr.Column():
476
+ interval_between_sent = gr.Slider(
477
+ minimum=0,
478
+ maximum=5,
479
+ value=0.2,
480
+ step=0.1,
481
+ label="句間停頓(秒),勾選按句切分才生效",
482
+ )
483
+ interval_between_para = gr.Slider(
484
+ minimum=0,
485
+ maximum=10,
486
+ value=1,
487
+ step=0.1,
488
+ label="段間停頓(秒),需要大於句間停頓才有效",
489
+ )
490
+ opt_cut_by_sent = gr.Checkbox(
491
+ label="按句切分 在按段落切分的基礎上再按句子切分文本"
492
+ )
493
+ slicer = gr.Button("切分生成", variant="primary")
494
+ text_output = gr.Textbox(label="狀態訊息")
495
+ audio_output = gr.Audio(label="輸出音頻")
496
+ # explain_image = gr.Image(
497
+ # label="参数解释信息",
498
+ # show_label=True,
499
+ # show_share_button=False,
500
+ # show_download_button=False,
501
+ # value=os.path.abspath("./img/参数说明.png"),
502
+ # )
503
+ btn.click(
504
+ tts_fn,
505
+ inputs=[
506
+ text,
507
+ speaker,
508
+ sdp_ratio,
509
+ noise_scale,
510
+ noise_scale_w,
511
+ length_scale,
512
+ language,
513
+ audio_prompt,
514
+ text_prompt,
515
+ prompt_mode,
516
+ style_text,
517
+ style_weight,
518
+ ],
519
+ outputs=[text_output, audio_output],
520
+ api_name="api"
521
+ )
522
+ slicer.click(
523
+ tts_split,
524
+ inputs=[
525
+ text,
526
+ speaker,
527
+ sdp_ratio,
528
+ noise_scale,
529
+ noise_scale_w,
530
+ length_scale,
531
+ language,
532
+ opt_cut_by_sent,
533
+ interval_between_para,
534
+ interval_between_sent,
535
+ audio_prompt,
536
+ text_prompt,
537
+ style_text,
538
+ style_weight,
539
+ ],
540
+ outputs=[text_output, audio_output],
541
+ )
542
+
543
+ prompt_mode.change(
544
+ lambda x: gr_util(x),
545
+ inputs=[prompt_mode],
546
+ outputs=[text_prompt, audio_prompt],
547
+ )
548
+
549
+ audio_prompt.upload(
550
+ lambda x: load_audio(x),
551
+ inputs=[audio_prompt],
552
+ outputs=[audio_prompt],
553
+ )
554
+
555
+ app.launch(show_error=True)
attentions.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ import commons
7
+ import logging
8
+
9
+ logger = logging.getLogger(__name__)
10
+
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
+ @torch.jit.script
28
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
29
+ n_channels_int = n_channels[0]
30
+ in_act = input_a + input_b
31
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
32
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
33
+ acts = t_act * s_act
34
+ return acts
35
+
36
+
37
+ class Encoder(nn.Module):
38
+ def __init__(
39
+ self,
40
+ hidden_channels,
41
+ filter_channels,
42
+ n_heads,
43
+ n_layers,
44
+ kernel_size=1,
45
+ p_dropout=0.0,
46
+ window_size=4,
47
+ isflow=True,
48
+ **kwargs
49
+ ):
50
+ super().__init__()
51
+ self.hidden_channels = hidden_channels
52
+ self.filter_channels = filter_channels
53
+ self.n_heads = n_heads
54
+ self.n_layers = n_layers
55
+ self.kernel_size = kernel_size
56
+ self.p_dropout = p_dropout
57
+ self.window_size = window_size
58
+ # if isflow:
59
+ # cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
60
+ # self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
61
+ # self.cond_layer = weight_norm(cond_layer, name='weight')
62
+ # self.gin_channels = 256
63
+ self.cond_layer_idx = self.n_layers
64
+ if "gin_channels" in kwargs:
65
+ self.gin_channels = kwargs["gin_channels"]
66
+ if self.gin_channels != 0:
67
+ self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
68
+ # vits2 says 3rd block, so idx is 2 by default
69
+ self.cond_layer_idx = (
70
+ kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
71
+ )
72
+ logging.debug(self.gin_channels, self.cond_layer_idx)
73
+ assert (
74
+ self.cond_layer_idx < self.n_layers
75
+ ), "cond_layer_idx should be less than n_layers"
76
+ self.drop = nn.Dropout(p_dropout)
77
+ self.attn_layers = nn.ModuleList()
78
+ self.norm_layers_1 = nn.ModuleList()
79
+ self.ffn_layers = nn.ModuleList()
80
+ self.norm_layers_2 = nn.ModuleList()
81
+ for i in range(self.n_layers):
82
+ self.attn_layers.append(
83
+ MultiHeadAttention(
84
+ hidden_channels,
85
+ hidden_channels,
86
+ n_heads,
87
+ p_dropout=p_dropout,
88
+ window_size=window_size,
89
+ )
90
+ )
91
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
92
+ self.ffn_layers.append(
93
+ FFN(
94
+ hidden_channels,
95
+ hidden_channels,
96
+ filter_channels,
97
+ kernel_size,
98
+ p_dropout=p_dropout,
99
+ )
100
+ )
101
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
102
+
103
+ def forward(self, x, x_mask, g=None):
104
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
105
+ x = x * x_mask
106
+ for i in range(self.n_layers):
107
+ if i == self.cond_layer_idx and g is not None:
108
+ g = self.spk_emb_linear(g.transpose(1, 2))
109
+ g = g.transpose(1, 2)
110
+ x = x + g
111
+ x = x * x_mask
112
+ y = self.attn_layers[i](x, x, attn_mask)
113
+ y = self.drop(y)
114
+ x = self.norm_layers_1[i](x + y)
115
+
116
+ y = self.ffn_layers[i](x, x_mask)
117
+ y = self.drop(y)
118
+ x = self.norm_layers_2[i](x + y)
119
+ x = x * x_mask
120
+ return x
121
+
122
+
123
+ class Decoder(nn.Module):
124
+ def __init__(
125
+ self,
126
+ hidden_channels,
127
+ filter_channels,
128
+ n_heads,
129
+ n_layers,
130
+ kernel_size=1,
131
+ p_dropout=0.0,
132
+ proximal_bias=False,
133
+ proximal_init=True,
134
+ **kwargs
135
+ ):
136
+ super().__init__()
137
+ self.hidden_channels = hidden_channels
138
+ self.filter_channels = filter_channels
139
+ self.n_heads = n_heads
140
+ self.n_layers = n_layers
141
+ self.kernel_size = kernel_size
142
+ self.p_dropout = p_dropout
143
+ self.proximal_bias = proximal_bias
144
+ self.proximal_init = proximal_init
145
+
146
+ self.drop = nn.Dropout(p_dropout)
147
+ self.self_attn_layers = nn.ModuleList()
148
+ self.norm_layers_0 = nn.ModuleList()
149
+ self.encdec_attn_layers = nn.ModuleList()
150
+ self.norm_layers_1 = nn.ModuleList()
151
+ self.ffn_layers = nn.ModuleList()
152
+ self.norm_layers_2 = nn.ModuleList()
153
+ for i in range(self.n_layers):
154
+ self.self_attn_layers.append(
155
+ MultiHeadAttention(
156
+ hidden_channels,
157
+ hidden_channels,
158
+ n_heads,
159
+ p_dropout=p_dropout,
160
+ proximal_bias=proximal_bias,
161
+ proximal_init=proximal_init,
162
+ )
163
+ )
164
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
165
+ self.encdec_attn_layers.append(
166
+ MultiHeadAttention(
167
+ hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
168
+ )
169
+ )
170
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
171
+ self.ffn_layers.append(
172
+ FFN(
173
+ hidden_channels,
174
+ hidden_channels,
175
+ filter_channels,
176
+ kernel_size,
177
+ p_dropout=p_dropout,
178
+ causal=True,
179
+ )
180
+ )
181
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
182
+
183
+ def forward(self, x, x_mask, h, h_mask):
184
+ """
185
+ x: decoder input
186
+ h: encoder output
187
+ """
188
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
189
+ device=x.device, dtype=x.dtype
190
+ )
191
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
192
+ x = x * x_mask
193
+ for i in range(self.n_layers):
194
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
195
+ y = self.drop(y)
196
+ x = self.norm_layers_0[i](x + y)
197
+
198
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
199
+ y = self.drop(y)
200
+ x = self.norm_layers_1[i](x + y)
201
+
202
+ y = self.ffn_layers[i](x, x_mask)
203
+ y = self.drop(y)
204
+ x = self.norm_layers_2[i](x + y)
205
+ x = x * x_mask
206
+ return x
207
+
208
+
209
+ class MultiHeadAttention(nn.Module):
210
+ def __init__(
211
+ self,
212
+ channels,
213
+ out_channels,
214
+ n_heads,
215
+ p_dropout=0.0,
216
+ window_size=None,
217
+ heads_share=True,
218
+ block_length=None,
219
+ proximal_bias=False,
220
+ proximal_init=False,
221
+ ):
222
+ super().__init__()
223
+ assert channels % n_heads == 0
224
+
225
+ self.channels = channels
226
+ self.out_channels = out_channels
227
+ self.n_heads = n_heads
228
+ self.p_dropout = p_dropout
229
+ self.window_size = window_size
230
+ self.heads_share = heads_share
231
+ self.block_length = block_length
232
+ self.proximal_bias = proximal_bias
233
+ self.proximal_init = proximal_init
234
+ self.attn = None
235
+
236
+ self.k_channels = channels // n_heads
237
+ self.conv_q = nn.Conv1d(channels, channels, 1)
238
+ self.conv_k = nn.Conv1d(channels, channels, 1)
239
+ self.conv_v = nn.Conv1d(channels, channels, 1)
240
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
241
+ self.drop = nn.Dropout(p_dropout)
242
+
243
+ if window_size is not None:
244
+ n_heads_rel = 1 if heads_share else n_heads
245
+ rel_stddev = self.k_channels**-0.5
246
+ self.emb_rel_k = nn.Parameter(
247
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
248
+ * rel_stddev
249
+ )
250
+ self.emb_rel_v = nn.Parameter(
251
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
252
+ * rel_stddev
253
+ )
254
+
255
+ nn.init.xavier_uniform_(self.conv_q.weight)
256
+ nn.init.xavier_uniform_(self.conv_k.weight)
257
+ nn.init.xavier_uniform_(self.conv_v.weight)
258
+ if proximal_init:
259
+ with torch.no_grad():
260
+ self.conv_k.weight.copy_(self.conv_q.weight)
261
+ self.conv_k.bias.copy_(self.conv_q.bias)
262
+
263
+ def forward(self, x, c, attn_mask=None):
264
+ q = self.conv_q(x)
265
+ k = self.conv_k(c)
266
+ v = self.conv_v(c)
267
+
268
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
269
+
270
+ x = self.conv_o(x)
271
+ return x
272
+
273
+ def attention(self, query, key, value, mask=None):
274
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
275
+ b, d, t_s, t_t = (*key.size(), query.size(2))
276
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
277
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
278
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
279
+
280
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
281
+ if self.window_size is not None:
282
+ assert (
283
+ t_s == t_t
284
+ ), "Relative attention is only available for self-attention."
285
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
286
+ rel_logits = self._matmul_with_relative_keys(
287
+ query / math.sqrt(self.k_channels), key_relative_embeddings
288
+ )
289
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
290
+ scores = scores + scores_local
291
+ if self.proximal_bias:
292
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
293
+ scores = scores + self._attention_bias_proximal(t_s).to(
294
+ device=scores.device, dtype=scores.dtype
295
+ )
296
+ if mask is not None:
297
+ scores = scores.masked_fill(mask == 0, -1e4)
298
+ if self.block_length is not None:
299
+ assert (
300
+ t_s == t_t
301
+ ), "Local attention is only available for self-attention."
302
+ block_mask = (
303
+ torch.ones_like(scores)
304
+ .triu(-self.block_length)
305
+ .tril(self.block_length)
306
+ )
307
+ scores = scores.masked_fill(block_mask == 0, -1e4)
308
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
309
+ p_attn = self.drop(p_attn)
310
+ output = torch.matmul(p_attn, value)
311
+ if self.window_size is not None:
312
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
313
+ value_relative_embeddings = self._get_relative_embeddings(
314
+ self.emb_rel_v, t_s
315
+ )
316
+ output = output + self._matmul_with_relative_values(
317
+ relative_weights, value_relative_embeddings
318
+ )
319
+ output = (
320
+ output.transpose(2, 3).contiguous().view(b, d, t_t)
321
+ ) # [b, n_h, t_t, d_k] -> [b, d, t_t]
322
+ return output, p_attn
323
+
324
+ def _matmul_with_relative_values(self, x, y):
325
+ """
326
+ x: [b, h, l, m]
327
+ y: [h or 1, m, d]
328
+ ret: [b, h, l, d]
329
+ """
330
+ ret = torch.matmul(x, y.unsqueeze(0))
331
+ return ret
332
+
333
+ def _matmul_with_relative_keys(self, x, y):
334
+ """
335
+ x: [b, h, l, d]
336
+ y: [h or 1, m, d]
337
+ ret: [b, h, l, m]
338
+ """
339
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
340
+ return ret
341
+
342
+ def _get_relative_embeddings(self, relative_embeddings, length):
343
+ 2 * self.window_size + 1
344
+ # Pad first before slice to avoid using cond ops.
345
+ pad_length = max(length - (self.window_size + 1), 0)
346
+ slice_start_position = max((self.window_size + 1) - length, 0)
347
+ slice_end_position = slice_start_position + 2 * length - 1
348
+ if pad_length > 0:
349
+ padded_relative_embeddings = F.pad(
350
+ relative_embeddings,
351
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
352
+ )
353
+ else:
354
+ padded_relative_embeddings = relative_embeddings
355
+ used_relative_embeddings = padded_relative_embeddings[
356
+ :, slice_start_position:slice_end_position
357
+ ]
358
+ return used_relative_embeddings
359
+
360
+ def _relative_position_to_absolute_position(self, x):
361
+ """
362
+ x: [b, h, l, 2*l-1]
363
+ ret: [b, h, l, l]
364
+ """
365
+ batch, heads, length, _ = x.size()
366
+ # Concat columns of pad to shift from relative to absolute indexing.
367
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
368
+
369
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
370
+ x_flat = x.view([batch, heads, length * 2 * length])
371
+ x_flat = F.pad(
372
+ x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
373
+ )
374
+
375
+ # Reshape and slice out the padded elements.
376
+ x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
377
+ :, :, :length, length - 1 :
378
+ ]
379
+ return x_final
380
+
381
+ def _absolute_position_to_relative_position(self, x):
382
+ """
383
+ x: [b, h, l, l]
384
+ ret: [b, h, l, 2*l-1]
385
+ """
386
+ batch, heads, length, _ = x.size()
387
+ # pad along column
388
+ x = F.pad(
389
+ x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
390
+ )
391
+ x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
392
+ # add 0's in the beginning that will skew the elements after reshape
393
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
394
+ x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
395
+ return x_final
396
+
397
+ def _attention_bias_proximal(self, length):
398
+ """Bias for self-attention to encourage attention to close positions.
399
+ Args:
400
+ length: an integer scalar.
401
+ Returns:
402
+ a Tensor with shape [1, 1, length, length]
403
+ """
404
+ r = torch.arange(length, dtype=torch.float32)
405
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
406
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
407
+
408
+
409
+ class FFN(nn.Module):
410
+ def __init__(
411
+ self,
412
+ in_channels,
413
+ out_channels,
414
+ filter_channels,
415
+ kernel_size,
416
+ p_dropout=0.0,
417
+ activation=None,
418
+ causal=False,
419
+ ):
420
+ super().__init__()
421
+ self.in_channels = in_channels
422
+ self.out_channels = out_channels
423
+ self.filter_channels = filter_channels
424
+ self.kernel_size = kernel_size
425
+ self.p_dropout = p_dropout
426
+ self.activation = activation
427
+ self.causal = causal
428
+
429
+ if causal:
430
+ self.padding = self._causal_padding
431
+ else:
432
+ self.padding = self._same_padding
433
+
434
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
435
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
436
+ self.drop = nn.Dropout(p_dropout)
437
+
438
+ def forward(self, x, x_mask):
439
+ x = self.conv_1(self.padding(x * x_mask))
440
+ if self.activation == "gelu":
441
+ x = x * torch.sigmoid(1.702 * x)
442
+ else:
443
+ x = torch.relu(x)
444
+ x = self.drop(x)
445
+ x = self.conv_2(self.padding(x * x_mask))
446
+ return x * x_mask
447
+
448
+ def _causal_padding(self, x):
449
+ if self.kernel_size == 1:
450
+ return x
451
+ pad_l = self.kernel_size - 1
452
+ pad_r = 0
453
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
454
+ x = F.pad(x, commons.convert_pad_shape(padding))
455
+ return x
456
+
457
+ def _same_padding(self, x):
458
+ if self.kernel_size == 1:
459
+ return x
460
+ pad_l = (self.kernel_size - 1) // 2
461
+ pad_r = self.kernel_size // 2
462
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
463
+ x = F.pad(x, commons.convert_pad_shape(padding))
464
+ return x
author_and_voice_data.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "author": "習近平",
3
+ "voice": "XJP"
4
+ }
bert_gen.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from multiprocessing import Pool
3
+ import commons
4
+ import utils
5
+ from tqdm import tqdm
6
+ from text import check_bert_models, cleaned_text_to_sequence, get_bert
7
+ import argparse
8
+ import torch.multiprocessing as mp
9
+ from config import config
10
+
11
+
12
+ def process_line(x):
13
+ line, add_blank = x
14
+ device = config.bert_gen_config.device
15
+ if config.bert_gen_config.use_multi_device:
16
+ rank = mp.current_process()._identity
17
+ rank = rank[0] if len(rank) > 0 else 0
18
+ if torch.cuda.is_available():
19
+ gpu_id = rank % torch.cuda.device_count()
20
+ device = torch.device(f"cuda:{gpu_id}")
21
+ else:
22
+ device = torch.device("cpu")
23
+ wav_path, _, language_str, text, phones, tone, word2ph = line.strip().split("|")
24
+ phone = phones.split(" ")
25
+ tone = [int(i) for i in tone.split(" ")]
26
+ word2ph = [int(i) for i in word2ph.split(" ")]
27
+ word2ph = [i for i in word2ph]
28
+ phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
29
+
30
+ if add_blank:
31
+ phone = commons.intersperse(phone, 0)
32
+ tone = commons.intersperse(tone, 0)
33
+ language = commons.intersperse(language, 0)
34
+ for i in range(len(word2ph)):
35
+ word2ph[i] = word2ph[i] * 2
36
+ word2ph[0] += 1
37
+
38
+ bert_path = wav_path.replace(".WAV", ".wav").replace(".wav", ".bert.pt")
39
+
40
+ try:
41
+ bert = torch.load(bert_path)
42
+ assert bert.shape[-1] == len(phone)
43
+ except Exception:
44
+ bert = get_bert(text, word2ph, language_str, device)
45
+ assert bert.shape[-1] == len(phone)
46
+ torch.save(bert, bert_path)
47
+
48
+
49
+ preprocess_text_config = config.preprocess_text_config
50
+
51
+ if __name__ == "__main__":
52
+ parser = argparse.ArgumentParser()
53
+ parser.add_argument(
54
+ "-c", "--config", type=str, default=config.bert_gen_config.config_path
55
+ )
56
+ parser.add_argument(
57
+ "--num_processes", type=int, default=config.bert_gen_config.num_processes
58
+ )
59
+ args, _ = parser.parse_known_args()
60
+ config_path = args.config
61
+ hps = utils.get_hparams_from_file(config_path)
62
+ check_bert_models()
63
+ lines = []
64
+ with open(hps.data.training_files, encoding="utf-8") as f:
65
+ lines.extend(f.readlines())
66
+
67
+ with open(hps.data.validation_files, encoding="utf-8") as f:
68
+ lines.extend(f.readlines())
69
+ add_blank = [hps.data.add_blank] * len(lines)
70
+
71
+ if len(lines) != 0:
72
+ num_processes = args.num_processes
73
+ with Pool(processes=num_processes) as pool:
74
+ for _ in tqdm(
75
+ pool.imap_unordered(process_line, zip(lines, add_blank)),
76
+ total=len(lines),
77
+ ):
78
+ # 这里是缩进的代码块,表示循环体
79
+ pass # 使用pass语句作为占位符
80
+
81
+ print(f"bert生成完毕!, 共有{len(lines)}个bert.pt生成!")
clap_gen.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from multiprocessing import Pool, cpu_count
3
+
4
+ import torch
5
+ import torch.multiprocessing as mp
6
+ from tqdm import tqdm
7
+
8
+ import utils
9
+ from config import config
10
+ from clap_wrapper import get_clap_audio_feature
11
+ import librosa
12
+ import os
13
+
14
+ os.environ["OMP_NUM_THREADS"] = "1"
15
+ os.environ["MKL_NUM_THREADS"] = "1"
16
+
17
+
18
+ def process_line(line):
19
+ device = config.emo_gen_config.device
20
+ if config.emo_gen_config.use_multi_device:
21
+ rank = mp.current_process()._identity
22
+ rank = rank[0] if len(rank) > 0 else 0
23
+ if torch.cuda.is_available():
24
+ gpu_id = rank % torch.cuda.device_count()
25
+ device = torch.device(f"cuda:{gpu_id}")
26
+ else:
27
+ device = torch.device("cpu")
28
+ wav_path, _, language_str, text, phones, tone, word2ph = line.strip().split("|")
29
+
30
+ clap_path = wav_path.replace(".WAV", ".wav").replace(".wav", ".emo.pt")
31
+ if os.path.isfile(clap_path):
32
+ return
33
+
34
+ audio = librosa.load(wav_path, 48000)[0]
35
+ # audio = librosa.resample(audio, 44100, 48000)
36
+
37
+ clap = get_clap_audio_feature(audio, device)
38
+ torch.save(clap, clap_path)
39
+
40
+
41
+ if __name__ == "__main__":
42
+ parser = argparse.ArgumentParser()
43
+ parser.add_argument(
44
+ "-c", "--config", type=str, default=config.emo_gen_config.config_path
45
+ )
46
+ parser.add_argument(
47
+ "--num_processes", type=int, default=config.emo_gen_config.num_processes
48
+ )
49
+ args, _ = parser.parse_known_args()
50
+ config_path = args.config
51
+ hps = utils.get_hparams_from_file(config_path)
52
+ lines = []
53
+ with open(hps.data.training_files, encoding="utf-8") as f:
54
+ lines.extend(f.readlines())
55
+
56
+ with open(hps.data.validation_files, encoding="utf-8") as f:
57
+ lines.extend(f.readlines())
58
+ if len(lines) != 0:
59
+ num_processes = min(args.num_processes, cpu_count())
60
+ with Pool(processes=num_processes) as pool:
61
+ for _ in tqdm(pool.imap_unordered(process_line, lines), total=len(lines)):
62
+ pass
63
+
64
+ print(f"clap生成完毕!, 共有{len(lines)}个emo.pt生成!")
clap_wrapper.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import torch
4
+ from transformers import ClapModel, ClapProcessor
5
+
6
+ from config import config
7
+
8
+ models = dict()
9
+ processor = ClapProcessor.from_pretrained("./emotional/clap-htsat-fused")
10
+
11
+
12
+ def get_clap_audio_feature(audio_data, device=config.bert_gen_config.device):
13
+ if (
14
+ sys.platform == "darwin"
15
+ and torch.backends.mps.is_available()
16
+ and device == "cpu"
17
+ ):
18
+ device = "mps"
19
+ if not device:
20
+ device = "cuda"
21
+ if device not in models.keys():
22
+ models[device] = ClapModel.from_pretrained("./emotional/clap-htsat-fused").to(
23
+ device
24
+ )
25
+ with torch.no_grad():
26
+ inputs = processor(
27
+ audios=audio_data, return_tensors="pt", sampling_rate=48000
28
+ ).to(device)
29
+ emb = models[device].get_audio_features(**inputs)
30
+ return emb.T
31
+
32
+
33
+ def get_clap_text_feature(text, device=config.bert_gen_config.device):
34
+ if (
35
+ sys.platform == "darwin"
36
+ and torch.backends.mps.is_available()
37
+ and device == "cpu"
38
+ ):
39
+ device = "mps"
40
+ if not device:
41
+ device = "cuda"
42
+ if device not in models.keys():
43
+ models[device] = ClapModel.from_pretrained("./emotional/clap-htsat-fused").to(
44
+ device
45
+ )
46
+ with torch.no_grad():
47
+ inputs = processor(text=text, return_tensors="pt").to(device)
48
+ emb = models[device].get_text_features(**inputs)
49
+ return emb.T
commons.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch.nn import functional as F
4
+
5
+
6
+ def init_weights(m, mean=0.0, std=0.01):
7
+ classname = m.__class__.__name__
8
+ if classname.find("Conv") != -1:
9
+ m.weight.data.normal_(mean, std)
10
+
11
+
12
+ def get_padding(kernel_size, dilation=1):
13
+ return int((kernel_size * dilation - dilation) / 2)
14
+
15
+
16
+ def convert_pad_shape(pad_shape):
17
+ layer = pad_shape[::-1]
18
+ pad_shape = [item for sublist in layer for item in sublist]
19
+ return pad_shape
20
+
21
+
22
+ def intersperse(lst, item):
23
+ result = [item] * (len(lst) * 2 + 1)
24
+ result[1::2] = lst
25
+ return result
26
+
27
+
28
+ def kl_divergence(m_p, logs_p, m_q, logs_q):
29
+ """KL(P||Q)"""
30
+ kl = (logs_q - logs_p) - 0.5
31
+ kl += (
32
+ 0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
33
+ )
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
+ gather_indices = ids_str.view(x.size(0), 1, 1).repeat(
50
+ 1, x.size(1), 1
51
+ ) + torch.arange(segment_size, device=x.device)
52
+ return torch.gather(x, 2, gather_indices)
53
+
54
+
55
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
56
+ b, d, t = x.size()
57
+ if x_lengths is None:
58
+ x_lengths = t
59
+ ids_str_max = torch.clamp(x_lengths - segment_size + 1, min=0)
60
+ ids_str = (torch.rand([b], device=x.device) * ids_str_max).to(dtype=torch.long)
61
+ ret = slice_segments(x, ids_str, segment_size)
62
+ return ret, ids_str
63
+
64
+
65
+ def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
66
+ position = torch.arange(length, dtype=torch.float)
67
+ num_timescales = channels // 2
68
+ log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (
69
+ num_timescales - 1
70
+ )
71
+ inv_timescales = min_timescale * torch.exp(
72
+ torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
73
+ )
74
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
75
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
76
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
77
+ signal = signal.view(1, channels, length)
78
+ return signal
79
+
80
+
81
+ def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
82
+ b, channels, length = x.size()
83
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
84
+ return x + signal.to(dtype=x.dtype, device=x.device)
85
+
86
+
87
+ def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
88
+ b, channels, length = x.size()
89
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
90
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
91
+
92
+
93
+ def subsequent_mask(length):
94
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
95
+ return mask
96
+
97
+
98
+ @torch.jit.script
99
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
100
+ n_channels_int = n_channels[0]
101
+ in_act = input_a + input_b
102
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
103
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
104
+ acts = t_act * s_act
105
+ return acts
106
+
107
+
108
+ def convert_pad_shape(pad_shape):
109
+ layer = pad_shape[::-1]
110
+ pad_shape = [item for sublist in layer for item in sublist]
111
+ return pad_shape
112
+
113
+
114
+ def shift_1d(x):
115
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
116
+ return x
117
+
118
+
119
+ def sequence_mask(length, max_length=None):
120
+ if max_length is None:
121
+ max_length = length.max()
122
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
123
+ return x.unsqueeze(0) < length.unsqueeze(1)
124
+
125
+
126
+ def generate_path(duration, mask):
127
+ """
128
+ duration: [b, 1, t_x]
129
+ mask: [b, 1, t_y, t_x]
130
+ """
131
+
132
+ b, _, t_y, t_x = mask.shape
133
+ cum_duration = torch.cumsum(duration, -1)
134
+
135
+ cum_duration_flat = cum_duration.view(b * t_x)
136
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
137
+ path = path.view(b, t_x, t_y)
138
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
139
+ path = path.unsqueeze(1).transpose(2, 3) * mask
140
+ return path
141
+
142
+
143
+ def clip_grad_value_(parameters, clip_value, norm_type=2):
144
+ if isinstance(parameters, torch.Tensor):
145
+ parameters = [parameters]
146
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
147
+ norm_type = float(norm_type)
148
+ if clip_value is not None:
149
+ clip_value = float(clip_value)
150
+
151
+ total_norm = 0
152
+ for p in parameters:
153
+ param_norm = p.grad.data.norm(norm_type)
154
+ total_norm += param_norm.item() ** norm_type
155
+ if clip_value is not None:
156
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
157
+ total_norm = total_norm ** (1.0 / norm_type)
158
+ return total_norm
compress_model.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from text.symbols import symbols
3
+ import torch
4
+
5
+ from tools.log import logger
6
+ import utils
7
+ from models import SynthesizerTrn
8
+ import os
9
+
10
+
11
+ def copyStateDict(state_dict):
12
+ if list(state_dict.keys())[0].startswith("module"):
13
+ start_idx = 1
14
+ else:
15
+ start_idx = 0
16
+ new_state_dict = OrderedDict()
17
+ for k, v in state_dict.items():
18
+ name = ",".join(k.split(".")[start_idx:])
19
+ new_state_dict[name] = v
20
+ return new_state_dict
21
+
22
+
23
+ def removeOptimizer(config: str, input_model: str, ishalf: bool, output_model: str):
24
+ hps = utils.get_hparams_from_file(config)
25
+
26
+ net_g = SynthesizerTrn(
27
+ len(symbols),
28
+ hps.data.filter_length // 2 + 1,
29
+ hps.train.segment_size // hps.data.hop_length,
30
+ n_speakers=hps.data.n_speakers,
31
+ **hps.model,
32
+ )
33
+
34
+ optim_g = torch.optim.AdamW(
35
+ net_g.parameters(),
36
+ hps.train.learning_rate,
37
+ betas=hps.train.betas,
38
+ eps=hps.train.eps,
39
+ )
40
+
41
+ state_dict_g = torch.load(input_model, map_location="cpu")
42
+ new_dict_g = copyStateDict(state_dict_g)
43
+ keys = []
44
+ for k, v in new_dict_g["model"].items():
45
+ if "enc_q" in k:
46
+ continue # noqa: E701
47
+ keys.append(k)
48
+
49
+ new_dict_g = (
50
+ {k: new_dict_g["model"][k].half() for k in keys}
51
+ if ishalf
52
+ else {k: new_dict_g["model"][k] for k in keys}
53
+ )
54
+
55
+ torch.save(
56
+ {
57
+ "model": new_dict_g,
58
+ "iteration": 0,
59
+ "optimizer": optim_g.state_dict(),
60
+ "learning_rate": 0.0001,
61
+ },
62
+ output_model,
63
+ )
64
+
65
+
66
+ if __name__ == "__main__":
67
+ import argparse
68
+
69
+ parser = argparse.ArgumentParser()
70
+ parser.add_argument("-c", "--config", type=str, default="configs/config.json")
71
+ parser.add_argument("-i", "--input", type=str)
72
+ parser.add_argument("-o", "--output", type=str, default=None)
73
+ parser.add_argument(
74
+ "-hf", "--half", action="store_true", default=False, help="Save as FP16"
75
+ )
76
+
77
+ args = parser.parse_args()
78
+
79
+ output = args.output
80
+
81
+ if output is None:
82
+ import os.path
83
+
84
+ filename, ext = os.path.splitext(args.input)
85
+ half = "_half" if args.half else ""
86
+ output = filename + "_release" + half + ext
87
+
88
+ removeOptimizer(args.config, args.input, args.half, output)
89
+ logger.info(f"压缩模型成功, 输出模型: {os.path.abspath(output)}")
config.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ @Desc: 全局配置文件读取
3
+ """
4
+ import argparse
5
+ import yaml
6
+ from typing import Dict, List
7
+ import os
8
+ import shutil
9
+ import sys
10
+
11
+
12
+ class Resample_config:
13
+ """重采样配置"""
14
+
15
+ def __init__(self, in_dir: str, out_dir: str, sampling_rate: int = 44100):
16
+ self.sampling_rate: int = sampling_rate # 目标采样率
17
+ self.in_dir: str = in_dir # 待处理音频目录路径
18
+ self.out_dir: str = out_dir # 重采样输出路径
19
+
20
+ @classmethod
21
+ def from_dict(cls, dataset_path: str, data: Dict[str, any]):
22
+ """从字典中生成实例"""
23
+
24
+ # 不检查路径是否有效,此逻辑在resample.py中处理
25
+ data["in_dir"] = os.path.join(dataset_path, data["in_dir"])
26
+ data["out_dir"] = os.path.join(dataset_path, data["out_dir"])
27
+
28
+ return cls(**data)
29
+
30
+
31
+ class Preprocess_text_config:
32
+ """数据预处理配置"""
33
+
34
+ def __init__(
35
+ self,
36
+ transcription_path: str,
37
+ cleaned_path: str,
38
+ train_path: str,
39
+ val_path: str,
40
+ config_path: str,
41
+ val_per_lang: int = 5,
42
+ max_val_total: int = 10000,
43
+ clean: bool = True,
44
+ ):
45
+ self.transcription_path: str = transcription_path # 原始文本文件路径,文本格式应为{wav_path}|{speaker_name}|{language}|{text}。
46
+ self.cleaned_path: str = cleaned_path # 数据清洗后文本路径,可以不填。不填则将在原始文本目录生成
47
+ self.train_path: str = train_path # 训练集路径,可以不填。不填则将在原始文本目录生成
48
+ self.val_path: str = val_path # 验证集路径,可以不填。不填则将在原始文本目录生成
49
+ self.config_path: str = config_path # 配置文件路径
50
+ self.val_per_lang: int = val_per_lang # 每个speaker的验证集条数
51
+ self.max_val_total: int = max_val_total # 验证集最大条数,多于的会被截断并放到训练集中
52
+ self.clean: bool = clean # 是否进行数据清洗
53
+
54
+ @classmethod
55
+ def from_dict(cls, dataset_path: str, data: Dict[str, any]):
56
+ """从字典中生成实例"""
57
+
58
+ data["transcription_path"] = os.path.join(
59
+ dataset_path, data["transcription_path"]
60
+ )
61
+ if data["cleaned_path"] == "" or data["cleaned_path"] is None:
62
+ data["cleaned_path"] = None
63
+ else:
64
+ data["cleaned_path"] = os.path.join(dataset_path, data["cleaned_path"])
65
+ data["train_path"] = os.path.join(dataset_path, data["train_path"])
66
+ data["val_path"] = os.path.join(dataset_path, data["val_path"])
67
+ data["config_path"] = os.path.join(dataset_path, data["config_path"])
68
+
69
+ return cls(**data)
70
+
71
+
72
+ class Bert_gen_config:
73
+ """bert_gen 配置"""
74
+
75
+ def __init__(
76
+ self,
77
+ config_path: str,
78
+ num_processes: int = 2,
79
+ device: str = "cuda",
80
+ use_multi_device: bool = False,
81
+ ):
82
+ self.config_path = config_path
83
+ self.num_processes = num_processes
84
+ self.device = device
85
+ self.use_multi_device = use_multi_device
86
+
87
+ @classmethod
88
+ def from_dict(cls, dataset_path: str, data: Dict[str, any]):
89
+ data["config_path"] = os.path.join(dataset_path, data["config_path"])
90
+
91
+ return cls(**data)
92
+
93
+
94
+ class Emo_gen_config:
95
+ """emo_gen 配置"""
96
+
97
+ def __init__(
98
+ self,
99
+ config_path: str,
100
+ num_processes: int = 2,
101
+ device: str = "cuda",
102
+ use_multi_device: bool = False,
103
+ ):
104
+ self.config_path = config_path
105
+ self.num_processes = num_processes
106
+ self.device = device
107
+ self.use_multi_device = use_multi_device
108
+
109
+ @classmethod
110
+ def from_dict(cls, dataset_path: str, data: Dict[str, any]):
111
+ data["config_path"] = os.path.join(dataset_path, data["config_path"])
112
+
113
+ return cls(**data)
114
+
115
+
116
+ class Train_ms_config:
117
+ """训练配置"""
118
+
119
+ def __init__(
120
+ self,
121
+ config_path: str,
122
+ env: Dict[str, any],
123
+ base: Dict[str, any],
124
+ model: str,
125
+ num_workers: int,
126
+ spec_cache: bool,
127
+ keep_ckpts: int,
128
+ ):
129
+ self.env = env # 需要加载的环境变量
130
+ self.base = base # 底模配置
131
+ self.model = model # 训练模型存储目录,该路径为相对于dataset_path的路径,而非项目根目录
132
+ self.config_path = config_path # 配置文件路径
133
+ self.num_workers = num_workers # worker数量
134
+ self.spec_cache = spec_cache # 是否启用spec缓存
135
+ self.keep_ckpts = keep_ckpts # ckpt数量
136
+
137
+ @classmethod
138
+ def from_dict(cls, dataset_path: str, data: Dict[str, any]):
139
+ # data["model"] = os.path.join(dataset_path, data["model"])
140
+ data["config_path"] = os.path.join(dataset_path, data["config_path"])
141
+
142
+ return cls(**data)
143
+
144
+
145
+ class Webui_config:
146
+ """webui 配置"""
147
+
148
+ def __init__(
149
+ self,
150
+ device: str,
151
+ model: str,
152
+ config_path: str,
153
+ language_identification_library: str,
154
+ port: int = 7860,
155
+ share: bool = False,
156
+ debug: bool = False,
157
+ ):
158
+ self.device: str = device
159
+ self.model: str = model # 端口号
160
+ self.config_path: str = config_path # 是否公开部署,对外网开放
161
+ self.port: int = port # 是否开启debug模式
162
+ self.share: bool = share # 模型路径
163
+ self.debug: bool = debug # 配置文件路径
164
+ self.language_identification_library: str = (
165
+ language_identification_library # 语种识别库
166
+ )
167
+
168
+ @classmethod
169
+ def from_dict(cls, dataset_path: str, data: Dict[str, any]):
170
+ data["config_path"] = os.path.join(dataset_path, data["config_path"])
171
+ data["model"] = os.path.join(dataset_path, data["model"])
172
+ return cls(**data)
173
+
174
+
175
+ class Server_config:
176
+ def __init__(
177
+ self, models: List[Dict[str, any]], port: int = 5000, device: str = "cuda"
178
+ ):
179
+ self.models: List[Dict[str, any]] = models # 需要加载的所有模型的配置
180
+ self.port: int = port # 端口号
181
+ self.device: str = device # 模型默认使用设备
182
+
183
+ @classmethod
184
+ def from_dict(cls, data: Dict[str, any]):
185
+ return cls(**data)
186
+
187
+
188
+ class Translate_config:
189
+ """翻译api配置"""
190
+
191
+ def __init__(self, app_key: str, secret_key: str):
192
+ self.app_key = app_key
193
+ self.secret_key = secret_key
194
+
195
+ @classmethod
196
+ def from_dict(cls, data: Dict[str, any]):
197
+ return cls(**data)
198
+
199
+
200
+ class Config:
201
+ def __init__(self, config_path: str):
202
+ if not os.path.isfile(config_path) and os.path.isfile("default_config.yml"):
203
+ shutil.copy(src="default_config.yml", dst=config_path)
204
+ print(
205
+ f"已根据默认配置文件default_config.yml生成配置文件{config_path}。请按该配置文件的说明进行配置后重新运行。"
206
+ )
207
+ print("如无特殊需求,请勿修改default_config.yml或备份该文件。")
208
+ sys.exit(0)
209
+ with open(file=config_path, mode="r", encoding="utf-8") as file:
210
+ yaml_config: Dict[str, any] = yaml.safe_load(file.read())
211
+ dataset_path: str = yaml_config["dataset_path"]
212
+ openi_token: str = yaml_config["openi_token"]
213
+ self.dataset_path: str = dataset_path
214
+ self.mirror: str = yaml_config["mirror"]
215
+ self.openi_token: str = openi_token
216
+ self.resample_config: Resample_config = Resample_config.from_dict(
217
+ dataset_path, yaml_config["resample"]
218
+ )
219
+ self.preprocess_text_config: Preprocess_text_config = (
220
+ Preprocess_text_config.from_dict(
221
+ dataset_path, yaml_config["preprocess_text"]
222
+ )
223
+ )
224
+ self.bert_gen_config: Bert_gen_config = Bert_gen_config.from_dict(
225
+ dataset_path, yaml_config["bert_gen"]
226
+ )
227
+ self.emo_gen_config: Emo_gen_config = Emo_gen_config.from_dict(
228
+ dataset_path, yaml_config["emo_gen"]
229
+ )
230
+ self.train_ms_config: Train_ms_config = Train_ms_config.from_dict(
231
+ dataset_path, yaml_config["train_ms"]
232
+ )
233
+ self.webui_config: Webui_config = Webui_config.from_dict(
234
+ dataset_path, yaml_config["webui"]
235
+ )
236
+ self.server_config: Server_config = Server_config.from_dict(
237
+ yaml_config["server"]
238
+ )
239
+ self.translate_config: Translate_config = Translate_config.from_dict(
240
+ yaml_config["translate"]
241
+ )
242
+
243
+
244
+ parser = argparse.ArgumentParser()
245
+ # 为避免与以前的config.json起冲突,将其更名如下
246
+ parser.add_argument("-y", "--yml_config", type=str, default="config.yml")
247
+ args, _ = parser.parse_known_args()
248
+ config = Config(args.yml_config)
config.yml ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 全局配置
2
+ # 对于希望在同一时间使用多个配置文件的情况,例如两个GPU同时跑两个训练集:通过环境变量指定配置文件,不指定则默认为./config.yml
3
+
4
+ # 拟提供通用路径配置,统一存放数据,避免数据放得很乱
5
+ # 每个数据集与其对应的模型存放至统一路径下,后续所有的路径配置均为相对于datasetPath的路径
6
+ # 不填或者填空则路径为相对于项目根目录的路径
7
+ dataset_path: "Data/XJP"
8
+
9
+ # 模型镜像源,默认huggingface,使用openi镜像源需指定openi_token
10
+ mirror: ""
11
+ openi_token: "" # openi token
12
+
13
+ # resample 音频重采样配置
14
+ # 注意, “:” 后需要加空格
15
+ resample:
16
+ # 目标重采样率
17
+ sampling_rate: 44100
18
+ # 音频文件输入路径,重采样会将该路径下所有.wav音频文件重采样
19
+ # 请填入相对于datasetPath的相对路径
20
+ in_dir: "audios/raw" # 相对于根目录的路径为 /datasetPath/in_dir
21
+ # 音频文件重采样后输出路径
22
+ out_dir: "audios/wavs"
23
+
24
+
25
+ # preprocess_text 数据集预处理相关配置
26
+ # 注意, “:” 后需要加空格
27
+ preprocess_text:
28
+ # 原始文本文件路径,文本格式应为{wav_path}|{speaker_name}|{language}|{text}。
29
+ transcription_path: "filelists/Azusa.list"
30
+ # 数据清洗后文本路径,可以不填。不填则将在原始文本目录生成
31
+ cleaned_path: ""
32
+ # 训练集路径
33
+ train_path: "filelists/train.list"
34
+ # 验证集路径
35
+ val_path: "filelists/val.list"
36
+ # 配置文件路径
37
+ config_path: "config.json"
38
+ # 每个语言的验证集条数
39
+ val_per_lang: 4
40
+ # 验证集最大条数,多于的会被截断并放到训练集中
41
+ max_val_total: 12
42
+ # 是否进行数据清洗
43
+ clean: true
44
+
45
+
46
+ # bert_gen 相关配置
47
+ # 注意, “:” 后需要加空格
48
+ bert_gen:
49
+ # 训练数据集配置文件路径
50
+ config_path: "config.json"
51
+ # 并行数
52
+ num_processes: 4
53
+ # 使用设备:可选项 "cuda" 显卡推理,"cpu" cpu推理
54
+ # 该选项同时决定了get_bert_feature的默认设备
55
+ device: "cuda"
56
+ # 使用多卡推理
57
+ use_multi_device: false
58
+
59
+ # emo_gen 相关配置
60
+ # 注意, “:” 后需要加空格
61
+ emo_gen:
62
+ # 训练数据集配置文件路径
63
+ config_path: "config.json"
64
+ # 并行数
65
+ num_processes: 4
66
+ # 使用设备:可选项 "cuda" 显卡推理,"cpu" cpu推理
67
+ device: "cuda"
68
+ # 使用多卡推理
69
+ use_multi_device: false
70
+
71
+ # train 训练配置
72
+ # 注意, “:” 后需要加空格
73
+ train_ms:
74
+ env:
75
+ MASTER_ADDR: "localhost"
76
+ MASTER_PORT: 10086
77
+ WORLD_SIZE: 1
78
+ LOCAL_RANK: 0
79
+ RANK: 0
80
+ # 可以填写任意名的环境变量
81
+ # THE_ENV_VAR_YOU_NEED_TO_USE: "1234567"
82
+ # 底模设置
83
+ base:
84
+ use_base_model: True
85
+ repo_id: "Stardust_minus/Bert-VITS2"
86
+ model_image: "Bert-VITS2_2.3_huge" # openi网页的模型名
87
+ # 训练模型存储目录:与旧版本的区别,原先数据集是存放在logs/model_name下的,现在改为统一存放在Data/你的数据集/models下
88
+ model: "models"
89
+ # 配置文件路径
90
+ config_path: "config.json"
91
+ # 训练使用的worker,不建议超过CPU核心数
92
+ num_workers: 16
93
+ # 关闭此项可以节约接近50%的磁盘空间,但是可能导致实际训练速度变慢和更高的CPU使用率。
94
+ spec_cache: True
95
+ # 保存的检查点数量,多于此数目的权重会被删除来节省空间。
96
+ keep_ckpts: 100
97
+
98
+
99
+ # webui webui配置
100
+ # 注意, “:” 后需要加空格
101
+ webui:
102
+ # 推理设备
103
+ device: "cpu"
104
+ # 模型路径
105
+ model: "models/G_3000.pth"
106
+ # 配置文件路径
107
+ config_path: "config.json"
108
+ # 端口号
109
+ port: 7860
110
+ # 是否公开部署,对外网开放
111
+ share: false
112
+ # 是否开启debug模式
113
+ debug: false
114
+ # 语种识别库,可选langid, fastlid
115
+ language_identification_library: "langid"
116
+
117
+
118
+ # server-fastapi配置
119
+ # 注意, “:” 后需要加空格
120
+ # 注意,本配置下的所有配置均为相对于根目录的路径
121
+ server:
122
+ # 端口号
123
+ port: 5000
124
+ # 模型默认使用设备:但是当前并没有实现这个配置。
125
+ device: "cuda"
126
+ # 需要加载的所有模型的配置,可以填多个模型,也可以不填模型,等网页成功后手动加载模型
127
+ # 不加载模型的配置格式:删除默认给的两个模型配置,给models赋值 [ ],也就是空列表。参考模型2的speakers 即 models: [ ]
128
+ # 注意,所有模型都必须正确配置model与config的路径,空路径会导致加载错误。
129
+ # 也可以不填模型,等网页加载成功后手动填写models。
130
+ models:
131
+ - # 模型的路径
132
+ model: ""
133
+ # 模型config.json的路径
134
+ config: ""
135
+ # 模型使用设备,若填写则会覆盖默认配置
136
+ device: "cuda"
137
+ # 模型默认使用的语言
138
+ language: "ZH"
139
+ # 模型人物默认参数
140
+ # 不必填写所有人物,不填的使用默认值
141
+ # 暂时不用填写,当前尚未实现按人区分配置
142
+ speakers:
143
+ - speaker: "科比"
144
+ sdp_ratio: 0.2
145
+ noise_scale: 0.6
146
+ noise_scale_w: 0.8
147
+ length_scale: 1
148
+ - speaker: "五条悟"
149
+ sdp_ratio: 0.3
150
+ noise_scale: 0.7
151
+ noise_scale_w: 0.8
152
+ length_scale: 0.5
153
+ - speaker: "安倍晋三"
154
+ sdp_ratio: 0.2
155
+ noise_scale: 0.6
156
+ noise_scale_w: 0.8
157
+ length_scale: 1.2
158
+ - # 模型的路径
159
+ model: ""
160
+ # 模型config.json的路径
161
+ config: ""
162
+ # 模型使用设备,若填写则会覆盖默认配置
163
+ device: "cpu"
164
+ # 模型默认使用的语言
165
+ language: "JP"
166
+ # 模型人物默认参数
167
+ # 不必填写所有人物,不填的使用默认值
168
+ speakers: [ ] # 也可以不填
169
+
170
+ # 百度翻译开放平台 api配置
171
+ # api接入文档 https://api.fanyi.baidu.com/doc/21
172
+ # 请不要在github等网站公开分享你的app id 与 key
173
+ translate:
174
+ # 你的APPID
175
+ "app_key": ""
176
+ # 你的密钥
177
+ "secret_key": ""
data_utils.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import torch
4
+ import torch.utils.data
5
+ from tqdm import tqdm
6
+ import numpy as np
7
+ from tools.log import logger
8
+ import commons
9
+ from mel_processing import spectrogram_torch, mel_spectrogram_torch
10
+ from utils import load_wav_to_torch, load_filepaths_and_text
11
+ from text import cleaned_text_to_sequence
12
+ from config import config
13
+
14
+ """Multi speaker version"""
15
+
16
+
17
+ class TextAudioSpeakerLoader(torch.utils.data.Dataset):
18
+ """
19
+ 1) loads audio, speaker_id, text pairs
20
+ 2) normalizes text and converts them to sequences of integers
21
+ 3) computes spectrograms from audio files.
22
+ """
23
+
24
+ def __init__(self, audiopaths_sid_text, hparams):
25
+ self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
26
+ self.max_wav_value = hparams.max_wav_value
27
+ self.sampling_rate = hparams.sampling_rate
28
+ self.filter_length = hparams.filter_length
29
+ self.hop_length = hparams.hop_length
30
+ self.win_length = hparams.win_length
31
+ self.sampling_rate = hparams.sampling_rate
32
+ self.spk_map = hparams.spk2id
33
+ self.hparams = hparams
34
+
35
+ self.use_mel_spec_posterior = getattr(
36
+ hparams, "use_mel_posterior_encoder", False
37
+ )
38
+ if self.use_mel_spec_posterior:
39
+ self.n_mel_channels = getattr(hparams, "n_mel_channels", 80)
40
+
41
+ self.cleaned_text = getattr(hparams, "cleaned_text", False)
42
+
43
+ self.add_blank = hparams.add_blank
44
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
45
+ self.max_text_len = getattr(hparams, "max_text_len", 384)
46
+
47
+ random.seed(1234)
48
+ random.shuffle(self.audiopaths_sid_text)
49
+ self._filter()
50
+
51
+ def _filter(self):
52
+ """
53
+ Filter text & store spec lengths
54
+ """
55
+ # Store spectrogram lengths for Bucketing
56
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
57
+ # spec_length = wav_length // hop_length
58
+
59
+ audiopaths_sid_text_new = []
60
+ lengths = []
61
+ skipped = 0
62
+ logger.info("Init dataset...")
63
+ for _id, spk, language, text, phones, tone, word2ph in tqdm(
64
+ self.audiopaths_sid_text
65
+ ):
66
+ audiopath = f"{_id}"
67
+ if self.min_text_len <= len(phones) and len(phones) <= self.max_text_len:
68
+ phones = phones.split(" ")
69
+ tone = [int(i) for i in tone.split(" ")]
70
+ word2ph = [int(i) for i in word2ph.split(" ")]
71
+ audiopaths_sid_text_new.append(
72
+ [audiopath, spk, language, text, phones, tone, word2ph]
73
+ )
74
+ lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
75
+ else:
76
+ skipped += 1
77
+ logger.info(
78
+ "skipped: "
79
+ + str(skipped)
80
+ + ", total: "
81
+ + str(len(self.audiopaths_sid_text))
82
+ )
83
+ self.audiopaths_sid_text = audiopaths_sid_text_new
84
+ self.lengths = lengths
85
+
86
+ def get_audio_text_speaker_pair(self, audiopath_sid_text):
87
+ # separate filename, speaker_id and text
88
+ audiopath, sid, language, text, phones, tone, word2ph = audiopath_sid_text
89
+
90
+ bert, ja_bert, en_bert, phones, tone, language = self.get_text(
91
+ text, word2ph, phones, tone, language, audiopath
92
+ )
93
+
94
+ spec, wav = self.get_audio(audiopath)
95
+ sid = torch.LongTensor([int(self.spk_map[sid])])
96
+
97
+ return (phones, spec, wav, sid, tone, language, bert, ja_bert, en_bert)
98
+
99
+ def get_audio(self, filename):
100
+ audio, sampling_rate = load_wav_to_torch(filename)
101
+ if sampling_rate != self.sampling_rate:
102
+ raise ValueError(
103
+ "{} {} SR doesn't match target {} SR".format(
104
+ filename, sampling_rate, self.sampling_rate
105
+ )
106
+ )
107
+ audio_norm = audio / self.max_wav_value
108
+ audio_norm = audio_norm.unsqueeze(0)
109
+ spec_filename = filename.replace(".wav", ".spec.pt")
110
+ if self.use_mel_spec_posterior:
111
+ spec_filename = spec_filename.replace(".spec.pt", ".mel.pt")
112
+ try:
113
+ spec = torch.load(spec_filename)
114
+ except:
115
+ if self.use_mel_spec_posterior:
116
+ spec = mel_spectrogram_torch(
117
+ audio_norm,
118
+ self.filter_length,
119
+ self.n_mel_channels,
120
+ self.sampling_rate,
121
+ self.hop_length,
122
+ self.win_length,
123
+ self.hparams.mel_fmin,
124
+ self.hparams.mel_fmax,
125
+ center=False,
126
+ )
127
+ else:
128
+ spec = spectrogram_torch(
129
+ audio_norm,
130
+ self.filter_length,
131
+ self.sampling_rate,
132
+ self.hop_length,
133
+ self.win_length,
134
+ center=False,
135
+ )
136
+ spec = torch.squeeze(spec, 0)
137
+ if config.train_ms_config.spec_cache:
138
+ torch.save(spec, spec_filename)
139
+ return spec, audio_norm
140
+
141
+ def get_text(self, text, word2ph, phone, tone, language_str, wav_path):
142
+ phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
143
+ if self.add_blank:
144
+ phone = commons.intersperse(phone, 0)
145
+ tone = commons.intersperse(tone, 0)
146
+ language = commons.intersperse(language, 0)
147
+ for i in range(len(word2ph)):
148
+ word2ph[i] = word2ph[i] * 2
149
+ word2ph[0] += 1
150
+ bert_path = wav_path.replace(".wav", ".bert.pt")
151
+ try:
152
+ bert_ori = torch.load(bert_path)
153
+ assert bert_ori.shape[-1] == len(phone)
154
+ except Exception as e:
155
+ logger.warning("Bert load Failed")
156
+ logger.warning(e)
157
+
158
+ if language_str == "ZH":
159
+ bert = bert_ori
160
+ ja_bert = torch.randn(1024, len(phone))
161
+ en_bert = torch.randn(1024, len(phone))
162
+ elif language_str == "JP":
163
+ bert = torch.randn(1024, len(phone))
164
+ ja_bert = bert_ori
165
+ en_bert = torch.randn(1024, len(phone))
166
+ elif language_str == "EN":
167
+ bert = torch.randn(1024, len(phone))
168
+ ja_bert = torch.randn(1024, len(phone))
169
+ en_bert = bert_ori
170
+ phone = torch.LongTensor(phone)
171
+ tone = torch.LongTensor(tone)
172
+ language = torch.LongTensor(language)
173
+ return bert, ja_bert, en_bert, phone, tone, language
174
+
175
+ def get_sid(self, sid):
176
+ sid = torch.LongTensor([int(sid)])
177
+ return sid
178
+
179
+ def __getitem__(self, index):
180
+ return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
181
+
182
+ def __len__(self):
183
+ return len(self.audiopaths_sid_text)
184
+
185
+
186
+ class TextAudioSpeakerCollate:
187
+ """Zero-pads model inputs and targets"""
188
+
189
+ def __init__(self, return_ids=False):
190
+ self.return_ids = return_ids
191
+
192
+ def __call__(self, batch):
193
+ """Collate's training batch from normalized text, audio and speaker identities
194
+ PARAMS
195
+ ------
196
+ batch: [text_normalized, spec_normalized, wav_normalized, sid]
197
+ """
198
+ # Right zero-pad all one-hot text sequences to max input length
199
+ _, ids_sorted_decreasing = torch.sort(
200
+ torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True
201
+ )
202
+
203
+ max_text_len = max([len(x[0]) for x in batch])
204
+ max_spec_len = max([x[1].size(1) for x in batch])
205
+ max_wav_len = max([x[2].size(1) for x in batch])
206
+
207
+ text_lengths = torch.LongTensor(len(batch))
208
+ spec_lengths = torch.LongTensor(len(batch))
209
+ wav_lengths = torch.LongTensor(len(batch))
210
+ sid = torch.LongTensor(len(batch))
211
+
212
+ text_padded = torch.LongTensor(len(batch), max_text_len)
213
+ tone_padded = torch.LongTensor(len(batch), max_text_len)
214
+ language_padded = torch.LongTensor(len(batch), max_text_len)
215
+ bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
216
+ ja_bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
217
+ en_bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
218
+
219
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
220
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
221
+ text_padded.zero_()
222
+ tone_padded.zero_()
223
+ language_padded.zero_()
224
+ spec_padded.zero_()
225
+ wav_padded.zero_()
226
+ bert_padded.zero_()
227
+ ja_bert_padded.zero_()
228
+ en_bert_padded.zero_()
229
+
230
+ for i in range(len(ids_sorted_decreasing)):
231
+ row = batch[ids_sorted_decreasing[i]]
232
+
233
+ text = row[0]
234
+ text_padded[i, : text.size(0)] = text
235
+ text_lengths[i] = text.size(0)
236
+
237
+ spec = row[1]
238
+ spec_padded[i, :, : spec.size(1)] = spec
239
+ spec_lengths[i] = spec.size(1)
240
+
241
+ wav = row[2]
242
+ wav_padded[i, :, : wav.size(1)] = wav
243
+ wav_lengths[i] = wav.size(1)
244
+
245
+ sid[i] = row[3]
246
+
247
+ tone = row[4]
248
+ tone_padded[i, : tone.size(0)] = tone
249
+
250
+ language = row[5]
251
+ language_padded[i, : language.size(0)] = language
252
+
253
+ bert = row[6]
254
+ bert_padded[i, :, : bert.size(1)] = bert
255
+
256
+ ja_bert = row[7]
257
+ ja_bert_padded[i, :, : ja_bert.size(1)] = ja_bert
258
+
259
+ en_bert = row[8]
260
+ en_bert_padded[i, :, : en_bert.size(1)] = en_bert
261
+
262
+ return (
263
+ text_padded,
264
+ text_lengths,
265
+ spec_padded,
266
+ spec_lengths,
267
+ wav_padded,
268
+ wav_lengths,
269
+ sid,
270
+ tone_padded,
271
+ language_padded,
272
+ bert_padded,
273
+ ja_bert_padded,
274
+ en_bert_padded,
275
+ )
276
+
277
+
278
+ class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
279
+ """
280
+ Maintain similar input lengths in a batch.
281
+ Length groups are specified by boundaries.
282
+ Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
283
+
284
+ It removes samples which are not included in the boundaries.
285
+ Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
286
+ """
287
+
288
+ def __init__(
289
+ self,
290
+ dataset,
291
+ batch_size,
292
+ boundaries,
293
+ num_replicas=None,
294
+ rank=None,
295
+ shuffle=True,
296
+ ):
297
+ super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
298
+ self.lengths = dataset.lengths
299
+ self.batch_size = batch_size
300
+ self.boundaries = boundaries
301
+
302
+ self.buckets, self.num_samples_per_bucket = self._create_buckets()
303
+ self.total_size = sum(self.num_samples_per_bucket)
304
+ self.num_samples = self.total_size // self.num_replicas
305
+
306
+ def _create_buckets(self):
307
+ buckets = [[] for _ in range(len(self.boundaries) - 1)]
308
+ for i in range(len(self.lengths)):
309
+ length = self.lengths[i]
310
+ idx_bucket = self._bisect(length)
311
+ if idx_bucket != -1:
312
+ buckets[idx_bucket].append(i)
313
+
314
+ try:
315
+ for i in range(len(buckets) - 1, 0, -1):
316
+ if len(buckets[i]) == 0:
317
+ buckets.pop(i)
318
+ self.boundaries.pop(i + 1)
319
+ assert all(len(bucket) > 0 for bucket in buckets)
320
+ # When one bucket is not traversed
321
+ except Exception as e:
322
+ print("Bucket warning ", e)
323
+ for i in range(len(buckets) - 1, -1, -1):
324
+ if len(buckets[i]) == 0:
325
+ buckets.pop(i)
326
+ self.boundaries.pop(i + 1)
327
+
328
+ num_samples_per_bucket = []
329
+ for i in range(len(buckets)):
330
+ len_bucket = len(buckets[i])
331
+ total_batch_size = self.num_replicas * self.batch_size
332
+ rem = (
333
+ total_batch_size - (len_bucket % total_batch_size)
334
+ ) % total_batch_size
335
+ num_samples_per_bucket.append(len_bucket + rem)
336
+ return buckets, num_samples_per_bucket
337
+
338
+ def __iter__(self):
339
+ # deterministically shuffle based on epoch
340
+ g = torch.Generator()
341
+ g.manual_seed(self.epoch)
342
+
343
+ indices = []
344
+ if self.shuffle:
345
+ for bucket in self.buckets:
346
+ indices.append(torch.randperm(len(bucket), generator=g).tolist())
347
+ else:
348
+ for bucket in self.buckets:
349
+ indices.append(list(range(len(bucket))))
350
+
351
+ batches = []
352
+ for i in range(len(self.buckets)):
353
+ bucket = self.buckets[i]
354
+ len_bucket = len(bucket)
355
+ if len_bucket == 0:
356
+ continue
357
+ ids_bucket = indices[i]
358
+ num_samples_bucket = self.num_samples_per_bucket[i]
359
+
360
+ # add extra samples to make it evenly divisible
361
+ rem = num_samples_bucket - len_bucket
362
+ ids_bucket = (
363
+ ids_bucket
364
+ + ids_bucket * (rem // len_bucket)
365
+ + ids_bucket[: (rem % len_bucket)]
366
+ )
367
+
368
+ # subsample
369
+ ids_bucket = ids_bucket[self.rank :: self.num_replicas]
370
+
371
+ # batching
372
+ for j in range(len(ids_bucket) // self.batch_size):
373
+ batch = [
374
+ bucket[idx]
375
+ for idx in ids_bucket[
376
+ j * self.batch_size : (j + 1) * self.batch_size
377
+ ]
378
+ ]
379
+ batches.append(batch)
380
+
381
+ if self.shuffle:
382
+ batch_ids = torch.randperm(len(batches), generator=g).tolist()
383
+ batches = [batches[i] for i in batch_ids]
384
+ self.batches = batches
385
+
386
+ assert len(self.batches) * self.batch_size == self.num_samples
387
+ return iter(self.batches)
388
+
389
+ def _bisect(self, x, lo=0, hi=None):
390
+ if hi is None:
391
+ hi = len(self.boundaries) - 1
392
+
393
+ if hi > lo:
394
+ mid = (hi + lo) // 2
395
+ if self.boundaries[mid] < x and x <= self.boundaries[mid + 1]:
396
+ return mid
397
+ elif x <= self.boundaries[mid]:
398
+ return self._bisect(x, lo, mid)
399
+ else:
400
+ return self._bisect(x, mid + 1, hi)
401
+ else:
402
+ return -1
403
+
404
+ def __len__(self):
405
+ return self.num_samples // self.batch_size
default_config.yml ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 全局配置
2
+ # 对于希望在同一时间使用多个配置文件的情况,例如两个GPU同时跑两个训练集:通过环境变量指定配置文件,不指定则默认为./config.yml
3
+
4
+ # 拟提供通用路径配置,统一存放数据,避免数据放得很乱
5
+ # 每个数据集与其对应的模型存放至统一路径下,后续所有的路径配置均为相对于datasetPath的路径
6
+ # 不填或者填空则路径为相对于项目根目录的路径
7
+ dataset_path: "Data/"
8
+
9
+ # 模型镜像源,默认huggingface,使用openi镜像源需指定openi_token
10
+ mirror: ""
11
+ openi_token: "" # openi token
12
+
13
+ # resample 音频重采样配置
14
+ # 注意, “:” 后需要加空格
15
+ resample:
16
+ # 目标重采样率
17
+ sampling_rate: 44100
18
+ # 音频文件输入路径,重采样会将该路径下所有.wav音频文件重采样
19
+ # 请填入相对于datasetPath的相对路径
20
+ in_dir: "audios/raw" # 相对于根目录的路径为 /datasetPath/in_dir
21
+ # 音频文件重采样后输出路径
22
+ out_dir: "audios/wavs"
23
+
24
+
25
+ # preprocess_text 数据集预处理相关配置
26
+ # 注意, “:” 后需要加空格
27
+ preprocess_text:
28
+ # 原始文本文件路径,文本格式应为{wav_path}|{speaker_name}|{language}|{text}。
29
+ transcription_path: "filelists/你的数据集文本.list"
30
+ # 数据清洗后文本路径,可以不填。不填则将在原始文本目录生成
31
+ cleaned_path: ""
32
+ # 训练集路径
33
+ train_path: "filelists/train.list"
34
+ # 验证集路径
35
+ val_path: "filelists/val.list"
36
+ # 配置文件路径
37
+ config_path: "config.json"
38
+ # 每个语言的验证集条数
39
+ val_per_lang: 4
40
+ # 验证集最大条数,多于的会被截断并放到训练集中
41
+ max_val_total: 12
42
+ # 是否进行数据清洗
43
+ clean: true
44
+
45
+
46
+ # bert_gen 相关配置
47
+ # 注意, “:” 后需要加空格
48
+ bert_gen:
49
+ # 训练数据集配置文件路径
50
+ config_path: "config.json"
51
+ # 并行数
52
+ num_processes: 4
53
+ # 使用设备:可选项 "cuda" 显卡推理,"cpu" cpu推理
54
+ # 该选项同时决定了get_bert_feature的默认设备
55
+ device: "cuda"
56
+ # 使用多卡推理
57
+ use_multi_device: false
58
+
59
+ # emo_gen 相关配置
60
+ # 注意, “:” 后需要加空格
61
+ emo_gen:
62
+ # 训练数据集配置文件路径
63
+ config_path: "config.json"
64
+ # 并行数
65
+ num_processes: 4
66
+ # 使用设备:可选项 "cuda" 显卡推理,"cpu" cpu推理
67
+ device: "cuda"
68
+ # 使用多卡推理
69
+ use_multi_device: false
70
+
71
+ # train 训练配置
72
+ # 注意, “:” 后需要加空格
73
+ train_ms:
74
+ env:
75
+ MASTER_ADDR: "localhost"
76
+ MASTER_PORT: 10086
77
+ WORLD_SIZE: 1
78
+ LOCAL_RANK: 0
79
+ RANK: 0
80
+ # 可以填写任意名的环境变量
81
+ # THE_ENV_VAR_YOU_NEED_TO_USE: "1234567"
82
+ # 底模设置
83
+ base:
84
+ use_base_model: false
85
+ repo_id: "Stardust_minus/Bert-VITS2"
86
+ model_image: "Bert-VITS2_2.3底模" # openi网页的模型名
87
+ # 训练模型存储目录:与旧版本的区别,原先数据集是存放在logs/model_name下的,现在改为统一存放在Data/你的数据集/models下
88
+ model: "models"
89
+ # 配置文件路径
90
+ config_path: "config.json"
91
+ # 训练使用的worker,不建议超过CPU核心数
92
+ num_workers: 16
93
+ # 关闭此项可以节约接近50%的磁盘空间,但是可能导致实际训练速度变慢和更高的CPU使用率。
94
+ spec_cache: True
95
+ # 保存的检查点数量,多于此数目的权重会被删除来节省空间。
96
+ keep_ckpts: 8
97
+
98
+
99
+ # webui webui配置
100
+ # 注意, “:” 后需要加空格
101
+ webui:
102
+ # 推理设备
103
+ device: "cuda"
104
+ # 模型路径
105
+ model: "models/G_8000.pth"
106
+ # 配置文件路径
107
+ config_path: "config.json"
108
+ # 端口号
109
+ port: 7860
110
+ # 是否公开部署,对外网开放
111
+ share: false
112
+ # 是否开启debug模式
113
+ debug: false
114
+ # 语种识别库,可选langid, fastlid
115
+ language_identification_library: "langid"
116
+
117
+
118
+ # server-fastapi配置
119
+ # 注意, “:” 后需要加空格
120
+ # 注意,本配置下的所有配置均为相对于根目录的路径
121
+ server:
122
+ # 端口号
123
+ port: 5000
124
+ # 模型默认使用设备:但是当前并没有实现这个配置。
125
+ device: "cuda"
126
+ # 需要加载的所有模型的配置,可以填多个模型,也可以不填模型,等网页成功后手动加载模型
127
+ # 不加载模型的配置格式:删除默认给的两个模型配置,给models赋值 [ ],也就是空列表。参考模型2的speakers 即 models: [ ]
128
+ # 注意,所有模型都必须正确配置model与config的路径,空路径会导致加载错误。
129
+ # 也可以不填模型,等网页加载成功后手动填写models。
130
+ models:
131
+ - # 模型的路径
132
+ model: ""
133
+ # 模型config.json的路径
134
+ config: ""
135
+ # 模型使用设备,若填写则会覆盖默认配置
136
+ device: "cuda"
137
+ # 模型默认使用的语言
138
+ language: "ZH"
139
+ # 模型人物默认参数
140
+ # 不必填写所有人物,不填的使用默认值
141
+ # 暂时不用填写,当前尚未实现按人区分配置
142
+ speakers:
143
+ - speaker: "科比"
144
+ sdp_ratio: 0.2
145
+ noise_scale: 0.6
146
+ noise_scale_w: 0.8
147
+ length_scale: 1
148
+ - speaker: "五条悟"
149
+ sdp_ratio: 0.3
150
+ noise_scale: 0.7
151
+ noise_scale_w: 0.8
152
+ length_scale: 0.5
153
+ - speaker: "安倍晋三"
154
+ sdp_ratio: 0.2
155
+ noise_scale: 0.6
156
+ noise_scale_w: 0.8
157
+ length_scale: 1.2
158
+ - # 模型的路径
159
+ model: ""
160
+ # 模型config.json的路径
161
+ config: ""
162
+ # 模型使用设备,若填写则会覆盖默认配置
163
+ device: "cpu"
164
+ # 模型默认使用的语言
165
+ language: "JP"
166
+ # 模型人物默认参数
167
+ # 不必填写所有人物,不填的使用默认值
168
+ speakers: [ ] # 也可以不填
169
+
170
+ # 百度翻译开放平台 api配置
171
+ # api接入文档 https://api.fanyi.baidu.com/doc/21
172
+ # 请不要在github等网站公开分享你的app id 与 key
173
+ translate:
174
+ # 你的APPID
175
+ "app_key": ""
176
+ # 你的密钥
177
+ "secret_key": ""
empty_emo.npy ADDED
Binary file (3.24 kB). View file
 
export_onnx.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from onnx_modules import export_onnx
2
+ import os
3
+
4
+ if __name__ == "__main__":
5
+ export_path = "BertVits2.2PT"
6
+ model_path = "model\\G_0.pth"
7
+ config_path = "model\\config.json"
8
+ novq = False
9
+ dev = False
10
+ if not os.path.exists("onnx"):
11
+ os.makedirs("onnx")
12
+ if not os.path.exists(f"onnx/{export_path}"):
13
+ os.makedirs(f"onnx/{export_path}")
14
+ export_onnx(export_path, model_path, config_path, novq, dev)
infer.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 版本管理、兼容推理及模型加载实现。
3
+ 版本说明:
4
+ 1. 版本号与github的release版本号对应,使用哪个release版本训练的模型即对应其版本号
5
+ 2. 请在模型的config.json中显示声明版本号,添加一个字段"version" : "你的版本号"
6
+ 特殊版本说明:
7
+ 1.1.1-fix: 1.1.1版本训练的模型,但是在推理时使用dev的日语修复
8
+ 2.3:当前版本
9
+ """
10
+ import torch
11
+ import commons
12
+ from text import cleaned_text_to_sequence, get_bert
13
+
14
+ # from clap_wrapper import get_clap_audio_feature, get_clap_text_feature
15
+ from text.cleaner import clean_text
16
+ import utils
17
+ import numpy as np
18
+
19
+ from models import SynthesizerTrn
20
+ from text.symbols import symbols
21
+
22
+ # from oldVersion.V210.models import SynthesizerTrn as V210SynthesizerTrn
23
+ # from oldVersion.V210.text import symbols as V210symbols
24
+ # from oldVersion.V200.models import SynthesizerTrn as V200SynthesizerTrn
25
+ # from oldVersion.V200.text import symbols as V200symbols
26
+ # from oldVersion.V111.models import SynthesizerTrn as V111SynthesizerTrn
27
+ # from oldVersion.V111.text import symbols as V111symbols
28
+ # from oldVersion.V110.models import SynthesizerTrn as V110SynthesizerTrn
29
+ # from oldVersion.V110.text import symbols as V110symbols
30
+ # from oldVersion.V101.models import SynthesizerTrn as V101SynthesizerTrn
31
+ # from oldVersion.V101.text import symbols as V101symbols
32
+
33
+ # from oldVersion import V111, V110, V101, V200, V210
34
+
35
+ # 当前版本信息
36
+ latest_version = "2.3"
37
+
38
+ # 版本兼容
39
+ SynthesizerTrnMap = {
40
+ # "2.1": V210SynthesizerTrn,
41
+ # "2.0.2-fix": V200SynthesizerTrn,
42
+ # "2.0.1": V200SynthesizerTrn,
43
+ # "2.0": V200SynthesizerTrn,
44
+ # "1.1.1-fix": V111SynthesizerTrn,
45
+ # "1.1.1": V111SynthesizerTrn,
46
+ # "1.1": V110SynthesizerTrn,
47
+ # "1.1.0": V110SynthesizerTrn,
48
+ # "1.0.1": V101SynthesizerTrn,
49
+ # "1.0": V101SynthesizerTrn,
50
+ # "1.0.0": V101SynthesizerTrn,
51
+ }
52
+
53
+ symbolsMap = {
54
+ # "2.1": V210symbols,
55
+ # "2.0.2-fix": V200symbols,
56
+ # "2.0.1": V200symbols,
57
+ # "2.0": V200symbols,
58
+ # "1.1.1-fix": V111symbols,
59
+ # "1.1.1": V111symbols,
60
+ # "1.1": V110symbols,
61
+ # "1.1.0": V110symbols,
62
+ # "1.0.1": V101symbols,
63
+ # "1.0": V101symbols,
64
+ # "1.0.0": V101symbols,
65
+ }
66
+
67
+
68
+ # def get_emo_(reference_audio, emotion, sid):
69
+ # emo = (
70
+ # torch.from_numpy(get_emo(reference_audio))
71
+ # if reference_audio and emotion == -1
72
+ # else torch.FloatTensor(
73
+ # np.load(f"emo_clustering/{sid}/cluster_center_{emotion}.npy")
74
+ # )
75
+ # )
76
+ # return emo
77
+
78
+
79
+ def get_net_g(model_path: str, version: str, device: str, hps):
80
+ if version != latest_version:
81
+ net_g = SynthesizerTrnMap[version](
82
+ len(symbolsMap[version]),
83
+ hps.data.filter_length // 2 + 1,
84
+ hps.train.segment_size // hps.data.hop_length,
85
+ n_speakers=hps.data.n_speakers,
86
+ **hps.model,
87
+ ).to(device)
88
+ else:
89
+ # 当前版本模型 net_g
90
+ net_g = SynthesizerTrn(
91
+ len(symbols),
92
+ hps.data.filter_length // 2 + 1,
93
+ hps.train.segment_size // hps.data.hop_length,
94
+ n_speakers=hps.data.n_speakers,
95
+ **hps.model,
96
+ ).to(device)
97
+ _ = net_g.eval()
98
+ _ = utils.load_checkpoint(model_path, net_g, None, skip_optimizer=True)
99
+ return net_g
100
+
101
+
102
+ def get_text(text, language_str, hps, device, style_text=None, style_weight=0.7):
103
+ style_text = None if style_text == "" else style_text
104
+ # 在此处实现当前版本的get_text
105
+ norm_text, phone, tone, word2ph = clean_text(text, language_str)
106
+ phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
107
+
108
+ if hps.data.add_blank:
109
+ phone = commons.intersperse(phone, 0)
110
+ tone = commons.intersperse(tone, 0)
111
+ language = commons.intersperse(language, 0)
112
+ for i in range(len(word2ph)):
113
+ word2ph[i] = word2ph[i] * 2
114
+ word2ph[0] += 1
115
+ bert_ori = get_bert(
116
+ norm_text, word2ph, language_str, device, style_text, style_weight
117
+ )
118
+ del word2ph
119
+ assert bert_ori.shape[-1] == len(phone), phone
120
+
121
+ if language_str == "ZH":
122
+ bert = bert_ori
123
+ ja_bert = torch.randn(1024, len(phone))
124
+ en_bert = torch.randn(1024, len(phone))
125
+ elif language_str == "JP":
126
+ bert = torch.randn(1024, len(phone))
127
+ ja_bert = bert_ori
128
+ en_bert = torch.randn(1024, len(phone))
129
+ elif language_str == "EN":
130
+ bert = torch.randn(1024, len(phone))
131
+ ja_bert = torch.randn(1024, len(phone))
132
+ en_bert = bert_ori
133
+ else:
134
+ raise ValueError("language_str should be ZH, JP or EN")
135
+
136
+ assert bert.shape[-1] == len(
137
+ phone
138
+ ), f"Bert seq len {bert.shape[-1]} != {len(phone)}"
139
+
140
+ phone = torch.LongTensor(phone)
141
+ tone = torch.LongTensor(tone)
142
+ language = torch.LongTensor(language)
143
+ return bert, ja_bert, en_bert, phone, tone, language
144
+
145
+
146
+ def infer(
147
+ text,
148
+ emotion,
149
+ sdp_ratio,
150
+ noise_scale,
151
+ noise_scale_w,
152
+ length_scale,
153
+ sid,
154
+ language,
155
+ hps,
156
+ net_g,
157
+ device,
158
+ reference_audio=None,
159
+ skip_start=False,
160
+ skip_end=False,
161
+ style_text=None,
162
+ style_weight=0.7,
163
+ ):
164
+ # 2.2版本参数位置变了
165
+ # 2.1 参数新增 emotion reference_audio skip_start skip_end
166
+ # inferMap_V3 = {
167
+ # "2.1": V210.infer,
168
+ #}
169
+ # 支持中日英三语版本
170
+ inferMap_V2 = {
171
+ # "2.0.2-fix": V200.infer,
172
+ # "2.0.1": V200.infer,
173
+ # "2.0": V200.infer,
174
+ # "1.1.1-fix": V111.infer_fix,
175
+ # "1.1.1": V111.infer,
176
+ # "1.1": V110.infer,
177
+ # "1.1.0": V110.infer,
178
+ }
179
+ # 仅支持中文版本
180
+ # 在测试中,并未发现两个版本的模型不能互相通用
181
+ inferMap_V1 = {
182
+ # "1.0.1": V101.infer,
183
+ # "1.0": V101.infer,
184
+ # "1.0.0": V101.infer,
185
+ }
186
+ version = hps.version if hasattr(hps, "version") else latest_version
187
+ # 非当前版本,根据版本号选择合适的infer
188
+ if version != latest_version:
189
+ if version in inferMap_V3.keys():
190
+ emotion = 0
191
+ return inferMap_V3[version](
192
+ text,
193
+ sdp_ratio,
194
+ noise_scale,
195
+ noise_scale_w,
196
+ length_scale,
197
+ sid,
198
+ language,
199
+ hps,
200
+ net_g,
201
+ device,
202
+ reference_audio,
203
+ emotion,
204
+ skip_start,
205
+ skip_end,
206
+ style_text,
207
+ style_weight,
208
+ )
209
+ if version in inferMap_V2.keys():
210
+ return inferMap_V2[version](
211
+ text,
212
+ sdp_ratio,
213
+ noise_scale,
214
+ noise_scale_w,
215
+ length_scale,
216
+ sid,
217
+ language,
218
+ hps,
219
+ net_g,
220
+ device,
221
+ )
222
+ if version in inferMap_V1.keys():
223
+ return inferMap_V1[version](
224
+ text,
225
+ sdp_ratio,
226
+ noise_scale,
227
+ noise_scale_w,
228
+ length_scale,
229
+ sid,
230
+ hps,
231
+ net_g,
232
+ device,
233
+ )
234
+ # 在此处实现当前版本的推理
235
+ # emo = get_emo_(reference_audio, emotion, sid)
236
+ # if isinstance(reference_audio, np.ndarray):
237
+ # emo = get_clap_audio_feature(reference_audio, device)
238
+ # else:
239
+ # emo = get_clap_text_feature(emotion, device)
240
+ # emo = torch.squeeze(emo, dim=1)
241
+
242
+ bert, ja_bert, en_bert, phones, tones, lang_ids = get_text(
243
+ text,
244
+ language,
245
+ hps,
246
+ device,
247
+ style_text=style_text,
248
+ style_weight=style_weight,
249
+ )
250
+ if skip_start:
251
+ phones = phones[3:]
252
+ tones = tones[3:]
253
+ lang_ids = lang_ids[3:]
254
+ bert = bert[:, 3:]
255
+ ja_bert = ja_bert[:, 3:]
256
+ en_bert = en_bert[:, 3:]
257
+ if skip_end:
258
+ phones = phones[:-2]
259
+ tones = tones[:-2]
260
+ lang_ids = lang_ids[:-2]
261
+ bert = bert[:, :-2]
262
+ ja_bert = ja_bert[:, :-2]
263
+ en_bert = en_bert[:, :-2]
264
+ with torch.no_grad():
265
+ x_tst = phones.to(device).unsqueeze(0)
266
+ tones = tones.to(device).unsqueeze(0)
267
+ lang_ids = lang_ids.to(device).unsqueeze(0)
268
+ bert = bert.to(device).unsqueeze(0)
269
+ ja_bert = ja_bert.to(device).unsqueeze(0)
270
+ en_bert = en_bert.to(device).unsqueeze(0)
271
+ x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device)
272
+ # emo = emo.to(device).unsqueeze(0)
273
+ del phones
274
+ speakers = torch.LongTensor([hps.data.spk2id[sid]]).to(device)
275
+ audio = (
276
+ net_g.infer(
277
+ x_tst,
278
+ x_tst_lengths,
279
+ speakers,
280
+ tones,
281
+ lang_ids,
282
+ bert,
283
+ ja_bert,
284
+ en_bert,
285
+ sdp_ratio=sdp_ratio,
286
+ noise_scale=noise_scale,
287
+ noise_scale_w=noise_scale_w,
288
+ length_scale=length_scale,
289
+ )[0][0, 0]
290
+ .data.cpu()
291
+ .float()
292
+ .numpy()
293
+ )
294
+ del (
295
+ x_tst,
296
+ tones,
297
+ lang_ids,
298
+ bert,
299
+ x_tst_lengths,
300
+ speakers,
301
+ ja_bert,
302
+ en_bert,
303
+ ) # , emo
304
+ if torch.cuda.is_available():
305
+ torch.cuda.empty_cache()
306
+ return audio
307
+
308
+
309
+ def infer_multilang(
310
+ text,
311
+ sdp_ratio,
312
+ noise_scale,
313
+ noise_scale_w,
314
+ length_scale,
315
+ sid,
316
+ language,
317
+ hps,
318
+ net_g,
319
+ device,
320
+ reference_audio=None,
321
+ emotion=None,
322
+ skip_start=False,
323
+ skip_end=False,
324
+ ):
325
+ bert, ja_bert, en_bert, phones, tones, lang_ids = [], [], [], [], [], []
326
+ # emo = get_emo_(reference_audio, emotion, sid)
327
+ # if isinstance(reference_audio, np.ndarray):
328
+ # emo = get_clap_audio_feature(reference_audio, device)
329
+ # else:
330
+ # emo = get_clap_text_feature(emotion, device)
331
+ # emo = torch.squeeze(emo, dim=1)
332
+ for idx, (txt, lang) in enumerate(zip(text, language)):
333
+ _skip_start = (idx != 0) or (skip_start and idx == 0)
334
+ _skip_end = (idx != len(language) - 1) or skip_end
335
+ (
336
+ temp_bert,
337
+ temp_ja_bert,
338
+ temp_en_bert,
339
+ temp_phones,
340
+ temp_tones,
341
+ temp_lang_ids,
342
+ ) = get_text(txt, lang, hps, device)
343
+ if _skip_start:
344
+ temp_bert = temp_bert[:, 3:]
345
+ temp_ja_bert = temp_ja_bert[:, 3:]
346
+ temp_en_bert = temp_en_bert[:, 3:]
347
+ temp_phones = temp_phones[3:]
348
+ temp_tones = temp_tones[3:]
349
+ temp_lang_ids = temp_lang_ids[3:]
350
+ if _skip_end:
351
+ temp_bert = temp_bert[:, :-2]
352
+ temp_ja_bert = temp_ja_bert[:, :-2]
353
+ temp_en_bert = temp_en_bert[:, :-2]
354
+ temp_phones = temp_phones[:-2]
355
+ temp_tones = temp_tones[:-2]
356
+ temp_lang_ids = temp_lang_ids[:-2]
357
+ bert.append(temp_bert)
358
+ ja_bert.append(temp_ja_bert)
359
+ en_bert.append(temp_en_bert)
360
+ phones.append(temp_phones)
361
+ tones.append(temp_tones)
362
+ lang_ids.append(temp_lang_ids)
363
+ bert = torch.concatenate(bert, dim=1)
364
+ ja_bert = torch.concatenate(ja_bert, dim=1)
365
+ en_bert = torch.concatenate(en_bert, dim=1)
366
+ phones = torch.concatenate(phones, dim=0)
367
+ tones = torch.concatenate(tones, dim=0)
368
+ lang_ids = torch.concatenate(lang_ids, dim=0)
369
+ with torch.no_grad():
370
+ x_tst = phones.to(device).unsqueeze(0)
371
+ tones = tones.to(device).unsqueeze(0)
372
+ lang_ids = lang_ids.to(device).unsqueeze(0)
373
+ bert = bert.to(device).unsqueeze(0)
374
+ ja_bert = ja_bert.to(device).unsqueeze(0)
375
+ en_bert = en_bert.to(device).unsqueeze(0)
376
+ # emo = emo.to(device).unsqueeze(0)
377
+ x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device)
378
+ del phones
379
+ speakers = torch.LongTensor([hps.data.spk2id[sid]]).to(device)
380
+ audio = (
381
+ net_g.infer(
382
+ x_tst,
383
+ x_tst_lengths,
384
+ speakers,
385
+ tones,
386
+ lang_ids,
387
+ bert,
388
+ ja_bert,
389
+ en_bert,
390
+ sdp_ratio=sdp_ratio,
391
+ noise_scale=noise_scale,
392
+ noise_scale_w=noise_scale_w,
393
+ length_scale=length_scale,
394
+ )[0][0, 0]
395
+ .data.cpu()
396
+ .float()
397
+ .numpy()
398
+ )
399
+ del (
400
+ x_tst,
401
+ tones,
402
+ lang_ids,
403
+ bert,
404
+ x_tst_lengths,
405
+ speakers,
406
+ ja_bert,
407
+ en_bert,
408
+ ) # , emo
409
+ if torch.cuda.is_available():
410
+ torch.cuda.empty_cache()
411
+ return audio
losses.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchaudio
3
+ from transformers import AutoModel
4
+
5
+
6
+ def feature_loss(fmap_r, fmap_g):
7
+ loss = 0
8
+ for dr, dg in zip(fmap_r, fmap_g):
9
+ for rl, gl in zip(dr, dg):
10
+ rl = rl.float().detach()
11
+ gl = gl.float()
12
+ loss += torch.mean(torch.abs(rl - gl))
13
+
14
+ return loss * 2
15
+
16
+
17
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
18
+ loss = 0
19
+ r_losses = []
20
+ g_losses = []
21
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
22
+ dr = dr.float()
23
+ dg = dg.float()
24
+ r_loss = torch.mean((1 - dr) ** 2)
25
+ g_loss = torch.mean(dg**2)
26
+ loss += r_loss + g_loss
27
+ r_losses.append(r_loss.item())
28
+ g_losses.append(g_loss.item())
29
+
30
+ return loss, r_losses, g_losses
31
+
32
+
33
+ def generator_loss(disc_outputs):
34
+ loss = 0
35
+ gen_losses = []
36
+ for dg in disc_outputs:
37
+ dg = dg.float()
38
+ l = torch.mean((1 - dg) ** 2)
39
+ gen_losses.append(l)
40
+ loss += l
41
+
42
+ return loss, gen_losses
43
+
44
+
45
+ def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
46
+ """
47
+ z_p, logs_q: [b, h, t_t]
48
+ m_p, logs_p: [b, h, t_t]
49
+ """
50
+ z_p = z_p.float()
51
+ logs_q = logs_q.float()
52
+ m_p = m_p.float()
53
+ logs_p = logs_p.float()
54
+ z_mask = z_mask.float()
55
+
56
+ kl = logs_p - logs_q - 0.5
57
+ kl += 0.5 * ((z_p - m_p) ** 2) * torch.exp(-2.0 * logs_p)
58
+ kl = torch.sum(kl * z_mask)
59
+ l = kl / torch.sum(z_mask)
60
+ return l
61
+
62
+
63
+ class WavLMLoss(torch.nn.Module):
64
+ def __init__(self, model, wd, model_sr, slm_sr=16000):
65
+ super(WavLMLoss, self).__init__()
66
+ self.wavlm = AutoModel.from_pretrained(model)
67
+ self.wd = wd
68
+ self.resample = torchaudio.transforms.Resample(model_sr, slm_sr)
69
+ self.wavlm.eval()
70
+ for param in self.wavlm.parameters():
71
+ param.requires_grad = False
72
+
73
+ def forward(self, wav, y_rec):
74
+ with torch.no_grad():
75
+ wav_16 = self.resample(wav)
76
+ wav_embeddings = self.wavlm(
77
+ input_values=wav_16, output_hidden_states=True
78
+ ).hidden_states
79
+ y_rec_16 = self.resample(y_rec)
80
+ y_rec_embeddings = self.wavlm(
81
+ input_values=y_rec_16.squeeze(), output_hidden_states=True
82
+ ).hidden_states
83
+
84
+ floss = 0
85
+ for er, eg in zip(wav_embeddings, y_rec_embeddings):
86
+ floss += torch.mean(torch.abs(er - eg))
87
+
88
+ return floss.mean()
89
+
90
+ def generator(self, y_rec):
91
+ y_rec_16 = self.resample(y_rec)
92
+ y_rec_embeddings = self.wavlm(
93
+ input_values=y_rec_16, output_hidden_states=True
94
+ ).hidden_states
95
+ y_rec_embeddings = (
96
+ torch.stack(y_rec_embeddings, dim=1)
97
+ .transpose(-1, -2)
98
+ .flatten(start_dim=1, end_dim=2)
99
+ )
100
+ y_df_hat_g = self.wd(y_rec_embeddings)
101
+ loss_gen = torch.mean((1 - y_df_hat_g) ** 2)
102
+
103
+ return loss_gen
104
+
105
+ def discriminator(self, wav, y_rec):
106
+ with torch.no_grad():
107
+ wav_16 = self.resample(wav)
108
+ wav_embeddings = self.wavlm(
109
+ input_values=wav_16, output_hidden_states=True
110
+ ).hidden_states
111
+ y_rec_16 = self.resample(y_rec)
112
+ y_rec_embeddings = self.wavlm(
113
+ input_values=y_rec_16, output_hidden_states=True
114
+ ).hidden_states
115
+
116
+ y_embeddings = (
117
+ torch.stack(wav_embeddings, dim=1)
118
+ .transpose(-1, -2)
119
+ .flatten(start_dim=1, end_dim=2)
120
+ )
121
+ y_rec_embeddings = (
122
+ torch.stack(y_rec_embeddings, dim=1)
123
+ .transpose(-1, -2)
124
+ .flatten(start_dim=1, end_dim=2)
125
+ )
126
+
127
+ y_d_rs = self.wd(y_embeddings)
128
+ y_d_gs = self.wd(y_rec_embeddings)
129
+
130
+ y_df_hat_r, y_df_hat_g = y_d_rs, y_d_gs
131
+
132
+ r_loss = torch.mean((1 - y_df_hat_r) ** 2)
133
+ g_loss = torch.mean((y_df_hat_g) ** 2)
134
+
135
+ loss_disc_f = r_loss + g_loss
136
+
137
+ return loss_disc_f.mean()
138
+
139
+ def discriminator_forward(self, wav):
140
+ with torch.no_grad():
141
+ wav_16 = self.resample(wav)
142
+ wav_embeddings = self.wavlm(
143
+ input_values=wav_16, output_hidden_states=True
144
+ ).hidden_states
145
+ y_embeddings = (
146
+ torch.stack(wav_embeddings, dim=1)
147
+ .transpose(-1, -2)
148
+ .flatten(start_dim=1, end_dim=2)
149
+ )
150
+
151
+ y_d_rs = self.wd(y_embeddings)
152
+
153
+ return y_d_rs
mel_processing.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.utils.data
3
+ from librosa.filters import mel as librosa_mel_fn
4
+ import warnings
5
+
6
+ # warnings.simplefilter(action='ignore', category=FutureWarning)
7
+ warnings.filterwarnings(action="ignore")
8
+ MAX_WAV_VALUE = 32768.0
9
+
10
+
11
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
12
+ """
13
+ PARAMS
14
+ ------
15
+ C: compression factor
16
+ """
17
+ return torch.log(torch.clamp(x, min=clip_val) * C)
18
+
19
+
20
+ def dynamic_range_decompression_torch(x, C=1):
21
+ """
22
+ PARAMS
23
+ ------
24
+ C: compression factor used to compress
25
+ """
26
+ return torch.exp(x) / C
27
+
28
+
29
+ def spectral_normalize_torch(magnitudes):
30
+ output = dynamic_range_compression_torch(magnitudes)
31
+ return output
32
+
33
+
34
+ def spectral_de_normalize_torch(magnitudes):
35
+ output = dynamic_range_decompression_torch(magnitudes)
36
+ return output
37
+
38
+
39
+ mel_basis = {}
40
+ hann_window = {}
41
+
42
+
43
+ def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
44
+ if torch.min(y) < -1.0:
45
+ print("min value is ", torch.min(y))
46
+ if torch.max(y) > 1.0:
47
+ print("max value is ", torch.max(y))
48
+
49
+ global hann_window
50
+ dtype_device = str(y.dtype) + "_" + str(y.device)
51
+ wnsize_dtype_device = str(win_size) + "_" + dtype_device
52
+ if wnsize_dtype_device not in hann_window:
53
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
54
+ dtype=y.dtype, device=y.device
55
+ )
56
+
57
+ y = torch.nn.functional.pad(
58
+ y.unsqueeze(1),
59
+ (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
60
+ mode="reflect",
61
+ )
62
+ y = y.squeeze(1)
63
+
64
+ spec = torch.stft(
65
+ y,
66
+ n_fft,
67
+ hop_length=hop_size,
68
+ win_length=win_size,
69
+ window=hann_window[wnsize_dtype_device],
70
+ center=center,
71
+ pad_mode="reflect",
72
+ normalized=False,
73
+ onesided=True,
74
+ return_complex=False,
75
+ )
76
+
77
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
78
+ return spec
79
+
80
+
81
+ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
82
+ global mel_basis
83
+ dtype_device = str(spec.dtype) + "_" + str(spec.device)
84
+ fmax_dtype_device = str(fmax) + "_" + dtype_device
85
+ if fmax_dtype_device not in mel_basis:
86
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
87
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
88
+ dtype=spec.dtype, device=spec.device
89
+ )
90
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
91
+ spec = spectral_normalize_torch(spec)
92
+ return spec
93
+
94
+
95
+ def mel_spectrogram_torch(
96
+ y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False
97
+ ):
98
+ if torch.min(y) < -1.0:
99
+ print("min value is ", torch.min(y))
100
+ if torch.max(y) > 1.0:
101
+ print("max value is ", torch.max(y))
102
+
103
+ global mel_basis, hann_window
104
+ dtype_device = str(y.dtype) + "_" + str(y.device)
105
+ fmax_dtype_device = str(fmax) + "_" + dtype_device
106
+ wnsize_dtype_device = str(win_size) + "_" + dtype_device
107
+ if fmax_dtype_device not in mel_basis:
108
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
109
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
110
+ dtype=y.dtype, device=y.device
111
+ )
112
+ if wnsize_dtype_device not in hann_window:
113
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
114
+ dtype=y.dtype, device=y.device
115
+ )
116
+
117
+ y = torch.nn.functional.pad(
118
+ y.unsqueeze(1),
119
+ (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
120
+ mode="reflect",
121
+ )
122
+ y = y.squeeze(1)
123
+
124
+ spec = torch.stft(
125
+ y,
126
+ n_fft,
127
+ hop_length=hop_size,
128
+ win_length=win_size,
129
+ window=hann_window[wnsize_dtype_device],
130
+ center=center,
131
+ pad_mode="reflect",
132
+ normalized=False,
133
+ onesided=True,
134
+ return_complex=False,
135
+ )
136
+
137
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
138
+
139
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
140
+ spec = spectral_normalize_torch(spec)
141
+
142
+ return spec
models.py ADDED
@@ -0,0 +1,1076 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ import commons
7
+ import modules
8
+ import attentions
9
+ import monotonic_align
10
+
11
+ from torch.nn import Conv1d, ConvTranspose1d, Conv2d
12
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
13
+
14
+ from commons import init_weights, get_padding
15
+ from text import symbols, num_tones, num_languages
16
+
17
+ from vector_quantize_pytorch import VectorQuantize
18
+
19
+
20
+ class DurationDiscriminator(nn.Module): # vits2
21
+ def __init__(
22
+ self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0
23
+ ):
24
+ super().__init__()
25
+
26
+ self.in_channels = in_channels
27
+ self.filter_channels = filter_channels
28
+ self.kernel_size = kernel_size
29
+ self.p_dropout = p_dropout
30
+ self.gin_channels = gin_channels
31
+
32
+ self.drop = nn.Dropout(p_dropout)
33
+ self.conv_1 = nn.Conv1d(
34
+ in_channels, filter_channels, kernel_size, padding=kernel_size // 2
35
+ )
36
+ self.norm_1 = modules.LayerNorm(filter_channels)
37
+ self.conv_2 = nn.Conv1d(
38
+ filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
39
+ )
40
+ self.norm_2 = modules.LayerNorm(filter_channels)
41
+ self.dur_proj = nn.Conv1d(1, filter_channels, 1)
42
+
43
+ self.LSTM = nn.LSTM(
44
+ 2 * filter_channels, filter_channels, batch_first=True, bidirectional=True
45
+ )
46
+
47
+ if gin_channels != 0:
48
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
49
+
50
+ self.output_layer = nn.Sequential(
51
+ nn.Linear(2 * filter_channels, 1), nn.Sigmoid()
52
+ )
53
+
54
+ def forward_probability(self, x, dur):
55
+ dur = self.dur_proj(dur)
56
+ x = torch.cat([x, dur], dim=1)
57
+ x = x.transpose(1, 2)
58
+ x, _ = self.LSTM(x)
59
+ output_prob = self.output_layer(x)
60
+ return output_prob
61
+
62
+ def forward(self, x, x_mask, dur_r, dur_hat, g=None):
63
+ x = torch.detach(x)
64
+ if g is not None:
65
+ g = torch.detach(g)
66
+ x = x + self.cond(g)
67
+ x = self.conv_1(x * x_mask)
68
+ x = torch.relu(x)
69
+ x = self.norm_1(x)
70
+ x = self.drop(x)
71
+ x = self.conv_2(x * x_mask)
72
+ x = torch.relu(x)
73
+ x = self.norm_2(x)
74
+ x = self.drop(x)
75
+
76
+ output_probs = []
77
+ for dur in [dur_r, dur_hat]:
78
+ output_prob = self.forward_probability(x, dur)
79
+ output_probs.append(output_prob)
80
+
81
+ return output_probs
82
+
83
+
84
+ class TransformerCouplingBlock(nn.Module):
85
+ def __init__(
86
+ self,
87
+ channels,
88
+ hidden_channels,
89
+ filter_channels,
90
+ n_heads,
91
+ n_layers,
92
+ kernel_size,
93
+ p_dropout,
94
+ n_flows=4,
95
+ gin_channels=0,
96
+ share_parameter=False,
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 = (
109
+ attentions.FFT(
110
+ hidden_channels,
111
+ filter_channels,
112
+ n_heads,
113
+ n_layers,
114
+ kernel_size,
115
+ p_dropout,
116
+ isflow=True,
117
+ gin_channels=self.gin_channels,
118
+ )
119
+ if share_parameter
120
+ else None
121
+ )
122
+
123
+ for i in range(n_flows):
124
+ self.flows.append(
125
+ modules.TransformerCouplingLayer(
126
+ channels,
127
+ hidden_channels,
128
+ kernel_size,
129
+ n_layers,
130
+ n_heads,
131
+ p_dropout,
132
+ filter_channels,
133
+ mean_only=True,
134
+ wn_sharing_parameter=self.wn,
135
+ gin_channels=self.gin_channels,
136
+ )
137
+ )
138
+ self.flows.append(modules.Flip())
139
+
140
+ def forward(self, x, x_mask, g=None, reverse=False):
141
+ if not reverse:
142
+ for flow in self.flows:
143
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
144
+ else:
145
+ for flow in reversed(self.flows):
146
+ x = flow(x, x_mask, g=g, reverse=reverse)
147
+ return x
148
+
149
+
150
+ class StochasticDurationPredictor(nn.Module):
151
+ def __init__(
152
+ self,
153
+ in_channels,
154
+ filter_channels,
155
+ kernel_size,
156
+ p_dropout,
157
+ n_flows=4,
158
+ gin_channels=0,
159
+ ):
160
+ super().__init__()
161
+ filter_channels = in_channels # it needs to be removed from future version.
162
+ self.in_channels = in_channels
163
+ self.filter_channels = filter_channels
164
+ self.kernel_size = kernel_size
165
+ self.p_dropout = p_dropout
166
+ self.n_flows = n_flows
167
+ self.gin_channels = gin_channels
168
+
169
+ self.log_flow = modules.Log()
170
+ self.flows = nn.ModuleList()
171
+ self.flows.append(modules.ElementwiseAffine(2))
172
+ for i in range(n_flows):
173
+ self.flows.append(
174
+ modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
175
+ )
176
+ self.flows.append(modules.Flip())
177
+
178
+ self.post_pre = nn.Conv1d(1, filter_channels, 1)
179
+ self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
180
+ self.post_convs = modules.DDSConv(
181
+ filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
182
+ )
183
+ self.post_flows = nn.ModuleList()
184
+ self.post_flows.append(modules.ElementwiseAffine(2))
185
+ for i in range(4):
186
+ self.post_flows.append(
187
+ modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
188
+ )
189
+ self.post_flows.append(modules.Flip())
190
+
191
+ self.pre = nn.Conv1d(in_channels, filter_channels, 1)
192
+ self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
193
+ self.convs = modules.DDSConv(
194
+ filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
195
+ )
196
+ if gin_channels != 0:
197
+ self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
198
+
199
+ def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
200
+ x = torch.detach(x)
201
+ x = self.pre(x)
202
+ if g is not None:
203
+ g = torch.detach(g)
204
+ x = x + self.cond(g)
205
+ x = self.convs(x, x_mask)
206
+ x = self.proj(x) * x_mask
207
+
208
+ if not reverse:
209
+ flows = self.flows
210
+ assert w is not None
211
+
212
+ logdet_tot_q = 0
213
+ h_w = self.post_pre(w)
214
+ h_w = self.post_convs(h_w, x_mask)
215
+ h_w = self.post_proj(h_w) * x_mask
216
+ e_q = (
217
+ torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype)
218
+ * x_mask
219
+ )
220
+ z_q = e_q
221
+ for flow in self.post_flows:
222
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
223
+ logdet_tot_q += logdet_q
224
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
225
+ u = torch.sigmoid(z_u) * x_mask
226
+ z0 = (w - u) * x_mask
227
+ logdet_tot_q += torch.sum(
228
+ (F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2]
229
+ )
230
+ logq = (
231
+ torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q**2)) * x_mask, [1, 2])
232
+ - logdet_tot_q
233
+ )
234
+
235
+ logdet_tot = 0
236
+ z0, logdet = self.log_flow(z0, x_mask)
237
+ logdet_tot += logdet
238
+ z = torch.cat([z0, z1], 1)
239
+ for flow in flows:
240
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
241
+ logdet_tot = logdet_tot + logdet
242
+ nll = (
243
+ torch.sum(0.5 * (math.log(2 * math.pi) + (z**2)) * x_mask, [1, 2])
244
+ - logdet_tot
245
+ )
246
+ return nll + logq # [b]
247
+ else:
248
+ flows = list(reversed(self.flows))
249
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
250
+ z = (
251
+ torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype)
252
+ * noise_scale
253
+ )
254
+ for flow in flows:
255
+ z = flow(z, x_mask, g=x, reverse=reverse)
256
+ z0, z1 = torch.split(z, [1, 1], 1)
257
+ logw = z0
258
+ return logw
259
+
260
+
261
+ class DurationPredictor(nn.Module):
262
+ def __init__(
263
+ self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0
264
+ ):
265
+ super().__init__()
266
+
267
+ self.in_channels = in_channels
268
+ self.filter_channels = filter_channels
269
+ self.kernel_size = kernel_size
270
+ self.p_dropout = p_dropout
271
+ self.gin_channels = gin_channels
272
+
273
+ self.drop = nn.Dropout(p_dropout)
274
+ self.conv_1 = nn.Conv1d(
275
+ in_channels, filter_channels, kernel_size, padding=kernel_size // 2
276
+ )
277
+ self.norm_1 = modules.LayerNorm(filter_channels)
278
+ self.conv_2 = nn.Conv1d(
279
+ filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
280
+ )
281
+ self.norm_2 = modules.LayerNorm(filter_channels)
282
+ self.proj = nn.Conv1d(filter_channels, 1, 1)
283
+
284
+ if gin_channels != 0:
285
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
286
+
287
+ def forward(self, x, x_mask, g=None):
288
+ x = torch.detach(x)
289
+ if g is not None:
290
+ g = torch.detach(g)
291
+ x = x + self.cond(g)
292
+ x = self.conv_1(x * x_mask)
293
+ x = torch.relu(x)
294
+ x = self.norm_1(x)
295
+ x = self.drop(x)
296
+ x = self.conv_2(x * x_mask)
297
+ x = torch.relu(x)
298
+ x = self.norm_2(x)
299
+ x = self.drop(x)
300
+ x = self.proj(x * x_mask)
301
+ return x * x_mask
302
+
303
+
304
+ class Bottleneck(nn.Sequential):
305
+ def __init__(self, in_dim, hidden_dim):
306
+ c_fc1 = nn.Linear(in_dim, hidden_dim, bias=False)
307
+ c_fc2 = nn.Linear(in_dim, hidden_dim, bias=False)
308
+ super().__init__(*[c_fc1, c_fc2])
309
+
310
+
311
+ class Block(nn.Module):
312
+ def __init__(self, in_dim, hidden_dim) -> None:
313
+ super().__init__()
314
+ self.norm = nn.LayerNorm(in_dim)
315
+ self.mlp = MLP(in_dim, hidden_dim)
316
+
317
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
318
+ x = x + self.mlp(self.norm(x))
319
+ return x
320
+
321
+
322
+ class MLP(nn.Module):
323
+ def __init__(self, in_dim, hidden_dim):
324
+ super().__init__()
325
+ self.c_fc1 = nn.Linear(in_dim, hidden_dim, bias=False)
326
+ self.c_fc2 = nn.Linear(in_dim, hidden_dim, bias=False)
327
+ self.c_proj = nn.Linear(hidden_dim, in_dim, bias=False)
328
+
329
+ def forward(self, x: torch.Tensor):
330
+ x = F.silu(self.c_fc1(x)) * self.c_fc2(x)
331
+ x = self.c_proj(x)
332
+ return x
333
+
334
+
335
+ class TextEncoder(nn.Module):
336
+ def __init__(
337
+ self,
338
+ n_vocab,
339
+ out_channels,
340
+ hidden_channels,
341
+ filter_channels,
342
+ n_heads,
343
+ n_layers,
344
+ kernel_size,
345
+ p_dropout,
346
+ gin_channels=0,
347
+ ):
348
+ super().__init__()
349
+ self.n_vocab = n_vocab
350
+ self.out_channels = out_channels
351
+ self.hidden_channels = hidden_channels
352
+ self.filter_channels = filter_channels
353
+ self.n_heads = n_heads
354
+ self.n_layers = n_layers
355
+ self.kernel_size = kernel_size
356
+ self.p_dropout = p_dropout
357
+ self.gin_channels = gin_channels
358
+ self.emb = nn.Embedding(len(symbols), hidden_channels)
359
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
360
+ self.tone_emb = nn.Embedding(num_tones, hidden_channels)
361
+ nn.init.normal_(self.tone_emb.weight, 0.0, hidden_channels**-0.5)
362
+ self.language_emb = nn.Embedding(num_languages, hidden_channels)
363
+ nn.init.normal_(self.language_emb.weight, 0.0, hidden_channels**-0.5)
364
+ self.bert_proj = nn.Conv1d(1024, hidden_channels, 1)
365
+ self.ja_bert_proj = nn.Conv1d(1024, hidden_channels, 1)
366
+ self.en_bert_proj = nn.Conv1d(1024, hidden_channels, 1)
367
+
368
+ self.encoder = attentions.Encoder(
369
+ hidden_channels,
370
+ filter_channels,
371
+ n_heads,
372
+ n_layers,
373
+ kernel_size,
374
+ p_dropout,
375
+ gin_channels=self.gin_channels,
376
+ )
377
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
378
+
379
+ def forward(self, x, x_lengths, tone, language, bert, ja_bert, en_bert, g=None):
380
+ bert_emb = self.bert_proj(bert).transpose(1, 2)
381
+ ja_bert_emb = self.ja_bert_proj(ja_bert).transpose(1, 2)
382
+ en_bert_emb = self.en_bert_proj(en_bert).transpose(1, 2)
383
+ x = (
384
+ self.emb(x)
385
+ + self.tone_emb(tone)
386
+ + self.language_emb(language)
387
+ + bert_emb
388
+ + ja_bert_emb
389
+ + en_bert_emb
390
+ ) * math.sqrt(
391
+ self.hidden_channels
392
+ ) # [b, t, h]
393
+ x = torch.transpose(x, 1, -1) # [b, h, t]
394
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
395
+ x.dtype
396
+ )
397
+
398
+ x = self.encoder(x * x_mask, x_mask, g=g)
399
+ stats = self.proj(x) * x_mask
400
+
401
+ m, logs = torch.split(stats, self.out_channels, dim=1)
402
+ return x, m, logs, x_mask
403
+
404
+
405
+ class ResidualCouplingBlock(nn.Module):
406
+ def __init__(
407
+ self,
408
+ channels,
409
+ hidden_channels,
410
+ kernel_size,
411
+ dilation_rate,
412
+ n_layers,
413
+ n_flows=4,
414
+ gin_channels=0,
415
+ ):
416
+ super().__init__()
417
+ self.channels = channels
418
+ self.hidden_channels = hidden_channels
419
+ self.kernel_size = kernel_size
420
+ self.dilation_rate = dilation_rate
421
+ self.n_layers = n_layers
422
+ self.n_flows = n_flows
423
+ self.gin_channels = gin_channels
424
+
425
+ self.flows = nn.ModuleList()
426
+ for i in range(n_flows):
427
+ self.flows.append(
428
+ modules.ResidualCouplingLayer(
429
+ channels,
430
+ hidden_channels,
431
+ kernel_size,
432
+ dilation_rate,
433
+ n_layers,
434
+ gin_channels=gin_channels,
435
+ mean_only=True,
436
+ )
437
+ )
438
+ self.flows.append(modules.Flip())
439
+
440
+ def forward(self, x, x_mask, g=None, reverse=False):
441
+ if not reverse:
442
+ for flow in self.flows:
443
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
444
+ else:
445
+ for flow in reversed(self.flows):
446
+ x = flow(x, x_mask, g=g, reverse=reverse)
447
+ return x
448
+
449
+
450
+ class PosteriorEncoder(nn.Module):
451
+ def __init__(
452
+ self,
453
+ in_channels,
454
+ out_channels,
455
+ hidden_channels,
456
+ kernel_size,
457
+ dilation_rate,
458
+ n_layers,
459
+ gin_channels=0,
460
+ ):
461
+ super().__init__()
462
+ self.in_channels = in_channels
463
+ self.out_channels = out_channels
464
+ self.hidden_channels = hidden_channels
465
+ self.kernel_size = kernel_size
466
+ self.dilation_rate = dilation_rate
467
+ self.n_layers = n_layers
468
+ self.gin_channels = gin_channels
469
+
470
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
471
+ self.enc = modules.WN(
472
+ hidden_channels,
473
+ kernel_size,
474
+ dilation_rate,
475
+ n_layers,
476
+ gin_channels=gin_channels,
477
+ )
478
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
479
+
480
+ def forward(self, x, x_lengths, g=None):
481
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
482
+ x.dtype
483
+ )
484
+ x = self.pre(x) * x_mask
485
+ x = self.enc(x, x_mask, g=g)
486
+ stats = self.proj(x) * x_mask
487
+ m, logs = torch.split(stats, self.out_channels, dim=1)
488
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
489
+ return z, m, logs, x_mask
490
+
491
+
492
+ class Generator(torch.nn.Module):
493
+ def __init__(
494
+ self,
495
+ initial_channel,
496
+ resblock,
497
+ resblock_kernel_sizes,
498
+ resblock_dilation_sizes,
499
+ upsample_rates,
500
+ upsample_initial_channel,
501
+ upsample_kernel_sizes,
502
+ gin_channels=0,
503
+ ):
504
+ super(Generator, self).__init__()
505
+ self.num_kernels = len(resblock_kernel_sizes)
506
+ self.num_upsamples = len(upsample_rates)
507
+ self.conv_pre = Conv1d(
508
+ initial_channel, upsample_initial_channel, 7, 1, padding=3
509
+ )
510
+ resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
511
+
512
+ self.ups = nn.ModuleList()
513
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
514
+ self.ups.append(
515
+ weight_norm(
516
+ ConvTranspose1d(
517
+ upsample_initial_channel // (2**i),
518
+ upsample_initial_channel // (2 ** (i + 1)),
519
+ k,
520
+ u,
521
+ padding=(k - u) // 2,
522
+ )
523
+ )
524
+ )
525
+
526
+ self.resblocks = nn.ModuleList()
527
+ for i in range(len(self.ups)):
528
+ ch = upsample_initial_channel // (2 ** (i + 1))
529
+ for j, (k, d) in enumerate(
530
+ zip(resblock_kernel_sizes, resblock_dilation_sizes)
531
+ ):
532
+ self.resblocks.append(resblock(ch, k, d))
533
+
534
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
535
+ self.ups.apply(init_weights)
536
+
537
+ if gin_channels != 0:
538
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
539
+
540
+ def forward(self, x, g=None):
541
+ x = self.conv_pre(x)
542
+ if g is not None:
543
+ x = x + self.cond(g)
544
+
545
+ for i in range(self.num_upsamples):
546
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
547
+ x = self.ups[i](x)
548
+ xs = None
549
+ for j in range(self.num_kernels):
550
+ if xs is None:
551
+ xs = self.resblocks[i * self.num_kernels + j](x)
552
+ else:
553
+ xs += self.resblocks[i * self.num_kernels + j](x)
554
+ x = xs / self.num_kernels
555
+ x = F.leaky_relu(x)
556
+ x = self.conv_post(x)
557
+ x = torch.tanh(x)
558
+
559
+ return x
560
+
561
+ def remove_weight_norm(self):
562
+ print("Removing weight norm...")
563
+ for layer in self.ups:
564
+ remove_weight_norm(layer)
565
+ for layer in self.resblocks:
566
+ layer.remove_weight_norm()
567
+
568
+
569
+ class DiscriminatorP(torch.nn.Module):
570
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
571
+ super(DiscriminatorP, self).__init__()
572
+ self.period = period
573
+ self.use_spectral_norm = use_spectral_norm
574
+ norm_f = weight_norm if use_spectral_norm is False else spectral_norm
575
+ self.convs = nn.ModuleList(
576
+ [
577
+ norm_f(
578
+ Conv2d(
579
+ 1,
580
+ 32,
581
+ (kernel_size, 1),
582
+ (stride, 1),
583
+ padding=(get_padding(kernel_size, 1), 0),
584
+ )
585
+ ),
586
+ norm_f(
587
+ Conv2d(
588
+ 32,
589
+ 128,
590
+ (kernel_size, 1),
591
+ (stride, 1),
592
+ padding=(get_padding(kernel_size, 1), 0),
593
+ )
594
+ ),
595
+ norm_f(
596
+ Conv2d(
597
+ 128,
598
+ 512,
599
+ (kernel_size, 1),
600
+ (stride, 1),
601
+ padding=(get_padding(kernel_size, 1), 0),
602
+ )
603
+ ),
604
+ norm_f(
605
+ Conv2d(
606
+ 512,
607
+ 1024,
608
+ (kernel_size, 1),
609
+ (stride, 1),
610
+ padding=(get_padding(kernel_size, 1), 0),
611
+ )
612
+ ),
613
+ norm_f(
614
+ Conv2d(
615
+ 1024,
616
+ 1024,
617
+ (kernel_size, 1),
618
+ 1,
619
+ padding=(get_padding(kernel_size, 1), 0),
620
+ )
621
+ ),
622
+ ]
623
+ )
624
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
625
+
626
+ def forward(self, x):
627
+ fmap = []
628
+
629
+ # 1d to 2d
630
+ b, c, t = x.shape
631
+ if t % self.period != 0: # pad first
632
+ n_pad = self.period - (t % self.period)
633
+ x = F.pad(x, (0, n_pad), "reflect")
634
+ t = t + n_pad
635
+ x = x.view(b, c, t // self.period, self.period)
636
+
637
+ for layer in self.convs:
638
+ x = layer(x)
639
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
640
+ fmap.append(x)
641
+ x = self.conv_post(x)
642
+ fmap.append(x)
643
+ x = torch.flatten(x, 1, -1)
644
+
645
+ return x, fmap
646
+
647
+
648
+ class DiscriminatorS(torch.nn.Module):
649
+ def __init__(self, use_spectral_norm=False):
650
+ super(DiscriminatorS, self).__init__()
651
+ norm_f = weight_norm if use_spectral_norm is False else spectral_norm
652
+ self.convs = nn.ModuleList(
653
+ [
654
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
655
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
656
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
657
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
658
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
659
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
660
+ ]
661
+ )
662
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
663
+
664
+ def forward(self, x):
665
+ fmap = []
666
+
667
+ for layer in self.convs:
668
+ x = layer(x)
669
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
670
+ fmap.append(x)
671
+ x = self.conv_post(x)
672
+ fmap.append(x)
673
+ x = torch.flatten(x, 1, -1)
674
+
675
+ return x, fmap
676
+
677
+
678
+ class MultiPeriodDiscriminator(torch.nn.Module):
679
+ def __init__(self, use_spectral_norm=False):
680
+ super(MultiPeriodDiscriminator, self).__init__()
681
+ periods = [2, 3, 5, 7, 11]
682
+
683
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
684
+ discs = discs + [
685
+ DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
686
+ ]
687
+ self.discriminators = nn.ModuleList(discs)
688
+
689
+ def forward(self, y, y_hat):
690
+ y_d_rs = []
691
+ y_d_gs = []
692
+ fmap_rs = []
693
+ fmap_gs = []
694
+ for i, d in enumerate(self.discriminators):
695
+ y_d_r, fmap_r = d(y)
696
+ y_d_g, fmap_g = d(y_hat)
697
+ y_d_rs.append(y_d_r)
698
+ y_d_gs.append(y_d_g)
699
+ fmap_rs.append(fmap_r)
700
+ fmap_gs.append(fmap_g)
701
+
702
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
703
+
704
+
705
+ class WavLMDiscriminator(nn.Module):
706
+ """docstring for Discriminator."""
707
+
708
+ def __init__(
709
+ self, slm_hidden=768, slm_layers=13, initial_channel=64, use_spectral_norm=False
710
+ ):
711
+ super(WavLMDiscriminator, self).__init__()
712
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
713
+ self.pre = norm_f(
714
+ Conv1d(slm_hidden * slm_layers, initial_channel, 1, 1, padding=0)
715
+ )
716
+
717
+ self.convs = nn.ModuleList(
718
+ [
719
+ norm_f(
720
+ nn.Conv1d(
721
+ initial_channel, initial_channel * 2, kernel_size=5, padding=2
722
+ )
723
+ ),
724
+ norm_f(
725
+ nn.Conv1d(
726
+ initial_channel * 2,
727
+ initial_channel * 4,
728
+ kernel_size=5,
729
+ padding=2,
730
+ )
731
+ ),
732
+ norm_f(
733
+ nn.Conv1d(initial_channel * 4, initial_channel * 4, 5, 1, padding=2)
734
+ ),
735
+ ]
736
+ )
737
+
738
+ self.conv_post = norm_f(Conv1d(initial_channel * 4, 1, 3, 1, padding=1))
739
+
740
+ def forward(self, x):
741
+ x = self.pre(x)
742
+
743
+ fmap = []
744
+ for l in self.convs:
745
+ x = l(x)
746
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
747
+ fmap.append(x)
748
+ x = self.conv_post(x)
749
+ x = torch.flatten(x, 1, -1)
750
+
751
+ return x
752
+
753
+
754
+ class ReferenceEncoder(nn.Module):
755
+ """
756
+ inputs --- [N, Ty/r, n_mels*r] mels
757
+ outputs --- [N, ref_enc_gru_size]
758
+ """
759
+
760
+ def __init__(self, spec_channels, gin_channels=0):
761
+ super().__init__()
762
+ self.spec_channels = spec_channels
763
+ ref_enc_filters = [32, 32, 64, 64, 128, 128]
764
+ K = len(ref_enc_filters)
765
+ filters = [1] + ref_enc_filters
766
+ convs = [
767
+ weight_norm(
768
+ nn.Conv2d(
769
+ in_channels=filters[i],
770
+ out_channels=filters[i + 1],
771
+ kernel_size=(3, 3),
772
+ stride=(2, 2),
773
+ padding=(1, 1),
774
+ )
775
+ )
776
+ for i in range(K)
777
+ ]
778
+ self.convs = nn.ModuleList(convs)
779
+ # self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)]) # noqa: E501
780
+
781
+ out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K)
782
+ self.gru = nn.GRU(
783
+ input_size=ref_enc_filters[-1] * out_channels,
784
+ hidden_size=256 // 2,
785
+ batch_first=True,
786
+ )
787
+ self.proj = nn.Linear(128, gin_channels)
788
+
789
+ def forward(self, inputs, mask=None):
790
+ N = inputs.size(0)
791
+ out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs]
792
+ for conv in self.convs:
793
+ out = conv(out)
794
+ # out = wn(out)
795
+ out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K]
796
+
797
+ out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
798
+ T = out.size(1)
799
+ N = out.size(0)
800
+ out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
801
+
802
+ self.gru.flatten_parameters()
803
+ memory, out = self.gru(out) # out --- [1, N, 128]
804
+
805
+ return self.proj(out.squeeze(0))
806
+
807
+ def calculate_channels(self, L, kernel_size, stride, pad, n_convs):
808
+ for i in range(n_convs):
809
+ L = (L - kernel_size + 2 * pad) // stride + 1
810
+ return L
811
+
812
+
813
+ class SynthesizerTrn(nn.Module):
814
+ """
815
+ Synthesizer for Training
816
+ """
817
+
818
+ def __init__(
819
+ self,
820
+ n_vocab,
821
+ spec_channels,
822
+ segment_size,
823
+ inter_channels,
824
+ hidden_channels,
825
+ filter_channels,
826
+ n_heads,
827
+ n_layers,
828
+ kernel_size,
829
+ p_dropout,
830
+ resblock,
831
+ resblock_kernel_sizes,
832
+ resblock_dilation_sizes,
833
+ upsample_rates,
834
+ upsample_initial_channel,
835
+ upsample_kernel_sizes,
836
+ n_speakers=256,
837
+ gin_channels=256,
838
+ use_sdp=True,
839
+ n_flow_layer=4,
840
+ n_layers_trans_flow=4,
841
+ flow_share_parameter=False,
842
+ use_transformer_flow=True,
843
+ **kwargs
844
+ ):
845
+ super().__init__()
846
+ self.n_vocab = n_vocab
847
+ self.spec_channels = spec_channels
848
+ self.inter_channels = inter_channels
849
+ self.hidden_channels = hidden_channels
850
+ self.filter_channels = filter_channels
851
+ self.n_heads = n_heads
852
+ self.n_layers = n_layers
853
+ self.kernel_size = kernel_size
854
+ self.p_dropout = p_dropout
855
+ self.resblock = resblock
856
+ self.resblock_kernel_sizes = resblock_kernel_sizes
857
+ self.resblock_dilation_sizes = resblock_dilation_sizes
858
+ self.upsample_rates = upsample_rates
859
+ self.upsample_initial_channel = upsample_initial_channel
860
+ self.upsample_kernel_sizes = upsample_kernel_sizes
861
+ self.segment_size = segment_size
862
+ self.n_speakers = n_speakers
863
+ self.gin_channels = gin_channels
864
+ self.n_layers_trans_flow = n_layers_trans_flow
865
+ self.use_spk_conditioned_encoder = kwargs.get(
866
+ "use_spk_conditioned_encoder", True
867
+ )
868
+ self.use_sdp = use_sdp
869
+ self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False)
870
+ self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01)
871
+ self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6)
872
+ self.current_mas_noise_scale = self.mas_noise_scale_initial
873
+ if self.use_spk_conditioned_encoder and gin_channels > 0:
874
+ self.enc_gin_channels = gin_channels
875
+ self.enc_p = TextEncoder(
876
+ n_vocab,
877
+ inter_channels,
878
+ hidden_channels,
879
+ filter_channels,
880
+ n_heads,
881
+ n_layers,
882
+ kernel_size,
883
+ p_dropout,
884
+ gin_channels=self.enc_gin_channels,
885
+ )
886
+ self.dec = Generator(
887
+ inter_channels,
888
+ resblock,
889
+ resblock_kernel_sizes,
890
+ resblock_dilation_sizes,
891
+ upsample_rates,
892
+ upsample_initial_channel,
893
+ upsample_kernel_sizes,
894
+ gin_channels=gin_channels,
895
+ )
896
+ self.enc_q = PosteriorEncoder(
897
+ spec_channels,
898
+ inter_channels,
899
+ hidden_channels,
900
+ 5,
901
+ 1,
902
+ 16,
903
+ gin_channels=gin_channels,
904
+ )
905
+ if use_transformer_flow:
906
+ self.flow = TransformerCouplingBlock(
907
+ inter_channels,
908
+ hidden_channels,
909
+ filter_channels,
910
+ n_heads,
911
+ n_layers_trans_flow,
912
+ 5,
913
+ p_dropout,
914
+ n_flow_layer,
915
+ gin_channels=gin_channels,
916
+ share_parameter=flow_share_parameter,
917
+ )
918
+ else:
919
+ self.flow = ResidualCouplingBlock(
920
+ inter_channels,
921
+ hidden_channels,
922
+ 5,
923
+ 1,
924
+ n_flow_layer,
925
+ gin_channels=gin_channels,
926
+ )
927
+ self.sdp = StochasticDurationPredictor(
928
+ hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels
929
+ )
930
+ self.dp = DurationPredictor(
931
+ hidden_channels, 256, 3, 0.5, gin_channels=gin_channels
932
+ )
933
+
934
+ if n_speakers >= 1:
935
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
936
+ else:
937
+ self.ref_enc = ReferenceEncoder(spec_channels, gin_channels)
938
+
939
+ def forward(
940
+ self,
941
+ x,
942
+ x_lengths,
943
+ y,
944
+ y_lengths,
945
+ sid,
946
+ tone,
947
+ language,
948
+ bert,
949
+ ja_bert,
950
+ en_bert,
951
+ ):
952
+ if self.n_speakers > 0:
953
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
954
+ else:
955
+ g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
956
+ x, m_p, logs_p, x_mask = self.enc_p(
957
+ x, x_lengths, tone, language, bert, ja_bert, en_bert, g=g
958
+ )
959
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
960
+ z_p = self.flow(z, y_mask, g=g)
961
+
962
+ with torch.no_grad():
963
+ # negative cross-entropy
964
+ s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
965
+ neg_cent1 = torch.sum(
966
+ -0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True
967
+ ) # [b, 1, t_s]
968
+ neg_cent2 = torch.matmul(
969
+ -0.5 * (z_p**2).transpose(1, 2), s_p_sq_r
970
+ ) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
971
+ neg_cent3 = torch.matmul(
972
+ z_p.transpose(1, 2), (m_p * s_p_sq_r)
973
+ ) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
974
+ neg_cent4 = torch.sum(
975
+ -0.5 * (m_p**2) * s_p_sq_r, [1], keepdim=True
976
+ ) # [b, 1, t_s]
977
+ neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
978
+ if self.use_noise_scaled_mas:
979
+ epsilon = (
980
+ torch.std(neg_cent)
981
+ * torch.randn_like(neg_cent)
982
+ * self.current_mas_noise_scale
983
+ )
984
+ neg_cent = neg_cent + epsilon
985
+
986
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
987
+ attn = (
988
+ monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1))
989
+ .unsqueeze(1)
990
+ .detach()
991
+ )
992
+
993
+ w = attn.sum(2)
994
+
995
+ l_length_sdp = self.sdp(x, x_mask, w, g=g)
996
+ l_length_sdp = l_length_sdp / torch.sum(x_mask)
997
+
998
+ logw_ = torch.log(w + 1e-6) * x_mask
999
+ logw = self.dp(x, x_mask, g=g)
1000
+ logw_sdp = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=1.0)
1001
+ l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(
1002
+ x_mask
1003
+ ) # for averaging
1004
+ l_length_sdp += torch.sum((logw_sdp - logw_) ** 2, [1, 2]) / torch.sum(x_mask)
1005
+
1006
+ l_length = l_length_dp + l_length_sdp
1007
+
1008
+ # expand prior
1009
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
1010
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
1011
+
1012
+ z_slice, ids_slice = commons.rand_slice_segments(
1013
+ z, y_lengths, self.segment_size
1014
+ )
1015
+ o = self.dec(z_slice, g=g)
1016
+ return (
1017
+ o,
1018
+ l_length,
1019
+ attn,
1020
+ ids_slice,
1021
+ x_mask,
1022
+ y_mask,
1023
+ (z, z_p, m_p, logs_p, m_q, logs_q),
1024
+ (x, logw, logw_, logw_sdp),
1025
+ g,
1026
+ )
1027
+
1028
+ def infer(
1029
+ self,
1030
+ x,
1031
+ x_lengths,
1032
+ sid,
1033
+ tone,
1034
+ language,
1035
+ bert,
1036
+ ja_bert,
1037
+ en_bert,
1038
+ noise_scale=0.667,
1039
+ length_scale=1,
1040
+ noise_scale_w=0.8,
1041
+ max_len=None,
1042
+ sdp_ratio=0,
1043
+ y=None,
1044
+ ):
1045
+ # x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert)
1046
+ # g = self.gst(y)
1047
+ if self.n_speakers > 0:
1048
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
1049
+ else:
1050
+ g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
1051
+ x, m_p, logs_p, x_mask = self.enc_p(
1052
+ x, x_lengths, tone, language, bert, ja_bert, en_bert, g=g
1053
+ )
1054
+ logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (
1055
+ sdp_ratio
1056
+ ) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio)
1057
+ w = torch.exp(logw) * x_mask * length_scale
1058
+ w_ceil = torch.ceil(w)
1059
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
1060
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(
1061
+ x_mask.dtype
1062
+ )
1063
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
1064
+ attn = commons.generate_path(w_ceil, attn_mask)
1065
+
1066
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(
1067
+ 1, 2
1068
+ ) # [b, t', t], [b, t, d] -> [b, d, t']
1069
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(
1070
+ 1, 2
1071
+ ) # [b, t', t], [b, t, d] -> [b, d, t']
1072
+
1073
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
1074
+ z = self.flow(z_p, y_mask, g=g, reverse=True)
1075
+ o = self.dec((z * y_mask)[:, :, :max_len], g=g)
1076
+ return o, attn, y_mask, (z, z_p, m_p, logs_p)
modules.py ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ from torch.nn import Conv1d
7
+ from torch.nn.utils import weight_norm, remove_weight_norm
8
+
9
+ import commons
10
+ from commons import init_weights, get_padding
11
+ from transforms import piecewise_rational_quadratic_transform
12
+ from attentions import Encoder
13
+
14
+ LRELU_SLOPE = 0.1
15
+
16
+
17
+ class LayerNorm(nn.Module):
18
+ def __init__(self, channels, eps=1e-5):
19
+ super().__init__()
20
+ self.channels = channels
21
+ self.eps = eps
22
+
23
+ self.gamma = nn.Parameter(torch.ones(channels))
24
+ self.beta = nn.Parameter(torch.zeros(channels))
25
+
26
+ def forward(self, x):
27
+ x = x.transpose(1, -1)
28
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
29
+ return x.transpose(1, -1)
30
+
31
+
32
+ class ConvReluNorm(nn.Module):
33
+ def __init__(
34
+ self,
35
+ in_channels,
36
+ hidden_channels,
37
+ out_channels,
38
+ kernel_size,
39
+ n_layers,
40
+ p_dropout,
41
+ ):
42
+ super().__init__()
43
+ self.in_channels = in_channels
44
+ self.hidden_channels = hidden_channels
45
+ self.out_channels = out_channels
46
+ self.kernel_size = kernel_size
47
+ self.n_layers = n_layers
48
+ self.p_dropout = p_dropout
49
+ assert n_layers > 1, "Number of layers should be larger than 0."
50
+
51
+ self.conv_layers = nn.ModuleList()
52
+ self.norm_layers = nn.ModuleList()
53
+ self.conv_layers.append(
54
+ nn.Conv1d(
55
+ in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
56
+ )
57
+ )
58
+ self.norm_layers.append(LayerNorm(hidden_channels))
59
+ self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
60
+ for _ in range(n_layers - 1):
61
+ self.conv_layers.append(
62
+ nn.Conv1d(
63
+ hidden_channels,
64
+ hidden_channels,
65
+ kernel_size,
66
+ padding=kernel_size // 2,
67
+ )
68
+ )
69
+ self.norm_layers.append(LayerNorm(hidden_channels))
70
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
71
+ self.proj.weight.data.zero_()
72
+ self.proj.bias.data.zero_()
73
+
74
+ def forward(self, x, x_mask):
75
+ x_org = x
76
+ for i in range(self.n_layers):
77
+ x = self.conv_layers[i](x * x_mask)
78
+ x = self.norm_layers[i](x)
79
+ x = self.relu_drop(x)
80
+ x = x_org + self.proj(x)
81
+ return x * x_mask
82
+
83
+
84
+ class DDSConv(nn.Module):
85
+ """
86
+ Dialted and Depth-Separable Convolution
87
+ """
88
+
89
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
90
+ super().__init__()
91
+ self.channels = channels
92
+ self.kernel_size = kernel_size
93
+ self.n_layers = n_layers
94
+ self.p_dropout = p_dropout
95
+
96
+ self.drop = nn.Dropout(p_dropout)
97
+ self.convs_sep = nn.ModuleList()
98
+ self.convs_1x1 = nn.ModuleList()
99
+ self.norms_1 = nn.ModuleList()
100
+ self.norms_2 = nn.ModuleList()
101
+ for i in range(n_layers):
102
+ dilation = kernel_size**i
103
+ padding = (kernel_size * dilation - dilation) // 2
104
+ self.convs_sep.append(
105
+ nn.Conv1d(
106
+ channels,
107
+ channels,
108
+ kernel_size,
109
+ groups=channels,
110
+ dilation=dilation,
111
+ padding=padding,
112
+ )
113
+ )
114
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
115
+ self.norms_1.append(LayerNorm(channels))
116
+ self.norms_2.append(LayerNorm(channels))
117
+
118
+ def forward(self, x, x_mask, g=None):
119
+ if g is not None:
120
+ x = x + g
121
+ for i in range(self.n_layers):
122
+ y = self.convs_sep[i](x * x_mask)
123
+ y = self.norms_1[i](y)
124
+ y = F.gelu(y)
125
+ y = self.convs_1x1[i](y)
126
+ y = self.norms_2[i](y)
127
+ y = F.gelu(y)
128
+ y = self.drop(y)
129
+ x = x + y
130
+ return x * x_mask
131
+
132
+
133
+ class WN(torch.nn.Module):
134
+ def __init__(
135
+ self,
136
+ hidden_channels,
137
+ kernel_size,
138
+ dilation_rate,
139
+ n_layers,
140
+ gin_channels=0,
141
+ p_dropout=0,
142
+ ):
143
+ super(WN, self).__init__()
144
+ assert kernel_size % 2 == 1
145
+ self.hidden_channels = hidden_channels
146
+ self.kernel_size = (kernel_size,)
147
+ self.dilation_rate = dilation_rate
148
+ self.n_layers = n_layers
149
+ self.gin_channels = gin_channels
150
+ self.p_dropout = p_dropout
151
+
152
+ self.in_layers = torch.nn.ModuleList()
153
+ self.res_skip_layers = torch.nn.ModuleList()
154
+ self.drop = nn.Dropout(p_dropout)
155
+
156
+ if gin_channels != 0:
157
+ cond_layer = torch.nn.Conv1d(
158
+ gin_channels, 2 * hidden_channels * n_layers, 1
159
+ )
160
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
161
+
162
+ for i in range(n_layers):
163
+ dilation = dilation_rate**i
164
+ padding = int((kernel_size * dilation - dilation) / 2)
165
+ in_layer = torch.nn.Conv1d(
166
+ hidden_channels,
167
+ 2 * hidden_channels,
168
+ kernel_size,
169
+ dilation=dilation,
170
+ padding=padding,
171
+ )
172
+ in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
173
+ self.in_layers.append(in_layer)
174
+
175
+ # last one is not necessary
176
+ if i < n_layers - 1:
177
+ res_skip_channels = 2 * hidden_channels
178
+ else:
179
+ res_skip_channels = hidden_channels
180
+
181
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
182
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
183
+ self.res_skip_layers.append(res_skip_layer)
184
+
185
+ def forward(self, x, x_mask, g=None, **kwargs):
186
+ output = torch.zeros_like(x)
187
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
188
+
189
+ if g is not None:
190
+ g = self.cond_layer(g)
191
+
192
+ for i in range(self.n_layers):
193
+ x_in = self.in_layers[i](x)
194
+ if g is not None:
195
+ cond_offset = i * 2 * self.hidden_channels
196
+ g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
197
+ else:
198
+ g_l = torch.zeros_like(x_in)
199
+
200
+ acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
201
+ acts = self.drop(acts)
202
+
203
+ res_skip_acts = self.res_skip_layers[i](acts)
204
+ if i < self.n_layers - 1:
205
+ res_acts = res_skip_acts[:, : self.hidden_channels, :]
206
+ x = (x + res_acts) * x_mask
207
+ output = output + res_skip_acts[:, self.hidden_channels :, :]
208
+ else:
209
+ output = output + res_skip_acts
210
+ return output * x_mask
211
+
212
+ def remove_weight_norm(self):
213
+ if self.gin_channels != 0:
214
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
215
+ for l in self.in_layers:
216
+ torch.nn.utils.remove_weight_norm(l)
217
+ for l in self.res_skip_layers:
218
+ torch.nn.utils.remove_weight_norm(l)
219
+
220
+
221
+ class ResBlock1(torch.nn.Module):
222
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
223
+ super(ResBlock1, self).__init__()
224
+ self.convs1 = nn.ModuleList(
225
+ [
226
+ weight_norm(
227
+ Conv1d(
228
+ channels,
229
+ channels,
230
+ kernel_size,
231
+ 1,
232
+ dilation=dilation[0],
233
+ padding=get_padding(kernel_size, dilation[0]),
234
+ )
235
+ ),
236
+ weight_norm(
237
+ Conv1d(
238
+ channels,
239
+ channels,
240
+ kernel_size,
241
+ 1,
242
+ dilation=dilation[1],
243
+ padding=get_padding(kernel_size, dilation[1]),
244
+ )
245
+ ),
246
+ weight_norm(
247
+ Conv1d(
248
+ channels,
249
+ channels,
250
+ kernel_size,
251
+ 1,
252
+ dilation=dilation[2],
253
+ padding=get_padding(kernel_size, dilation[2]),
254
+ )
255
+ ),
256
+ ]
257
+ )
258
+ self.convs1.apply(init_weights)
259
+
260
+ self.convs2 = nn.ModuleList(
261
+ [
262
+ weight_norm(
263
+ Conv1d(
264
+ channels,
265
+ channels,
266
+ kernel_size,
267
+ 1,
268
+ dilation=1,
269
+ padding=get_padding(kernel_size, 1),
270
+ )
271
+ ),
272
+ weight_norm(
273
+ Conv1d(
274
+ channels,
275
+ channels,
276
+ kernel_size,
277
+ 1,
278
+ dilation=1,
279
+ padding=get_padding(kernel_size, 1),
280
+ )
281
+ ),
282
+ weight_norm(
283
+ Conv1d(
284
+ channels,
285
+ channels,
286
+ kernel_size,
287
+ 1,
288
+ dilation=1,
289
+ padding=get_padding(kernel_size, 1),
290
+ )
291
+ ),
292
+ ]
293
+ )
294
+ self.convs2.apply(init_weights)
295
+
296
+ def forward(self, x, x_mask=None):
297
+ for c1, c2 in zip(self.convs1, self.convs2):
298
+ xt = F.leaky_relu(x, LRELU_SLOPE)
299
+ if x_mask is not None:
300
+ xt = xt * x_mask
301
+ xt = c1(xt)
302
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
303
+ if x_mask is not None:
304
+ xt = xt * x_mask
305
+ xt = c2(xt)
306
+ x = xt + x
307
+ if x_mask is not None:
308
+ x = x * x_mask
309
+ return x
310
+
311
+ def remove_weight_norm(self):
312
+ for l in self.convs1:
313
+ remove_weight_norm(l)
314
+ for l in self.convs2:
315
+ remove_weight_norm(l)
316
+
317
+
318
+ class ResBlock2(torch.nn.Module):
319
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
320
+ super(ResBlock2, self).__init__()
321
+ self.convs = nn.ModuleList(
322
+ [
323
+ weight_norm(
324
+ Conv1d(
325
+ channels,
326
+ channels,
327
+ kernel_size,
328
+ 1,
329
+ dilation=dilation[0],
330
+ padding=get_padding(kernel_size, dilation[0]),
331
+ )
332
+ ),
333
+ weight_norm(
334
+ Conv1d(
335
+ channels,
336
+ channels,
337
+ kernel_size,
338
+ 1,
339
+ dilation=dilation[1],
340
+ padding=get_padding(kernel_size, dilation[1]),
341
+ )
342
+ ),
343
+ ]
344
+ )
345
+ self.convs.apply(init_weights)
346
+
347
+ def forward(self, x, x_mask=None):
348
+ for c in self.convs:
349
+ xt = F.leaky_relu(x, LRELU_SLOPE)
350
+ if x_mask is not None:
351
+ xt = xt * x_mask
352
+ xt = c(xt)
353
+ x = xt + x
354
+ if x_mask is not None:
355
+ x = x * x_mask
356
+ return x
357
+
358
+ def remove_weight_norm(self):
359
+ for l in self.convs:
360
+ remove_weight_norm(l)
361
+
362
+
363
+ class Log(nn.Module):
364
+ def forward(self, x, x_mask, reverse=False, **kwargs):
365
+ if not reverse:
366
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
367
+ logdet = torch.sum(-y, [1, 2])
368
+ return y, logdet
369
+ else:
370
+ x = torch.exp(x) * x_mask
371
+ return x
372
+
373
+
374
+ class Flip(nn.Module):
375
+ def forward(self, x, *args, reverse=False, **kwargs):
376
+ x = torch.flip(x, [1])
377
+ if not reverse:
378
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
379
+ return x, logdet
380
+ else:
381
+ return x
382
+
383
+
384
+ class ElementwiseAffine(nn.Module):
385
+ def __init__(self, channels):
386
+ super().__init__()
387
+ self.channels = channels
388
+ self.m = nn.Parameter(torch.zeros(channels, 1))
389
+ self.logs = nn.Parameter(torch.zeros(channels, 1))
390
+
391
+ def forward(self, x, x_mask, reverse=False, **kwargs):
392
+ if not reverse:
393
+ y = self.m + torch.exp(self.logs) * x
394
+ y = y * x_mask
395
+ logdet = torch.sum(self.logs * x_mask, [1, 2])
396
+ return y, logdet
397
+ else:
398
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
399
+ return x
400
+
401
+
402
+ class ResidualCouplingLayer(nn.Module):
403
+ def __init__(
404
+ self,
405
+ channels,
406
+ hidden_channels,
407
+ kernel_size,
408
+ dilation_rate,
409
+ n_layers,
410
+ p_dropout=0,
411
+ gin_channels=0,
412
+ mean_only=False,
413
+ ):
414
+ assert channels % 2 == 0, "channels should be divisible by 2"
415
+ super().__init__()
416
+ self.channels = channels
417
+ self.hidden_channels = hidden_channels
418
+ self.kernel_size = kernel_size
419
+ self.dilation_rate = dilation_rate
420
+ self.n_layers = n_layers
421
+ self.half_channels = channels // 2
422
+ self.mean_only = mean_only
423
+
424
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
425
+ self.enc = WN(
426
+ hidden_channels,
427
+ kernel_size,
428
+ dilation_rate,
429
+ n_layers,
430
+ p_dropout=p_dropout,
431
+ gin_channels=gin_channels,
432
+ )
433
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
434
+ self.post.weight.data.zero_()
435
+ self.post.bias.data.zero_()
436
+
437
+ def forward(self, x, x_mask, g=None, reverse=False):
438
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
439
+ h = self.pre(x0) * x_mask
440
+ h = self.enc(h, x_mask, g=g)
441
+ stats = self.post(h) * x_mask
442
+ if not self.mean_only:
443
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
444
+ else:
445
+ m = stats
446
+ logs = torch.zeros_like(m)
447
+
448
+ if not reverse:
449
+ x1 = m + x1 * torch.exp(logs) * x_mask
450
+ x = torch.cat([x0, x1], 1)
451
+ logdet = torch.sum(logs, [1, 2])
452
+ return x, logdet
453
+ else:
454
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
455
+ x = torch.cat([x0, x1], 1)
456
+ return x
457
+
458
+
459
+ class ConvFlow(nn.Module):
460
+ def __init__(
461
+ self,
462
+ in_channels,
463
+ filter_channels,
464
+ kernel_size,
465
+ n_layers,
466
+ num_bins=10,
467
+ tail_bound=5.0,
468
+ ):
469
+ super().__init__()
470
+ self.in_channels = in_channels
471
+ self.filter_channels = filter_channels
472
+ self.kernel_size = kernel_size
473
+ self.n_layers = n_layers
474
+ self.num_bins = num_bins
475
+ self.tail_bound = tail_bound
476
+ self.half_channels = in_channels // 2
477
+
478
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
479
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
480
+ self.proj = nn.Conv1d(
481
+ filter_channels, self.half_channels * (num_bins * 3 - 1), 1
482
+ )
483
+ self.proj.weight.data.zero_()
484
+ self.proj.bias.data.zero_()
485
+
486
+ def forward(self, x, x_mask, g=None, reverse=False):
487
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
488
+ h = self.pre(x0)
489
+ h = self.convs(h, x_mask, g=g)
490
+ h = self.proj(h) * x_mask
491
+
492
+ b, c, t = x0.shape
493
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
494
+
495
+ unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
496
+ unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
497
+ self.filter_channels
498
+ )
499
+ unnormalized_derivatives = h[..., 2 * self.num_bins :]
500
+
501
+ x1, logabsdet = piecewise_rational_quadratic_transform(
502
+ x1,
503
+ unnormalized_widths,
504
+ unnormalized_heights,
505
+ unnormalized_derivatives,
506
+ inverse=reverse,
507
+ tails="linear",
508
+ tail_bound=self.tail_bound,
509
+ )
510
+
511
+ x = torch.cat([x0, x1], 1) * x_mask
512
+ logdet = torch.sum(logabsdet * x_mask, [1, 2])
513
+ if not reverse:
514
+ return x, logdet
515
+ else:
516
+ return x
517
+
518
+
519
+ class TransformerCouplingLayer(nn.Module):
520
+ def __init__(
521
+ self,
522
+ channels,
523
+ hidden_channels,
524
+ kernel_size,
525
+ n_layers,
526
+ n_heads,
527
+ p_dropout=0,
528
+ filter_channels=0,
529
+ mean_only=False,
530
+ wn_sharing_parameter=None,
531
+ gin_channels=0,
532
+ ):
533
+ assert channels % 2 == 0, "channels should be divisible by 2"
534
+ super().__init__()
535
+ self.channels = channels
536
+ self.hidden_channels = hidden_channels
537
+ self.kernel_size = kernel_size
538
+ self.n_layers = n_layers
539
+ self.half_channels = channels // 2
540
+ self.mean_only = mean_only
541
+
542
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
543
+ self.enc = (
544
+ Encoder(
545
+ hidden_channels,
546
+ filter_channels,
547
+ n_heads,
548
+ n_layers,
549
+ kernel_size,
550
+ p_dropout,
551
+ isflow=True,
552
+ gin_channels=gin_channels,
553
+ )
554
+ if wn_sharing_parameter is None
555
+ else wn_sharing_parameter
556
+ )
557
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
558
+ self.post.weight.data.zero_()
559
+ self.post.bias.data.zero_()
560
+
561
+ def forward(self, x, x_mask, g=None, reverse=False):
562
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
563
+ h = self.pre(x0) * x_mask
564
+ h = self.enc(h, x_mask, g=g)
565
+ stats = self.post(h) * x_mask
566
+ if not self.mean_only:
567
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
568
+ else:
569
+ m = stats
570
+ logs = torch.zeros_like(m)
571
+
572
+ if not reverse:
573
+ x1 = m + x1 * torch.exp(logs) * x_mask
574
+ x = torch.cat([x0, x1], 1)
575
+ logdet = torch.sum(logs, [1, 2])
576
+ return x, logdet
577
+ else:
578
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
579
+ x = torch.cat([x0, x1], 1)
580
+ return x
581
+
582
+ x1, logabsdet = piecewise_rational_quadratic_transform(
583
+ x1,
584
+ unnormalized_widths,
585
+ unnormalized_heights,
586
+ unnormalized_derivatives,
587
+ inverse=reverse,
588
+ tails="linear",
589
+ tail_bound=self.tail_bound,
590
+ )
591
+
592
+ x = torch.cat([x0, x1], 1) * x_mask
593
+ logdet = torch.sum(logabsdet * x_mask, [1, 2])
594
+ if not reverse:
595
+ return x, logdet
596
+ else:
597
+ return x
onnx_infer.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from onnx_modules.V220_OnnxInference import OnnxInferenceSession
2
+ import numpy as np
3
+ Session = OnnxInferenceSession(
4
+ {
5
+ "enc" : "onnx/BertVits2.2PT/BertVits2.2PT_enc_p.onnx",
6
+ "emb_g" : "onnx/BertVits2.2PT/BertVits2.2PT_emb.onnx",
7
+ "dp" : "onnx/BertVits2.2PT/BertVits2.2PT_dp.onnx",
8
+ "sdp" : "onnx/BertVits2.2PT/BertVits2.2PT_sdp.onnx",
9
+ "flow" : "onnx/BertVits2.2PT/BertVits2.2PT_flow.onnx",
10
+ "dec" : "onnx/BertVits2.2PT/BertVits2.2PT_dec.onnx"
11
+ },
12
+ Providers = ["CPUExecutionProvider"]
13
+ )
14
+
15
+ #这里的输入和原版是一样的,只需要在原版预处理结果出来之后加上.numpy()即可
16
+ x = np.array(
17
+ [
18
+ 0,
19
+ 97,
20
+ 0,
21
+ 8,
22
+ 0,
23
+ 78,
24
+ 0,
25
+ 8,
26
+ 0,
27
+ 76,
28
+ 0,
29
+ 37,
30
+ 0,
31
+ 40,
32
+ 0,
33
+ 97,
34
+ 0,
35
+ 8,
36
+ 0,
37
+ 23,
38
+ 0,
39
+ 8,
40
+ 0,
41
+ 74,
42
+ 0,
43
+ 26,
44
+ 0,
45
+ 104,
46
+ 0,
47
+ ]
48
+ )
49
+ tone = np.zeros_like(x)
50
+ language = np.zeros_like(x)
51
+ sid = np.array([0])
52
+ bert = np.random.randn(x.shape[0], 1024)
53
+ ja_bert = np.random.randn(x.shape[0], 1024)
54
+ en_bert = np.random.randn(x.shape[0], 1024)
55
+ emo = np.random.randn(512, 1)
56
+
57
+ audio = Session(
58
+ x,
59
+ tone,
60
+ language,
61
+ bert,
62
+ ja_bert,
63
+ en_bert,
64
+ emo,
65
+ sid
66
+ )
67
+
68
+ print(audio)
preprocess_text.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from collections import defaultdict
3
+ from random import shuffle
4
+ from typing import Optional
5
+ import os
6
+
7
+ from tqdm import tqdm
8
+ import click
9
+ from text.cleaner import clean_text
10
+ from config import config
11
+ from infer import latest_version
12
+
13
+ preprocess_text_config = config.preprocess_text_config
14
+
15
+
16
+ @click.command()
17
+ @click.option(
18
+ "--transcription-path",
19
+ default=preprocess_text_config.transcription_path,
20
+ type=click.Path(exists=True, file_okay=True, dir_okay=False),
21
+ )
22
+ @click.option("--cleaned-path", default=preprocess_text_config.cleaned_path)
23
+ @click.option("--train-path", default=preprocess_text_config.train_path)
24
+ @click.option("--val-path", default=preprocess_text_config.val_path)
25
+ @click.option(
26
+ "--config-path",
27
+ default=preprocess_text_config.config_path,
28
+ type=click.Path(exists=True, file_okay=True, dir_okay=False),
29
+ )
30
+ @click.option("--val-per-lang", default=preprocess_text_config.val_per_lang)
31
+ @click.option("--max-val-total", default=preprocess_text_config.max_val_total)
32
+ @click.option("--clean/--no-clean", default=preprocess_text_config.clean)
33
+ @click.option("-y", "--yml_config")
34
+ def preprocess(
35
+ transcription_path: str,
36
+ cleaned_path: Optional[str],
37
+ train_path: str,
38
+ val_path: str,
39
+ config_path: str,
40
+ val_per_lang: int,
41
+ max_val_total: int,
42
+ clean: bool,
43
+ yml_config: str, # 这个不要删
44
+ ):
45
+ if cleaned_path == "" or cleaned_path is None:
46
+ cleaned_path = transcription_path + ".cleaned"
47
+
48
+ if clean:
49
+ with open(cleaned_path, "w", encoding="utf-8") as out_file:
50
+ with open(transcription_path, "r", encoding="utf-8") as trans_file:
51
+ lines = trans_file.readlines()
52
+ # print(lines, ' ', len(lines))
53
+ if len(lines) != 0:
54
+ for line in tqdm(lines):
55
+ try:
56
+ utt, spk, language, text = line.strip().split("|")
57
+ norm_text, phones, tones, word2ph = clean_text(
58
+ text, language
59
+ )
60
+ out_file.write(
61
+ "{}|{}|{}|{}|{}|{}|{}\n".format(
62
+ utt,
63
+ spk,
64
+ language,
65
+ norm_text,
66
+ " ".join(phones),
67
+ " ".join([str(i) for i in tones]),
68
+ " ".join([str(i) for i in word2ph]),
69
+ )
70
+ )
71
+ except Exception as e:
72
+ print(line)
73
+ print(f"生成训练集和验证集时发生错误!, 详细信息:\n{e}")
74
+
75
+ transcription_path = cleaned_path
76
+ spk_utt_map = defaultdict(list)
77
+ spk_id_map = {}
78
+ current_sid = 0
79
+
80
+ with open(transcription_path, "r", encoding="utf-8") as f:
81
+ audioPaths = set()
82
+ countSame = 0
83
+ countNotFound = 0
84
+ for line in f.readlines():
85
+ utt, spk, language, text, phones, tones, word2ph = line.strip().split("|")
86
+ if utt in audioPaths:
87
+ # 过滤数据集错误:相同的音频匹配多个文本,导致后续bert出问题
88
+ print(f"重复音频文本:{line}")
89
+ countSame += 1
90
+ continue
91
+ if not os.path.isfile(utt):
92
+ # 过滤数据集错误:不存在对应音频
93
+ print(f"没有找到对应的音频:{utt}")
94
+ countNotFound += 1
95
+ continue
96
+ audioPaths.add(utt)
97
+ spk_utt_map[language].append(line)
98
+ if spk not in spk_id_map.keys():
99
+ spk_id_map[spk] = current_sid
100
+ current_sid += 1
101
+ print(f"总重复音频数:{countSame},总未找到的音频数:{countNotFound}")
102
+
103
+ train_list = []
104
+ val_list = []
105
+
106
+ for spk, utts in spk_utt_map.items():
107
+ shuffle(utts)
108
+ val_list += utts[:val_per_lang]
109
+ train_list += utts[val_per_lang:]
110
+
111
+ shuffle(val_list)
112
+ if len(val_list) > max_val_total:
113
+ train_list += val_list[max_val_total:]
114
+ val_list = val_list[:max_val_total]
115
+
116
+ with open(train_path, "w", encoding="utf-8") as f:
117
+ for line in train_list:
118
+ f.write(line)
119
+
120
+ with open(val_path, "w", encoding="utf-8") as f:
121
+ for line in val_list:
122
+ f.write(line)
123
+
124
+ json_config = json.load(open(config_path, encoding="utf-8"))
125
+ json_config["data"]["spk2id"] = spk_id_map
126
+ json_config["data"]["n_speakers"] = len(spk_id_map)
127
+ # 新增写入:写入训练版本、数据集路径
128
+ json_config["version"] = latest_version
129
+ json_config["data"]["training_files"] = os.path.normpath(train_path).replace(
130
+ "\\", "/"
131
+ )
132
+ json_config["data"]["validation_files"] = os.path.normpath(val_path).replace(
133
+ "\\", "/"
134
+ )
135
+ with open(config_path, "w", encoding="utf-8") as f:
136
+ json.dump(json_config, f, indent=2, ensure_ascii=False)
137
+ print("训练集和验证集生成完成!")
138
+
139
+
140
+ if __name__ == "__main__":
141
+ preprocess()
re_matching.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+
4
+ def extract_language_and_text_updated(speaker, dialogue):
5
+ # 使用正则表达式匹配<语言>标签和其后的文本
6
+ pattern_language_text = r"<(\S+?)>([^<]+)"
7
+ matches = re.findall(pattern_language_text, dialogue, re.DOTALL)
8
+ speaker = speaker[1:-1]
9
+ # 清理文本:去除两边的空白字符
10
+ matches_cleaned = [(lang.upper(), text.strip()) for lang, text in matches]
11
+ matches_cleaned.append(speaker)
12
+ return matches_cleaned
13
+
14
+
15
+ def validate_text(input_text):
16
+ # 验证说话人的正则表达式
17
+ pattern_speaker = r"(\[\S+?\])((?:\s*<\S+?>[^<\[\]]+?)+)"
18
+
19
+ # 使用re.DOTALL标志使.匹配包括换行符在内的所有字符
20
+ matches = re.findall(pattern_speaker, input_text, re.DOTALL)
21
+
22
+ # 对每个匹配到的说话人内容进行进一步验证
23
+ for _, dialogue in matches:
24
+ language_text_matches = extract_language_and_text_updated(_, dialogue)
25
+ if not language_text_matches:
26
+ return (
27
+ False,
28
+ "Error: Invalid format detected in dialogue content. Please check your input.",
29
+ )
30
+
31
+ # 如果输入的文本中没有找到任何匹配项
32
+ if not matches:
33
+ return (
34
+ False,
35
+ "Error: No valid speaker format detected. Please check your input.",
36
+ )
37
+
38
+ return True, "Input is valid."
39
+
40
+
41
+ def text_matching(text: str) -> list:
42
+ speaker_pattern = r"(\[\S+?\])(.+?)(?=\[\S+?\]|$)"
43
+ matches = re.findall(speaker_pattern, text, re.DOTALL)
44
+ result = []
45
+ for speaker, dialogue in matches:
46
+ result.append(extract_language_and_text_updated(speaker, dialogue))
47
+ return result
48
+
49
+
50
+ def cut_para(text):
51
+ splitted_para = re.split("[\n]", text) # 按段分
52
+ splitted_para = [
53
+ sentence.strip() for sentence in splitted_para if sentence.strip()
54
+ ] # 删除空字符串
55
+ return splitted_para
56
+
57
+
58
+ def cut_sent(para):
59
+ para = re.sub("([。!;?\?])([^”’])", r"\1\n\2", para) # 单字符断句符
60
+ para = re.sub("(\.{6})([^”’])", r"\1\n\2", para) # 英文省略号
61
+ para = re.sub("(\…{2})([^”’])", r"\1\n\2", para) # 中文省略号
62
+ para = re.sub("([。!?\?][”’])([^,。!?\?])", r"\1\n\2", para)
63
+ para = para.rstrip() # 段尾如果有多余的\n就去掉它
64
+ return para.split("\n")
65
+
66
+
67
+ if __name__ == "__main__":
68
+ text = """
69
+ [说话人1]
70
+ [说话人2]<zh>你好吗?<jp>元気ですか?<jp>こんにちは,世界。<zh>你好吗?
71
+ [说话人3]<zh>谢谢。<jp>どういたしまして。
72
+ """
73
+ text_matching(text)
74
+ # 测试函数
75
+ test_text = """
76
+ [说话人1]<zh>你好,こんにちは!<jp>こんにちは,世界。
77
+ [说话人2]<zh>你好吗?
78
+ """
79
+ text_matching(test_text)
80
+ res = validate_text(test_text)
81
+ print(res)
requirements.txt ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ librosa==0.9.2
2
+ matplotlib
3
+ numpy
4
+ numba
5
+ phonemizer
6
+ scipy
7
+ tensorboard
8
+ Unidecode
9
+ amfm_decompy
10
+ jieba
11
+ transformers
12
+ pypinyin
13
+ cn2an
14
+ gradio==3.41.2
15
+ av
16
+ mecab-python3
17
+ loguru
18
+ unidic-lite
19
+ cmudict
20
+ fugashi
21
+ num2words
22
+ PyYAML
23
+ requests
24
+ pyopenjtalk-prebuilt
25
+ jaconv
26
+ psutil
27
+ GPUtil
28
+ vector_quantize_pytorch
29
+ g2p_en
30
+ sentencepiece
31
+ pykakasi
32
+ langid
resample.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import librosa
4
+ from multiprocessing import Pool, cpu_count
5
+
6
+ import soundfile
7
+ from tqdm import tqdm
8
+
9
+ from config import config
10
+
11
+
12
+ def process(item):
13
+ spkdir, wav_name, args = item
14
+ wav_path = os.path.join(args.in_dir, spkdir, wav_name)
15
+ if os.path.exists(wav_path) and wav_path.lower().endswith(".wav"):
16
+ wav, sr = librosa.load(wav_path, sr=args.sr)
17
+ soundfile.write(os.path.join(args.out_dir, spkdir, wav_name), wav, sr)
18
+
19
+
20
+ if __name__ == "__main__":
21
+ parser = argparse.ArgumentParser()
22
+ parser.add_argument(
23
+ "--sr",
24
+ type=int,
25
+ default=config.resample_config.sampling_rate,
26
+ help="sampling rate",
27
+ )
28
+ parser.add_argument(
29
+ "--in_dir",
30
+ type=str,
31
+ default=config.resample_config.in_dir,
32
+ help="path to source dir",
33
+ )
34
+ parser.add_argument(
35
+ "--out_dir",
36
+ type=str,
37
+ default=config.resample_config.out_dir,
38
+ help="path to target dir",
39
+ )
40
+ parser.add_argument(
41
+ "--processes",
42
+ type=int,
43
+ default=0,
44
+ help="cpu_processes",
45
+ )
46
+ args, _ = parser.parse_known_args()
47
+ # autodl 无卡模式会识别出46个cpu
48
+ if args.processes == 0:
49
+ processes = cpu_count() - 2 if cpu_count() > 4 else 1
50
+ else:
51
+ processes = args.processes
52
+ pool = Pool(processes=processes)
53
+
54
+ tasks = []
55
+
56
+ for dirpath, _, filenames in os.walk(args.in_dir):
57
+ # 子级目录
58
+ spk_dir = os.path.relpath(dirpath, args.in_dir)
59
+ spk_dir_out = os.path.join(args.out_dir, spk_dir)
60
+ if not os.path.isdir(spk_dir_out):
61
+ os.makedirs(spk_dir_out, exist_ok=True)
62
+ for filename in filenames:
63
+ if filename.lower().endswith(".wav"):
64
+ twople = (spk_dir, filename, args)
65
+ tasks.append(twople)
66
+
67
+ for _ in tqdm(
68
+ pool.imap_unordered(process, tasks),
69
+ ):
70
+ pass
71
+
72
+ pool.close()
73
+ pool.join()
74
+
75
+ print("音频重采样完毕!")
resample_legacy.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import librosa
4
+ from multiprocessing import Pool, cpu_count
5
+
6
+ import soundfile
7
+ from tqdm import tqdm
8
+
9
+ from config import config
10
+
11
+
12
+ def process(item):
13
+ wav_name, args = item
14
+ wav_path = os.path.join(args.in_dir, wav_name)
15
+ if os.path.exists(wav_path) and wav_path.lower().endswith(".wav"):
16
+ wav, sr = librosa.load(wav_path, sr=args.sr)
17
+ soundfile.write(os.path.join(args.out_dir, wav_name), wav, sr)
18
+
19
+
20
+ if __name__ == "__main__":
21
+ parser = argparse.ArgumentParser()
22
+ parser.add_argument(
23
+ "--sr",
24
+ type=int,
25
+ default=config.resample_config.sampling_rate,
26
+ help="sampling rate",
27
+ )
28
+ parser.add_argument(
29
+ "--in_dir",
30
+ type=str,
31
+ default=config.resample_config.in_dir,
32
+ help="path to source dir",
33
+ )
34
+ parser.add_argument(
35
+ "--out_dir",
36
+ type=str,
37
+ default=config.resample_config.out_dir,
38
+ help="path to target dir",
39
+ )
40
+ parser.add_argument(
41
+ "--processes",
42
+ type=int,
43
+ default=0,
44
+ help="cpu_processes",
45
+ )
46
+ args, _ = parser.parse_known_args()
47
+ # autodl 无卡模式会识别出46个cpu
48
+ if args.processes == 0:
49
+ processes = cpu_count() - 2 if cpu_count() > 4 else 1
50
+ else:
51
+ processes = args.processes
52
+ pool = Pool(processes=processes)
53
+
54
+ tasks = []
55
+
56
+ for dirpath, _, filenames in os.walk(args.in_dir):
57
+ if not os.path.isdir(args.out_dir):
58
+ os.makedirs(args.out_dir, exist_ok=True)
59
+ for filename in filenames:
60
+ if filename.lower().endswith(".wav"):
61
+ tasks.append((filename, args))
62
+
63
+ for _ in tqdm(
64
+ pool.imap_unordered(process, tasks),
65
+ ):
66
+ pass
67
+
68
+ pool.close()
69
+ pool.join()
70
+
71
+ print("音频重采样完毕!")
run_MnodesAndMgpus.sh ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #多机多卡训练
2
+
3
+ #--nnodes=1:3 表示 使用一到三台机器 弹性分配资源
4
+ #--nnodes=<最小节点数>:<最大节点数>
5
+ #--nproc_per_node=每台机器上可用的GPU数
6
+ #--rdzv_endpoint=主节点(最先启动的)ip:端口号
7
+ #其他不需要变
8
+
9
+ #注意: 此版本的分布式训练是基于数据并行的,多机多卡相当于开更大的batchsize,此时epoch迭代速度会增加,
10
+ #但由于 该版本的代码中 保存模型是按照global step来计算的,所以会出现的效果就是 : 保存模型的时间不会有明显加速,
11
+ #但每次保存模型时epoch都比之前迭代了更多次,也就是 “更少的步数,实现更好的效果”
12
+
13
+ #*************************
14
+ # torchrun \
15
+ # --nnodes=1:3\
16
+ # --nproc_per_node=2\
17
+ # --rdzv_id=1\
18
+ # --rdzv_backend=c10d\
19
+ # --rdzv_endpoint="inspur1:8880"\
20
+ # train_ms.py
21
+ #****************************
22
+
23
+ #多卡训练
24
+ #nproc_per_node = 机器上可用的GPU数
25
+
26
+ #*************************
27
+ torchrun \
28
+ --nnodes=1\
29
+ --nproc_per_node=2\
30
+ train_ms.py
31
+ #*************************
server_fastapi.py ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ api服务 多版本多模型 fastapi实现
3
+ """
4
+ import logging
5
+ import gc
6
+ import random
7
+
8
+ import librosa
9
+ import gradio
10
+ import numpy as np
11
+ import utils
12
+ from fastapi import FastAPI, Query, Request, File, UploadFile, Form
13
+ from fastapi.responses import Response, FileResponse
14
+ from fastapi.staticfiles import StaticFiles
15
+ from io import BytesIO
16
+ from scipy.io import wavfile
17
+ import uvicorn
18
+ import torch
19
+ import webbrowser
20
+ import psutil
21
+ import GPUtil
22
+ from typing import Dict, Optional, List, Set, Union
23
+ import os
24
+ from tools.log import logger
25
+ from urllib.parse import unquote
26
+
27
+ from infer import infer, get_net_g, latest_version
28
+ import tools.translate as trans
29
+ from re_matching import cut_sent
30
+
31
+
32
+ from config import config
33
+
34
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
35
+
36
+
37
+ class Model:
38
+ """模型封装类"""
39
+
40
+ def __init__(self, config_path: str, model_path: str, device: str, language: str):
41
+ self.config_path: str = os.path.normpath(config_path)
42
+ self.model_path: str = os.path.normpath(model_path)
43
+ self.device: str = device
44
+ self.language: str = language
45
+ self.hps = utils.get_hparams_from_file(config_path)
46
+ self.spk2id: Dict[str, int] = self.hps.data.spk2id # spk - id 映射字典
47
+ self.id2spk: Dict[int, str] = dict() # id - spk 映射字典
48
+ for speaker, speaker_id in self.hps.data.spk2id.items():
49
+ self.id2spk[speaker_id] = speaker
50
+ self.version: str = (
51
+ self.hps.version if hasattr(self.hps, "version") else latest_version
52
+ )
53
+ self.net_g = get_net_g(
54
+ model_path=model_path,
55
+ version=self.version,
56
+ device=device,
57
+ hps=self.hps,
58
+ )
59
+
60
+ def to_dict(self) -> Dict[str, any]:
61
+ return {
62
+ "config_path": self.config_path,
63
+ "model_path": self.model_path,
64
+ "device": self.device,
65
+ "language": self.language,
66
+ "spk2id": self.spk2id,
67
+ "id2spk": self.id2spk,
68
+ "version": self.version,
69
+ }
70
+
71
+
72
+ class Models:
73
+ def __init__(self):
74
+ self.models: Dict[int, Model] = dict()
75
+ self.num = 0
76
+ # spkInfo[角色名][模型id] = 角色id
77
+ self.spk_info: Dict[str, Dict[int, int]] = dict()
78
+ self.path2ids: Dict[str, Set[int]] = dict() # 路径指向的model的id
79
+
80
+ def init_model(
81
+ self, config_path: str, model_path: str, device: str, language: str
82
+ ) -> int:
83
+ """
84
+ 初始化并添加一个模型
85
+
86
+ :param config_path: 模型config.json路径
87
+ :param model_path: 模型路径
88
+ :param device: 模型推理使用设备
89
+ :param language: 模型推理默认语言
90
+ """
91
+ # 若文件不存在则不进行加载
92
+ if not os.path.isfile(model_path):
93
+ if model_path != "":
94
+ logger.warning(f"模型文件{model_path} 不存在,不进行初始化")
95
+ return self.num
96
+ if not os.path.isfile(config_path):
97
+ if config_path != "":
98
+ logger.warning(f"配置文件{config_path} 不存在,不进行初始化")
99
+ return self.num
100
+
101
+ # 若路径中的模型已存在,则不添加模型,若不存在,则进行初始化。
102
+ model_path = os.path.realpath(model_path)
103
+ if model_path not in self.path2ids.keys():
104
+ self.path2ids[model_path] = {self.num}
105
+ self.models[self.num] = Model(
106
+ config_path=config_path,
107
+ model_path=model_path,
108
+ device=device,
109
+ language=language,
110
+ )
111
+ logger.success(f"添加模型{model_path},使用配置文件{os.path.realpath(config_path)}")
112
+ else:
113
+ # 获取一个指向id
114
+ m_id = next(iter(self.path2ids[model_path]))
115
+ self.models[self.num] = self.models[m_id]
116
+ self.path2ids[model_path].add(self.num)
117
+ logger.success("模型已存在,添加模型引用。")
118
+ # 添加角色信息
119
+ for speaker, speaker_id in self.models[self.num].spk2id.items():
120
+ if speaker not in self.spk_info.keys():
121
+ self.spk_info[speaker] = {self.num: speaker_id}
122
+ else:
123
+ self.spk_info[speaker][self.num] = speaker_id
124
+ # 修改计数
125
+ self.num += 1
126
+ return self.num - 1
127
+
128
+ def del_model(self, index: int) -> Optional[int]:
129
+ """删除对应序号的模型,若不存在则返回None"""
130
+ if index not in self.models.keys():
131
+ return None
132
+ # 删除角色信息
133
+ for speaker, speaker_id in self.models[index].spk2id.items():
134
+ self.spk_info[speaker].pop(index)
135
+ if len(self.spk_info[speaker]) == 0:
136
+ # 若对应角色的所有模型都被删除,则清除该角色信息
137
+ self.spk_info.pop(speaker)
138
+ # 删除路径信息
139
+ model_path = os.path.realpath(self.models[index].model_path)
140
+ self.path2ids[model_path].remove(index)
141
+ if len(self.path2ids[model_path]) == 0:
142
+ self.path2ids.pop(model_path)
143
+ logger.success(f"删除模型{model_path}, id = {index}")
144
+ else:
145
+ logger.success(f"删除模型引用{model_path}, id = {index}")
146
+ # 删除模型
147
+ self.models.pop(index)
148
+ gc.collect()
149
+ if torch.cuda.is_available():
150
+ torch.cuda.empty_cache()
151
+ return index
152
+
153
+ def get_models(self):
154
+ """获取所有模型"""
155
+ return self.models
156
+
157
+
158
+ if __name__ == "__main__":
159
+ app = FastAPI()
160
+ app.logger = logger
161
+ # 挂载静态文件
162
+ logger.info("开始挂载网页页面")
163
+ StaticDir: str = "./Web"
164
+ if not os.path.isdir(StaticDir):
165
+ logger.warning(
166
+ "缺少网页资源,无法开启网页页面,如有需要请在 https://github.com/jiangyuxiaoxiao/Bert-VITS2-UI 或者Bert-VITS对应版本的release页面下载"
167
+ )
168
+ else:
169
+ dirs = [fir.name for fir in os.scandir(StaticDir) if fir.is_dir()]
170
+ files = [fir.name for fir in os.scandir(StaticDir) if fir.is_dir()]
171
+ for dirName in dirs:
172
+ app.mount(
173
+ f"/{dirName}",
174
+ StaticFiles(directory=f"./{StaticDir}/{dirName}"),
175
+ name=dirName,
176
+ )
177
+ loaded_models = Models()
178
+ # 加载模型
179
+ logger.info("开始加载模型")
180
+ models_info = config.server_config.models
181
+ for model_info in models_info:
182
+ loaded_models.init_model(
183
+ config_path=model_info["config"],
184
+ model_path=model_info["model"],
185
+ device=model_info["device"],
186
+ language=model_info["language"],
187
+ )
188
+
189
+ @app.get("/")
190
+ async def index():
191
+ return FileResponse("./Web/index.html")
192
+
193
+ async def _voice(
194
+ text: str,
195
+ model_id: int,
196
+ speaker_name: str,
197
+ speaker_id: int,
198
+ sdp_ratio: float,
199
+ noise: float,
200
+ noisew: float,
201
+ length: float,
202
+ language: str,
203
+ auto_translate: bool,
204
+ auto_split: bool,
205
+ emotion: Optional[Union[int, str]] = None,
206
+ reference_audio=None,
207
+ style_text: Optional[str] = None,
208
+ style_weight: float = 0.7,
209
+ ) -> Union[Response, Dict[str, any]]:
210
+ """TTS实现函数"""
211
+ # 检查模型是否存在
212
+ if model_id not in loaded_models.models.keys():
213
+ logger.error(f"/voice 请求错误:模型model_id={model_id}未加载")
214
+ return {"status": 10, "detail": f"模型model_id={model_id}未加载"}
215
+ # 检查是否提供speaker
216
+ if speaker_name is None and speaker_id is None:
217
+ logger.error("/voice 请求错误:推理请求未提供speaker_name或speaker_id")
218
+ return {"status": 11, "detail": "请提供speaker_name或speaker_id"}
219
+ elif speaker_name is None:
220
+ # 检查speaker_id是否存在
221
+ if speaker_id not in loaded_models.models[model_id].id2spk.keys():
222
+ logger.error(f"/voice 请求错误:角色speaker_id={speaker_id}不存在")
223
+ return {"status": 12, "detail": f"角色speaker_id={speaker_id}不存在"}
224
+ speaker_name = loaded_models.models[model_id].id2spk[speaker_id]
225
+ # 检查speaker_name是否存在
226
+ if speaker_name not in loaded_models.models[model_id].spk2id.keys():
227
+ logger.error(f"/voice 请求错误:角色speaker_name={speaker_name}不存在")
228
+ return {"status": 13, "detail": f"角色speaker_name={speaker_name}不存在"}
229
+ # 未传入则使用默认语言
230
+ if language is None:
231
+ language = loaded_models.models[model_id].language
232
+ # 翻译会破坏mix结构,auto也会变得无意义。不要在这两个模式下使用
233
+ if auto_translate:
234
+ if language == "auto" or language == "mix":
235
+ logger.error(
236
+ f"/voice 请求错误:请勿同时使用language = {language}与auto_translate模式"
237
+ )
238
+ return {
239
+ "status": 20,
240
+ "detail": f"请勿同时使用language = {language}与auto_translate模式",
241
+ }
242
+ text = trans.translate(Sentence=text, to_Language=language.lower())
243
+ if reference_audio is not None:
244
+ ref_audio = BytesIO(await reference_audio.read())
245
+ # 2.2 适配
246
+ if loaded_models.models[model_id].version == "2.2":
247
+ ref_audio, _ = librosa.load(ref_audio, 48000)
248
+
249
+ else:
250
+ ref_audio = reference_audio
251
+ if not auto_split:
252
+ with torch.no_grad():
253
+ audio = infer(
254
+ text=text,
255
+ sdp_ratio=sdp_ratio,
256
+ noise_scale=noise,
257
+ noise_scale_w=noisew,
258
+ length_scale=length,
259
+ sid=speaker_name,
260
+ language=language,
261
+ hps=loaded_models.models[model_id].hps,
262
+ net_g=loaded_models.models[model_id].net_g,
263
+ device=loaded_models.models[model_id].device,
264
+ emotion=emotion,
265
+ reference_audio=ref_audio,
266
+ style_text=style_text,
267
+ style_weight=style_weight,
268
+ )
269
+ audio = gradio.processing_utils.convert_to_16_bit_wav(audio)
270
+ else:
271
+ texts = cut_sent(text)
272
+ audios = []
273
+ with torch.no_grad():
274
+ for t in texts:
275
+ audios.append(
276
+ infer(
277
+ text=t,
278
+ sdp_ratio=sdp_ratio,
279
+ noise_scale=noise,
280
+ noise_scale_w=noisew,
281
+ length_scale=length,
282
+ sid=speaker_name,
283
+ language=language,
284
+ hps=loaded_models.models[model_id].hps,
285
+ net_g=loaded_models.models[model_id].net_g,
286
+ device=loaded_models.models[model_id].device,
287
+ emotion=emotion,
288
+ reference_audio=ref_audio,
289
+ style_text=style_text,
290
+ style_weight=style_weight,
291
+ )
292
+ )
293
+ audios.append(np.zeros(int(44100 * 0.2)))
294
+ audio = np.concatenate(audios)
295
+ audio = gradio.processing_utils.convert_to_16_bit_wav(audio)
296
+ with BytesIO() as wavContent:
297
+ wavfile.write(
298
+ wavContent, loaded_models.models[model_id].hps.data.sampling_rate, audio
299
+ )
300
+ response = Response(content=wavContent.getvalue(), media_type="audio/wav")
301
+ return response
302
+
303
+ @app.post("/voice")
304
+ async def voice(
305
+ request: Request, # fastapi自动注入
306
+ text: str = Form(...),
307
+ model_id: int = Query(..., description="模型ID"), # 模型序号
308
+ speaker_name: str = Query(
309
+ None, description="说话人名"
310
+ ), # speaker_name与 speaker_id二者选其一
311
+ speaker_id: int = Query(None, description="说话人id,与speaker_name二选一"),
312
+ sdp_ratio: float = Query(0.2, description="SDP/DP混合比"),
313
+ noise: float = Query(0.2, description="感情"),
314
+ noisew: float = Query(0.9, description="音素长度"),
315
+ length: float = Query(1, description="语速"),
316
+ language: str = Query(None, description="语言"), # 若不指定使用语言则使用默认值
317
+ auto_translate: bool = Query(False, description="自动翻译"),
318
+ auto_split: bool = Query(False, description="自动切分"),
319
+ emotion: Optional[Union[int, str]] = Query(None, description="emo"),
320
+ reference_audio: UploadFile = File(None),
321
+ style_text: Optional[str] = Form(None, description="风格文本"),
322
+ style_weight: float = Query(0.7, description="风格权重"),
323
+ ):
324
+ """语音接口,若需要上传参考音频请仅使用post请求"""
325
+ logger.info(
326
+ f"{request.client.host}:{request.client.port}/voice { unquote(str(request.query_params) )} text={text}"
327
+ )
328
+ return await _voice(
329
+ text=text,
330
+ model_id=model_id,
331
+ speaker_name=speaker_name,
332
+ speaker_id=speaker_id,
333
+ sdp_ratio=sdp_ratio,
334
+ noise=noise,
335
+ noisew=noisew,
336
+ length=length,
337
+ language=language,
338
+ auto_translate=auto_translate,
339
+ auto_split=auto_split,
340
+ emotion=emotion,
341
+ reference_audio=reference_audio,
342
+ style_text=style_text,
343
+ style_weight=style_weight,
344
+ )
345
+
346
+ @app.get("/voice")
347
+ async def voice(
348
+ request: Request, # fastapi自动注入
349
+ text: str = Query(..., description="输入文字"),
350
+ model_id: int = Query(..., description="模型ID"), # 模型序号
351
+ speaker_name: str = Query(
352
+ None, description="说话人名"
353
+ ), # speaker_name与 speaker_id二者选其一
354
+ speaker_id: int = Query(None, description="说话人id,与speaker_name二选一"),
355
+ sdp_ratio: float = Query(0.2, description="SDP/DP混合比"),
356
+ noise: float = Query(0.2, description="感情"),
357
+ noisew: float = Query(0.9, description="音素长度"),
358
+ length: float = Query(1, description="语速"),
359
+ language: str = Query(None, description="语言"), # 若不指定使用语言则使用默认值
360
+ auto_translate: bool = Query(False, description="自动翻译"),
361
+ auto_split: bool = Query(False, description="自动切分"),
362
+ emotion: Optional[Union[int, str]] = Query(None, description="emo"),
363
+ style_text: Optional[str] = Query(None, description="风格文本"),
364
+ style_weight: float = Query(0.7, description="风格权重"),
365
+ ):
366
+ """语音接口"""
367
+ logger.info(
368
+ f"{request.client.host}:{request.client.port}/voice { unquote(str(request.query_params) )}"
369
+ )
370
+ return await _voice(
371
+ text=text,
372
+ model_id=model_id,
373
+ speaker_name=speaker_name,
374
+ speaker_id=speaker_id,
375
+ sdp_ratio=sdp_ratio,
376
+ noise=noise,
377
+ noisew=noisew,
378
+ length=length,
379
+ language=language,
380
+ auto_translate=auto_translate,
381
+ auto_split=auto_split,
382
+ emotion=emotion,
383
+ style_text=style_text,
384
+ style_weight=style_weight,
385
+ )
386
+
387
+ @app.get("/models/info")
388
+ def get_loaded_models_info(request: Request):
389
+ """获取已加载模型信息"""
390
+
391
+ result: Dict[str, Dict] = dict()
392
+ for key, model in loaded_models.models.items():
393
+ result[str(key)] = model.to_dict()
394
+ return result
395
+
396
+ @app.get("/models/delete")
397
+ def delete_model(
398
+ request: Request, model_id: int = Query(..., description="删除模型id")
399
+ ):
400
+ """删除指定模型"""
401
+ logger.info(
402
+ f"{request.client.host}:{request.client.port}/models/delete { unquote(str(request.query_params) )}"
403
+ )
404
+ result = loaded_models.del_model(model_id)
405
+ if result is None:
406
+ logger.error(f"/models/delete 模型删除错误:模型{model_id}不存在,删除失败")
407
+ return {"status": 14, "detail": f"模型{model_id}不存在,删除失败"}
408
+
409
+ return {"status": 0, "detail": "删除成功"}
410
+
411
+ @app.get("/models/add")
412
+ def add_model(
413
+ request: Request,
414
+ model_path: str = Query(..., description="添加模型路径"),
415
+ config_path: str = Query(
416
+ None, description="添加模型配置文件路径,不填则使用./config.json或../config.json"
417
+ ),
418
+ device: str = Query("cuda", description="推理使用设备"),
419
+ language: str = Query("ZH", description="模型默认语言"),
420
+ ):
421
+ """添加指定模型:允许重复添加相同路径模型,且不重复占用内存"""
422
+ logger.info(
423
+ f"{request.client.host}:{request.client.port}/models/add { unquote(str(request.query_params) )}"
424
+ )
425
+ if config_path is None:
426
+ model_dir = os.path.dirname(model_path)
427
+ if os.path.isfile(os.path.join(model_dir, "config.json")):
428
+ config_path = os.path.join(model_dir, "config.json")
429
+ elif os.path.isfile(os.path.join(model_dir, "../config.json")):
430
+ config_path = os.path.join(model_dir, "../config.json")
431
+ else:
432
+ logger.error("/models/add 模型添加失败:未在模型所在目录以及上级目录找到config.json文件")
433
+ return {
434
+ "status": 15,
435
+ "detail": "查询未传入配置文件路径,同时默认路径./与../中不存在配置文件config.json。",
436
+ }
437
+ try:
438
+ model_id = loaded_models.init_model(
439
+ config_path=config_path,
440
+ model_path=model_path,
441
+ device=device,
442
+ language=language,
443
+ )
444
+ except Exception:
445
+ logging.exception("模型加载出错")
446
+ return {
447
+ "status": 16,
448
+ "detail": "模型加载出错,详细查看日志",
449
+ }
450
+ return {
451
+ "status": 0,
452
+ "detail": "模型添加成功",
453
+ "Data": {
454
+ "model_id": model_id,
455
+ "model_info": loaded_models.models[model_id].to_dict(),
456
+ },
457
+ }
458
+
459
+ def _get_all_models(root_dir: str = "Data", only_unloaded: bool = False):
460
+ """从root_dir搜索获取所有可用模型"""
461
+ result: Dict[str, List[str]] = dict()
462
+ files = os.listdir(root_dir) + ["."]
463
+ for file in files:
464
+ if os.path.isdir(os.path.join(root_dir, file)):
465
+ sub_dir = os.path.join(root_dir, file)
466
+ # 搜索 "sub_dir" 、 "sub_dir/models" 两个路径
467
+ result[file] = list()
468
+ sub_files = os.listdir(sub_dir)
469
+ model_files = []
470
+ for sub_file in sub_files:
471
+ relpath = os.path.realpath(os.path.join(sub_dir, sub_file))
472
+ if only_unloaded and relpath in loaded_models.path2ids.keys():
473
+ continue
474
+ if sub_file.endswith(".pth") and sub_file.startswith("G_"):
475
+ if os.path.isfile(relpath):
476
+ model_files.append(sub_file)
477
+ # 对模型文件按步数排序
478
+ model_files = sorted(
479
+ model_files,
480
+ key=lambda pth: int(pth.lstrip("G_").rstrip(".pth"))
481
+ if pth.lstrip("G_").rstrip(".pth").isdigit()
482
+ else 10**10,
483
+ )
484
+ result[file] = model_files
485
+ models_dir = os.path.join(sub_dir, "models")
486
+ model_files = []
487
+ if os.path.isdir(models_dir):
488
+ sub_files = os.listdir(models_dir)
489
+ for sub_file in sub_files:
490
+ relpath = os.path.realpath(os.path.join(models_dir, sub_file))
491
+ if only_unloaded and relpath in loaded_models.path2ids.keys():
492
+ continue
493
+ if sub_file.endswith(".pth") and sub_file.startswith("G_"):
494
+ if os.path.isfile(os.path.join(models_dir, sub_file)):
495
+ model_files.append(f"models/{sub_file}")
496
+ # 对模型文件按步数排序
497
+ model_files = sorted(
498
+ model_files,
499
+ key=lambda pth: int(pth.lstrip("models/G_").rstrip(".pth"))
500
+ if pth.lstrip("models/G_").rstrip(".pth").isdigit()
501
+ else 10**10,
502
+ )
503
+ result[file] += model_files
504
+ if len(result[file]) == 0:
505
+ result.pop(file)
506
+
507
+ return result
508
+
509
+ @app.get("/models/get_unloaded")
510
+ def get_unloaded_models_info(
511
+ request: Request, root_dir: str = Query("Data", description="搜索根目录")
512
+ ):
513
+ """获取未加载模型"""
514
+ logger.info(
515
+ f"{request.client.host}:{request.client.port}/models/get_unloaded { unquote(str(request.query_params) )}"
516
+ )
517
+ return _get_all_models(root_dir, only_unloaded=True)
518
+
519
+ @app.get("/models/get_local")
520
+ def get_local_models_info(
521
+ request: Request, root_dir: str = Query("Data", description="搜索根目录")
522
+ ):
523
+ """获取全部本地模型"""
524
+ logger.info(
525
+ f"{request.client.host}:{request.client.port}/models/get_local { unquote(str(request.query_params) )}"
526
+ )
527
+ return _get_all_models(root_dir, only_unloaded=False)
528
+
529
+ @app.get("/status")
530
+ def get_status():
531
+ """获取电脑运行状态"""
532
+ cpu_percent = psutil.cpu_percent(interval=1)
533
+ memory_info = psutil.virtual_memory()
534
+ memory_total = memory_info.total
535
+ memory_available = memory_info.available
536
+ memory_used = memory_info.used
537
+ memory_percent = memory_info.percent
538
+ gpuInfo = []
539
+ devices = ["cpu"]
540
+ for i in range(torch.cuda.device_count()):
541
+ devices.append(f"cuda:{i}")
542
+ gpus = GPUtil.getGPUs()
543
+ for gpu in gpus:
544
+ gpuInfo.append(
545
+ {
546
+ "gpu_id": gpu.id,
547
+ "gpu_load": gpu.load,
548
+ "gpu_memory": {
549
+ "total": gpu.memoryTotal,
550
+ "used": gpu.memoryUsed,
551
+ "free": gpu.memoryFree,
552
+ },
553
+ }
554
+ )
555
+ return {
556
+ "devices": devices,
557
+ "cpu_percent": cpu_percent,
558
+ "memory_total": memory_total,
559
+ "memory_available": memory_available,
560
+ "memory_used": memory_used,
561
+ "memory_percent": memory_percent,
562
+ "gpu": gpuInfo,
563
+ }
564
+
565
+ @app.get("/tools/translate")
566
+ def translate(
567
+ request: Request,
568
+ texts: str = Query(..., description="待翻译文本"),
569
+ to_language: str = Query(..., description="翻译目标语言"),
570
+ ):
571
+ """翻译"""
572
+ logger.info(
573
+ f"{request.client.host}:{request.client.port}/tools/translate { unquote(str(request.query_params) )}"
574
+ )
575
+ return {"texts": trans.translate(Sentence=texts, to_Language=to_language)}
576
+
577
+ all_examples: Dict[str, Dict[str, List]] = dict() # 存放示例
578
+
579
+ @app.get("/tools/random_example")
580
+ def random_example(
581
+ request: Request,
582
+ language: str = Query(None, description="指定语言,未指定则随机返回"),
583
+ root_dir: str = Query("Data", description="搜索根目录"),
584
+ ):
585
+ """
586
+ 获取一个随机音频+文本,用于对比,音频会从本地目录随机选择。
587
+ """
588
+ logger.info(
589
+ f"{request.client.host}:{request.client.port}/tools/random_example { unquote(str(request.query_params) )}"
590
+ )
591
+ global all_examples
592
+ # 数据初始化
593
+ if root_dir not in all_examples.keys():
594
+ all_examples[root_dir] = {"ZH": [], "JP": [], "EN": []}
595
+
596
+ examples = all_examples[root_dir]
597
+
598
+ # 从项目Data目录中搜索train/val.list
599
+ for root, directories, _files in os.walk(root_dir):
600
+ for file in _files:
601
+ if file in ["train.list", "val.list"]:
602
+ with open(
603
+ os.path.join(root, file), mode="r", encoding="utf-8"
604
+ ) as f:
605
+ lines = f.readlines()
606
+ for line in lines:
607
+ data = line.split("|")
608
+ if len(data) != 7:
609
+ continue
610
+ # 音频存在 且语言为ZH/EN/JP
611
+ if os.path.isfile(data[0]) and data[2] in [
612
+ "ZH",
613
+ "JP",
614
+ "EN",
615
+ ]:
616
+ examples[data[2]].append(
617
+ {
618
+ "text": data[3],
619
+ "audio": data[0],
620
+ "speaker": data[1],
621
+ }
622
+ )
623
+
624
+ examples = all_examples[root_dir]
625
+ if language is None:
626
+ if len(examples["ZH"]) + len(examples["JP"]) + len(examples["EN"]) == 0:
627
+ return {"status": 17, "detail": "没有加载任何示例数据"}
628
+ else:
629
+ # 随机选一个
630
+ rand_num = random.randint(
631
+ 0,
632
+ len(examples["ZH"]) + len(examples["JP"]) + len(examples["EN"]) - 1,
633
+ )
634
+ # ZH
635
+ if rand_num < len(examples["ZH"]):
636
+ return {"status": 0, "Data": examples["ZH"][rand_num]}
637
+ # JP
638
+ if rand_num < len(examples["ZH"]) + len(examples["JP"]):
639
+ return {
640
+ "status": 0,
641
+ "Data": examples["JP"][rand_num - len(examples["ZH"])],
642
+ }
643
+ # EN
644
+ return {
645
+ "status": 0,
646
+ "Data": examples["EN"][
647
+ rand_num - len(examples["ZH"]) - len(examples["JP"])
648
+ ],
649
+ }
650
+
651
+ else:
652
+ if len(examples[language]) == 0:
653
+ return {"status": 17, "detail": f"没有加载任何{language}数据"}
654
+ return {
655
+ "status": 0,
656
+ "Data": examples[language][
657
+ random.randint(0, len(examples[language]) - 1)
658
+ ],
659
+ }
660
+
661
+ @app.get("/tools/get_audio")
662
+ def get_audio(request: Request, path: str = Query(..., description="本地音频路径")):
663
+ logger.info(
664
+ f"{request.client.host}:{request.client.port}/tools/get_audio { unquote(str(request.query_params) )}"
665
+ )
666
+ if not os.path.isfile(path):
667
+ logger.error(f"/tools/get_audio 获取音频错误:指定音频{path}不存在")
668
+ return {"status": 18, "detail": "指定音频不存在"}
669
+ if not path.lower().endswith(".wav"):
670
+ logger.error(f"/tools/get_audio 获取音频错误:音频{path}非wav文件")
671
+ return {"status": 19, "detail": "非wav格式文件"}
672
+ return FileResponse(path=path)
673
+
674
+ logger.warning("本地服务,请勿将服务端口暴露于外网")
675
+ logger.info(f"api文档地址 http://127.0.0.1:{config.server_config.port}/docs")
676
+ if os.path.isdir(StaticDir):
677
+ webbrowser.open(f"http://127.0.0.1:{config.server_config.port}")
678
+ uvicorn.run(
679
+ app, port=config.server_config.port, host="0.0.0.0", log_level="warning"
680
+ )
spec_gen.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from tqdm import tqdm
3
+ from multiprocessing import Pool
4
+ from mel_processing import spectrogram_torch, mel_spectrogram_torch
5
+ from utils import load_wav_to_torch
6
+
7
+
8
+ class AudioProcessor:
9
+ def __init__(
10
+ self,
11
+ max_wav_value,
12
+ use_mel_spec_posterior,
13
+ filter_length,
14
+ n_mel_channels,
15
+ sampling_rate,
16
+ hop_length,
17
+ win_length,
18
+ mel_fmin,
19
+ mel_fmax,
20
+ ):
21
+ self.max_wav_value = max_wav_value
22
+ self.use_mel_spec_posterior = use_mel_spec_posterior
23
+ self.filter_length = filter_length
24
+ self.n_mel_channels = n_mel_channels
25
+ self.sampling_rate = sampling_rate
26
+ self.hop_length = hop_length
27
+ self.win_length = win_length
28
+ self.mel_fmin = mel_fmin
29
+ self.mel_fmax = mel_fmax
30
+
31
+ def process_audio(self, filename):
32
+ audio, sampling_rate = load_wav_to_torch(filename)
33
+ audio_norm = audio / self.max_wav_value
34
+ audio_norm = audio_norm.unsqueeze(0)
35
+ spec_filename = filename.replace(".wav", ".spec.pt")
36
+ if self.use_mel_spec_posterior:
37
+ spec_filename = spec_filename.replace(".spec.pt", ".mel.pt")
38
+ try:
39
+ spec = torch.load(spec_filename)
40
+ except:
41
+ if self.use_mel_spec_posterior:
42
+ spec = mel_spectrogram_torch(
43
+ audio_norm,
44
+ self.filter_length,
45
+ self.n_mel_channels,
46
+ self.sampling_rate,
47
+ self.hop_length,
48
+ self.win_length,
49
+ self.mel_fmin,
50
+ self.mel_fmax,
51
+ center=False,
52
+ )
53
+ else:
54
+ spec = spectrogram_torch(
55
+ audio_norm,
56
+ self.filter_length,
57
+ self.sampling_rate,
58
+ self.hop_length,
59
+ self.win_length,
60
+ center=False,
61
+ )
62
+ spec = torch.squeeze(spec, 0)
63
+ torch.save(spec, spec_filename)
64
+ return spec, audio_norm
65
+
66
+
67
+ # 使用示例
68
+ processor = AudioProcessor(
69
+ max_wav_value=32768.0,
70
+ use_mel_spec_posterior=False,
71
+ filter_length=2048,
72
+ n_mel_channels=128,
73
+ sampling_rate=44100,
74
+ hop_length=512,
75
+ win_length=2048,
76
+ mel_fmin=0.0,
77
+ mel_fmax="null",
78
+ )
79
+
80
+ with open("filelists/train.list", "r") as f:
81
+ filepaths = [line.split("|")[0] for line in f] # 取每一行的第一部分作为audiopath
82
+
83
+ # 使用多进程处理
84
+ with Pool(processes=32) as pool: # 使用4个进程
85
+ with tqdm(total=len(filepaths)) as pbar:
86
+ for i, _ in enumerate(pool.imap_unordered(processor.process_audio, filepaths)):
87
+ pbar.update()
train_ms.py ADDED
@@ -0,0 +1,840 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: E402
2
+ import platform
3
+ import os
4
+ import torch
5
+ from torch.nn import functional as F
6
+ from torch.utils.data import DataLoader
7
+ from torch.utils.tensorboard import SummaryWriter
8
+ import torch.distributed as dist
9
+ from torch.nn.parallel import DistributedDataParallel as DDP
10
+ from torch.cuda.amp import autocast, GradScaler
11
+ from tqdm import tqdm
12
+ import logging
13
+ from config import config
14
+ import argparse
15
+ import datetime
16
+ import gc
17
+
18
+ logging.getLogger("numba").setLevel(logging.WARNING)
19
+ import commons
20
+ import utils
21
+ from data_utils import (
22
+ TextAudioSpeakerLoader,
23
+ TextAudioSpeakerCollate,
24
+ DistributedBucketSampler,
25
+ )
26
+ from models import (
27
+ SynthesizerTrn,
28
+ MultiPeriodDiscriminator,
29
+ DurationDiscriminator,
30
+ WavLMDiscriminator,
31
+ )
32
+ from losses import (
33
+ generator_loss,
34
+ discriminator_loss,
35
+ feature_loss,
36
+ kl_loss,
37
+ WavLMLoss,
38
+ )
39
+ from mel_processing import mel_spectrogram_torch, spec_to_mel_torch
40
+ from text.symbols import symbols
41
+
42
+ torch.backends.cuda.matmul.allow_tf32 = True
43
+ torch.backends.cudnn.allow_tf32 = (
44
+ True # If encontered training problem,please try to disable TF32.
45
+ )
46
+ torch.set_float32_matmul_precision("medium")
47
+ torch.backends.cuda.sdp_kernel("flash")
48
+ torch.backends.cuda.enable_flash_sdp(True)
49
+ torch.backends.cuda.enable_mem_efficient_sdp(
50
+ True
51
+ ) # Not available if torch version is lower than 2.0
52
+ global_step = 0
53
+
54
+
55
+ def run():
56
+ # 环境变量解析
57
+ envs = config.train_ms_config.env
58
+ for env_name, env_value in envs.items():
59
+ if env_name not in os.environ.keys():
60
+ print("加载config中的配置{}".format(str(env_value)))
61
+ os.environ[env_name] = str(env_value)
62
+ print(
63
+ "加载环境变量 \nMASTER_ADDR: {},\nMASTER_PORT: {},\nWORLD_SIZE: {},\nRANK: {},\nLOCAL_RANK: {}".format(
64
+ os.environ["MASTER_ADDR"],
65
+ os.environ["MASTER_PORT"],
66
+ os.environ["WORLD_SIZE"],
67
+ os.environ["RANK"],
68
+ os.environ["LOCAL_RANK"],
69
+ )
70
+ )
71
+
72
+ backend = "nccl"
73
+ if platform.system() == "Windows":
74
+ backend = "gloo" # If Windows,switch to gloo backend.
75
+ dist.init_process_group(
76
+ backend=backend,
77
+ init_method="env://",
78
+ timeout=datetime.timedelta(seconds=300),
79
+ ) # Use torchrun instead of mp.spawn
80
+ rank = dist.get_rank()
81
+ local_rank = int(os.environ["LOCAL_RANK"])
82
+ n_gpus = dist.get_world_size()
83
+
84
+ # 命令行/config.yml配置解析
85
+ # hps = utils.get_hparams()
86
+ parser = argparse.ArgumentParser()
87
+ # 非必要不建议使用命令行配置,请使用config.yml文件
88
+ parser.add_argument(
89
+ "-c",
90
+ "--config",
91
+ type=str,
92
+ default=config.train_ms_config.config_path,
93
+ help="JSON file for configuration",
94
+ )
95
+
96
+ parser.add_argument(
97
+ "-m",
98
+ "--model",
99
+ type=str,
100
+ help="数据集文件夹路径,请注意,数据不再默认放在/logs文件夹下。如果需要用命令行配置,请声明相对于根目录的路径",
101
+ default=config.dataset_path,
102
+ )
103
+ args = parser.parse_args()
104
+ model_dir = os.path.join(args.model, config.train_ms_config.model)
105
+ if not os.path.exists(model_dir):
106
+ os.makedirs(model_dir)
107
+ hps = utils.get_hparams_from_file(args.config)
108
+ hps.model_dir = model_dir
109
+ # 比较路径是否相同
110
+ if os.path.realpath(args.config) != os.path.realpath(
111
+ config.train_ms_config.config_path
112
+ ):
113
+ with open(args.config, "r", encoding="utf-8") as f:
114
+ data = f.read()
115
+ with open(config.train_ms_config.config_path, "w", encoding="utf-8") as f:
116
+ f.write(data)
117
+
118
+ torch.manual_seed(hps.train.seed)
119
+ torch.cuda.set_device(local_rank)
120
+
121
+ global global_step
122
+ if rank == 0:
123
+ logger = utils.get_logger(hps.model_dir)
124
+ logger.info(hps)
125
+ utils.check_git_hash(hps.model_dir)
126
+ writer = SummaryWriter(log_dir=hps.model_dir)
127
+ writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval"))
128
+ train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data)
129
+ train_sampler = DistributedBucketSampler(
130
+ train_dataset,
131
+ hps.train.batch_size,
132
+ [32, 300, 400, 500, 600, 700, 800, 900, 1000],
133
+ num_replicas=n_gpus,
134
+ rank=rank,
135
+ shuffle=True,
136
+ )
137
+ collate_fn = TextAudioSpeakerCollate()
138
+ train_loader = DataLoader(
139
+ train_dataset,
140
+ num_workers=min(config.train_ms_config.num_workers, os.cpu_count() - 1),
141
+ shuffle=False,
142
+ pin_memory=True,
143
+ collate_fn=collate_fn,
144
+ batch_sampler=train_sampler,
145
+ persistent_workers=True,
146
+ prefetch_factor=4,
147
+ ) # DataLoader config could be adjusted.
148
+ if rank == 0:
149
+ eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data)
150
+ eval_loader = DataLoader(
151
+ eval_dataset,
152
+ num_workers=0,
153
+ shuffle=False,
154
+ batch_size=1,
155
+ pin_memory=True,
156
+ drop_last=False,
157
+ collate_fn=collate_fn,
158
+ )
159
+ if (
160
+ "use_noise_scaled_mas" in hps.model.keys()
161
+ and hps.model.use_noise_scaled_mas is True
162
+ ):
163
+ print("Using noise scaled MAS for VITS2")
164
+ mas_noise_scale_initial = 0.01
165
+ noise_scale_delta = 2e-6
166
+ else:
167
+ print("Using normal MAS for VITS1")
168
+ mas_noise_scale_initial = 0.0
169
+ noise_scale_delta = 0.0
170
+ if (
171
+ "use_duration_discriminator" in hps.model.keys()
172
+ and hps.model.use_duration_discriminator is True
173
+ ):
174
+ print("Using duration discriminator for VITS2")
175
+ net_dur_disc = DurationDiscriminator(
176
+ hps.model.hidden_channels,
177
+ hps.model.hidden_channels,
178
+ 3,
179
+ 0.1,
180
+ gin_channels=hps.model.gin_channels if hps.data.n_speakers != 0 else 0,
181
+ ).cuda(local_rank)
182
+ else:
183
+ net_dur_disc = None
184
+ if (
185
+ "use_spk_conditioned_encoder" in hps.model.keys()
186
+ and hps.model.use_spk_conditioned_encoder is True
187
+ ):
188
+ if hps.data.n_speakers == 0:
189
+ raise ValueError(
190
+ "n_speakers must be > 0 when using spk conditioned encoder to train multi-speaker model"
191
+ )
192
+ else:
193
+ print("Using normal encoder for VITS1")
194
+
195
+ net_g = SynthesizerTrn(
196
+ len(symbols),
197
+ hps.data.filter_length // 2 + 1,
198
+ hps.train.segment_size // hps.data.hop_length,
199
+ n_speakers=hps.data.n_speakers,
200
+ mas_noise_scale_initial=mas_noise_scale_initial,
201
+ noise_scale_delta=noise_scale_delta,
202
+ **hps.model,
203
+ ).cuda(local_rank)
204
+
205
+ if getattr(hps.train, "freeze_ZH_bert", False):
206
+ print("Freezing ZH bert encoder !!!")
207
+ for param in net_g.enc_p.bert_proj.parameters():
208
+ param.requires_grad = False
209
+
210
+ if getattr(hps.train, "freeze_EN_bert", False):
211
+ print("Freezing EN bert encoder !!!")
212
+ for param in net_g.enc_p.en_bert_proj.parameters():
213
+ param.requires_grad = False
214
+
215
+ if getattr(hps.train, "freeze_JP_bert", False):
216
+ print("Freezing JP bert encoder !!!")
217
+ for param in net_g.enc_p.ja_bert_proj.parameters():
218
+ param.requires_grad = False
219
+
220
+ net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(local_rank)
221
+ net_wd = WavLMDiscriminator(
222
+ hps.model.slm.hidden, hps.model.slm.nlayers, hps.model.slm.initial_channel
223
+ ).cuda(local_rank)
224
+ optim_g = torch.optim.AdamW(
225
+ filter(lambda p: p.requires_grad, net_g.parameters()),
226
+ hps.train.learning_rate,
227
+ betas=hps.train.betas,
228
+ eps=hps.train.eps,
229
+ )
230
+ optim_d = torch.optim.AdamW(
231
+ net_d.parameters(),
232
+ hps.train.learning_rate,
233
+ betas=hps.train.betas,
234
+ eps=hps.train.eps,
235
+ )
236
+ optim_wd = torch.optim.AdamW(
237
+ net_wd.parameters(),
238
+ hps.train.learning_rate,
239
+ betas=hps.train.betas,
240
+ eps=hps.train.eps,
241
+ )
242
+ if net_dur_disc is not None:
243
+ optim_dur_disc = torch.optim.AdamW(
244
+ net_dur_disc.parameters(),
245
+ hps.train.learning_rate,
246
+ betas=hps.train.betas,
247
+ eps=hps.train.eps,
248
+ )
249
+ else:
250
+ optim_dur_disc = None
251
+ net_g = DDP(net_g, device_ids=[local_rank], bucket_cap_mb=512)
252
+ net_d = DDP(net_d, device_ids=[local_rank], bucket_cap_mb=512)
253
+ net_wd = DDP(net_wd, device_ids=[local_rank], bucket_cap_mb=512)
254
+ if net_dur_disc is not None:
255
+ net_dur_disc = DDP(
256
+ net_dur_disc,
257
+ device_ids=[local_rank],
258
+ bucket_cap_mb=512,
259
+ )
260
+
261
+ # 下载底模
262
+ if config.train_ms_config.base["use_base_model"]:
263
+ utils.download_checkpoint(
264
+ hps.model_dir,
265
+ config.train_ms_config.base,
266
+ token=config.openi_token,
267
+ mirror=config.mirror,
268
+ )
269
+ dur_resume_lr = hps.train.learning_rate
270
+ wd_resume_lr = hps.train.learning_rate
271
+ if net_dur_disc is not None:
272
+ try:
273
+ _, _, dur_resume_lr, epoch_str = utils.load_checkpoint(
274
+ utils.latest_checkpoint_path(hps.model_dir, "DUR_*.pth"),
275
+ net_dur_disc,
276
+ optim_dur_disc,
277
+ skip_optimizer=hps.train.skip_optimizer
278
+ if "skip_optimizer" in hps.train
279
+ else True,
280
+ )
281
+ if not optim_dur_disc.param_groups[0].get("initial_lr"):
282
+ optim_dur_disc.param_groups[0]["initial_lr"] = dur_resume_lr
283
+ except:
284
+ print("Initialize dur_disc")
285
+
286
+ try:
287
+ _, optim_g, g_resume_lr, epoch_str = utils.load_checkpoint(
288
+ utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"),
289
+ net_g,
290
+ optim_g,
291
+ skip_optimizer=hps.train.skip_optimizer
292
+ if "skip_optimizer" in hps.train
293
+ else True,
294
+ )
295
+ _, optim_d, d_resume_lr, epoch_str = utils.load_checkpoint(
296
+ utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"),
297
+ net_d,
298
+ optim_d,
299
+ skip_optimizer=hps.train.skip_optimizer
300
+ if "skip_optimizer" in hps.train
301
+ else True,
302
+ )
303
+ if not optim_g.param_groups[0].get("initial_lr"):
304
+ optim_g.param_groups[0]["initial_lr"] = g_resume_lr
305
+ if not optim_d.param_groups[0].get("initial_lr"):
306
+ optim_d.param_groups[0]["initial_lr"] = d_resume_lr
307
+
308
+ epoch_str = max(epoch_str, 1)
309
+ # global_step = (epoch_str - 1) * len(train_loader)
310
+ global_step = int(
311
+ utils.get_steps(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"))
312
+ )
313
+ print(
314
+ f"******************检测到模型存在,epoch为 {epoch_str},gloabl step为 {global_step}*********************"
315
+ )
316
+ except Exception as e:
317
+ print(e)
318
+ epoch_str = 1
319
+ global_step = 0
320
+
321
+ try:
322
+ _, optim_wd, wd_resume_lr, epoch_str = utils.load_checkpoint(
323
+ utils.latest_checkpoint_path(hps.model_dir, "WD_*.pth"),
324
+ net_wd,
325
+ optim_wd,
326
+ skip_optimizer=hps.train.skip_optimizer
327
+ if "skip_optimizer" in hps.train
328
+ else True,
329
+ )
330
+ if not optim_wd.param_groups[0].get("initial_lr"):
331
+ optim_wd.param_groups[0]["initial_lr"] = wd_resume_lr
332
+ except Exception as e:
333
+ print(e)
334
+
335
+ scheduler_g = torch.optim.lr_scheduler.ExponentialLR(
336
+ optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2
337
+ )
338
+ scheduler_d = torch.optim.lr_scheduler.ExponentialLR(
339
+ optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2
340
+ )
341
+ scheduler_wd = torch.optim.lr_scheduler.ExponentialLR(
342
+ optim_wd, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2
343
+ )
344
+ if net_dur_disc is not None:
345
+ scheduler_dur_disc = torch.optim.lr_scheduler.ExponentialLR(
346
+ optim_dur_disc, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2
347
+ )
348
+ else:
349
+ scheduler_dur_disc = None
350
+ scaler = GradScaler(enabled=hps.train.bf16_run)
351
+
352
+ wl = WavLMLoss(
353
+ hps.model.slm.model,
354
+ net_wd,
355
+ hps.data.sampling_rate,
356
+ hps.model.slm.sr,
357
+ ).to(local_rank)
358
+
359
+ for epoch in range(epoch_str, hps.train.epochs + 1):
360
+ if rank == 0:
361
+ train_and_evaluate(
362
+ rank,
363
+ local_rank,
364
+ epoch,
365
+ hps,
366
+ [net_g, net_d, net_dur_disc, net_wd, wl],
367
+ [optim_g, optim_d, optim_dur_disc, optim_wd],
368
+ [scheduler_g, scheduler_d, scheduler_dur_disc, scheduler_wd],
369
+ scaler,
370
+ [train_loader, eval_loader],
371
+ logger,
372
+ [writer, writer_eval],
373
+ )
374
+ else:
375
+ train_and_evaluate(
376
+ rank,
377
+ local_rank,
378
+ epoch,
379
+ hps,
380
+ [net_g, net_d, net_dur_disc, net_wd, wl],
381
+ [optim_g, optim_d, optim_dur_disc, optim_wd],
382
+ [scheduler_g, scheduler_d, scheduler_dur_disc, scheduler_wd],
383
+ scaler,
384
+ [train_loader, None],
385
+ None,
386
+ None,
387
+ )
388
+ scheduler_g.step()
389
+ scheduler_d.step()
390
+ scheduler_wd.step()
391
+ if net_dur_disc is not None:
392
+ scheduler_dur_disc.step()
393
+
394
+
395
+ def train_and_evaluate(
396
+ rank,
397
+ local_rank,
398
+ epoch,
399
+ hps,
400
+ nets,
401
+ optims,
402
+ schedulers,
403
+ scaler,
404
+ loaders,
405
+ logger,
406
+ writers,
407
+ ):
408
+ net_g, net_d, net_dur_disc, net_wd, wl = nets
409
+ optim_g, optim_d, optim_dur_disc, optim_wd = optims
410
+ scheduler_g, scheduler_d, scheduler_dur_disc, scheduler_wd = schedulers
411
+ train_loader, eval_loader = loaders
412
+ if writers is not None:
413
+ writer, writer_eval = writers
414
+
415
+ train_loader.batch_sampler.set_epoch(epoch)
416
+ global global_step
417
+
418
+ net_g.train()
419
+ net_d.train()
420
+ net_wd.train()
421
+ if net_dur_disc is not None:
422
+ net_dur_disc.train()
423
+ for batch_idx, (
424
+ x,
425
+ x_lengths,
426
+ spec,
427
+ spec_lengths,
428
+ y,
429
+ y_lengths,
430
+ speakers,
431
+ tone,
432
+ language,
433
+ bert,
434
+ ja_bert,
435
+ en_bert,
436
+ ) in enumerate(tqdm(train_loader)):
437
+ if net_g.module.use_noise_scaled_mas:
438
+ current_mas_noise_scale = (
439
+ net_g.module.mas_noise_scale_initial
440
+ - net_g.module.noise_scale_delta * global_step
441
+ )
442
+ net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0)
443
+ x, x_lengths = x.cuda(local_rank, non_blocking=True), x_lengths.cuda(
444
+ local_rank, non_blocking=True
445
+ )
446
+ spec, spec_lengths = spec.cuda(
447
+ local_rank, non_blocking=True
448
+ ), spec_lengths.cuda(local_rank, non_blocking=True)
449
+ y, y_lengths = y.cuda(local_rank, non_blocking=True), y_lengths.cuda(
450
+ local_rank, non_blocking=True
451
+ )
452
+ speakers = speakers.cuda(local_rank, non_blocking=True)
453
+ tone = tone.cuda(local_rank, non_blocking=True)
454
+ language = language.cuda(local_rank, non_blocking=True)
455
+ bert = bert.cuda(local_rank, non_blocking=True)
456
+ ja_bert = ja_bert.cuda(local_rank, non_blocking=True)
457
+ en_bert = en_bert.cuda(local_rank, non_blocking=True)
458
+
459
+ with autocast(enabled=hps.train.bf16_run, dtype=torch.bfloat16):
460
+ (
461
+ y_hat,
462
+ l_length,
463
+ attn,
464
+ ids_slice,
465
+ x_mask,
466
+ z_mask,
467
+ (z, z_p, m_p, logs_p, m_q, logs_q),
468
+ (hidden_x, logw, logw_, logw_sdp),
469
+ g,
470
+ ) = net_g(
471
+ x,
472
+ x_lengths,
473
+ spec,
474
+ spec_lengths,
475
+ speakers,
476
+ tone,
477
+ language,
478
+ bert,
479
+ ja_bert,
480
+ en_bert,
481
+ )
482
+ mel = spec_to_mel_torch(
483
+ spec,
484
+ hps.data.filter_length,
485
+ hps.data.n_mel_channels,
486
+ hps.data.sampling_rate,
487
+ hps.data.mel_fmin,
488
+ hps.data.mel_fmax,
489
+ )
490
+ y_mel = commons.slice_segments(
491
+ mel, ids_slice, hps.train.segment_size // hps.data.hop_length
492
+ )
493
+ y_hat_mel = mel_spectrogram_torch(
494
+ y_hat.squeeze(1).float(),
495
+ hps.data.filter_length,
496
+ hps.data.n_mel_channels,
497
+ hps.data.sampling_rate,
498
+ hps.data.hop_length,
499
+ hps.data.win_length,
500
+ hps.data.mel_fmin,
501
+ hps.data.mel_fmax,
502
+ )
503
+
504
+ y = commons.slice_segments(
505
+ y, ids_slice * hps.data.hop_length, hps.train.segment_size
506
+ ) # slice
507
+
508
+ # Discriminator
509
+ y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach())
510
+ with autocast(enabled=hps.train.bf16_run, dtype=torch.bfloat16):
511
+ loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(
512
+ y_d_hat_r, y_d_hat_g
513
+ )
514
+ loss_disc_all = loss_disc
515
+ if net_dur_disc is not None:
516
+ y_dur_hat_r, y_dur_hat_g = net_dur_disc(
517
+ hidden_x.detach(),
518
+ x_mask.detach(),
519
+ logw_.detach(),
520
+ logw.detach(),
521
+ g.detach(),
522
+ )
523
+ y_dur_hat_r_sdp, y_dur_hat_g_sdp = net_dur_disc(
524
+ hidden_x.detach(),
525
+ x_mask.detach(),
526
+ logw_.detach(),
527
+ logw_sdp.detach(),
528
+ g.detach(),
529
+ )
530
+ y_dur_hat_r = y_dur_hat_r + y_dur_hat_r_sdp
531
+ y_dur_hat_g = y_dur_hat_g + y_dur_hat_g_sdp
532
+ with autocast(enabled=hps.train.bf16_run, dtype=torch.bfloat16):
533
+ # TODO: I think need to mean using the mask, but for now, just mean all
534
+ (
535
+ loss_dur_disc,
536
+ losses_dur_disc_r,
537
+ losses_dur_disc_g,
538
+ ) = discriminator_loss(y_dur_hat_r, y_dur_hat_g)
539
+ loss_dur_disc_all = loss_dur_disc
540
+ optim_dur_disc.zero_grad()
541
+ scaler.scale(loss_dur_disc_all).backward()
542
+ scaler.unscale_(optim_dur_disc)
543
+ # torch.nn.utils.clip_grad_norm_(
544
+ # parameters=net_dur_disc.parameters(), max_norm=100
545
+ # )
546
+ grad_norm_dur = commons.clip_grad_value_(
547
+ net_dur_disc.parameters(), None
548
+ )
549
+ scaler.step(optim_dur_disc)
550
+
551
+ optim_d.zero_grad()
552
+ scaler.scale(loss_disc_all).backward()
553
+ scaler.unscale_(optim_d)
554
+ if getattr(hps.train, "bf16_run", False):
555
+ torch.nn.utils.clip_grad_norm_(parameters=net_d.parameters(), max_norm=200)
556
+ grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None)
557
+ scaler.step(optim_d)
558
+
559
+ with autocast(enabled=hps.train.bf16_run, dtype=torch.bfloat16):
560
+ loss_slm = wl.discriminator(
561
+ y.detach().squeeze(), y_hat.detach().squeeze()
562
+ ).mean()
563
+
564
+ optim_wd.zero_grad()
565
+ scaler.scale(loss_slm).backward()
566
+ scaler.unscale_(optim_wd)
567
+ # torch.nn.utils.clip_grad_norm_(parameters=net_wd.parameters(), max_norm=200)
568
+ grad_norm_wd = commons.clip_grad_value_(net_wd.parameters(), None)
569
+ scaler.step(optim_wd)
570
+
571
+ with autocast(enabled=hps.train.bf16_run, dtype=torch.bfloat16):
572
+ # Generator
573
+ y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat)
574
+ if net_dur_disc is not None:
575
+ _, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw_, logw, g)
576
+ _, y_dur_hat_g_sdp = net_dur_disc(hidden_x, x_mask, logw_, logw_sdp, g)
577
+ y_dur_hat_g = y_dur_hat_g + y_dur_hat_g_sdp
578
+ with autocast(enabled=hps.train.bf16_run, dtype=torch.bfloat16):
579
+ loss_dur = torch.sum(l_length.float())
580
+ loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel
581
+ loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
582
+
583
+ loss_fm = feature_loss(fmap_r, fmap_g)
584
+ loss_gen, losses_gen = generator_loss(y_d_hat_g)
585
+
586
+ loss_lm = wl(y.detach().squeeze(), y_hat.squeeze()).mean()
587
+ loss_lm_gen = wl.generator(y_hat.squeeze())
588
+
589
+ loss_gen_all = (
590
+ loss_gen
591
+ + loss_fm
592
+ + loss_mel
593
+ + loss_dur
594
+ + loss_kl
595
+ + loss_lm
596
+ + loss_lm_gen
597
+ )
598
+ if net_dur_disc is not None:
599
+ loss_dur_gen, losses_dur_gen = generator_loss(y_dur_hat_g)
600
+ loss_gen_all += loss_dur_gen
601
+ optim_g.zero_grad()
602
+ scaler.scale(loss_gen_all).backward()
603
+ scaler.unscale_(optim_g)
604
+ if getattr(hps.train, "bf16_run", False):
605
+ torch.nn.utils.clip_grad_norm_(parameters=net_g.parameters(), max_norm=500)
606
+ grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None)
607
+ scaler.step(optim_g)
608
+ scaler.update()
609
+
610
+ if rank == 0:
611
+ if global_step % hps.train.log_interval == 0:
612
+ lr = optim_g.param_groups[0]["lr"]
613
+ losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_dur, loss_kl]
614
+ logger.info(
615
+ "Train Epoch: {} [{:.0f}%]".format(
616
+ epoch, 100.0 * batch_idx / len(train_loader)
617
+ )
618
+ )
619
+ logger.info([x.item() for x in losses] + [global_step, lr])
620
+
621
+ scalar_dict = {
622
+ "loss/g/total": loss_gen_all,
623
+ "loss/d/total": loss_disc_all,
624
+ "loss/wd/total": loss_slm,
625
+ "learning_rate": lr,
626
+ "grad_norm_d": grad_norm_d,
627
+ "grad_norm_g": grad_norm_g,
628
+ "grad_norm_dur": grad_norm_dur,
629
+ "grad_norm_wd": grad_norm_wd,
630
+ }
631
+ scalar_dict.update(
632
+ {
633
+ "loss/g/fm": loss_fm,
634
+ "loss/g/mel": loss_mel,
635
+ "loss/g/dur": loss_dur,
636
+ "loss/g/kl": loss_kl,
637
+ "loss/g/lm": loss_lm,
638
+ "loss/g/lm_gen": loss_lm_gen,
639
+ }
640
+ )
641
+ scalar_dict.update(
642
+ {"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)}
643
+ )
644
+ scalar_dict.update(
645
+ {"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)}
646
+ )
647
+ scalar_dict.update(
648
+ {"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)}
649
+ )
650
+
651
+ if net_dur_disc is not None:
652
+ scalar_dict.update({"loss/dur_disc/total": loss_dur_disc_all})
653
+
654
+ scalar_dict.update(
655
+ {
656
+ "loss/dur_disc_g/{}".format(i): v
657
+ for i, v in enumerate(losses_dur_disc_g)
658
+ }
659
+ )
660
+ scalar_dict.update(
661
+ {
662
+ "loss/dur_disc_r/{}".format(i): v
663
+ for i, v in enumerate(losses_dur_disc_r)
664
+ }
665
+ )
666
+
667
+ scalar_dict.update({"loss/g/dur_gen": loss_dur_gen})
668
+ scalar_dict.update(
669
+ {
670
+ "loss/g/dur_gen_{}".format(i): v
671
+ for i, v in enumerate(losses_dur_gen)
672
+ }
673
+ )
674
+
675
+ image_dict = {
676
+ "slice/mel_org": utils.plot_spectrogram_to_numpy(
677
+ y_mel[0].data.cpu().numpy()
678
+ ),
679
+ "slice/mel_gen": utils.plot_spectrogram_to_numpy(
680
+ y_hat_mel[0].data.cpu().numpy()
681
+ ),
682
+ "all/mel": utils.plot_spectrogram_to_numpy(
683
+ mel[0].data.cpu().numpy()
684
+ ),
685
+ "all/attn": utils.plot_alignment_to_numpy(
686
+ attn[0, 0].data.cpu().numpy()
687
+ ),
688
+ }
689
+ utils.summarize(
690
+ writer=writer,
691
+ global_step=global_step,
692
+ images=image_dict,
693
+ scalars=scalar_dict,
694
+ )
695
+
696
+ if global_step % hps.train.eval_interval == 0:
697
+ evaluate(hps, net_g, eval_loader, writer_eval)
698
+ utils.save_checkpoint(
699
+ net_g,
700
+ optim_g,
701
+ hps.train.learning_rate,
702
+ epoch,
703
+ os.path.join(hps.model_dir, "G_{}.pth".format(global_step)),
704
+ )
705
+ utils.save_checkpoint(
706
+ net_d,
707
+ optim_d,
708
+ hps.train.learning_rate,
709
+ epoch,
710
+ os.path.join(hps.model_dir, "D_{}.pth".format(global_step)),
711
+ )
712
+ utils.save_checkpoint(
713
+ net_wd,
714
+ optim_wd,
715
+ hps.train.learning_rate,
716
+ epoch,
717
+ os.path.join(hps.model_dir, "WD_{}.pth".format(global_step)),
718
+ )
719
+ if net_dur_disc is not None:
720
+ utils.save_checkpoint(
721
+ net_dur_disc,
722
+ optim_dur_disc,
723
+ hps.train.learning_rate,
724
+ epoch,
725
+ os.path.join(hps.model_dir, "DUR_{}.pth".format(global_step)),
726
+ )
727
+ keep_ckpts = config.train_ms_config.keep_ckpts
728
+ if keep_ckpts > 0:
729
+ utils.clean_checkpoints(
730
+ path_to_models=hps.model_dir,
731
+ n_ckpts_to_keep=keep_ckpts,
732
+ sort_by_time=True,
733
+ )
734
+
735
+ global_step += 1
736
+
737
+ gc.collect()
738
+ torch.cuda.empty_cache()
739
+ if rank == 0:
740
+ logger.info("====> Epoch: {}".format(epoch))
741
+
742
+
743
+ def evaluate(hps, generator, eval_loader, writer_eval):
744
+ generator.eval()
745
+ image_dict = {}
746
+ audio_dict = {}
747
+ print("Evaluating ...")
748
+ with torch.no_grad():
749
+ for batch_idx, (
750
+ x,
751
+ x_lengths,
752
+ spec,
753
+ spec_lengths,
754
+ y,
755
+ y_lengths,
756
+ speakers,
757
+ tone,
758
+ language,
759
+ bert,
760
+ ja_bert,
761
+ en_bert,
762
+ ) in enumerate(eval_loader):
763
+ x, x_lengths = x.cuda(), x_lengths.cuda()
764
+ spec, spec_lengths = spec.cuda(), spec_lengths.cuda()
765
+ y, y_lengths = y.cuda(), y_lengths.cuda()
766
+ speakers = speakers.cuda()
767
+ bert = bert.cuda()
768
+ ja_bert = ja_bert.cuda()
769
+ en_bert = en_bert.cuda()
770
+ tone = tone.cuda()
771
+ language = language.cuda()
772
+ for use_sdp in [True, False]:
773
+ y_hat, attn, mask, *_ = generator.module.infer(
774
+ x,
775
+ x_lengths,
776
+ speakers,
777
+ tone,
778
+ language,
779
+ bert,
780
+ ja_bert,
781
+ en_bert,
782
+ y=spec,
783
+ max_len=1000,
784
+ sdp_ratio=0.0 if not use_sdp else 1.0,
785
+ )
786
+ y_hat_lengths = mask.sum([1, 2]).long() * hps.data.hop_length
787
+
788
+ mel = spec_to_mel_torch(
789
+ spec,
790
+ hps.data.filter_length,
791
+ hps.data.n_mel_channels,
792
+ hps.data.sampling_rate,
793
+ hps.data.mel_fmin,
794
+ hps.data.mel_fmax,
795
+ )
796
+ y_hat_mel = mel_spectrogram_torch(
797
+ y_hat.squeeze(1).float(),
798
+ hps.data.filter_length,
799
+ hps.data.n_mel_channels,
800
+ hps.data.sampling_rate,
801
+ hps.data.hop_length,
802
+ hps.data.win_length,
803
+ hps.data.mel_fmin,
804
+ hps.data.mel_fmax,
805
+ )
806
+ image_dict.update(
807
+ {
808
+ f"gen/mel_{batch_idx}": utils.plot_spectrogram_to_numpy(
809
+ y_hat_mel[0].cpu().numpy()
810
+ )
811
+ }
812
+ )
813
+ audio_dict.update(
814
+ {
815
+ f"gen/audio_{batch_idx}_{use_sdp}": y_hat[
816
+ 0, :, : y_hat_lengths[0]
817
+ ]
818
+ }
819
+ )
820
+ image_dict.update(
821
+ {
822
+ f"gt/mel_{batch_idx}": utils.plot_spectrogram_to_numpy(
823
+ mel[0].cpu().numpy()
824
+ )
825
+ }
826
+ )
827
+ audio_dict.update({f"gt/audio_{batch_idx}": y[0, :, : y_lengths[0]]})
828
+
829
+ utils.summarize(
830
+ writer=writer_eval,
831
+ global_step=global_step,
832
+ images=image_dict,
833
+ audios=audio_dict,
834
+ audio_sampling_rate=hps.data.sampling_rate,
835
+ )
836
+ generator.train()
837
+
838
+
839
+ if __name__ == "__main__":
840
+ run()
transforms.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
13
+ inputs,
14
+ unnormalized_widths,
15
+ unnormalized_heights,
16
+ unnormalized_derivatives,
17
+ inverse=False,
18
+ tails=None,
19
+ tail_bound=1.0,
20
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
21
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
22
+ min_derivative=DEFAULT_MIN_DERIVATIVE,
23
+ ):
24
+ if tails is None:
25
+ spline_fn = rational_quadratic_spline
26
+ spline_kwargs = {}
27
+ else:
28
+ spline_fn = unconstrained_rational_quadratic_spline
29
+ spline_kwargs = {"tails": tails, "tail_bound": tail_bound}
30
+
31
+ outputs, logabsdet = spline_fn(
32
+ inputs=inputs,
33
+ unnormalized_widths=unnormalized_widths,
34
+ unnormalized_heights=unnormalized_heights,
35
+ unnormalized_derivatives=unnormalized_derivatives,
36
+ inverse=inverse,
37
+ min_bin_width=min_bin_width,
38
+ min_bin_height=min_bin_height,
39
+ min_derivative=min_derivative,
40
+ **spline_kwargs
41
+ )
42
+ return outputs, logabsdet
43
+
44
+
45
+ def searchsorted(bin_locations, inputs, eps=1e-6):
46
+ bin_locations[..., -1] += eps
47
+ return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1
48
+
49
+
50
+ def unconstrained_rational_quadratic_spline(
51
+ inputs,
52
+ unnormalized_widths,
53
+ unnormalized_heights,
54
+ unnormalized_derivatives,
55
+ inverse=False,
56
+ tails="linear",
57
+ tail_bound=1.0,
58
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
59
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
60
+ min_derivative=DEFAULT_MIN_DERIVATIVE,
61
+ ):
62
+ inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
63
+ outside_interval_mask = ~inside_interval_mask
64
+
65
+ outputs = torch.zeros_like(inputs)
66
+ logabsdet = torch.zeros_like(inputs)
67
+
68
+ if tails == "linear":
69
+ unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
70
+ constant = np.log(np.exp(1 - min_derivative) - 1)
71
+ unnormalized_derivatives[..., 0] = constant
72
+ unnormalized_derivatives[..., -1] = constant
73
+
74
+ outputs[outside_interval_mask] = inputs[outside_interval_mask]
75
+ logabsdet[outside_interval_mask] = 0
76
+ else:
77
+ raise RuntimeError("{} tails are not implemented.".format(tails))
78
+
79
+ (
80
+ outputs[inside_interval_mask],
81
+ logabsdet[inside_interval_mask],
82
+ ) = 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,
89
+ right=tail_bound,
90
+ bottom=-tail_bound,
91
+ top=tail_bound,
92
+ min_bin_width=min_bin_width,
93
+ min_bin_height=min_bin_height,
94
+ min_derivative=min_derivative,
95
+ )
96
+
97
+ return outputs, logabsdet
98
+
99
+
100
+ def rational_quadratic_spline(
101
+ inputs,
102
+ unnormalized_widths,
103
+ unnormalized_heights,
104
+ unnormalized_derivatives,
105
+ inverse=False,
106
+ left=0.0,
107
+ right=1.0,
108
+ bottom=0.0,
109
+ top=1.0,
110
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
111
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
112
+ min_derivative=DEFAULT_MIN_DERIVATIVE,
113
+ ):
114
+ if torch.min(inputs) < left or torch.max(inputs) > right:
115
+ raise ValueError("Input to a transform is not within its domain")
116
+
117
+ num_bins = unnormalized_widths.shape[-1]
118
+
119
+ if min_bin_width * num_bins > 1.0:
120
+ raise ValueError("Minimal bin width too large for the number of bins")
121
+ if min_bin_height * num_bins > 1.0:
122
+ raise ValueError("Minimal bin height too large for the number of bins")
123
+
124
+ widths = F.softmax(unnormalized_widths, dim=-1)
125
+ widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
126
+ cumwidths = torch.cumsum(widths, dim=-1)
127
+ cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0)
128
+ cumwidths = (right - left) * cumwidths + left
129
+ cumwidths[..., 0] = left
130
+ cumwidths[..., -1] = right
131
+ widths = cumwidths[..., 1:] - cumwidths[..., :-1]
132
+
133
+ derivatives = min_derivative + F.softplus(unnormalized_derivatives)
134
+
135
+ heights = F.softmax(unnormalized_heights, dim=-1)
136
+ heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
137
+ cumheights = torch.cumsum(heights, dim=-1)
138
+ cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0)
139
+ cumheights = (top - bottom) * cumheights + bottom
140
+ cumheights[..., 0] = bottom
141
+ cumheights[..., -1] = top
142
+ heights = cumheights[..., 1:] - cumheights[..., :-1]
143
+
144
+ if inverse:
145
+ bin_idx = searchsorted(cumheights, inputs)[..., None]
146
+ else:
147
+ bin_idx = searchsorted(cumwidths, inputs)[..., None]
148
+
149
+ input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
150
+ input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
151
+
152
+ input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
153
+ delta = heights / widths
154
+ input_delta = delta.gather(-1, bin_idx)[..., 0]
155
+
156
+ input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
157
+ input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
158
+
159
+ input_heights = heights.gather(-1, bin_idx)[..., 0]
160
+
161
+ if inverse:
162
+ a = (inputs - input_cumheights) * (
163
+ input_derivatives + input_derivatives_plus_one - 2 * input_delta
164
+ ) + input_heights * (input_delta - input_derivatives)
165
+ b = input_heights * input_derivatives - (inputs - input_cumheights) * (
166
+ input_derivatives + input_derivatives_plus_one - 2 * input_delta
167
+ )
168
+ c = -input_delta * (inputs - input_cumheights)
169
+
170
+ discriminant = b.pow(2) - 4 * a * c
171
+ assert (discriminant >= 0).all()
172
+
173
+ root = (2 * c) / (-b - torch.sqrt(discriminant))
174
+ outputs = root * input_bin_widths + input_cumwidths
175
+
176
+ theta_one_minus_theta = root * (1 - root)
177
+ denominator = input_delta + (
178
+ (input_derivatives + input_derivatives_plus_one - 2 * input_delta)
179
+ * theta_one_minus_theta
180
+ )
181
+ derivative_numerator = input_delta.pow(2) * (
182
+ input_derivatives_plus_one * root.pow(2)
183
+ + 2 * input_delta * theta_one_minus_theta
184
+ + input_derivatives * (1 - root).pow(2)
185
+ )
186
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
187
+
188
+ return outputs, -logabsdet
189
+ else:
190
+ theta = (inputs - input_cumwidths) / input_bin_widths
191
+ theta_one_minus_theta = theta * (1 - theta)
192
+
193
+ numerator = input_heights * (
194
+ input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta
195
+ )
196
+ denominator = input_delta + (
197
+ (input_derivatives + input_derivatives_plus_one - 2 * input_delta)
198
+ * theta_one_minus_theta
199
+ )
200
+ outputs = input_cumheights + numerator / denominator
201
+
202
+ derivative_numerator = input_delta.pow(2) * (
203
+ input_derivatives_plus_one * theta.pow(2)
204
+ + 2 * input_delta * theta_one_minus_theta
205
+ + input_derivatives * (1 - theta).pow(2)
206
+ )
207
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
208
+
209
+ return outputs, logabsdet
update_status.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+
4
+ lang_dict = {"EN(英文)": "_en", "ZH(中文)": "_zh", "JP(日语)": "_jp"}
5
+
6
+
7
+ def raw_dir_convert_to_path(target_dir: str, lang):
8
+ res = target_dir.rstrip("/").rstrip("\\")
9
+ if (not target_dir.startswith("raw")) and (not target_dir.startswith("./raw")):
10
+ res = os.path.join("./raw", res)
11
+ if (
12
+ (not res.endswith("_zh"))
13
+ and (not res.endswith("_jp"))
14
+ and (not res.endswith("_en"))
15
+ ):
16
+ res += lang_dict[lang]
17
+ return res
18
+
19
+
20
+ def update_g_files():
21
+ g_files = []
22
+ cnt = 0
23
+ for root, dirs, files in os.walk(os.path.abspath("./logs")):
24
+ for file in files:
25
+ if file.startswith("G_") and file.endswith(".pth"):
26
+ g_files.append(os.path.join(root, file))
27
+ cnt += 1
28
+ print(g_files)
29
+ return f"更新模型列表完成, 共找到{cnt}个模型", gr.Dropdown.update(choices=g_files)
30
+
31
+
32
+ def update_c_files():
33
+ c_files = []
34
+ cnt = 0
35
+ for root, dirs, files in os.walk(os.path.abspath("./logs")):
36
+ for file in files:
37
+ if file.startswith("config.json"):
38
+ c_files.append(os.path.join(root, file))
39
+ cnt += 1
40
+ print(c_files)
41
+ return f"更新模型列表完成, 共找到{cnt}个配置文件", gr.Dropdown.update(choices=c_files)
42
+
43
+
44
+ def update_model_folders():
45
+ subdirs = []
46
+ cnt = 0
47
+ for root, dirs, files in os.walk(os.path.abspath("./logs")):
48
+ for dir_name in dirs:
49
+ if os.path.basename(dir_name) != "eval":
50
+ subdirs.append(os.path.join(root, dir_name))
51
+ cnt += 1
52
+ print(subdirs)
53
+ return f"更新模型文件夹列表完成, 共找到{cnt}个文件夹", gr.Dropdown.update(choices=subdirs)
54
+
55
+
56
+ def update_wav_lab_pairs():
57
+ wav_count = tot_count = 0
58
+ for root, _, files in os.walk("./raw"):
59
+ for file in files:
60
+ # print(file)
61
+ file_path = os.path.join(root, file)
62
+ if file.lower().endswith(".wav"):
63
+ lab_file = os.path.splitext(file_path)[0] + ".lab"
64
+ if os.path.exists(lab_file):
65
+ wav_count += 1
66
+ tot_count += 1
67
+ return f"{wav_count} / {tot_count}"
68
+
69
+
70
+ def update_raw_folders():
71
+ subdirs = []
72
+ cnt = 0
73
+ script_path = os.path.dirname(os.path.abspath(__file__)) # 获取当前脚本的绝对路径
74
+ raw_path = os.path.join(script_path, "raw")
75
+ print(raw_path)
76
+ os.makedirs(raw_path, exist_ok=True)
77
+ for root, dirs, files in os.walk(raw_path):
78
+ for dir_name in dirs:
79
+ relative_path = os.path.relpath(
80
+ os.path.join(root, dir_name), script_path
81
+ ) # 获取相对路径
82
+ subdirs.append(relative_path)
83
+ cnt += 1
84
+ print(subdirs)
85
+ return (
86
+ f"更新raw音频文件夹列表完成, 共找到{cnt}个文件夹",
87
+ gr.Dropdown.update(choices=subdirs),
88
+ gr.Textbox.update(value=update_wav_lab_pairs()),
89
+ )
utils.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import argparse
4
+ import logging
5
+ import json
6
+ import shutil
7
+ import subprocess
8
+ import numpy as np
9
+ from huggingface_hub import hf_hub_download
10
+ from scipy.io.wavfile import read
11
+ import torch
12
+ import re
13
+
14
+ MATPLOTLIB_FLAG = False
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ def download_emo_models(mirror, repo_id, model_name):
20
+ if mirror == "openi":
21
+ import openi
22
+
23
+ openi.model.download_model(
24
+ "Stardust_minus/Bert-VITS2",
25
+ repo_id.split("/")[-1],
26
+ "./emotional",
27
+ )
28
+ else:
29
+ hf_hub_download(
30
+ repo_id,
31
+ "pytorch_model.bin",
32
+ local_dir=model_name,
33
+ local_dir_use_symlinks=False,
34
+ )
35
+
36
+
37
+ def download_checkpoint(
38
+ dir_path, repo_config, token=None, regex="G_*.pth", mirror="openi"
39
+ ):
40
+ repo_id = repo_config["repo_id"]
41
+ f_list = glob.glob(os.path.join(dir_path, regex))
42
+ if f_list:
43
+ print("Use existed model, skip downloading.")
44
+ return
45
+ if mirror.lower() == "openi":
46
+ import openi
47
+
48
+ kwargs = {"token": token} if token else {}
49
+ openi.login(**kwargs)
50
+
51
+ model_image = repo_config["model_image"]
52
+ openi.model.download_model(repo_id, model_image, dir_path)
53
+
54
+ fs = glob.glob(os.path.join(dir_path, model_image, "*.pth"))
55
+ for file in fs:
56
+ shutil.move(file, dir_path)
57
+ shutil.rmtree(os.path.join(dir_path, model_image))
58
+ else:
59
+ for file in ["DUR_0.pth", "D_0.pth", "G_0.pth"]:
60
+ hf_hub_download(
61
+ repo_id, file, local_dir=dir_path, local_dir_use_symlinks=False
62
+ )
63
+
64
+
65
+ def load_checkpoint(checkpoint_path, model, optimizer=None, skip_optimizer=False):
66
+ assert os.path.isfile(checkpoint_path)
67
+ checkpoint_dict = torch.load(checkpoint_path, map_location="cpu")
68
+ iteration = checkpoint_dict["iteration"]
69
+ learning_rate = checkpoint_dict["learning_rate"]
70
+ if (
71
+ optimizer is not None
72
+ and not skip_optimizer
73
+ and checkpoint_dict["optimizer"] is not None
74
+ ):
75
+ optimizer.load_state_dict(checkpoint_dict["optimizer"])
76
+ elif optimizer is None and not skip_optimizer:
77
+ # else: Disable this line if Infer and resume checkpoint,then enable the line upper
78
+ new_opt_dict = optimizer.state_dict()
79
+ new_opt_dict_params = new_opt_dict["param_groups"][0]["params"]
80
+ new_opt_dict["param_groups"] = checkpoint_dict["optimizer"]["param_groups"]
81
+ new_opt_dict["param_groups"][0]["params"] = new_opt_dict_params
82
+ optimizer.load_state_dict(new_opt_dict)
83
+
84
+ saved_state_dict = checkpoint_dict["model"]
85
+ if hasattr(model, "module"):
86
+ state_dict = model.module.state_dict()
87
+ else:
88
+ state_dict = model.state_dict()
89
+
90
+ new_state_dict = {}
91
+ for k, v in state_dict.items():
92
+ try:
93
+ # assert "emb_g" not in k
94
+ new_state_dict[k] = saved_state_dict[k]
95
+ assert saved_state_dict[k].shape == v.shape, (
96
+ saved_state_dict[k].shape,
97
+ v.shape,
98
+ )
99
+ except:
100
+ # For upgrading from the old version
101
+ if "ja_bert_proj" in k:
102
+ v = torch.zeros_like(v)
103
+ logger.warn(
104
+ f"Seems you are using the old version of the model, the {k} is automatically set to zero for backward compatibility"
105
+ )
106
+ else:
107
+ logger.error(f"{k} is not in the checkpoint")
108
+
109
+ new_state_dict[k] = v
110
+
111
+ if hasattr(model, "module"):
112
+ model.module.load_state_dict(new_state_dict, strict=False)
113
+ else:
114
+ model.load_state_dict(new_state_dict, strict=False)
115
+
116
+ logger.info(
117
+ "Loaded checkpoint '{}' (iteration {})".format(checkpoint_path, iteration)
118
+ )
119
+
120
+ return model, optimizer, learning_rate, iteration
121
+
122
+
123
+ def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
124
+ logger.info(
125
+ "Saving model and optimizer state at iteration {} to {}".format(
126
+ iteration, checkpoint_path
127
+ )
128
+ )
129
+ if hasattr(model, "module"):
130
+ state_dict = model.module.state_dict()
131
+ else:
132
+ state_dict = model.state_dict()
133
+ torch.save(
134
+ {
135
+ "model": state_dict,
136
+ "iteration": iteration,
137
+ "optimizer": optimizer.state_dict(),
138
+ "learning_rate": learning_rate,
139
+ },
140
+ checkpoint_path,
141
+ )
142
+
143
+
144
+ def summarize(
145
+ writer,
146
+ global_step,
147
+ scalars={},
148
+ histograms={},
149
+ images={},
150
+ audios={},
151
+ audio_sampling_rate=22050,
152
+ ):
153
+ for k, v in scalars.items():
154
+ writer.add_scalar(k, v, global_step)
155
+ for k, v in histograms.items():
156
+ writer.add_histogram(k, v, global_step)
157
+ for k, v in images.items():
158
+ writer.add_image(k, v, global_step, dataformats="HWC")
159
+ for k, v in audios.items():
160
+ writer.add_audio(k, v, global_step, audio_sampling_rate)
161
+
162
+
163
+ def latest_checkpoint_path(dir_path, regex="G_*.pth"):
164
+ f_list = glob.glob(os.path.join(dir_path, regex))
165
+ f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
166
+ x = f_list[-1]
167
+ return x
168
+
169
+
170
+ def plot_spectrogram_to_numpy(spectrogram):
171
+ global MATPLOTLIB_FLAG
172
+ if not MATPLOTLIB_FLAG:
173
+ import matplotlib
174
+
175
+ matplotlib.use("Agg")
176
+ MATPLOTLIB_FLAG = True
177
+ mpl_logger = logging.getLogger("matplotlib")
178
+ mpl_logger.setLevel(logging.WARNING)
179
+ import matplotlib.pylab as plt
180
+ import numpy as np
181
+
182
+ fig, ax = plt.subplots(figsize=(10, 2))
183
+ im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none")
184
+ plt.colorbar(im, ax=ax)
185
+ plt.xlabel("Frames")
186
+ plt.ylabel("Channels")
187
+ plt.tight_layout()
188
+
189
+ fig.canvas.draw()
190
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
191
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
192
+ plt.close()
193
+ return data
194
+
195
+
196
+ def plot_alignment_to_numpy(alignment, info=None):
197
+ global MATPLOTLIB_FLAG
198
+ if not MATPLOTLIB_FLAG:
199
+ import matplotlib
200
+
201
+ matplotlib.use("Agg")
202
+ MATPLOTLIB_FLAG = True
203
+ mpl_logger = logging.getLogger("matplotlib")
204
+ mpl_logger.setLevel(logging.WARNING)
205
+ import matplotlib.pylab as plt
206
+ import numpy as np
207
+
208
+ fig, ax = plt.subplots(figsize=(6, 4))
209
+ im = ax.imshow(
210
+ alignment.transpose(), aspect="auto", origin="lower", interpolation="none"
211
+ )
212
+ fig.colorbar(im, ax=ax)
213
+ xlabel = "Decoder timestep"
214
+ if info is not None:
215
+ xlabel += "\n\n" + info
216
+ plt.xlabel(xlabel)
217
+ plt.ylabel("Encoder timestep")
218
+ plt.tight_layout()
219
+
220
+ fig.canvas.draw()
221
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
222
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
223
+ plt.close()
224
+ return data
225
+
226
+
227
+ def load_wav_to_torch(full_path):
228
+ sampling_rate, data = read(full_path)
229
+ return torch.FloatTensor(data.astype(np.float32)), sampling_rate
230
+
231
+
232
+ def load_filepaths_and_text(filename, split="|"):
233
+ with open(filename, encoding="utf-8") as f:
234
+ filepaths_and_text = [line.strip().split(split) for line in f]
235
+ return filepaths_and_text
236
+
237
+
238
+ def get_hparams(init=True):
239
+ parser = argparse.ArgumentParser()
240
+ parser.add_argument(
241
+ "-c",
242
+ "--config",
243
+ type=str,
244
+ default="./configs/base.json",
245
+ help="JSON file for configuration",
246
+ )
247
+ parser.add_argument("-m", "--model", type=str, required=True, help="Model name")
248
+
249
+ args = parser.parse_args()
250
+ model_dir = os.path.join("./logs", args.model)
251
+
252
+ if not os.path.exists(model_dir):
253
+ os.makedirs(model_dir)
254
+
255
+ config_path = args.config
256
+ config_save_path = os.path.join(model_dir, "config.json")
257
+ if init:
258
+ with open(config_path, "r", encoding="utf-8") as f:
259
+ data = f.read()
260
+ with open(config_save_path, "w", encoding="utf-8") as f:
261
+ f.write(data)
262
+ else:
263
+ with open(config_save_path, "r", vencoding="utf-8") as f:
264
+ data = f.read()
265
+ config = json.loads(data)
266
+ hparams = HParams(**config)
267
+ hparams.model_dir = model_dir
268
+ return hparams
269
+
270
+
271
+ def clean_checkpoints(path_to_models="logs/44k/", n_ckpts_to_keep=2, sort_by_time=True):
272
+ """Freeing up space by deleting saved ckpts
273
+
274
+ Arguments:
275
+ path_to_models -- Path to the model directory
276
+ n_ckpts_to_keep -- Number of ckpts to keep, excluding G_0.pth and D_0.pth
277
+ sort_by_time -- True -> chronologically delete ckpts
278
+ False -> lexicographically delete ckpts
279
+ """
280
+ import re
281
+
282
+ ckpts_files = [
283
+ f
284
+ for f in os.listdir(path_to_models)
285
+ if os.path.isfile(os.path.join(path_to_models, f))
286
+ ]
287
+
288
+ def name_key(_f):
289
+ return int(re.compile("._(\\d+)\\.pth").match(_f).group(1))
290
+
291
+ def time_key(_f):
292
+ return os.path.getmtime(os.path.join(path_to_models, _f))
293
+
294
+ sort_key = time_key if sort_by_time else name_key
295
+
296
+ def x_sorted(_x):
297
+ return sorted(
298
+ [f for f in ckpts_files if f.startswith(_x) and not f.endswith("_0.pth")],
299
+ key=sort_key,
300
+ )
301
+
302
+ to_del = [
303
+ os.path.join(path_to_models, fn)
304
+ for fn in (
305
+ x_sorted("G")[:-n_ckpts_to_keep]
306
+ + x_sorted("D")[:-n_ckpts_to_keep]
307
+ + x_sorted("WD")[:-n_ckpts_to_keep]
308
+ )
309
+ ]
310
+
311
+ def del_info(fn):
312
+ return logger.info(f".. Free up space by deleting ckpt {fn}")
313
+
314
+ def del_routine(x):
315
+ return [os.remove(x), del_info(x)]
316
+
317
+ [del_routine(fn) for fn in to_del]
318
+
319
+
320
+ def get_hparams_from_dir(model_dir):
321
+ config_save_path = os.path.join(model_dir, "config.json")
322
+ with open(config_save_path, "r", encoding="utf-8") as f:
323
+ data = f.read()
324
+ config = json.loads(data)
325
+
326
+ hparams = HParams(**config)
327
+ hparams.model_dir = model_dir
328
+ return hparams
329
+
330
+
331
+ def get_hparams_from_file(config_path):
332
+ # print("config_path: ", config_path)
333
+ with open(config_path, "r", encoding="utf-8") as f:
334
+ data = f.read()
335
+ config = json.loads(data)
336
+
337
+ hparams = HParams(**config)
338
+ return hparams
339
+
340
+
341
+ def check_git_hash(model_dir):
342
+ source_dir = os.path.dirname(os.path.realpath(__file__))
343
+ if not os.path.exists(os.path.join(source_dir, ".git")):
344
+ logger.warn(
345
+ "{} is not a git repository, therefore hash value comparison will be ignored.".format(
346
+ source_dir
347
+ )
348
+ )
349
+ return
350
+
351
+ cur_hash = subprocess.getoutput("git rev-parse HEAD")
352
+
353
+ path = os.path.join(model_dir, "githash")
354
+ if os.path.exists(path):
355
+ saved_hash = open(path).read()
356
+ if saved_hash != cur_hash:
357
+ logger.warn(
358
+ "git hash values are different. {}(saved) != {}(current)".format(
359
+ saved_hash[:8], cur_hash[:8]
360
+ )
361
+ )
362
+ else:
363
+ open(path, "w").write(cur_hash)
364
+
365
+
366
+ def get_logger(model_dir, filename="train.log"):
367
+ global logger
368
+ logger = logging.getLogger(os.path.basename(model_dir))
369
+ logger.setLevel(logging.DEBUG)
370
+
371
+ formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
372
+ if not os.path.exists(model_dir):
373
+ os.makedirs(model_dir)
374
+ h = logging.FileHandler(os.path.join(model_dir, filename))
375
+ h.setLevel(logging.DEBUG)
376
+ h.setFormatter(formatter)
377
+ logger.addHandler(h)
378
+ return logger
379
+
380
+
381
+ class HParams:
382
+ def __init__(self, **kwargs):
383
+ for k, v in kwargs.items():
384
+ if type(v) == dict:
385
+ v = HParams(**v)
386
+ self[k] = v
387
+
388
+ def keys(self):
389
+ return self.__dict__.keys()
390
+
391
+ def items(self):
392
+ return self.__dict__.items()
393
+
394
+ def values(self):
395
+ return self.__dict__.values()
396
+
397
+ def __len__(self):
398
+ return len(self.__dict__)
399
+
400
+ def __getitem__(self, key):
401
+ return getattr(self, key)
402
+
403
+ def __setitem__(self, key, value):
404
+ return setattr(self, key, value)
405
+
406
+ def __contains__(self, key):
407
+ return key in self.__dict__
408
+
409
+ def __repr__(self):
410
+ return self.__dict__.__repr__()
411
+
412
+
413
+ def load_model(model_path, config_path):
414
+ hps = get_hparams_from_file(config_path)
415
+ net = SynthesizerTrn(
416
+ # len(symbols),
417
+ 108,
418
+ hps.data.filter_length // 2 + 1,
419
+ hps.train.segment_size // hps.data.hop_length,
420
+ n_speakers=hps.data.n_speakers,
421
+ **hps.model,
422
+ ).to("cpu")
423
+ _ = net.eval()
424
+ _ = load_checkpoint(model_path, net, None, skip_optimizer=True)
425
+ return net
426
+
427
+
428
+ def mix_model(
429
+ network1, network2, output_path, voice_ratio=(0.5, 0.5), tone_ratio=(0.5, 0.5)
430
+ ):
431
+ if hasattr(network1, "module"):
432
+ state_dict1 = network1.module.state_dict()
433
+ state_dict2 = network2.module.state_dict()
434
+ else:
435
+ state_dict1 = network1.state_dict()
436
+ state_dict2 = network2.state_dict()
437
+ for k in state_dict1.keys():
438
+ if k not in state_dict2.keys():
439
+ continue
440
+ if "enc_p" in k:
441
+ state_dict1[k] = (
442
+ state_dict1[k].clone() * tone_ratio[0]
443
+ + state_dict2[k].clone() * tone_ratio[1]
444
+ )
445
+ else:
446
+ state_dict1[k] = (
447
+ state_dict1[k].clone() * voice_ratio[0]
448
+ + state_dict2[k].clone() * voice_ratio[1]
449
+ )
450
+ for k in state_dict2.keys():
451
+ if k not in state_dict1.keys():
452
+ state_dict1[k] = state_dict2[k].clone()
453
+ torch.save(
454
+ {"model": state_dict1, "iteration": 0, "optimizer": None, "learning_rate": 0},
455
+ output_path,
456
+ )
457
+
458
+
459
+ def get_steps(model_path):
460
+ matches = re.findall(r"\d+", model_path)
461
+ return matches[-1] if matches else None
webui_preprocess.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import webbrowser
3
+ import os
4
+ import json
5
+ import subprocess
6
+ import shutil
7
+
8
+
9
+ def get_path(data_dir):
10
+ start_path = os.path.join("./data", data_dir)
11
+ lbl_path = os.path.join(start_path, "esd.list")
12
+ train_path = os.path.join(start_path, "train.list")
13
+ val_path = os.path.join(start_path, "val.list")
14
+ config_path = os.path.join(start_path, "configs", "config.json")
15
+ return start_path, lbl_path, train_path, val_path, config_path
16
+
17
+
18
+ def generate_config(data_dir, batch_size):
19
+ assert data_dir != "", "数据集名称不能为空"
20
+ start_path, _, train_path, val_path, config_path = get_path(data_dir)
21
+ if os.path.isfile(config_path):
22
+ config = json.load(open(config_path, "r", encoding="utf-8"))
23
+ else:
24
+ config = json.load(open("configs/config.json", "r", encoding="utf-8"))
25
+ config["data"]["training_files"] = train_path
26
+ config["data"]["validation_files"] = val_path
27
+ config["train"]["batch_size"] = batch_size
28
+ out_path = os.path.join(start_path, "configs")
29
+ if not os.path.isdir(out_path):
30
+ os.mkdir(out_path)
31
+ model_path = os.path.join(start_path, "models")
32
+ if not os.path.isdir(model_path):
33
+ os.mkdir(model_path)
34
+ with open(config_path, "w", encoding="utf-8") as f:
35
+ json.dump(config, f, indent=4)
36
+ if not os.path.exists("config.yml"):
37
+ shutil.copy(src="default_config.yml", dst="config.yml")
38
+ return "配置文件生成完成"
39
+
40
+
41
+ def resample(data_dir):
42
+ assert data_dir != "", "数据集名称不能为空"
43
+ start_path, _, _, _, config_path = get_path(data_dir)
44
+ in_dir = os.path.join(start_path, "raw")
45
+ out_dir = os.path.join(start_path, "wavs")
46
+ subprocess.run(
47
+ f"python resample_legacy.py "
48
+ f"--sr 44100 "
49
+ f"--in_dir {in_dir} "
50
+ f"--out_dir {out_dir} ",
51
+ shell=True,
52
+ )
53
+ return "音频文件预处理完成"
54
+
55
+
56
+ def preprocess_text(data_dir):
57
+ assert data_dir != "", "数据集名称不能为空"
58
+ start_path, lbl_path, train_path, val_path, config_path = get_path(data_dir)
59
+ lines = open(lbl_path, "r", encoding="utf-8").readlines()
60
+ with open(lbl_path, "w", encoding="utf-8") as f:
61
+ for line in lines:
62
+ path, spk, language, text = line.strip().split("|")
63
+ path = os.path.join(start_path, "wavs", os.path.basename(path)).replace(
64
+ "\\", "/"
65
+ )
66
+ f.writelines(f"{path}|{spk}|{language}|{text}\n")
67
+ subprocess.run(
68
+ f"python preprocess_text.py "
69
+ f"--transcription-path {lbl_path} "
70
+ f"--train-path {train_path} "
71
+ f"--val-path {val_path} "
72
+ f"--config-path {config_path}",
73
+ shell=True,
74
+ )
75
+ return "标签文件预处理完成"
76
+
77
+
78
+ def bert_gen(data_dir):
79
+ assert data_dir != "", "数据集名称不能为空"
80
+ _, _, _, _, config_path = get_path(data_dir)
81
+ subprocess.run(
82
+ f"python bert_gen.py " f"--config {config_path}",
83
+ shell=True,
84
+ )
85
+ return "BERT 特征文件生成完成"
86
+
87
+
88
+ if __name__ == "__main__":
89
+ with gr.Blocks() as app:
90
+ with gr.Row():
91
+ with gr.Column():
92
+ _ = gr.Markdown(
93
+ value="# Bert-VITS2 数据预处理\n"
94
+ "## 预先准备:\n"
95
+ "下载 BERT 和 WavLM 模型:\n"
96
+ "- [中文 RoBERTa](https://huggingface.co/hfl/chinese-roberta-wwm-ext-large)\n"
97
+ "- [日文 DeBERTa](https://huggingface.co/ku-nlp/deberta-v2-large-japanese-char-wwm)\n"
98
+ "- [英文 DeBERTa](https://huggingface.co/microsoft/deberta-v3-large)\n"
99
+ "- [WavLM](https://huggingface.co/microsoft/wavlm-base-plus)\n"
100
+ "\n"
101
+ "将 BERT 模型放置到 `bert` 文件夹下,WavLM 模型放置到 `slm` 文件夹下,覆盖同名文件夹。\n"
102
+ "\n"
103
+ "数据准备:\n"
104
+ "将数据放置在 data 文件夹下,按照如下结构组织:\n"
105
+ "\n"
106
+ "```\n"
107
+ "├── data\n"
108
+ "│ ├── {你的数据集名称}\n"
109
+ "│ │ ├── esd.list\n"
110
+ "│ │ ├── raw\n"
111
+ "│ │ │ ├── ****.wav\n"
112
+ "│ │ │ ├── ****.wav\n"
113
+ "│ │ │ ├── ...\n"
114
+ "```\n"
115
+ "\n"
116
+ "其中,`raw` 文件夹下保存所有的音频文件,`esd.list` 文件为标签文本,格式为\n"
117
+ "\n"
118
+ "```\n"
119
+ "****.wav|{说话人名}|{语言 ID}|{标签文本}\n"
120
+ "```\n"
121
+ "\n"
122
+ "例如:\n"
123
+ "```\n"
124
+ "vo_ABDLQ001_1_paimon_02.wav|派蒙|ZH|没什么没什么,只是���时他总是站在这里,有点奇怪而已。\n"
125
+ "noa_501_0001.wav|NOA|JP|そうだね、油断しないのはとても大事なことだと思う\n"
126
+ "Albedo_vo_ABDLQ002_4_albedo_01.wav|Albedo|EN|Who are you? Why did you alarm them?\n"
127
+ "...\n"
128
+ "```\n"
129
+ )
130
+ data_dir = gr.Textbox(
131
+ label="数据集名称",
132
+ placeholder="你放置在 data 文件夹下的数据集所在文件夹的名称,如 data/genshin 则填 genshin",
133
+ )
134
+ info = gr.Textbox(label="状态信息")
135
+ _ = gr.Markdown(value="## 第一步:生成配置文件")
136
+ with gr.Row():
137
+ batch_size = gr.Slider(
138
+ label="批大小(Batch size):24 GB 显存可用 12",
139
+ value=8,
140
+ minimum=1,
141
+ maximum=64,
142
+ step=1,
143
+ )
144
+ generate_config_btn = gr.Button(value="执行", variant="primary")
145
+ _ = gr.Markdown(value="## 第二步:预处理音频文件")
146
+ resample_btn = gr.Button(value="执行", variant="primary")
147
+ _ = gr.Markdown(value="## 第三步:预处理标签文件")
148
+ preprocess_text_btn = gr.Button(value="执行", variant="primary")
149
+ _ = gr.Markdown(value="## 第四步:生成 BERT 特征文件")
150
+ bert_gen_btn = gr.Button(value="执行", variant="primary")
151
+ _ = gr.Markdown(
152
+ value="## 训练模型及部署:\n"
153
+ "修改根目录下的 `config.yml` 中 `dataset_path` 一项为 `data/{你的数据集名称}`\n"
154
+ "- 训练:将[预训练模型文件](https://openi.pcl.ac.cn/Stardust_minus/Bert-VITS2/modelmanage/show_model)(`D_0.pth`、`DUR_0.pth`、`WD_0.pth` 和 `G_0.pth`)放到 `data/{你的数据集名称}/models` 文件夹下,执行 `torchrun --nproc_per_node=1 train_ms.py` 命令(多卡运行可参考 `run_MnodesAndMgpus.sh` 中的命令。\n"
155
+ "- 部署:修改根目录下的 `config.yml` 中 `webui` 下 `model` 一项为 `models/{权重文件名}.pth` (如 G_10000.pth),然后执行 `python webui.py`"
156
+ )
157
+
158
+ generate_config_btn.click(
159
+ generate_config, inputs=[data_dir, batch_size], outputs=[info]
160
+ )
161
+ resample_btn.click(resample, inputs=[data_dir], outputs=[info])
162
+ preprocess_text_btn.click(preprocess_text, inputs=[data_dir], outputs=[info])
163
+ bert_gen_btn.click(bert_gen, inputs=[data_dir], outputs=[info])
164
+
165
+ webbrowser.open("http://127.0.0.1:7860")
166
+ app.launch(share=False, server_port=7860)