horiyouta commited on
Commit
b5e3368
1 Parent(s): 24bd25e

202406080543

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
App.bat DELETED
@@ -1,11 +0,0 @@
1
- chcp 65001 > NUL
2
- @echo off
3
-
4
- pushd %~dp0
5
- echo Running app.py...
6
- venv\Scripts\python app.py
7
-
8
- if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
9
-
10
- popd
11
- pause
 
 
 
 
 
 
 
 
 
 
 
 
Data/.gitignore DELETED
@@ -1,2 +0,0 @@
1
- *
2
- !.gitignore
 
 
 
Dataset.bat DELETED
@@ -1,11 +0,0 @@
1
- chcp 65001 > NUL
2
- @echo off
3
-
4
- pushd %~dp0
5
- echo Running webui_dataset.py...
6
- venv\Scripts\python webui_dataset.py
7
-
8
- if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
9
-
10
- popd
11
- pause
 
 
 
 
 
 
 
 
 
 
 
 
Dockerfile.deploy → Dockerfile RENAMED
File without changes
Dockerfile.train DELETED
@@ -1,109 +0,0 @@
1
- # PaperspaceのGradient環境での学習環境構築用Dockerfileです。
2
- # 環境のみ構築するため、イメージには学習用のコードは含まれていません。
3
- # 以下を参照しました。
4
- # https://github.com/gradient-ai/base-container/tree/main/pt211-tf215-cudatk120-py311
5
-
6
- # 主なバージョン等
7
- # Ubuntu 22.04
8
- # Python 3.10
9
- # PyTorch 2.1.2 (CUDA 11.8)
10
- # CUDA Toolkit 12.0, CUDNN 8.9.7
11
-
12
-
13
- # ==================================================================
14
- # Initial setup
15
- # ------------------------------------------------------------------
16
-
17
- # Ubuntu 22.04 as base image
18
- FROM ubuntu:22.04
19
- # RUN yes| unminimize
20
-
21
- # Set ENV variables
22
- ENV LANG C.UTF-8
23
- ENV SHELL=/bin/bash
24
- ENV DEBIAN_FRONTEND=noninteractive
25
-
26
- ENV APT_INSTALL="apt-get install -y --no-install-recommends"
27
- ENV PIP_INSTALL="python3 -m pip --no-cache-dir install --upgrade"
28
- ENV GIT_CLONE="git clone --depth 10"
29
-
30
- # ==================================================================
31
- # Tools
32
- # ------------------------------------------------------------------
33
-
34
- RUN apt-get update && \
35
- $APT_INSTALL \
36
- sudo \
37
- build-essential \
38
- ca-certificates \
39
- wget \
40
- curl \
41
- git \
42
- zip \
43
- unzip \
44
- nano \
45
- ffmpeg \
46
- software-properties-common \
47
- gnupg \
48
- python3 \
49
- python3-pip \
50
- python3-dev
51
-
52
- # ==================================================================
53
- # Git-lfs
54
- # ------------------------------------------------------------------
55
-
56
- RUN curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash && \
57
- $APT_INSTALL git-lfs
58
-
59
-
60
- # Add symlink so python and python3 commands use same python3.9 executable
61
- RUN ln -s /usr/bin/python3 /usr/local/bin/python
62
-
63
- # ==================================================================
64
- # Installing CUDA packages (CUDA Toolkit 12.0 and CUDNN 8.9.7)
65
- # ------------------------------------------------------------------
66
- RUN wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-ubuntu2204.pin && \
67
- mv cuda-ubuntu2204.pin /etc/apt/preferences.d/cuda-repository-pin-600 && \
68
- wget https://developer.download.nvidia.com/compute/cuda/12.0.0/local_installers/cuda-repo-ubuntu2204-12-0-local_12.0.0-525.60.13-1_amd64.deb && \
69
- dpkg -i cuda-repo-ubuntu2204-12-0-local_12.0.0-525.60.13-1_amd64.deb && \
70
- cp /var/cuda-repo-ubuntu2204-12-0-local/cuda-*-keyring.gpg /usr/share/keyrings/ && \
71
- apt-get update && \
72
- $APT_INSTALL cuda && \
73
- rm cuda-repo-ubuntu2204-12-0-local_12.0.0-525.60.13-1_amd64.deb
74
-
75
- # Installing CUDNN
76
- RUN apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/3bf863cc.pub && \
77
- add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/ /" && \
78
- apt-get update && \
79
- $APT_INSTALL libcudnn8=8.9.7.29-1+cuda12.2 \
80
- libcudnn8-dev=8.9.7.29-1+cuda12.2
81
-
82
-
83
- ENV PATH=$PATH:/usr/local/cuda/bin
84
- ENV LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
85
-
86
-
87
- # ==================================================================
88
- # PyTorch
89
- # ------------------------------------------------------------------
90
-
91
- # Based on https://pytorch.org/get-started/locally/
92
-
93
- RUN $PIP_INSTALL torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
94
-
95
-
96
- RUN $PIP_INSTALL jupyterlab
97
-
98
- # Install requirements.txt from the project
99
- COPY requirements.txt /tmp/requirements.txt
100
- RUN $PIP_INSTALL -r /tmp/requirements.txt
101
- RUN rm /tmp/requirements.txt
102
-
103
- # ==================================================================
104
- # Startup
105
- # ------------------------------------------------------------------
106
-
107
- EXPOSE 8888 6006
108
-
109
- CMD jupyter lab --allow-root --ip=0.0.0.0 --no-browser --ServerApp.trust_xheaders=True --ServerApp.disable_check_xsrf=False --ServerApp.allow_remote_access=True --ServerApp.allow_origin='*' --ServerApp.allow_credentials=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Editor.bat DELETED
@@ -1,11 +0,0 @@
1
- chcp 65001 > NUL
2
- @echo off
3
-
4
- pushd %~dp0
5
- echo Running server_editor.py --inbrowser
6
- venv\Scripts\python server_editor.py --inbrowser
7
-
8
- if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
9
-
10
- popd
11
- pause
 
 
 
 
 
 
 
 
 
 
 
 
LGPL_LICENSE DELETED
@@ -1,165 +0,0 @@
1
- GNU LESSER GENERAL PUBLIC LICENSE
2
- Version 3, 29 June 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
-
9
- This version of the GNU Lesser General Public License incorporates
10
- the terms and conditions of version 3 of the GNU General Public
11
- License, supplemented by the additional permissions listed below.
12
-
13
- 0. Additional Definitions.
14
-
15
- As used herein, "this License" refers to version 3 of the GNU Lesser
16
- General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
- General Public License.
18
-
19
- "The Library" refers to a covered work governed by this License,
20
- other than an Application or a Combined Work as defined below.
21
-
22
- An "Application" is any work that makes use of an interface provided
23
- by the Library, but which is not otherwise based on the Library.
24
- Defining a subclass of a class defined by the Library is deemed a mode
25
- of using an interface provided by the Library.
26
-
27
- A "Combined Work" is a work produced by combining or linking an
28
- Application with the Library. The particular version of the Library
29
- with which the Combined Work was made is also called the "Linked
30
- Version".
31
-
32
- The "Minimal Corresponding Source" for a Combined Work means the
33
- Corresponding Source for the Combined Work, excluding any source code
34
- for portions of the Combined Work that, considered in isolation, are
35
- based on the Application, and not on the Linked Version.
36
-
37
- The "Corresponding Application Code" for a Combined Work means the
38
- object code and/or source code for the Application, including any data
39
- and utility programs needed for reproducing the Combined Work from the
40
- Application, but excluding the System Libraries of the Combined Work.
41
-
42
- 1. Exception to Section 3 of the GNU GPL.
43
-
44
- You may convey a covered work under sections 3 and 4 of this License
45
- without being bound by section 3 of the GNU GPL.
46
-
47
- 2. Conveying Modified Versions.
48
-
49
- If you modify a copy of the Library, and, in your modifications, a
50
- facility refers to a function or data to be supplied by an Application
51
- that uses the facility (other than as an argument passed when the
52
- facility is invoked), then you may convey a copy of the modified
53
- version:
54
-
55
- a) under this License, provided that you make a good faith effort to
56
- ensure that, in the event an Application does not supply the
57
- function or data, the facility still operates, and performs
58
- whatever part of its purpose remains meaningful, or
59
-
60
- b) under the GNU GPL, with none of the additional permissions of
61
- this License applicable to that copy.
62
-
63
- 3. Object Code Incorporating Material from Library Header Files.
64
-
65
- The object code form of an Application may incorporate material from
66
- a header file that is part of the Library. You may convey such object
67
- code under terms of your choice, provided that, if the incorporated
68
- material is not limited to numerical parameters, data structure
69
- layouts and accessors, or small macros, inline functions and templates
70
- (ten or fewer lines in length), you do both of the following:
71
-
72
- a) Give prominent notice with each copy of the object code that the
73
- Library is used in it and that the Library and its use are
74
- covered by this License.
75
-
76
- b) Accompany the object code with a copy of the GNU GPL and this license
77
- document.
78
-
79
- 4. Combined Works.
80
-
81
- You may convey a Combined Work under terms of your choice that,
82
- taken together, effectively do not restrict modification of the
83
- portions of the Library contained in the Combined Work and reverse
84
- engineering for debugging such modifications, if you also do each of
85
- the following:
86
-
87
- a) Give prominent notice with each copy of the Combined Work that
88
- the Library is used in it and that the Library and its use are
89
- covered by this License.
90
-
91
- b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
- document.
93
-
94
- c) For a Combined Work that displays copyright notices during
95
- execution, include the copyright notice for the Library among
96
- these notices, as well as a reference directing the user to the
97
- copies of the GNU GPL and this license document.
98
-
99
- d) Do one of the following:
100
-
101
- 0) Convey the Minimal Corresponding Source under the terms of this
102
- License, and the Corresponding Application Code in a form
103
- suitable for, and under terms that permit, the user to
104
- recombine or relink the Application with a modified version of
105
- the Linked Version to produce a modified Combined Work, in the
106
- manner specified by section 6 of the GNU GPL for conveying
107
- Corresponding Source.
108
-
109
- 1) Use a suitable shared library mechanism for linking with the
110
- Library. A suitable mechanism is one that (a) uses at run time
111
- a copy of the Library already present on the user's computer
112
- system, and (b) will operate properly with a modified version
113
- of the Library that is interface-compatible with the Linked
114
- Version.
115
-
116
- e) Provide Installation Information, but only if you would otherwise
117
- be required to provide such information under section 6 of the
118
- GNU GPL, and only to the extent that such information is
119
- necessary to install and execute a modified version of the
120
- Combined Work produced by recombining or relinking the
121
- Application with a modified version of the Linked Version. (If
122
- you use option 4d0, the Installation Information must accompany
123
- the Minimal Corresponding Source and Corresponding Application
124
- Code. If you use option 4d1, you must provide the Installation
125
- Information in the manner specified by section 6 of the GNU GPL
126
- for conveying Corresponding Source.)
127
-
128
- 5. Combined Libraries.
129
-
130
- You may place library facilities that are a work based on the
131
- Library side by side in a single library together with other library
132
- facilities that are not Applications and are not covered by this
133
- License, and convey such a combined library under terms of your
134
- choice, if you do both of the following:
135
-
136
- a) Accompany the combined library with a copy of the same work based
137
- on the Library, uncombined with any other library facilities,
138
- conveyed under the terms of this License.
139
-
140
- b) Give prominent notice with the combined library that part of it
141
- is a work based on the Library, and explaining where to find the
142
- accompanying uncombined form of the same work.
143
-
144
- 6. Revised Versions of the GNU Lesser General Public License.
145
-
146
- The Free Software Foundation may publish revised and/or new versions
147
- of the GNU Lesser General Public License from time to time. Such new
148
- versions will be similar in spirit to the present version, but may
149
- differ in detail to address new problems or concerns.
150
-
151
- Each version is given a distinguishing version number. If the
152
- Library as you received it specifies that a certain numbered version
153
- of the GNU Lesser General Public License "or any later version"
154
- applies to it, you have the option of following the terms and
155
- conditions either of that published version or of any later version
156
- published by the Free Software Foundation. If the Library as you
157
- received it does not specify a version number of the GNU Lesser
158
- General Public License, you may choose any version of the GNU Lesser
159
- General Public License ever published by the Free Software Foundation.
160
-
161
- If the Library as you received it specifies that a proxy can decide
162
- whether future versions of the GNU Lesser General Public License shall
163
- apply, that proxy's public statement of acceptance of any version is
164
- permanent authorization for you to choose that version for the
165
- Library.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
LICENSE DELETED
@@ -1,661 +0,0 @@
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/>.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Merge.bat DELETED
@@ -1,13 +0,0 @@
1
- chcp 65001 > NUL
2
-
3
- @echo off
4
-
5
- pushd %~dp0
6
-
7
- echo Running webui_merge.py...
8
- venv\Scripts\python webui_merge.py
9
-
10
- if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
11
-
12
- popd
13
- pause
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Server.bat DELETED
@@ -1,11 +0,0 @@
1
- chcp 65001 > NUL
2
- @echo off
3
-
4
- pushd %~dp0
5
- echo Running server_fastapi.py
6
- venv\Scripts\python server_fastapi.py
7
-
8
- if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
9
-
10
- popd
11
- pause
 
 
 
 
 
 
 
 
 
 
 
 
Style.bat DELETED
@@ -1,12 +0,0 @@
1
- chcp 65001 > NUL
2
-
3
- @echo off
4
-
5
- pushd %~dp0
6
- echo Running webui_style_vectors.py...
7
- venv\Scripts\python webui_style_vectors.py
8
-
9
- if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
10
-
11
- popd
12
- pause
 
 
 
 
 
 
 
 
 
 
 
 
 
Train.bat DELETED
@@ -1,13 +0,0 @@
1
- chcp 65001 > NUL
2
-
3
- @echo off
4
-
5
- pushd %~dp0
6
-
7
- echo Running webui_train.py...
8
- venv\Scripts\python webui_train.py
9
-
10
- if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
11
-
12
- popd
13
- pause
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py DELETED
@@ -1,65 +0,0 @@
1
- import argparse
2
- from pathlib import Path
3
-
4
- import gradio as gr
5
- import torch
6
- import yaml
7
-
8
- from gradio_tabs.dataset import create_dataset_app
9
- from gradio_tabs.inference import create_inference_app
10
- from gradio_tabs.merge import create_merge_app
11
- from gradio_tabs.style_vectors import create_style_vectors_app
12
- from gradio_tabs.train import create_train_app
13
- from style_bert_vits2.constants import GRADIO_THEME, VERSION
14
- from style_bert_vits2.nlp.japanese import pyopenjtalk_worker
15
- from style_bert_vits2.nlp.japanese.user_dict import update_dict
16
- from style_bert_vits2.tts_model import TTSModelHolder
17
-
18
-
19
- # このプロセスからはワーカーを起動して辞書を使いたいので、ここで初期化
20
- pyopenjtalk_worker.initialize_worker()
21
-
22
- # dict_data/ 以下の辞書データを pyopenjtalk に適用
23
- update_dict()
24
-
25
- # Get path settings
26
- with Path("configs/paths.yml").open("r", encoding="utf-8") as f:
27
- path_config: dict[str, str] = yaml.safe_load(f.read())
28
- # dataset_root = path_config["dataset_root"]
29
- assets_root = path_config["assets_root"]
30
-
31
- parser = argparse.ArgumentParser()
32
- parser.add_argument("--device", type=str, default="cuda")
33
- parser.add_argument("--host", type=str, default="127.0.0.1")
34
- parser.add_argument("--port", type=int, default=None)
35
- parser.add_argument("--no_autolaunch", action="store_true")
36
- parser.add_argument("--share", action="store_true")
37
-
38
- args = parser.parse_args()
39
- device = args.device
40
- if device == "cuda" and not torch.cuda.is_available():
41
- device = "cpu"
42
-
43
- model_holder = TTSModelHolder(Path(assets_root), device)
44
-
45
- with gr.Blocks(theme=GRADIO_THEME) as app:
46
- gr.Markdown(f"# Style-Bert-VITS2 WebUI (version {VERSION})")
47
- with gr.Tabs():
48
- with gr.Tab("音声合成"):
49
- create_inference_app(model_holder=model_holder)
50
- with gr.Tab("データセット作成"):
51
- create_dataset_app()
52
- with gr.Tab("学習"):
53
- create_train_app()
54
- with gr.Tab("スタイル作成"):
55
- create_style_vectors_app()
56
- with gr.Tab("マージ"):
57
- create_merge_app(model_holder=model_holder)
58
-
59
-
60
- app.launch(
61
- server_name=args.host,
62
- server_port=args.port,
63
- inbrowser=not args.no_autolaunch,
64
- share=args.share,
65
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
attentions.py DELETED
@@ -1,462 +0,0 @@
1
- import math
2
- import torch
3
- from torch import nn
4
- from torch.nn import functional as F
5
-
6
- import commons
7
- from common.log import logger as logging
8
-
9
-
10
- class LayerNorm(nn.Module):
11
- def __init__(self, channels, eps=1e-5):
12
- super().__init__()
13
- self.channels = channels
14
- self.eps = eps
15
-
16
- self.gamma = nn.Parameter(torch.ones(channels))
17
- self.beta = nn.Parameter(torch.zeros(channels))
18
-
19
- def forward(self, x):
20
- x = x.transpose(1, -1)
21
- x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
22
- return x.transpose(1, -1)
23
-
24
-
25
- @torch.jit.script
26
- def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
27
- n_channels_int = n_channels[0]
28
- in_act = input_a + input_b
29
- t_act = torch.tanh(in_act[:, :n_channels_int, :])
30
- s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
31
- acts = t_act * s_act
32
- return acts
33
-
34
-
35
- class Encoder(nn.Module):
36
- def __init__(
37
- self,
38
- hidden_channels,
39
- filter_channels,
40
- n_heads,
41
- n_layers,
42
- kernel_size=1,
43
- p_dropout=0.0,
44
- window_size=4,
45
- isflow=True,
46
- **kwargs
47
- ):
48
- super().__init__()
49
- self.hidden_channels = hidden_channels
50
- self.filter_channels = filter_channels
51
- self.n_heads = n_heads
52
- self.n_layers = n_layers
53
- self.kernel_size = kernel_size
54
- self.p_dropout = p_dropout
55
- self.window_size = window_size
56
- # if isflow:
57
- # cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
58
- # self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
59
- # self.cond_layer = weight_norm(cond_layer, name='weight')
60
- # self.gin_channels = 256
61
- self.cond_layer_idx = self.n_layers
62
- if "gin_channels" in kwargs:
63
- self.gin_channels = kwargs["gin_channels"]
64
- if self.gin_channels != 0:
65
- self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
66
- # vits2 says 3rd block, so idx is 2 by default
67
- self.cond_layer_idx = (
68
- kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
69
- )
70
- # logging.debug(self.gin_channels, self.cond_layer_idx)
71
- assert (
72
- self.cond_layer_idx < self.n_layers
73
- ), "cond_layer_idx should be less than n_layers"
74
- self.drop = nn.Dropout(p_dropout)
75
- self.attn_layers = nn.ModuleList()
76
- self.norm_layers_1 = nn.ModuleList()
77
- self.ffn_layers = nn.ModuleList()
78
- self.norm_layers_2 = nn.ModuleList()
79
- for i in range(self.n_layers):
80
- self.attn_layers.append(
81
- MultiHeadAttention(
82
- hidden_channels,
83
- hidden_channels,
84
- n_heads,
85
- p_dropout=p_dropout,
86
- window_size=window_size,
87
- )
88
- )
89
- self.norm_layers_1.append(LayerNorm(hidden_channels))
90
- self.ffn_layers.append(
91
- FFN(
92
- hidden_channels,
93
- hidden_channels,
94
- filter_channels,
95
- kernel_size,
96
- p_dropout=p_dropout,
97
- )
98
- )
99
- self.norm_layers_2.append(LayerNorm(hidden_channels))
100
-
101
- def forward(self, x, x_mask, g=None):
102
- attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
103
- x = x * x_mask
104
- for i in range(self.n_layers):
105
- if i == self.cond_layer_idx and g is not None:
106
- g = self.spk_emb_linear(g.transpose(1, 2))
107
- g = g.transpose(1, 2)
108
- x = x + g
109
- x = x * x_mask
110
- y = self.attn_layers[i](x, x, attn_mask)
111
- y = self.drop(y)
112
- x = self.norm_layers_1[i](x + y)
113
-
114
- y = self.ffn_layers[i](x, x_mask)
115
- y = self.drop(y)
116
- x = self.norm_layers_2[i](x + y)
117
- x = x * x_mask
118
- return x
119
-
120
-
121
- class Decoder(nn.Module):
122
- def __init__(
123
- self,
124
- hidden_channels,
125
- filter_channels,
126
- n_heads,
127
- n_layers,
128
- kernel_size=1,
129
- p_dropout=0.0,
130
- proximal_bias=False,
131
- proximal_init=True,
132
- **kwargs
133
- ):
134
- super().__init__()
135
- self.hidden_channels = hidden_channels
136
- self.filter_channels = filter_channels
137
- self.n_heads = n_heads
138
- self.n_layers = n_layers
139
- self.kernel_size = kernel_size
140
- self.p_dropout = p_dropout
141
- self.proximal_bias = proximal_bias
142
- self.proximal_init = proximal_init
143
-
144
- self.drop = nn.Dropout(p_dropout)
145
- self.self_attn_layers = nn.ModuleList()
146
- self.norm_layers_0 = nn.ModuleList()
147
- self.encdec_attn_layers = nn.ModuleList()
148
- self.norm_layers_1 = nn.ModuleList()
149
- self.ffn_layers = nn.ModuleList()
150
- self.norm_layers_2 = nn.ModuleList()
151
- for i in range(self.n_layers):
152
- self.self_attn_layers.append(
153
- MultiHeadAttention(
154
- hidden_channels,
155
- hidden_channels,
156
- n_heads,
157
- p_dropout=p_dropout,
158
- proximal_bias=proximal_bias,
159
- proximal_init=proximal_init,
160
- )
161
- )
162
- self.norm_layers_0.append(LayerNorm(hidden_channels))
163
- self.encdec_attn_layers.append(
164
- MultiHeadAttention(
165
- hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
166
- )
167
- )
168
- self.norm_layers_1.append(LayerNorm(hidden_channels))
169
- self.ffn_layers.append(
170
- FFN(
171
- hidden_channels,
172
- hidden_channels,
173
- filter_channels,
174
- kernel_size,
175
- p_dropout=p_dropout,
176
- causal=True,
177
- )
178
- )
179
- self.norm_layers_2.append(LayerNorm(hidden_channels))
180
-
181
- def forward(self, x, x_mask, h, h_mask):
182
- """
183
- x: decoder input
184
- h: encoder output
185
- """
186
- self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
187
- device=x.device, dtype=x.dtype
188
- )
189
- encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
190
- x = x * x_mask
191
- for i in range(self.n_layers):
192
- y = self.self_attn_layers[i](x, x, self_attn_mask)
193
- y = self.drop(y)
194
- x = self.norm_layers_0[i](x + y)
195
-
196
- y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
197
- y = self.drop(y)
198
- x = self.norm_layers_1[i](x + y)
199
-
200
- y = self.ffn_layers[i](x, x_mask)
201
- y = self.drop(y)
202
- x = self.norm_layers_2[i](x + y)
203
- x = x * x_mask
204
- return x
205
-
206
-
207
- class MultiHeadAttention(nn.Module):
208
- def __init__(
209
- self,
210
- channels,
211
- out_channels,
212
- n_heads,
213
- p_dropout=0.0,
214
- window_size=None,
215
- heads_share=True,
216
- block_length=None,
217
- proximal_bias=False,
218
- proximal_init=False,
219
- ):
220
- super().__init__()
221
- assert channels % n_heads == 0
222
-
223
- self.channels = channels
224
- self.out_channels = out_channels
225
- self.n_heads = n_heads
226
- self.p_dropout = p_dropout
227
- self.window_size = window_size
228
- self.heads_share = heads_share
229
- self.block_length = block_length
230
- self.proximal_bias = proximal_bias
231
- self.proximal_init = proximal_init
232
- self.attn = None
233
-
234
- self.k_channels = channels // n_heads
235
- self.conv_q = nn.Conv1d(channels, channels, 1)
236
- self.conv_k = nn.Conv1d(channels, channels, 1)
237
- self.conv_v = nn.Conv1d(channels, channels, 1)
238
- self.conv_o = nn.Conv1d(channels, out_channels, 1)
239
- self.drop = nn.Dropout(p_dropout)
240
-
241
- if window_size is not None:
242
- n_heads_rel = 1 if heads_share else n_heads
243
- rel_stddev = self.k_channels**-0.5
244
- self.emb_rel_k = nn.Parameter(
245
- torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
246
- * rel_stddev
247
- )
248
- self.emb_rel_v = nn.Parameter(
249
- torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
250
- * rel_stddev
251
- )
252
-
253
- nn.init.xavier_uniform_(self.conv_q.weight)
254
- nn.init.xavier_uniform_(self.conv_k.weight)
255
- nn.init.xavier_uniform_(self.conv_v.weight)
256
- if proximal_init:
257
- with torch.no_grad():
258
- self.conv_k.weight.copy_(self.conv_q.weight)
259
- self.conv_k.bias.copy_(self.conv_q.bias)
260
-
261
- def forward(self, x, c, attn_mask=None):
262
- q = self.conv_q(x)
263
- k = self.conv_k(c)
264
- v = self.conv_v(c)
265
-
266
- x, self.attn = self.attention(q, k, v, mask=attn_mask)
267
-
268
- x = self.conv_o(x)
269
- return x
270
-
271
- def attention(self, query, key, value, mask=None):
272
- # reshape [b, d, t] -> [b, n_h, t, d_k]
273
- b, d, t_s, t_t = (*key.size(), query.size(2))
274
- query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
275
- key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
276
- value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
277
-
278
- scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
279
- if self.window_size is not None:
280
- assert (
281
- t_s == t_t
282
- ), "Relative attention is only available for self-attention."
283
- key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
284
- rel_logits = self._matmul_with_relative_keys(
285
- query / math.sqrt(self.k_channels), key_relative_embeddings
286
- )
287
- scores_local = self._relative_position_to_absolute_position(rel_logits)
288
- scores = scores + scores_local
289
- if self.proximal_bias:
290
- assert t_s == t_t, "Proximal bias is only available for self-attention."
291
- scores = scores + self._attention_bias_proximal(t_s).to(
292
- device=scores.device, dtype=scores.dtype
293
- )
294
- if mask is not None:
295
- scores = scores.masked_fill(mask == 0, -1e4)
296
- if self.block_length is not None:
297
- assert (
298
- t_s == t_t
299
- ), "Local attention is only available for self-attention."
300
- block_mask = (
301
- torch.ones_like(scores)
302
- .triu(-self.block_length)
303
- .tril(self.block_length)
304
- )
305
- scores = scores.masked_fill(block_mask == 0, -1e4)
306
- p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
307
- p_attn = self.drop(p_attn)
308
- output = torch.matmul(p_attn, value)
309
- if self.window_size is not None:
310
- relative_weights = self._absolute_position_to_relative_position(p_attn)
311
- value_relative_embeddings = self._get_relative_embeddings(
312
- self.emb_rel_v, t_s
313
- )
314
- output = output + self._matmul_with_relative_values(
315
- relative_weights, value_relative_embeddings
316
- )
317
- output = (
318
- output.transpose(2, 3).contiguous().view(b, d, t_t)
319
- ) # [b, n_h, t_t, d_k] -> [b, d, t_t]
320
- return output, p_attn
321
-
322
- def _matmul_with_relative_values(self, x, y):
323
- """
324
- x: [b, h, l, m]
325
- y: [h or 1, m, d]
326
- ret: [b, h, l, d]
327
- """
328
- ret = torch.matmul(x, y.unsqueeze(0))
329
- return ret
330
-
331
- def _matmul_with_relative_keys(self, x, y):
332
- """
333
- x: [b, h, l, d]
334
- y: [h or 1, m, d]
335
- ret: [b, h, l, m]
336
- """
337
- ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
338
- return ret
339
-
340
- def _get_relative_embeddings(self, relative_embeddings, length):
341
- 2 * self.window_size + 1
342
- # Pad first before slice to avoid using cond ops.
343
- pad_length = max(length - (self.window_size + 1), 0)
344
- slice_start_position = max((self.window_size + 1) - length, 0)
345
- slice_end_position = slice_start_position + 2 * length - 1
346
- if pad_length > 0:
347
- padded_relative_embeddings = F.pad(
348
- relative_embeddings,
349
- commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
350
- )
351
- else:
352
- padded_relative_embeddings = relative_embeddings
353
- used_relative_embeddings = padded_relative_embeddings[
354
- :, slice_start_position:slice_end_position
355
- ]
356
- return used_relative_embeddings
357
-
358
- def _relative_position_to_absolute_position(self, x):
359
- """
360
- x: [b, h, l, 2*l-1]
361
- ret: [b, h, l, l]
362
- """
363
- batch, heads, length, _ = x.size()
364
- # Concat columns of pad to shift from relative to absolute indexing.
365
- x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
366
-
367
- # Concat extra elements so to add up to shape (len+1, 2*len-1).
368
- x_flat = x.view([batch, heads, length * 2 * length])
369
- x_flat = F.pad(
370
- x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
371
- )
372
-
373
- # Reshape and slice out the padded elements.
374
- x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
375
- :, :, :length, length - 1 :
376
- ]
377
- return x_final
378
-
379
- def _absolute_position_to_relative_position(self, x):
380
- """
381
- x: [b, h, l, l]
382
- ret: [b, h, l, 2*l-1]
383
- """
384
- batch, heads, length, _ = x.size()
385
- # pad along column
386
- x = F.pad(
387
- x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
388
- )
389
- x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
390
- # add 0's in the beginning that will skew the elements after reshape
391
- x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
392
- x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
393
- return x_final
394
-
395
- def _attention_bias_proximal(self, length):
396
- """Bias for self-attention to encourage attention to close positions.
397
- Args:
398
- length: an integer scalar.
399
- Returns:
400
- a Tensor with shape [1, 1, length, length]
401
- """
402
- r = torch.arange(length, dtype=torch.float32)
403
- diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
404
- return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
405
-
406
-
407
- class FFN(nn.Module):
408
- def __init__(
409
- self,
410
- in_channels,
411
- out_channels,
412
- filter_channels,
413
- kernel_size,
414
- p_dropout=0.0,
415
- activation=None,
416
- causal=False,
417
- ):
418
- super().__init__()
419
- self.in_channels = in_channels
420
- self.out_channels = out_channels
421
- self.filter_channels = filter_channels
422
- self.kernel_size = kernel_size
423
- self.p_dropout = p_dropout
424
- self.activation = activation
425
- self.causal = causal
426
-
427
- if causal:
428
- self.padding = self._causal_padding
429
- else:
430
- self.padding = self._same_padding
431
-
432
- self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
433
- self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
434
- self.drop = nn.Dropout(p_dropout)
435
-
436
- def forward(self, x, x_mask):
437
- x = self.conv_1(self.padding(x * x_mask))
438
- if self.activation == "gelu":
439
- x = x * torch.sigmoid(1.702 * x)
440
- else:
441
- x = torch.relu(x)
442
- x = self.drop(x)
443
- x = self.conv_2(self.padding(x * x_mask))
444
- return x * x_mask
445
-
446
- def _causal_padding(self, x):
447
- if self.kernel_size == 1:
448
- return x
449
- pad_l = self.kernel_size - 1
450
- pad_r = 0
451
- padding = [[0, 0], [0, 0], [pad_l, pad_r]]
452
- x = F.pad(x, commons.convert_pad_shape(padding))
453
- return x
454
-
455
- def _same_padding(self, x):
456
- if self.kernel_size == 1:
457
- return x
458
- pad_l = (self.kernel_size - 1) // 2
459
- pad_r = self.kernel_size // 2
460
- padding = [[0, 0], [0, 0], [pad_l, pad_r]]
461
- x = F.pad(x, commons.convert_pad_shape(padding))
462
- return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bert_gen.py DELETED
@@ -1,99 +0,0 @@
1
- import argparse
2
- from concurrent.futures import ThreadPoolExecutor
3
-
4
- import torch
5
- import torch.multiprocessing as mp
6
- from tqdm import tqdm
7
-
8
- from config import config
9
- from style_bert_vits2.constants import Languages
10
- from style_bert_vits2.logging import logger
11
- from style_bert_vits2.models import commons
12
- from style_bert_vits2.models.hyper_parameters import HyperParameters
13
- from style_bert_vits2.nlp import (
14
- bert_models,
15
- cleaned_text_to_sequence,
16
- extract_bert_feature,
17
- )
18
- from style_bert_vits2.nlp.japanese import pyopenjtalk_worker
19
- from style_bert_vits2.nlp.japanese.user_dict import update_dict
20
- from style_bert_vits2.utils.stdout_wrapper import SAFE_STDOUT
21
-
22
-
23
- # このプロセスからはワーカーを起動して辞書を使いたいので、ここで初期化
24
- pyopenjtalk_worker.initialize_worker()
25
-
26
- # dict_data/ 以下の辞書データを pyopenjtalk に適用
27
- update_dict()
28
-
29
-
30
- def process_line(x: tuple[str, bool]):
31
- line, add_blank = x
32
- device = config.bert_gen_config.device
33
- if config.bert_gen_config.use_multi_device:
34
- rank = mp.current_process()._identity
35
- rank = rank[0] if len(rank) > 0 else 0
36
- if torch.cuda.is_available():
37
- gpu_id = rank % torch.cuda.device_count()
38
- device = f"cuda:{gpu_id}"
39
- else:
40
- device = "cpu"
41
- wav_path, _, language_str, text, phones, tone, word2ph = line.strip().split("|")
42
- phone = phones.split(" ")
43
- tone = [int(i) for i in tone.split(" ")]
44
- word2ph = [int(i) for i in word2ph.split(" ")]
45
- word2ph = [i for i in word2ph]
46
- phone, tone, language = cleaned_text_to_sequence(
47
- phone, tone, Languages[language_str]
48
- )
49
-
50
- if add_blank:
51
- phone = commons.intersperse(phone, 0)
52
- tone = commons.intersperse(tone, 0)
53
- language = commons.intersperse(language, 0)
54
- for i in range(len(word2ph)):
55
- word2ph[i] = word2ph[i] * 2
56
- word2ph[0] += 1
57
-
58
- bert_path = wav_path.replace(".WAV", ".wav").replace(".wav", ".bert.pt")
59
-
60
- try:
61
- bert = torch.load(bert_path)
62
- assert bert.shape[-1] == len(phone)
63
- except Exception:
64
- bert = extract_bert_feature(text, word2ph, language_str, device)
65
- assert bert.shape[-1] == len(phone)
66
- torch.save(bert, bert_path)
67
-
68
-
69
- preprocess_text_config = config.preprocess_text_config
70
-
71
- if __name__ == "__main__":
72
- parser = argparse.ArgumentParser()
73
- parser.add_argument(
74
- "-c", "--config", type=str, default=config.bert_gen_config.config_path
75
- )
76
- args, _ = parser.parse_known_args()
77
- config_path = args.config
78
- hps = HyperParameters.load_from_json(config_path)
79
- lines: list[str] = []
80
- with open(hps.data.training_files, "r", encoding="utf-8") as f:
81
- lines.extend(f.readlines())
82
-
83
- with open(hps.data.validation_files, "r", encoding="utf-8") as f:
84
- lines.extend(f.readlines())
85
- add_blank = [hps.data.add_blank] * len(lines)
86
-
87
- if len(lines) != 0:
88
- # pyopenjtalkの別ワーカー化により、並列処理でエラーがでる模様なので、一旦シングルスレッド強制にする
89
- num_processes = 1
90
- with ThreadPoolExecutor(max_workers=num_processes) as executor:
91
- _ = list(
92
- tqdm(
93
- executor.map(process_line, zip(lines, add_blank)),
94
- total=len(lines),
95
- file=SAFE_STDOUT,
96
- )
97
- )
98
-
99
- logger.info(f"bert.pt is generated! total: {len(lines)} bert.pt files.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
clustering.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
colab.ipynb DELETED
@@ -1,384 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "metadata": {},
6
- "source": [
7
- "# Style-Bert-VITS2 (ver 2.4.1) のGoogle Colabでの学習\n",
8
- "\n",
9
- "Google Colab上でStyle-Bert-VITS2の学習を行うことができます。\n",
10
- "\n",
11
- "このnotebookでは、通常使用ではあなたのGoogle Driveにフォルダ`Style-Bert-VITS2`を作り、その内部での作業を行います。他のフォルダには触れません。\n",
12
- "Google Driveを使わない場合は、初期設定のところで適切なパスを指定してください。\n",
13
- "\n",
14
- "## 流れ\n",
15
- "\n",
16
- "### 学習を最初からやりたいとき\n",
17
- "上から順に実行していけばいいです。音声合成に必要なファイルはGoogle Driveの`Style-Bert-VITS2/model_assets/`に保存されます。また、途中経過も`Style-Bert-VITS2/Data/`に保存されるので、学習を中断したり、途中から再開することもできます。\n",
18
- "\n",
19
- "### 学習を途中から再開したいとき\n",
20
- "0と1を行い、3の前処理は飛ばして、4から始めてください。スタイル分け5は、学習が終わったら必要なら行ってください。\n"
21
- ]
22
- },
23
- {
24
- "cell_type": "markdown",
25
- "metadata": {},
26
- "source": [
27
- "## 0. 環境構築\n",
28
- "\n",
29
- "Style-Bert-VITS2の環境をcolab上に構築します。グラボモードが有効になっていることを確認し、以下のセルを順に実行してください。\n",
30
- "\n",
31
- "**最近のcolabのアップデートにより、エラーダイアログ「WARNING: The following packages were previously imported in this runtime: [pydevd_plugins]」が出るが、「キャンセル」を選択して続行してください。**"
32
- ]
33
- },
34
- {
35
- "cell_type": "code",
36
- "execution_count": null,
37
- "metadata": {},
38
- "outputs": [],
39
- "source": [
40
- "# このセルを実行して環境構築してください。\n",
41
- "# エラーダイアログ「WARNING: The following packages were previously imported in this runtime: [pydevd_plugins]」が出るが「キャンセル」を選択して続行してください。\n",
42
- "\n",
43
- "!git clone https://github.com/litagin02/Style-Bert-VITS2.git\n",
44
- "%cd Style-Bert-VITS2/\n",
45
- "!pip install -r requirements.txt\n",
46
- "!python initialize.py --skip_jvnv"
47
- ]
48
- },
49
- {
50
- "cell_type": "code",
51
- "execution_count": null,
52
- "metadata": {},
53
- "outputs": [],
54
- "source": [
55
- "# Google driveを使う方はこちらを実行してください。\n",
56
- "\n",
57
- "from google.colab import drive\n",
58
- "drive.mount(\"/content/drive\")"
59
- ]
60
- },
61
- {
62
- "cell_type": "markdown",
63
- "metadata": {},
64
- "source": [
65
- "## 1. 初期設定\n",
66
- "\n",
67
- "学習とその結果を保存するディレクトリ名を指定します。\n",
68
- "Google driveの場合はそのまま実行、カスタマイズしたい方は変更して実行してください。"
69
- ]
70
- },
71
- {
72
- "cell_type": "code",
73
- "execution_count": 1,
74
- "metadata": {},
75
- "outputs": [],
76
- "source": [
77
- "# 学習に必要なファイルや途中経過が保存されるディレクトリ\n",
78
- "dataset_root = \"/content/drive/MyDrive/Style-Bert-VITS2/Data\"\n",
79
- "\n",
80
- "# 学習結果(音声合成に必要なファイルたち)が保存されるディレクトリ\n",
81
- "assets_root = \"/content/drive/MyDrive/Style-Bert-VITS2/model_assets\"\n",
82
- "\n",
83
- "import yaml\n",
84
- "\n",
85
- "\n",
86
- "with open(\"configs/paths.yml\", \"w\", encoding=\"utf-8\") as f:\n",
87
- " yaml.dump({\"dataset_root\": dataset_root, \"assets_root\": assets_root}, f)"
88
- ]
89
- },
90
- {
91
- "cell_type": "markdown",
92
- "metadata": {},
93
- "source": [
94
- "## 2. 学習に使うデータ準備\n",
95
- "\n",
96
- "すでに音声ファイル(1ファイル2-12秒程度)とその書き起こしデータがある場合は2.2を、ない場合は2.1を実行してください。"
97
- ]
98
- },
99
- {
100
- "cell_type": "markdown",
101
- "metadata": {},
102
- "source": [
103
- "### 2.1 音声ファイルからのデータセットの作成(ある人はスキップ可)\n",
104
- "\n",
105
- "音声ファイル(1ファイル2-12秒程度)とその書き起こしのデータセットを持っていない方は、(日本語の)音声ファイルのみから以下の手順でデータセットを作成することができます。Google drive上の`Style-Bert-VITS2/inputs/`フォルダに音声ファイル(wavファイル形式、1ファイルでも複数ファイルでも可)を置いて、下を実行すると、データセットが���られ、自動的に正しい場所へ配置されます。"
106
- ]
107
- },
108
- {
109
- "cell_type": "code",
110
- "execution_count": null,
111
- "metadata": {},
112
- "outputs": [],
113
- "source": [
114
- "# 元となる音声ファイル(wav形式)を入れるディレクトリ\n",
115
- "input_dir = \"/content/drive/MyDrive/Style-Bert-VITS2/inputs\"\n",
116
- "# モデル名(話者名)を入力\n",
117
- "model_name = \"your_model_name\"\n",
118
- "\n",
119
- "# こういうふうに書き起こして欲しいという例文(句読点の入れ方・笑い方や固有名詞等)\n",
120
- "initial_prompt = \"こんにちは。元気、ですかー?ふふっ、私は……ちゃんと元気だよ!\"\n",
121
- "\n",
122
- "!python slice.py -i {input_dir} --model_name {model_name}\n",
123
- "!python transcribe.py --model_name {model_name} --initial_prompt {initial_prompt} --use_hf_whisper"
124
- ]
125
- },
126
- {
127
- "cell_type": "markdown",
128
- "metadata": {},
129
- "source": [
130
- "成功したらそのまま3へ進んでください"
131
- ]
132
- },
133
- {
134
- "cell_type": "markdown",
135
- "metadata": {},
136
- "source": [
137
- "### 2.2 音声ファイルと書き起こしデータがすでにある場合\n",
138
- "\n",
139
- "指示に従って適切にデータセットを配置してください。\n",
140
- "\n",
141
- "次のセルを実行して、学習データをいれるフォルダ(1で設定した`dataset_root`)を作成します。"
142
- ]
143
- },
144
- {
145
- "cell_type": "code",
146
- "execution_count": 5,
147
- "metadata": {
148
- "id": "esCNJl704h52"
149
- },
150
- "outputs": [],
151
- "source": [
152
- "import os\n",
153
- "\n",
154
- "os.makedirs(dataset_root, exist_ok=True)"
155
- ]
156
- },
157
- {
158
- "cell_type": "markdown",
159
- "metadata": {},
160
- "source": [
161
- "次に、学習に必要なデータを、Google driveに作成された`Style-Bert-VITS2/Data`フォルダに配置します。\n",
162
- "\n",
163
- "まず音声データ(wavファイルで1ファイルが2-12秒程度の、長すぎず短すぎない発話のものをいくつか)と、書き起こしテキストを用意してください。wavファイル名やモデルの名前は空白を含まない半角で、wavファイルの拡張子は小文字`.wav`である必要があります。\n",
164
- "\n",
165
- "書き起こしテキストは、次の形式で記述してください。\n",
166
- "```\n",
167
- "****.wav|{話者名}|{言語ID、ZHかJPかEN}|{書き起こしテキスト}\n",
168
- "```\n",
169
- "\n",
170
- "例:\n",
171
- "```\n",
172
- "wav_number1.wav|hanako|JP|こんにちは、聞こえて、いますか?\n",
173
- "wav_next.wav|taro|JP|はい、聞こえています……。\n",
174
- "english_teacher.wav|Mary|EN|How are you? I'm fine, thank you, and you?\n",
175
- "...\n",
176
- "```\n",
177
- "日本語話者の単一話者データセットで構いません。\n",
178
- "\n",
179
- "### データセットの配置\n",
180
- "\n",
181
- "次にモデルの名前を適当に決めてください(空白を含まない半角英数字がよいです)。\n",
182
- "そして、書き起こしファイルを`esd.list`という名前で保存し、またwavファイルも`raw`というフォルダを作成し、あなたのGoogle Driveの中の(上で自動的に作られるはずの)`Data`フォルダのなかに、次のように配置します。\n",
183
- "```\n",
184
- "├── Data\n",
185
- "│ ├── {モデルの名前}\n",
186
- "│ │ ├── esd.list\n",
187
- "│ │ ├── raw\n",
188
- "│ │ │ ├── ****.wav\n",
189
- "│ │ │ ├── ****.wav\n",
190
- "│ │ │ ├── ...\n",
191
- "```"
192
- ]
193
- },
194
- {
195
- "cell_type": "markdown",
196
- "metadata": {
197
- "id": "5r85-W20ECcr"
198
- },
199
- "source": [
200
- "## 3. 学習の前処理\n",
201
- "\n",
202
- "次に学習の前処理を行います。必要なパラメータをここで指定します。次のセルに設定等を入力して実行してください。「~~かどうか」は`True`もしくは`False`を指定してください。"
203
- ]
204
- },
205
- {
206
- "cell_type": "code",
207
- "execution_count": 6,
208
- "metadata": {
209
- "id": "CXR7kjuF5GlE"
210
- },
211
- "outputs": [],
212
- "source": [
213
- "# 上でつけたフォルダの名前`Data/{model_name}/`\n",
214
- "model_name = \"your_model_name\"\n",
215
- "\n",
216
- "# JP-Extra (日本語特化版)を使うかどうか。日本語の能力が向上する代わりに英語と中国語は使えなくなります。\n",
217
- "use_jp_extra = True\n",
218
- "\n",
219
- "# 学習のバッチサイズ。VRAMのはみ出具合に応じて調整してください。\n",
220
- "batch_size = 4\n",
221
- "\n",
222
- "# 学習のエポック数(データセットを合計何周するか)。\n",
223
- "# 100で多すぎるほどかもしれませんが、もっと多くやると質が上がるのかもしれません。\n",
224
- "epochs = 100\n",
225
- "\n",
226
- "# 保存頻度。何ステップごとにモデルを保存するか。分からなければデフォルトのままで。\n",
227
- "save_every_steps = 1000\n",
228
- "\n",
229
- "# 音声ファイルの音量を正規化するかどうか\n",
230
- "normalize = False\n",
231
- "\n",
232
- "# 音声ファイルの開始・終了にある無音区間を削除するかどうか\n",
233
- "trim = False\n",
234
- "\n",
235
- "# 読みのエラーが出た場合にどうするか。\n",
236
- "# \"raise\"ならテキスト前処理が終わったら中断、\"skip\"なら読めない行は学習に使わない、\"use\"なら無理やり使う\n",
237
- "yomi_error = \"skip\""
238
- ]
239
- },
240
- {
241
- "cell_type": "markdown",
242
- "metadata": {},
243
- "source": [
244
- "上のセルが実行されたら、次のセルを実行して学習の前処理を行います。"
245
- ]
246
- },
247
- {
248
- "cell_type": "code",
249
- "execution_count": null,
250
- "metadata": {
251
- "colab": {
252
- "base_uri": "https://localhost:8080/"
253
- },
254
- "id": "xMVaOIPLabV5",
255
- "outputId": "15fac868-9132-45d9-9f5f-365b6aeb67b0"
256
- },
257
- "outputs": [],
258
- "source": [
259
- "from gradio_tabs.train import preprocess_all\n",
260
- "\n",
261
- "preprocess_all(\n",
262
- " model_name=model_name,\n",
263
- " batch_size=batch_size,\n",
264
- " epochs=epochs,\n",
265
- " save_every_steps=save_every_steps,\n",
266
- " num_processes=2,\n",
267
- " normalize=normalize,\n",
268
- " trim=trim,\n",
269
- " freeze_EN_bert=False,\n",
270
- " freeze_JP_bert=False,\n",
271
- " freeze_ZH_bert=False,\n",
272
- " freeze_style=False,\n",
273
- " freeze_decoder=False, # ここをTrueにするともしかしたら違う結果になるかもしれません。\n",
274
- " use_jp_extra=use_jp_extra,\n",
275
- " val_per_lang=0,\n",
276
- " log_interval=200,\n",
277
- " yomi_error=yomi_error\n",
278
- ")"
279
- ]
280
- },
281
- {
282
- "cell_type": "markdown",
283
- "metadata": {},
284
- "source": [
285
- "## 4. 学習\n",
286
- "\n",
287
- "前処理が正常に終わったら、学習を行います。次のセルを実行すると学習が始まります。\n",
288
- "\n",
289
- "学習の結果は、上で指定した`save_every_steps`の間隔で、Google Driveの中の`Style-Bert-VITS2/Data/{モデルの名前}/model_assets/`フォルダに保存されます。\n",
290
- "\n",
291
- "このフォルダをダウンロードし、ローカルのStyle-Bert-VITS2の`model_assets`フォルダに上書きすれば、学習結果を使うことができます。"
292
- ]
293
- },
294
- {
295
- "cell_type": "code",
296
- "execution_count": null,
297
- "metadata": {
298
- "colab": {
299
- "base_uri": "https://localhost:8080/"
300
- },
301
- "id": "laieKrbEb6Ij",
302
- "outputId": "72238c88-f294-4ed9-84f6-84c1c17999ca"
303
- },
304
- "outputs": [],
305
- "source": [
306
- "# 上でつけたモデル名を入力。学習を途中からする場合はきちんとモデルが保存されているフォルダ名を入力。\n",
307
- "model_name = \"your_model_name\"\n",
308
- "\n",
309
- "\n",
310
- "import yaml\n",
311
- "from gradio_tabs.train import get_path\n",
312
- "\n",
313
- "dataset_path, _, _, _, config_path = get_path(model_name)\n",
314
- "\n",
315
- "with open(\"default_config.yml\", \"r\", encoding=\"utf-8\") as f:\n",
316
- " yml_data = yaml.safe_load(f)\n",
317
- "yml_data[\"model_name\"] = model_name\n",
318
- "with open(\"config.yml\", \"w\", encoding=\"utf-8\") as f:\n",
319
- " yaml.dump(yml_data, f, allow_unicode=True)"
320
- ]
321
- },
322
- {
323
- "cell_type": "code",
324
- "execution_count": null,
325
- "metadata": {},
326
- "outputs": [],
327
- "source": [
328
- "# 日本語特化版を「使う」場合\n",
329
- "!python train_ms_jp_extra.py --config {config_path} --model {dataset_path} --assets_root {assets_root}"
330
- ]
331
- },
332
- {
333
- "cell_type": "code",
334
- "execution_count": null,
335
- "metadata": {},
336
- "outputs": [],
337
- "source": [
338
- "# 日本語特化版を「使わない」場合\n",
339
- "!python train_ms.py --config {config_path} --model {dataset_path} --assets_root {assets_root}"
340
- ]
341
- },
342
- {
343
- "cell_type": "code",
344
- "execution_count": null,
345
- "metadata": {
346
- "colab": {
347
- "base_uri": "https://localhost:8080/"
348
- },
349
- "id": "c7g0hrdeP1Tl",
350
- "outputId": "94f9a6f6-027f-4554-ce0c-60ac56251c22"
351
- },
352
- "outputs": [],
353
- "source": [
354
- "# 学習結果を試す・マージ・���タイル分けはこちらから\n",
355
- "!python app.py --share"
356
- ]
357
- }
358
- ],
359
- "metadata": {
360
- "accelerator": "GPU",
361
- "colab": {
362
- "gpuType": "T4",
363
- "provenance": []
364
- },
365
- "kernelspec": {
366
- "display_name": "Python 3",
367
- "name": "python3"
368
- },
369
- "language_info": {
370
- "codemirror_mode": {
371
- "name": "ipython",
372
- "version": 3
373
- },
374
- "file_extension": ".py",
375
- "mimetype": "text/x-python",
376
- "name": "python",
377
- "nbconvert_exporter": "python",
378
- "pygments_lexer": "ipython3",
379
- "version": "3.10.11"
380
- }
381
- },
382
- "nbformat": 4,
383
- "nbformat_minor": 0
384
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
common/constants.py DELETED
@@ -1,28 +0,0 @@
1
- import enum
2
-
3
- # Built-in theme: "default", "base", "monochrome", "soft", "glass"
4
- # See https://huggingface.co/spaces/gradio/theme-gallery for more themes
5
- GRADIO_THEME: str = "NoCrypt/miku"
6
-
7
- LATEST_VERSION: str = "2.3.1"
8
-
9
- USER_DICT_DIR = "dict_data"
10
-
11
- DEFAULT_STYLE: str = "Neutral"
12
- DEFAULT_STYLE_WEIGHT: float = 5.0
13
-
14
-
15
- class Languages(str, enum.Enum):
16
- JP = "JP"
17
- EN = "EN"
18
- ZH = "ZH"
19
-
20
-
21
- DEFAULT_SDP_RATIO: float = 0.2
22
- DEFAULT_NOISE: float = 0.6
23
- DEFAULT_NOISEW: float = 0.8
24
- DEFAULT_LENGTH: float = 1.0
25
- DEFAULT_LINE_SPLIT: bool = True
26
- DEFAULT_SPLIT_INTERVAL: float = 0.5
27
- DEFAULT_ASSIST_TEXT_WEIGHT: float = 0.7
28
- DEFAULT_ASSIST_TEXT_WEIGHT: float = 1.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
common/log.py DELETED
@@ -1,17 +0,0 @@
1
- """
2
- logger封装
3
- """
4
-
5
- from loguru import logger
6
-
7
- from .stdout_wrapper import SAFE_STDOUT
8
-
9
- # 移除所有默认的处理器
10
- logger.remove()
11
-
12
- # 自定义格式并添加到标准输出
13
- log_format = (
14
- "<g>{time:MM-DD HH:mm:ss}</g> |<lvl>{level:^8}</lvl>| {file}:{line} | {message}"
15
- )
16
-
17
- logger.add(SAFE_STDOUT, format=log_format, backtrace=True, diagnose=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
common/stdout_wrapper.py DELETED
@@ -1,40 +0,0 @@
1
- """
2
- `sys.stdout` wrapper for both Google Colab and local environment.
3
- """
4
-
5
- import sys
6
- import tempfile
7
-
8
-
9
- class StdoutWrapper:
10
- def __init__(self):
11
- self.temp_file = tempfile.NamedTemporaryFile(
12
- mode="w+", delete=False, encoding="utf-8"
13
- )
14
- self.original_stdout = sys.stdout
15
-
16
- def write(self, message: str):
17
- self.temp_file.write(message)
18
- self.temp_file.flush()
19
- print(message, end="", file=self.original_stdout)
20
-
21
- def flush(self):
22
- self.temp_file.flush()
23
-
24
- def read(self):
25
- self.temp_file.seek(0)
26
- return self.temp_file.read()
27
-
28
- def close(self):
29
- self.temp_file.close()
30
-
31
- def fileno(self):
32
- return self.temp_file.fileno()
33
-
34
-
35
- try:
36
- import google.colab
37
-
38
- SAFE_STDOUT = StdoutWrapper()
39
- except ImportError:
40
- SAFE_STDOUT = sys.stdout
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
common/subprocess_utils.py DELETED
@@ -1,32 +0,0 @@
1
- import subprocess
2
- import sys
3
-
4
- from .log import logger
5
- from .stdout_wrapper import SAFE_STDOUT
6
-
7
- python = sys.executable
8
-
9
-
10
- def run_script_with_log(cmd: list[str], ignore_warning=False) -> tuple[bool, str]:
11
- logger.info(f"Running: {' '.join(cmd)}")
12
- result = subprocess.run(
13
- [python] + cmd,
14
- stdout=SAFE_STDOUT, # type: ignore
15
- stderr=subprocess.PIPE,
16
- text=True,
17
- )
18
- if result.returncode != 0:
19
- logger.error(f"Error: {' '.join(cmd)}\n{result.stderr}")
20
- return False, result.stderr
21
- elif result.stderr and not ignore_warning:
22
- logger.warning(f"Warning: {' '.join(cmd)}\n{result.stderr}")
23
- return True, result.stderr
24
- logger.success(f"Success: {' '.join(cmd)}")
25
- return True, ""
26
-
27
-
28
- def second_elem_of(original_function):
29
- def inner_function(*args, **kwargs):
30
- return original_function(*args, **kwargs)[1]
31
-
32
- return inner_function
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
common/tts_model.py DELETED
@@ -1,332 +0,0 @@
1
- import os
2
- import warnings
3
- from pathlib import Path
4
- from typing import Optional, Union
5
-
6
- import gradio as gr
7
- import numpy as np
8
-
9
- import torch
10
- from gradio.processing_utils import convert_to_16_bit_wav
11
-
12
- import utils
13
- from infer import get_net_g, infer
14
- from models import SynthesizerTrn
15
- from models_jp_extra import SynthesizerTrn as SynthesizerTrnJPExtra
16
-
17
- from .constants import (
18
- DEFAULT_ASSIST_TEXT_WEIGHT,
19
- DEFAULT_LENGTH,
20
- DEFAULT_LINE_SPLIT,
21
- DEFAULT_NOISE,
22
- DEFAULT_NOISEW,
23
- DEFAULT_SDP_RATIO,
24
- DEFAULT_SPLIT_INTERVAL,
25
- DEFAULT_STYLE,
26
- DEFAULT_STYLE_WEIGHT,
27
- )
28
- from .log import logger
29
-
30
-
31
- def adjust_voice(fs, wave, pitch_scale, intonation_scale):
32
- if pitch_scale == 1.0 and intonation_scale == 1.0:
33
- # 初期値の場合は、音質劣化を避けるためにそのまま返す
34
- return fs, wave
35
-
36
- try:
37
- import pyworld
38
- except ImportError:
39
- raise ImportError(
40
- "pyworld is not installed. Please install it by `pip install pyworld`"
41
- )
42
-
43
- # pyworldでf0を加工して合成
44
- # pyworldよりもよいのがあるかもしれないが……
45
-
46
- wave = wave.astype(np.double)
47
- f0, t = pyworld.harvest(wave, fs)
48
- # 質が高そうだしとりあえずharvestにしておく
49
-
50
- sp = pyworld.cheaptrick(wave, f0, t, fs)
51
- ap = pyworld.d4c(wave, f0, t, fs)
52
-
53
- non_zero_f0 = [f for f in f0 if f != 0]
54
- f0_mean = sum(non_zero_f0) / len(non_zero_f0)
55
-
56
- for i, f in enumerate(f0):
57
- if f == 0:
58
- continue
59
- f0[i] = pitch_scale * f0_mean + intonation_scale * (f - f0_mean)
60
-
61
- wave = pyworld.synthesize(f0, sp, ap, fs)
62
- return fs, wave
63
-
64
-
65
- class Model:
66
- def __init__(
67
- self, model_path: Path, config_path: Path, style_vec_path: Path, device: str
68
- ):
69
- self.model_path: Path = model_path
70
- self.config_path: Path = config_path
71
- self.style_vec_path: Path = style_vec_path
72
- self.device: str = device
73
- self.hps: utils.HParams = utils.get_hparams_from_file(self.config_path)
74
- self.spk2id: dict[str, int] = self.hps.data.spk2id
75
- self.id2spk: dict[int, str] = {v: k for k, v in self.spk2id.items()}
76
-
77
- self.num_styles: int = self.hps.data.num_styles
78
- if hasattr(self.hps.data, "style2id"):
79
- self.style2id: dict[str, int] = self.hps.data.style2id
80
- else:
81
- self.style2id: dict[str, int] = {str(i): i for i in range(self.num_styles)}
82
- if len(self.style2id) != self.num_styles:
83
- raise ValueError(
84
- f"Number of styles ({self.num_styles}) does not match the number of style2id ({len(self.style2id)})"
85
- )
86
-
87
- self.style_vectors: np.ndarray = np.load(self.style_vec_path)
88
- if self.style_vectors.shape[0] != self.num_styles:
89
- raise ValueError(
90
- f"The number of styles ({self.num_styles}) does not match the number of style vectors ({self.style_vectors.shape[0]})"
91
- )
92
-
93
- self.net_g: Union[SynthesizerTrn, SynthesizerTrnJPExtra, None] = None
94
-
95
- def load_net_g(self):
96
- self.net_g = get_net_g(
97
- model_path=str(self.model_path),
98
- version=self.hps.version,
99
- device=self.device,
100
- hps=self.hps,
101
- )
102
-
103
- def get_style_vector(self, style_id: int, weight: float = 1.0) -> np.ndarray:
104
- mean = self.style_vectors[0]
105
- style_vec = self.style_vectors[style_id]
106
- style_vec = mean + (style_vec - mean) * weight
107
- return style_vec
108
-
109
- def get_style_vector_from_audio(
110
- self, audio_path: str, weight: float = 1.0
111
- ) -> np.ndarray:
112
- from style_gen import get_style_vector
113
-
114
- xvec = get_style_vector(audio_path)
115
- mean = self.style_vectors[0]
116
- xvec = mean + (xvec - mean) * weight
117
- return xvec
118
-
119
- def infer(
120
- self,
121
- text: str,
122
- language: str = "JP",
123
- sid: int = 0,
124
- reference_audio_path: Optional[str] = None,
125
- sdp_ratio: float = DEFAULT_SDP_RATIO,
126
- noise: float = DEFAULT_NOISE,
127
- noisew: float = DEFAULT_NOISEW,
128
- length: float = DEFAULT_LENGTH,
129
- line_split: bool = DEFAULT_LINE_SPLIT,
130
- split_interval: float = DEFAULT_SPLIT_INTERVAL,
131
- assist_text: Optional[str] = None,
132
- assist_text_weight: float = DEFAULT_ASSIST_TEXT_WEIGHT,
133
- use_assist_text: bool = False,
134
- style: str = DEFAULT_STYLE,
135
- style_weight: float = DEFAULT_STYLE_WEIGHT,
136
- given_tone: Optional[list[int]] = None,
137
- pitch_scale: float = 1.0,
138
- intonation_scale: float = 1.0,
139
- ) -> tuple[int, np.ndarray]:
140
- logger.info(f"Start generating audio data from text:\n{text}")
141
- if language != "JP" and self.hps.version.endswith("JP-Extra"):
142
- raise ValueError(
143
- "The model is trained with JP-Extra, but the language is not JP"
144
- )
145
- if reference_audio_path == "":
146
- reference_audio_path = None
147
- if assist_text == "" or not use_assist_text:
148
- assist_text = None
149
-
150
- if self.net_g is None:
151
- self.load_net_g()
152
- if reference_audio_path is None:
153
- style_id = self.style2id[style]
154
- style_vector = self.get_style_vector(style_id, style_weight)
155
- else:
156
- style_vector = self.get_style_vector_from_audio(
157
- reference_audio_path, style_weight
158
- )
159
- if not line_split:
160
- with torch.no_grad():
161
- audio = infer(
162
- text=text,
163
- sdp_ratio=sdp_ratio,
164
- noise_scale=noise,
165
- noise_scale_w=noisew,
166
- length_scale=length,
167
- sid=sid,
168
- language=language,
169
- hps=self.hps,
170
- net_g=self.net_g,
171
- device=self.device,
172
- assist_text=assist_text,
173
- assist_text_weight=assist_text_weight,
174
- style_vec=style_vector,
175
- given_tone=given_tone,
176
- )
177
- else:
178
- texts = text.split("\n")
179
- texts = [t for t in texts if t != ""]
180
- audios = []
181
- with torch.no_grad():
182
- for i, t in enumerate(texts):
183
- audios.append(
184
- infer(
185
- text=t,
186
- sdp_ratio=sdp_ratio,
187
- noise_scale=noise,
188
- noise_scale_w=noisew,
189
- length_scale=length,
190
- sid=sid,
191
- language=language,
192
- hps=self.hps,
193
- net_g=self.net_g,
194
- device=self.device,
195
- assist_text=assist_text,
196
- assist_text_weight=assist_text_weight,
197
- style_vec=style_vector,
198
- )
199
- )
200
- if i != len(texts) - 1:
201
- audios.append(np.zeros(int(44100 * split_interval)))
202
- audio = np.concatenate(audios)
203
- logger.info("Audio data generated successfully")
204
- if not (pitch_scale == 1.0 and intonation_scale == 1.0):
205
- _, audio = adjust_voice(
206
- fs=self.hps.data.sampling_rate,
207
- wave=audio,
208
- pitch_scale=pitch_scale,
209
- intonation_scale=intonation_scale,
210
- )
211
- with warnings.catch_warnings():
212
- warnings.simplefilter("ignore")
213
- audio = convert_to_16_bit_wav(audio)
214
- return (self.hps.data.sampling_rate, audio)
215
-
216
-
217
- class ModelHolder:
218
- def __init__(self, root_dir: Path, device: str):
219
- self.root_dir: Path = root_dir
220
- self.device: str = device
221
- self.model_files_dict: dict[str, list[Path]] = {}
222
- self.current_model: Optional[Model] = None
223
- self.model_names: list[str] = []
224
- self.models: list[Model] = []
225
- self.refresh()
226
-
227
- def refresh(self):
228
- self.model_files_dict = {}
229
- self.model_names = []
230
- self.current_model = None
231
-
232
- model_dirs = [d for d in self.root_dir.iterdir() if d.is_dir()]
233
- for model_dir in model_dirs:
234
- model_files = [
235
- f
236
- for f in model_dir.iterdir()
237
- if f.suffix in [".pth", ".pt", ".safetensors"]
238
- ]
239
- if len(model_files) == 0:
240
- logger.warning(f"No model files found in {model_dir}, so skip it")
241
- continue
242
- config_path = model_dir / "config.json"
243
- if not config_path.exists():
244
- logger.warning(
245
- f"Config file {config_path} not found, so skip {model_dir}"
246
- )
247
- continue
248
- self.model_files_dict[model_dir.name] = model_files
249
- self.model_names.append(model_dir.name)
250
-
251
- def models_info(self):
252
- if hasattr(self, "_models_info"):
253
- return self._models_info
254
- result = []
255
- for name, files in self.model_files_dict.items():
256
- # Get styles
257
- config_path = self.root_dir / name / "config.json"
258
- hps = utils.get_hparams_from_file(config_path)
259
- style2id: dict[str, int] = hps.data.style2id
260
- styles = list(style2id.keys())
261
- result.append(
262
- {
263
- "name": name,
264
- "files": [str(f) for f in files],
265
- "styles": styles,
266
- }
267
- )
268
- self._models_info = result
269
- return result
270
-
271
- def load_model(self, model_name: str, model_path_str: str):
272
- model_path = Path(model_path_str)
273
- if model_name not in self.model_files_dict:
274
- raise ValueError(f"Model `{model_name}` is not found")
275
- if model_path not in self.model_files_dict[model_name]:
276
- raise ValueError(f"Model file `{model_path}` is not found")
277
- if self.current_model is None or self.current_model.model_path != model_path:
278
- self.current_model = Model(
279
- model_path=model_path,
280
- config_path=self.root_dir / model_name / "config.json",
281
- style_vec_path=self.root_dir / model_name / "style_vectors.npy",
282
- device=self.device,
283
- )
284
- return self.current_model
285
-
286
- def load_model_gr(
287
- self, model_name: str, model_path_str: str
288
- ) -> tuple[gr.Dropdown, gr.Button, gr.Dropdown]:
289
- model_path = Path(model_path_str)
290
- if model_name not in self.model_files_dict:
291
- raise ValueError(f"Model `{model_name}` is not found")
292
- if model_path not in self.model_files_dict[model_name]:
293
- raise ValueError(f"Model file `{model_path}` is not found")
294
- if (
295
- self.current_model is not None
296
- and self.current_model.model_path == model_path
297
- ):
298
- # Already loaded
299
- speakers = list(self.current_model.spk2id.keys())
300
- styles = list(self.current_model.style2id.keys())
301
- return (
302
- gr.Dropdown(choices=styles, value=styles[0]),
303
- gr.Button(interactive=True, value="音声合成"),
304
- gr.Dropdown(choices=speakers, value=speakers[0]),
305
- )
306
- self.current_model = Model(
307
- model_path=model_path,
308
- config_path=self.root_dir / model_name / "config.json",
309
- style_vec_path=self.root_dir / model_name / "style_vectors.npy",
310
- device=self.device,
311
- )
312
- speakers = list(self.current_model.spk2id.keys())
313
- styles = list(self.current_model.style2id.keys())
314
- return (
315
- gr.Dropdown(choices=styles, value=styles[0]),
316
- gr.Button(interactive=True, value="音声合成"),
317
- gr.Dropdown(choices=speakers, value=speakers[0]),
318
- )
319
-
320
- def update_model_files_gr(self, model_name: str) -> gr.Dropdown:
321
- model_files = self.model_files_dict[model_name]
322
- return gr.Dropdown(choices=model_files, value=model_files[0])
323
-
324
- def update_model_names_gr(self) -> tuple[gr.Dropdown, gr.Dropdown, gr.Button]:
325
- self.refresh()
326
- initial_model_name = self.model_names[0]
327
- initial_model_files = self.model_files_dict[initial_model_name]
328
- return (
329
- gr.Dropdown(choices=self.model_names, value=initial_model_name),
330
- gr.Dropdown(choices=initial_model_files, value=initial_model_files[0]),
331
- gr.Button(interactive=False), # For tts_button
332
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
commons.py DELETED
@@ -1,152 +0,0 @@
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 shift_1d(x):
109
- x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
110
- return x
111
-
112
-
113
- def sequence_mask(length, max_length=None):
114
- if max_length is None:
115
- max_length = length.max()
116
- x = torch.arange(max_length, dtype=length.dtype, device=length.device)
117
- return x.unsqueeze(0) < length.unsqueeze(1)
118
-
119
-
120
- def generate_path(duration, mask):
121
- """
122
- duration: [b, 1, t_x]
123
- mask: [b, 1, t_y, t_x]
124
- """
125
-
126
- b, _, t_y, t_x = mask.shape
127
- cum_duration = torch.cumsum(duration, -1)
128
-
129
- cum_duration_flat = cum_duration.view(b * t_x)
130
- path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
131
- path = path.view(b, t_x, t_y)
132
- path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
133
- path = path.unsqueeze(1).transpose(2, 3) * mask
134
- return path
135
-
136
-
137
- def clip_grad_value_(parameters, clip_value, norm_type=2):
138
- if isinstance(parameters, torch.Tensor):
139
- parameters = [parameters]
140
- parameters = list(filter(lambda p: p.grad is not None, parameters))
141
- norm_type = float(norm_type)
142
- if clip_value is not None:
143
- clip_value = float(clip_value)
144
-
145
- total_norm = 0
146
- for p in parameters:
147
- param_norm = p.grad.data.norm(norm_type)
148
- total_norm += param_norm.item() ** norm_type
149
- if clip_value is not None:
150
- p.grad.data.clamp_(min=-clip_value, max=clip_value)
151
- total_norm = total_norm ** (1.0 / norm_type)
152
- return total_norm
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
data_utils.py DELETED
@@ -1,458 +0,0 @@
1
- import os
2
- import random
3
- import sys
4
-
5
- import numpy as np
6
- import torch
7
- import torch.utils.data
8
- from tqdm import tqdm
9
-
10
- from config import config
11
- from mel_processing import mel_spectrogram_torch, spectrogram_torch
12
- from style_bert_vits2.logging import logger
13
- from style_bert_vits2.models import commons
14
- from style_bert_vits2.models.hyper_parameters import HyperParametersData
15
- from style_bert_vits2.models.utils import load_filepaths_and_text, load_wav_to_torch
16
- from style_bert_vits2.nlp import cleaned_text_to_sequence
17
-
18
-
19
- """Multi speaker version"""
20
-
21
-
22
- class TextAudioSpeakerLoader(torch.utils.data.Dataset):
23
- """
24
- 1) loads audio, speaker_id, text pairs
25
- 2) normalizes text and converts them to sequences of integers
26
- 3) computes spectrograms from audio files.
27
- """
28
-
29
- def __init__(self, audiopaths_sid_text: str, hparams: HyperParametersData):
30
- self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
31
- self.max_wav_value = hparams.max_wav_value
32
- self.sampling_rate = hparams.sampling_rate
33
- self.filter_length = hparams.filter_length
34
- self.hop_length = hparams.hop_length
35
- self.win_length = hparams.win_length
36
- self.sampling_rate = hparams.sampling_rate
37
- self.spk_map = hparams.spk2id
38
- self.hparams = hparams
39
- self.use_jp_extra = getattr(hparams, "use_jp_extra", False)
40
-
41
- self.use_mel_spec_posterior = getattr(
42
- hparams, "use_mel_posterior_encoder", False
43
- )
44
- if self.use_mel_spec_posterior:
45
- self.n_mel_channels = getattr(hparams, "n_mel_channels", 80)
46
-
47
- self.cleaned_text = getattr(hparams, "cleaned_text", False)
48
-
49
- self.add_blank = hparams.add_blank
50
- self.min_text_len = getattr(hparams, "min_text_len", 1)
51
- self.max_text_len = getattr(hparams, "max_text_len", 384)
52
-
53
- random.seed(1234)
54
- random.shuffle(self.audiopaths_sid_text)
55
- self._filter()
56
-
57
- def _filter(self):
58
- """
59
- Filter text & store spec lengths
60
- """
61
- # Store spectrogram lengths for Bucketing
62
- # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
63
- # spec_length = wav_length // hop_length
64
-
65
- audiopaths_sid_text_new = []
66
- lengths = []
67
- skipped = 0
68
- logger.info("Init dataset...")
69
- for _id, spk, language, text, phones, tone, word2ph in tqdm(
70
- self.audiopaths_sid_text, file=sys.stdout
71
- ):
72
- audiopath = f"{_id}"
73
- if self.min_text_len <= len(phones) and len(phones) <= self.max_text_len:
74
- phones = phones.split(" ")
75
- tone = [int(i) for i in tone.split(" ")]
76
- word2ph = [int(i) for i in word2ph.split(" ")]
77
- audiopaths_sid_text_new.append(
78
- [audiopath, spk, language, text, phones, tone, word2ph]
79
- )
80
- lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
81
- else:
82
- skipped += 1
83
- logger.info(
84
- "skipped: "
85
- + str(skipped)
86
- + ", total: "
87
- + str(len(self.audiopaths_sid_text))
88
- )
89
- self.audiopaths_sid_text = audiopaths_sid_text_new
90
- self.lengths = lengths
91
-
92
- def get_audio_text_speaker_pair(self, audiopath_sid_text):
93
- # separate filename, speaker_id and text
94
- audiopath, sid, language, text, phones, tone, word2ph = audiopath_sid_text
95
-
96
- bert, ja_bert, en_bert, phones, tone, language = self.get_text(
97
- text, word2ph, phones, tone, language, audiopath
98
- )
99
-
100
- spec, wav = self.get_audio(audiopath)
101
- sid = torch.LongTensor([int(self.spk_map[sid])])
102
- style_vec = torch.FloatTensor(np.load(f"{audiopath}.npy"))
103
- if self.use_jp_extra:
104
- return (phones, spec, wav, sid, tone, language, ja_bert, style_vec)
105
- else:
106
- return (
107
- phones,
108
- spec,
109
- wav,
110
- sid,
111
- tone,
112
- language,
113
- bert,
114
- ja_bert,
115
- en_bert,
116
- style_vec,
117
- )
118
-
119
- def get_audio(self, filename):
120
- audio, sampling_rate = load_wav_to_torch(filename)
121
- if sampling_rate != self.sampling_rate:
122
- raise ValueError(
123
- "{} {} SR doesn't match target {} SR".format(
124
- filename, sampling_rate, self.sampling_rate
125
- )
126
- )
127
- audio_norm = audio / self.max_wav_value
128
- audio_norm = audio_norm.unsqueeze(0)
129
- spec_filename = filename.replace(".wav", ".spec.pt")
130
- if self.use_mel_spec_posterior:
131
- spec_filename = spec_filename.replace(".spec.pt", ".mel.pt")
132
- try:
133
- spec = torch.load(spec_filename)
134
- except:
135
- if self.use_mel_spec_posterior:
136
- spec = mel_spectrogram_torch(
137
- audio_norm,
138
- self.filter_length,
139
- self.n_mel_channels,
140
- self.sampling_rate,
141
- self.hop_length,
142
- self.win_length,
143
- self.hparams.mel_fmin,
144
- self.hparams.mel_fmax,
145
- center=False,
146
- )
147
- else:
148
- spec = spectrogram_torch(
149
- audio_norm,
150
- self.filter_length,
151
- self.sampling_rate,
152
- self.hop_length,
153
- self.win_length,
154
- center=False,
155
- )
156
- spec = torch.squeeze(spec, 0)
157
- if config.train_ms_config.spec_cache:
158
- torch.save(spec, spec_filename)
159
- return spec, audio_norm
160
-
161
- def get_text(self, text, word2ph, phone, tone, language_str, wav_path):
162
- phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
163
- if self.add_blank:
164
- phone = commons.intersperse(phone, 0)
165
- tone = commons.intersperse(tone, 0)
166
- language = commons.intersperse(language, 0)
167
- for i in range(len(word2ph)):
168
- word2ph[i] = word2ph[i] * 2
169
- word2ph[0] += 1
170
- bert_path = wav_path.replace(".wav", ".bert.pt")
171
- try:
172
- bert_ori = torch.load(bert_path)
173
- assert bert_ori.shape[-1] == len(phone)
174
- except Exception as e:
175
- logger.warning("Bert load Failed")
176
- logger.warning(e)
177
-
178
- if language_str == "ZH":
179
- bert = bert_ori
180
- ja_bert = torch.zeros(1024, len(phone))
181
- en_bert = torch.zeros(1024, len(phone))
182
- elif language_str == "JP":
183
- bert = torch.zeros(1024, len(phone))
184
- ja_bert = bert_ori
185
- en_bert = torch.zeros(1024, len(phone))
186
- elif language_str == "EN":
187
- bert = torch.zeros(1024, len(phone))
188
- ja_bert = torch.zeros(1024, len(phone))
189
- en_bert = bert_ori
190
- phone = torch.LongTensor(phone)
191
- tone = torch.LongTensor(tone)
192
- language = torch.LongTensor(language)
193
- return bert, ja_bert, en_bert, phone, tone, language
194
-
195
- def get_sid(self, sid):
196
- sid = torch.LongTensor([int(sid)])
197
- return sid
198
-
199
- def __getitem__(self, index):
200
- return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
201
-
202
- def __len__(self):
203
- return len(self.audiopaths_sid_text)
204
-
205
-
206
- class TextAudioSpeakerCollate:
207
- """Zero-pads model inputs and targets"""
208
-
209
- def __init__(self, return_ids=False, use_jp_extra=False):
210
- self.return_ids = return_ids
211
- self.use_jp_extra = use_jp_extra
212
-
213
- def __call__(self, batch):
214
- """Collate's training batch from normalized text, audio and speaker identities
215
- PARAMS
216
- ------
217
- batch: [text_normalized, spec_normalized, wav_normalized, sid]
218
- """
219
- # Right zero-pad all one-hot text sequences to max input length
220
- _, ids_sorted_decreasing = torch.sort(
221
- torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True
222
- )
223
-
224
- max_text_len = max([len(x[0]) for x in batch])
225
- max_spec_len = max([x[1].size(1) for x in batch])
226
- max_wav_len = max([x[2].size(1) for x in batch])
227
-
228
- text_lengths = torch.LongTensor(len(batch))
229
- spec_lengths = torch.LongTensor(len(batch))
230
- wav_lengths = torch.LongTensor(len(batch))
231
- sid = torch.LongTensor(len(batch))
232
-
233
- text_padded = torch.LongTensor(len(batch), max_text_len)
234
- tone_padded = torch.LongTensor(len(batch), max_text_len)
235
- language_padded = torch.LongTensor(len(batch), max_text_len)
236
- # This is ZH bert if not use_jp_extra, JA bert if use_jp_extra
237
- bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
238
- if not self.use_jp_extra:
239
- ja_bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
240
- en_bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
241
- style_vec = torch.FloatTensor(len(batch), 256)
242
-
243
- spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
244
- wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
245
- text_padded.zero_()
246
- tone_padded.zero_()
247
- language_padded.zero_()
248
- spec_padded.zero_()
249
- wav_padded.zero_()
250
- bert_padded.zero_()
251
- if not self.use_jp_extra:
252
- ja_bert_padded.zero_()
253
- en_bert_padded.zero_()
254
- style_vec.zero_()
255
-
256
- for i in range(len(ids_sorted_decreasing)):
257
- row = batch[ids_sorted_decreasing[i]]
258
-
259
- text = row[0]
260
- text_padded[i, : text.size(0)] = text
261
- text_lengths[i] = text.size(0)
262
-
263
- spec = row[1]
264
- spec_padded[i, :, : spec.size(1)] = spec
265
- spec_lengths[i] = spec.size(1)
266
-
267
- wav = row[2]
268
- wav_padded[i, :, : wav.size(1)] = wav
269
- wav_lengths[i] = wav.size(1)
270
-
271
- sid[i] = row[3]
272
-
273
- tone = row[4]
274
- tone_padded[i, : tone.size(0)] = tone
275
-
276
- language = row[5]
277
- language_padded[i, : language.size(0)] = language
278
-
279
- bert = row[6]
280
- bert_padded[i, :, : bert.size(1)] = bert
281
-
282
- if self.use_jp_extra:
283
- style_vec[i, :] = row[7]
284
- else:
285
- ja_bert = row[7]
286
- ja_bert_padded[i, :, : ja_bert.size(1)] = ja_bert
287
-
288
- en_bert = row[8]
289
- en_bert_padded[i, :, : en_bert.size(1)] = en_bert
290
- style_vec[i, :] = row[9]
291
-
292
- if self.use_jp_extra:
293
- return (
294
- text_padded,
295
- text_lengths,
296
- spec_padded,
297
- spec_lengths,
298
- wav_padded,
299
- wav_lengths,
300
- sid,
301
- tone_padded,
302
- language_padded,
303
- bert_padded,
304
- style_vec,
305
- )
306
- else:
307
- return (
308
- text_padded,
309
- text_lengths,
310
- spec_padded,
311
- spec_lengths,
312
- wav_padded,
313
- wav_lengths,
314
- sid,
315
- tone_padded,
316
- language_padded,
317
- bert_padded,
318
- ja_bert_padded,
319
- en_bert_padded,
320
- style_vec,
321
- )
322
-
323
-
324
- class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
325
- """
326
- Maintain similar input lengths in a batch.
327
- Length groups are specified by boundaries.
328
- Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
329
-
330
- It removes samples which are not included in the boundaries.
331
- Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
332
- """
333
-
334
- def __init__(
335
- self,
336
- dataset,
337
- batch_size,
338
- boundaries,
339
- num_replicas=None,
340
- rank=None,
341
- shuffle=True,
342
- ):
343
- super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
344
- self.lengths = dataset.lengths
345
- self.batch_size = batch_size
346
- self.boundaries = boundaries
347
-
348
- self.buckets, self.num_samples_per_bucket = self._create_buckets()
349
- logger.info(f"Bucket info: {self.num_samples_per_bucket}")
350
- # logger.info(
351
- # f"Unused samples: {len(self.lengths) - sum(self.num_samples_per_bucket)}"
352
- # )
353
- # ↑マイナスになることあるし、別にこれは使われないサンプル数ではないようだ……
354
- # バケットの仕組みはよく分からない
355
-
356
- self.total_size = sum(self.num_samples_per_bucket)
357
- self.num_samples = self.total_size // self.num_replicas
358
-
359
- def _create_buckets(self):
360
- buckets = [[] for _ in range(len(self.boundaries) - 1)]
361
- for i in range(len(self.lengths)):
362
- length = self.lengths[i]
363
- idx_bucket = self._bisect(length)
364
- if idx_bucket != -1:
365
- buckets[idx_bucket].append(i)
366
-
367
- try:
368
- for i in range(len(buckets) - 1, 0, -1):
369
- if len(buckets[i]) == 0:
370
- buckets.pop(i)
371
- self.boundaries.pop(i + 1)
372
- assert all(len(bucket) > 0 for bucket in buckets)
373
- # When one bucket is not traversed
374
- except Exception as e:
375
- logger.info("Bucket warning ", e)
376
- for i in range(len(buckets) - 1, -1, -1):
377
- if len(buckets[i]) == 0:
378
- buckets.pop(i)
379
- self.boundaries.pop(i + 1)
380
-
381
- num_samples_per_bucket = []
382
- for i in range(len(buckets)):
383
- len_bucket = len(buckets[i])
384
- total_batch_size = self.num_replicas * self.batch_size
385
- rem = (
386
- total_batch_size - (len_bucket % total_batch_size)
387
- ) % total_batch_size
388
- num_samples_per_bucket.append(len_bucket + rem)
389
- return buckets, num_samples_per_bucket
390
-
391
- def __iter__(self):
392
- # deterministically shuffle based on epoch
393
- g = torch.Generator()
394
- g.manual_seed(self.epoch)
395
-
396
- indices = []
397
- if self.shuffle:
398
- for bucket in self.buckets:
399
- indices.append(torch.randperm(len(bucket), generator=g).tolist())
400
- else:
401
- for bucket in self.buckets:
402
- indices.append(list(range(len(bucket))))
403
-
404
- batches = []
405
- for i in range(len(self.buckets)):
406
- bucket = self.buckets[i]
407
- len_bucket = len(bucket)
408
- if len_bucket == 0:
409
- continue
410
- ids_bucket = indices[i]
411
- num_samples_bucket = self.num_samples_per_bucket[i]
412
-
413
- # add extra samples to make it evenly divisible
414
- rem = num_samples_bucket - len_bucket
415
- ids_bucket = (
416
- ids_bucket
417
- + ids_bucket * (rem // len_bucket)
418
- + ids_bucket[: (rem % len_bucket)]
419
- )
420
-
421
- # subsample
422
- ids_bucket = ids_bucket[self.rank :: self.num_replicas]
423
-
424
- # batching
425
- for j in range(len(ids_bucket) // self.batch_size):
426
- batch = [
427
- bucket[idx]
428
- for idx in ids_bucket[
429
- j * self.batch_size : (j + 1) * self.batch_size
430
- ]
431
- ]
432
- batches.append(batch)
433
-
434
- if self.shuffle:
435
- batch_ids = torch.randperm(len(batches), generator=g).tolist()
436
- batches = [batches[i] for i in batch_ids]
437
- self.batches = batches
438
-
439
- assert len(self.batches) * self.batch_size == self.num_samples
440
- return iter(self.batches)
441
-
442
- def _bisect(self, x, lo=0, hi=None):
443
- if hi is None:
444
- hi = len(self.boundaries) - 1
445
-
446
- if hi > lo:
447
- mid = (hi + lo) // 2
448
- if self.boundaries[mid] < x and x <= self.boundaries[mid + 1]:
449
- return mid
450
- elif x <= self.boundaries[mid]:
451
- return self._bisect(x, lo, mid)
452
- else:
453
- return self._bisect(x, mid + 1, hi)
454
- else:
455
- return -1
456
-
457
- def __len__(self):
458
- return self.num_samples // self.batch_size
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
default_style.py DELETED
@@ -1,34 +0,0 @@
1
- import json
2
- import os
3
- from pathlib import Path
4
- from typing import Union
5
-
6
- import numpy as np
7
-
8
- from style_bert_vits2.constants import DEFAULT_STYLE
9
- from style_bert_vits2.logging import logger
10
-
11
-
12
- def set_style_config(json_path: Path, output_path: Path):
13
- with open(json_path, "r", encoding="utf-8") as f:
14
- json_dict = json.load(f)
15
- json_dict["data"]["num_styles"] = 1
16
- json_dict["data"]["style2id"] = {DEFAULT_STYLE: 0}
17
- with open(output_path, "w", encoding="utf-8") as f:
18
- json.dump(json_dict, f, indent=2, ensure_ascii=False)
19
- logger.info(f"Save style config (only {DEFAULT_STYLE}) to {output_path}")
20
-
21
-
22
- def save_neutral_vector(wav_dir: Union[Path, str], output_path: Union[Path, str]):
23
- wav_dir = Path(wav_dir)
24
- output_path = Path(output_path)
25
- embs = []
26
- for file in wav_dir.rglob("*.npy"):
27
- xvec = np.load(file)
28
- embs.append(np.expand_dims(xvec, axis=0))
29
-
30
- x = np.concatenate(embs, axis=0) # (N, 256)
31
- mean = np.mean(x, axis=0) # (256,)
32
- only_mean = np.stack([mean]) # (1, 256)
33
- np.save(output_path, only_mean)
34
- logger.info(f"Saved mean style vector to {output_path}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/CHANGELOG.md DELETED
@@ -1,275 +0,0 @@
1
- # Changelog
2
-
3
- ## v2.4.1 (2024-03-16)
4
-
5
- **batファイルでのインストール・アップデート方法の変更**(それ以外の変更はありません)
6
-
7
- 諸事情により、インストール・アップデートのbatファイルを変更しました(Gitが使えないのでバージョンアップ時のアップデートの対応が困難だったため、Gitがない環境の場合はPortableGitをダウンロードして使うように)。
8
-
9
- 伴って、これまでWindowsでbatファイルをダブルクリックしてインストールしていた方は**再インストールが必須**となります。大変申し訳ありません。
10
-
11
- ### インストール手順
12
-
13
- (インストールの流れは変わりませんが、batファイルは変わっているので、新しいzipを必ずダウンロードしてください)
14
-
15
- - [sbv2.zip](https://github.com/litagin02/Style-Bert-VITS2/releases/download/2.4.1/sbv2.zip)をダウンロードし、解凍してください。
16
- - グラボがある方は、`Install-Style-Bert-VITS2.bat`をダブルクリックします。
17
- - グラボがない方は、`Install-Style-Bert-VITS2-CPU.bat`をダブルクリックします。CPU版では学習はできませんが、音声合成とマージは可能です。
18
-
19
- ### アップデート手順
20
-
21
- **以前のバージョンからのアップデート**
22
-
23
- 今までの環境を全て削除して新しくインストールする必要があります。
24
- 移行方法:
25
- - 重要なデータが入っている可能性のある`Data`フォルダと`model_assets`フォルダをバックアップ
26
- - 上のインストール手順から、新しい場所にStyle-Bert-VITS2をインストール
27
- - インストールが終了したら、バックアップした`Data`フォルダと`model_assets`フォルダを新しい`Style-Bert-VITS2`フォルダにコピー
28
- - これまでインストールされていたフォルダ(batファイルたち含む)は削除しても構いません
29
-
30
- **今後のアップデート**
31
-
32
- 今後は、新しくインストールされた中の`Update-Style-Bert-VITS2.bat`をダブルクリックしてください。今までの`Update-Style-Bert-VITS2.bat`等のファイルは使えません。
33
-
34
- ## v2.4.0 (2024-03-15)
35
-
36
- 大規模リファクタリング・日本語処理のワーカー化と機能追加等。データセット作り・学習・音声合成・マージ・スタイルWebUIは全て`app.py` (`App.bat`) へ統一されましたのでご注意ください。
37
-
38
- ### アップデート手順
39
- - 2.3未満(辞書・エディター追加前)からのアップデートの場合は、[Update-to-Dict-Editor.bat](https://github.com/litagin02/Style-Bert-VITS2/releases/download/2.4.0/Update-to-Dict-Editor.bat)をダウンロードし、`Style-Bert-VITS2`フォルダがある場所(インストールbatファイルとかがあったところ)においてダブルクリックしてください。
40
- - それ以外の場合は、単純に今までの`Update-Style-Bert-VITS2.bat`でアップデートできます。
41
- - ただしアップデートにより多くのファイルが移動したり不要になったりしたので、それらを削除したい場合は[Clean.bat](https://github.com/litagin02/Style-Bert-VITS2/releases/download/2.4.0/Clean.bat)を`Update-Style-Bert-VITS2.bat`と同じ場所に保存して実行してください。
42
-
43
- ### 内部改善
44
-
45
- - [tsukumijimaさんによる大規模リファクタリングのプルリク](https://github.com/litagin02/Style-Bert-VITS2/pull/92) によって、内部コードが非常に整理され可読性が高まりライブラリ化もされた。[tsukumijimaさん](https://github.com/tsukumijima) 大変な作業を本当にありがとうございます!
46
- - ライブラリとして`pip install style-bert-vits2`によりすぐにインストールでき、音声合成部分の機能が使えます(使用例は[/library.ipynb](/library.ipynb)を参照してください)
47
- - その他このプルリクに動機づけられ、多くのコードのリファクタリング・型アノテーションの追加等を行った
48
- - 日本語処理のpyopenjtalkをソケット通信を用いて別プロセス化し、複数同時に学習や音声合成を立ち上げても辞書の競合エラーが起きないように。[kale4eat](https://github.com/kale4eat) さんによる[PR](https://github.com/litagin02/Style-Bert-VITS2/pull/89) です、ありがとうございます!
49
-
50
- ### バグ修正
51
-
52
- - 上記にもある通り、音声合成と学習前処理など、日本語処理を扱うものを2つ以上起動しようとするとエラーが発生する仕様の解決。ユーザー辞書は追加すれば常にどこからでも適応されます。
53
- - `raw`フォルダの直下でなくサブフォルダ内に音声ファイルがある場合に、`wavs`フォルダでもその構造が保たれてしまい、書き起こしファイルとの整合性が取れなくなる挙動を修正し、常に`wav`フォルダ直下へ`wav`ファイルを保存するように変更
54
- - スライス時に元ファイル名にピリオド `.` が含まれると、スライス後のファイル名がおかしくなるバグの修正
55
-
56
- ### 機能改善・追加
57
-
58
- - 各種WebUIを一つ`app.py` `App.bat` に統一
59
- - その他以下の変更や、軽微なUI・説明文の改善等
60
-
61
- **データセット作成**
62
-
63
- - スライス処理の高速化(マルチスレッドにした、大量にスライス元ファイルファイルがある場合に高速になります)、またスライス元のファイルを`wav`以外の`mp3`や`ogg`などの形式にも対応
64
- - スライス処理時に、ファイル名にスライスされた開始終了区間を含めるオプションを追加([aka7774](https://github.com/aka7774) さんによるPRです、ありがとうございます!)
65
- - 書き起こしの高速化、またHugging FaceのWhisperモデルを使うオプションを追加。バッチサイズを上げることでVRAMを食う代わりに速度が大幅に向上します。
66
-
67
- **学習**
68
-
69
- - 学習元の音声ファイル(`Data/モデル名/raw`にいれるやつ)を、`wav`以外の`mp3`や`ogg`などの形式にも対応(前処理段階で自動的に`wav`ファイルに変換されます)(ただし変わらず1ファイル2-12秒程度の範囲の長さが望ましい)
70
-
71
- **音声合成**
72
-
73
- - 音声合成時に、生成音声の音の高さ(音高)と抑揚の幅を調整できるように(ただし音質が少し劣化する)。`App.bat`や`Editor.bat`のどちらからでも使えます。
74
- - `Editor.bat`の複数話者モデルでの話者指定を可能に
75
- - `Editor.bat`で、改行を含む文字列をペーストすると自動的に欄が増えるように。また「↑↓」キーで欄を追加・行き来できるように(エディター側で以前に既にアプデしていました)
76
- - `Editor.bat`でモデル一覧のリロードをメニューに追加
77
-
78
- **API**
79
-
80
- - `server_fastapi.py`の実行時に全てのモデルファイルを読み込もうとする挙動を修正。音声合成がリクエストされて初めてそのモデルを読み込むように変更(APIを使わない音声合成のときと同じ挙動)
81
- - `server_fastapi.py`の音声合成エンドポイント`/voice`について、GETメソッドに加えてPOSTメソッドを追加。GETメソッドでは多くの制約があるようなのでPOSTを使うことが推奨されます。
82
-
83
- **CLI**
84
-
85
- - `preprocess_text.py`で、書き起こしファイルでの音声ファイル名を自動的に正しい`Data/モデル名/wavs/`へ書き換える`--correct_path`オプションの追加(WebUIでは今までもこの挙動でした)
86
- - その他上述のデータセット作成の機能追加に伴うCLIのオプションの追加(詳しくは[CLI.md](/docs/CLI.md)を参照)
87
-
88
- ## v2.3.1 (2024-02-27)
89
-
90
- ### バグ修正
91
- - colabの学習用ノートブックが動かなかったのを修正
92
- - `App.bat`や`server_fastapi.py`では読めない文字でまだエラーが発生するようになっていたので、推論時は必ず読めない文字を無視して強引に読むように挙動を変更
93
-
94
- ### 改善
95
- - 読みが取得できない場合に、テキスト前処理完了時にエラーで中断する今までの挙動に加えて、「読み取得失敗ファイルを学習に使わずに進める」もしくは「読めない文字を無視して読んでファイルを学習に使い進める」というオプションを追加。
96
- - マージ方法に線形補間の他に球面線形補完を追加 ([@frodo821](https://github.com/frodo821) さんによるPRです、ありがとうございます!)
97
- - デプロイ用`.dockerignore`を更新
98
-
99
- ### アップデート手順
100
- - 2.3未満からのアップデートの場合は、[Update-to-Dict-Editor.bat](https://github.com/litagin02/Style-Bert-VITS2/releases/download/2.3/Update-to-Dict-Editor.bat)をダウンロードし、`Style-Bert-VITS2`フォルダがある場所(インストールbatファイルとかがあったところ)においてダブルクリックしてください。
101
- - 2.3からのアップデートの場合は、単純に今までの`Update-Style-Bert-VITS2.bat`でアップデートできます。
102
-
103
- ## v2.3 (2024-02-26)
104
-
105
- ### 大きな変更
106
-
107
- 大きい変更をいくつかしたため、**アップデートはまた専用の手順**が必要です。下記の指示にしたがってください。
108
-
109
- #### ユーザー辞書機能
110
- あらかじめ辞書に固有名詞を追加することができ、それが**学習時**・**音声合成時**の読み取得部分に適応されます。辞書の追加・編集は次のエディタ経由で行ってください。または、手持ちのOpenJTalkのcsv形式の辞書がある場合は、`dict_data/default.csv`ファイルを直接上書きや追加しても可能です。
111
-
112
- 使えそうな辞書(ライセンス等は各自ご確認ください)���他に良いのがあったら教えて下さい):
113
-
114
- - [WariHima/Kanayomi-dict](https://github.com/WariHima/KanaYomi-dict)
115
- - [takana-v/tsumu_dic](https://github.com/takana-v/tsumu_dic)
116
-
117
-
118
- 辞書機能部分の[実装](/text/user_dict/) は、中のREADMEにある通り、[VOICEVOX Editor](https://github.com/VOICEVOX/voicevox) のものを使っており、この部分のコードライセンスはLGPL-3.0です。
119
-
120
- #### 音声合成専用エディタ
121
-
122
- [🤗 オンラインデモはこちらから](https://huggingface.co/spaces/litagin/Style-Bert-VITS2-Editor-Demo)
123
-
124
- 音声合成専用エディタを追加。今までのWebUIでできた機能のほか、次のような機能が使えます(つまり既存の日本語音声合成ソフトウェアのエディタを真似ました):
125
- - セリフ単位でキャラや設定を変更しながら原稿を作り、それを一括で生成したり、原稿を保存等したり読み込んだり
126
- - GUIよる分かりやすいアクセント調整
127
- - ユーザー辞書への単語追加や編集
128
-
129
- `Editor.bat`をダブルクリックか`python server_editor.py --inbrowser`で起動します。エディター部分は[こちらの別リポジトリ](https://github.com/litagin02/Style-Bert-VITS2-Editor)になります。フロントエンド初心者なのでプルリクや改善案等をお待ちしています。
130
-
131
- ### バグ修正
132
-
133
- - 特定の状況で読みが正しく取得できず `list index out of range` となるバグの修正
134
- - 前処理時に、書き起こしファイルのある行の形式が不正だと、書き起こしファイルのそれ以降の内容が消えてしまうバグの修正
135
- - faster-whisperが1.0.0にメジャーバージョンアップされ(今のところ)大幅に劣化したので、バージョンを0.10.1へ固定
136
-
137
- ### 改善
138
-
139
- - テキスト前処理時に、読みの取得の失敗等があった場合に、処理を中断せず、エラーがおきた箇所を`text_error.log`ファイルへ保存するように変更。
140
- - 音声合成時に、読めない文字があったときはエラーを起こさず、その部分を無視して読み上げるように変更(学習段階ではエラーを出します)
141
- - コマンドラインで前処理や学習が簡単にできるよう、前処理を行う`preprocess_all.py`を追加(詳しくは[CLI.md](/docs/CLI.md)を参照)
142
- - 学習の際に、自動的に自分のhugging faceリポジトリへ結果をアップロードするオプションを追加。コマンドライン引数で`--repo_id username/my_model`のように指定してください(詳しくは[CLI.md](/docs/CLI.md)を参照)。🤗の無制限ストレージが使えるのでクラウドでの学習に便利です。
143
- - 学習時にデコーダー部分を凍結するオプションの追加。品質がもしかしたら上がるかもしれません。
144
- - `initialize.py`に引数`--dataset_root`と`--assets_root`を追加し、`configs/paths.yml`をその時点で変更できるようにした
145
-
146
- ### その他
147
-
148
- - [paperspaceでの学習の手引きを追加](/docs/paperspace.md)、paperspaceでのimageに使える[Dockerfile](/Dockerfile.train)を追加
149
- - [CLIでの各種処理の実行の仕方を追加](/docs/CLI.md)
150
- - [Hugging Face spacesで遊べる音声合成エディタ](https://huggingface.co/spaces/litagin/Style-Bert-VITS2-Editor-Demo)をデプロイするための[Dockerfile](Dockerfile.deploy)を追加
151
-
152
- ### アップデート手順
153
-
154
- - [Update-to-Dict-Editor.bat](https://github.com/litagin02/Style-Bert-VITS2/releases/download/2.3/Update-to-Dict-Editor.bat)をダウンロードし、`Style-Bert-VITS2`フォルダがある場所(インストールbatファイルとかがあったところ)においてダブルクリックしてください。
155
-
156
- - 手動での場合は、以下の手順で実行してください:
157
- ```bash
158
- git pull
159
- venv\Scripts\activate
160
- pip uninstall pyopenjtalk-prebuilt
161
- pip install -U -r requirements.txt
162
- # python initialize.py # これを1.x系からのアップデートの場合は実行してください
163
- python server_editor.py --inbrowser
164
- ```
165
-
166
- ### 新規インストール手順
167
- [このzip](https://github.com/litagin02/Style-Bert-VITS2/releases/download/2.3/Style-Bert-VITS2.zip)をダウンロードし、解凍してください。
168
- を展開し、`Install-Style-Bert-VITS2.bat`をダブルクリックしてください。
169
-
170
-
171
- ## v2.2 (2024-02-09)
172
-
173
- ### 変更・機能追加
174
- - bfloat16オプションはデメリットしか無さそうなので、常にオフで学習するよう変更
175
- - バッチサイズのデフォルトを4から2に変更。学習が遅い場合はバッチサイズを下げて試してみて、VRAMに余裕があれば上げてください。JP-Extra使用時でのバッチサイズごとのVRAM使用量目安は、1: 6GB, 2: 8GB, 3: 10GB, 4: 12GB くらいのようです。
176
- - 学習の際の検証データ数をデフォルトで0に変更し、また検証データ数を学習用WebUIで指定でき���ようにした
177
- - Tensorboardのログ間隔を学習用WebUIで指定できるようにした
178
- - UIのテーマを`common/constants.py`の`GRADIO_THEME`で指定できるようにした
179
-
180
- ### バグ修正
181
- - JP-Extra使用時にバッチサイズが1だと学習中にエラーが発生するバグを修正
182
- - 「こんにちは!?!?!?!?」等、感嘆符等の記号が連続すると学習・音声合成でエラーになるバグを修正
183
- - `—` (em dash, U+2014) や `―` (quotation dash, U+2015) 等のダッシュやハイフンの各種変種が、種類によって`-`(通常の半角ハイフン)に正規化されたりされていなかったりする処理を、全て正規化するように修正
184
-
185
- ## v2.1 (2024-02-07)
186
-
187
- ### 変更
188
- - 学習の際、デフォルトではbfloat16オプションを使わないよう変更(学習が発散したり質が下がることがある模様)
189
- - 学習の際のメモリ使用量を削減しようと頑張った
190
-
191
- ### バグ修正や改善
192
- - 学習WebUIからTensorboardのログを見れるように
193
- - 音声合成(やそのAPI)において、同時に別の話者が選択され音声合成がリクエストされた場合に発生するエラーを修正
194
- - モデルマージ時に、そのレシピを`recipe.json`ファイルへ保存するように変更
195
- - 「改行で分けて生成」がより感情が乗る旨の明記等、軽微な説明文の改善
196
- - 「`ーーそれは面白い`」や「`なるほど。ーーーそういうことか。`」等、長音記号の前が母音でない場合、長音記号`ー`でなくダッシュ`―`の勘違いだと思われるので、ダッシュ記号として処理するように変更
197
-
198
- ## v2.0.1 (2024-02-05)
199
-
200
- 軽微なバグ修正や改善
201
- - スタイルベクトルに`NaN`が含まれていた場合(主に音声ファイルが極端に短い場合に発生)、それを学習リストから除外するように修正
202
- - colabにマージの追加
203
- - 学習時のプログレスバーの表示がおかしかったのを修正
204
- - デフォルトのjvnvモデルをJP-Extra版にアップデート。新しいモデルを使いたい方は手動で[こちら](https://huggingface.co/litagin/style_bert_vits2_jvnv/tree/main)からダウンロードするか、`python initialize.py`をするか、[このbatファイル](https://github.com/litagin02/Style-Bert-VITS2/releases/download/2.0.1/Update-to-JP-Extra.bat)を`Style-Bert-VITS2`フォルダがある場所(インストールbatファイルとかがあったところ)においてダブルクリックしてください。
205
-
206
- ## v2.0 (2024-02-03)
207
-
208
- ### 大きい変更
209
- モデル構造に [Bert-VITS2の日本語特化モデル JP-Extra](https://github.com/fishaudio/Bert-VITS2/releases/tag/JP-Exta) を取り込んだものを使えるように変更、[事前学習モデル](https://huggingface.co/litagin/Style-Bert-VITS2-2.0-base-JP-Extra)も[Bert-VITS2 JP-Extra](https://huggingface.co/Stardust-minus/Bert-VITS2-Japanese-Extra)のものを改造してStyle-Bert-VITS2で使えるようにしました (モデル構造を見直して日本語での学習をしていただいた [@Stardust-minus](https://github.com/Stardust-minus) 様に感謝します)
210
- - これにより、日本語の発音やアクセントや抑揚や自然性が向上する傾向があります
211
- - スタイルベクトルを使ったスタイルの操作は変わらず使えます
212
- - ただしJP-Extraでは英語と中国語の音声合成は(現状は)できません
213
- - 旧モデルも引き続き使うことができ、また旧モデルで学習することもできます
214
- - デフォルトのJVNVモデルは現在は旧verのままです
215
-
216
- ### 改善
217
- - `Merge.bat`で、声音マージを、より細かく「声質」と「声の高さ」の点でマージできるように。
218
-
219
- ### バグ修正
220
- - PyTorchのバージョンに由来するバグを修正(torchのバージョンを2.1.2に固定)
221
- - `―`(ダッシュ、長音記号ではない)が2連続すると学習・音声合成でエラーになるバグを修正
222
- - 「三円」等「ん+母音」のアクセントの仮名表記が「サネン」等になり、また偶にエラーが発生する問題を修正(「ん」の音素表記を内部的には「N」で統一)
223
-
224
- ## v1.3 (2024-01-09)
225
-
226
- ### 大きい変更
227
- - 元々のBert-VITS2に存在した、日本語の発音・アクセント処理部分のバグを修正・リファクタリング
228
- - `車両`が`シャリヨオ`、`思う`が`オモオ`、`見つける`が`ミッケル`等に発音・学習されており、その単語以降のアクセント情報が全て死んでいた
229
- - `私はそれを見る`のアクセントが`ワ➚タシ➘ワ ソ➚レ➘オ ミ➘ル`だったのを`ワ➚タシワ ソ➚レオ ミ➘ル`に修正
230
- - 学習・音声合成で無視されていたアルファベット・ギリシャ文字を無視しないように変更(基本はアルファベット読みだけど簡単な単語は読めるらしい、学習の際は念のためカタカナ等にしたほうがよいです)
231
- - 修正の影響で、前処理時に(今まで無視されていた)読めない漢字等で引っかかるようになりました。その場合は書き起こしを確認して修正するようにしてください。
232
- - アクセントを調整して音声合成できるように(完全に制御できるわけではないが改善される場合がある)。
233
-
234
- これまでのモデルもこれまで通り使え、アクセントや発音等が改善される可能性があります。新しいバージョンで学習し直すとより良くなる可能性もあります。が劇的に良くなるかは分かりません。
235
-
236
- ### 改善
237
- - `Dataset.bat`の音声スライスと書き起こしをよりカスタマイズできるように(スライスの秒数設定や書き起こしのWhisperモデル指定や言語指定等)
238
- - `Style.bat`のスタイル分けで、スタイルごとのサンプル音声を指定した数だけ複数再生できるように。また新しい次元削減方法(UMAP)と新しいスタイル分けの方法(DBSCAN)を追加(UMAPのほうがよくスタイルが分かれるかもしれません)
239
- - `App.bat`での音声合成時に複数話者モデルの場合に話者を指定できるように
240
- - colabの[ノートブック](http://colab.research.google.com/github/litagin02/Style-Bert-VITS2/blob/master/colab.ipynb)で、音声ファイルのみからデータセットを作成するオプション部分を追加
241
- - クラウド実行等の際にパスの指定をこちらでできるように、パスの設定を`configs/paths.yml`にまとめた(colabの[ノートブック](http://colab.research.google.com/github/litagin02/Style-Bert-VITS2/blob/master/colab.ipynb)もそれに伴って更新)。デフォルトは`dataset_root: Data`と`assets_root: model_assets`なので、クラウド等でやる方はここを変更してください。
242
- - どのステップ数の出力がよいかの「一つの」指標として [SpeechMOS](https://github.com/tarepan/SpeechMOS) を使うスクリプトを追加:
243
- ```bash
244
- python speech_mos.py -m <model_name>
245
- ```
246
- ステップごとの自然性評価が表示され、`mos_results`フォルダの`mos_{model_name}.csv`と`mos_{model_name}.png`に結果が保存される。読み上げさせたい文章を変えたかったら中のファイルを弄って各自調整してください。あくまでアクセントや感情表現や抑揚を全く考えない基準での評価で、目安のひとつなので、実際に読み上げさせて選別するのが一番だと思います。
247
- - 学習時のウォームアップオプションを機能するように( [@kale4eat](https://github.com/kale4eat) 様によるPRです、ありがとうございます!)。前処理時に生成される`config.json`の`train`の`warmup_epochs`を変更することで、ウォームアップのエポック数を変更できます。デフォルトは`0`で今までと同じ学習率の挙動です。
248
-
249
- ### その他
250
- - `Dataset.bat`の音声スライスでノーマライズ機能を削除(学習前処理で行えるため)
251
- - `Train.bat`の音量ノーマライズと無音切り詰めをデフォルトでオフに変更
252
- - 学習時の進捗を全体エポック数で表示し、学習全体の進捗を見やすいように( [@RedRayz](https://github.com/RedRayz) 様によるPRです、ありがとうございます!)
253
- - その他バグ修正等( [@tinjyuu](https://github.com/@tinjyuu) 様、 [@darai0512](https://github.com/darai0512) 様ありがとうございます!)
254
- - `config.json`にスタイル埋め込み部分を学習しない`freeze_style`オプションを追加(デフォルトは`false`)
255
-
256
- ### TIPS
257
- - 日本語学習の場合、`config.json`の`freeze_bert`と`freeze_en_bert`を`true`にしておくと、英語と中国語の発話能力が学習の過程で落ちないかもしれませんが、あまり比較していなので分かりません。
258
-
259
- ## v1.2 (2023-12-31)
260
-
261
- - グラボがないユーザーでの音声合成をサポート、`Install-Style-Bert-VITS2-CPU.bat`でインストール。
262
- - Google Colabでの学習をサポート、[ノートブック](http://colab.research.google.com/github/litagin02/Style-Bert-VITS2/blob/master/colab.ipynb)を追加
263
- - 音声合成のAPIサーバーを追加、`python server_fastapi.py`で起動します。API仕様は起動後に`/docs`にて確認ください。( [@darai0512](https://github.com/darai0512) 様によるPRです、ありがとうございます!)
264
- - 学習時に自動的にデフォルトスタイル Neutral を生成するように。特にスタイル指定が必要のない方は、学習したらそのまま音声合成を試せます。これまで通りスタイルを自分で作ることもできます。
265
- - マージ機能の新規追加: `Merge.bat`, `webui_merge.py`
266
- - 前処理のリサンプリング時に音声ファイルの開始・終了部分の無音を削除するオプションを追加(デフォルトでオン)
267
- - `スタイルテキスト (style text)`がスタイル指定と紛らわしかったので、`アシストテキスト (assist text)`に変更
268
- - その他コードのリファクタリング
269
-
270
- ## v1.1 (2023-12-29)
271
- - TrainとDatasetのWebUIの改良・調整(一括事前処理ボタン等)
272
- - 前処理のリサンプリング時に音量を正規化するオプションを追加(デフォルトでオン)
273
-
274
- ## v1.0 (2023-12-27)
275
- - 初版
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/CLI.md DELETED
@@ -1,104 +0,0 @@
1
- # CLI
2
-
3
- ## 0. Install and global paths settings
4
-
5
- ```bash
6
- git clone https://github.com/litagin02/Style-Bert-VITS2.git
7
- cd Style-Bert-VITS2
8
- python -m venv venv
9
- venv\Scripts\activate
10
- pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
11
- pip install -r requirements.txt
12
- ```
13
-
14
- Then download the necessary models and the default TTS model, and set the global paths.
15
- ```bash
16
- python initialize.py [--skip_jvnv] [--dataset_root <path>] [--assets_root <path>]
17
- ```
18
-
19
- Optional:
20
- - `--skip_jvnv`: Skip downloading the default JVNV voice models (use this if you only have to train your own models).
21
- - `--dataset_root`: Default: `Data`. Root directory of the training dataset. The training dataset of `{model_name}` should be placed in `{dataset_root}/{model_name}`.
22
- - `--assets_root`: Default: `model_assets`. Root directory of the model assets (for inference). In training, the model assets will be saved to `{assets_root}/{model_name}`, and in inference, we load all the models from `{assets_root}`.
23
-
24
-
25
- ## 1. Dataset preparation
26
-
27
- ### 1.1. Slice audio files
28
-
29
- The following audio formats are supported: ".wav", ".flac", ".mp3", ".ogg", ".opus".
30
- ```bash
31
- python slice.py --model_name <model_name> [-i <input_dir>] [-m <min_sec>] [-M <max_sec>] [--time_suffix]
32
- ```
33
-
34
- Required:
35
- - `model_name`: Name of the speaker (to be used as the name of the trained model).
36
-
37
- Optional:
38
- - `input_dir`: Path to the directory containing the audio files to slice (default: `inputs`)
39
- - `min_sec`: Minimum duration of the sliced audio files in seconds (default: 2).
40
- - `max_sec`: Maximum duration of the sliced audio files in seconds (default: 12).
41
- - `--time_suffix`: Make the filename end with -start_ms-end_ms when saving wav.
42
-
43
- ### 1.2. Transcribe audio files
44
-
45
- ```bash
46
- python transcribe.py --model_name <model_name>
47
- ```
48
- Required:
49
- - `model_name`: Name of the speaker (to be used as the name of the trained model).
50
-
51
- Optional
52
- - `--initial_prompt`: Initial prompt to use for the transcription (default value is specific to Japanese).
53
- - `--device`: `cuda` or `cpu` (default: `cuda`).
54
- - `--language`: `jp`, `en`, or `en` (default: `jp`).
55
- - `--model`: Whisper model, default: `large-v3`
56
- - `--compute_type`: default: `bfloat16`. Only used if not `--use_hf_whisper`.
57
- - `--use_hf_whisper`: Use Hugging Face's whisper model instead of default faster-whisper (HF whisper is faster but requires more VRAM).
58
- - `--batch_size`: Batch size (default: 16). Only used if `--use_hf_whisper`.
59
- - `--num_beams`: Beam size (default: 1).
60
- - `--no_repeat_ngram_size`: N-gram size for no repeat (default: 10).
61
-
62
- ## 2. Preprocess
63
-
64
- ```bash
65
- python preprocess_all.py -m <model_name> [--use_jp_extra] [-b <batch_size>] [-e <epochs>] [-s <save_every_steps>] [--num_processes <num_processes>] [--normalize] [--trim] [--val_per_lang <val_per_lang>] [--log_interval <log_interval>] [--freeze_EN_bert] [--freeze_JP_bert] [--freeze_ZH_bert] [--freeze_style] [--freeze_decoder] [--yomi_error <yomi_error>]
66
- ```
67
-
68
- Required:
69
- - `model_name`: Name of the speaker (to be used as the name of the trained model).
70
-
71
- Optional:
72
- - `--batch_size`, `-b`: Batch size (default: 2).
73
- - `--epochs`, `-e`: Number of epochs (default: 100).
74
- - `--save_every_steps`, `-s`: Save every steps (default: 1000).
75
- - `--num_processes`: Number of processes (default: half of the number of CPU cores).
76
- - `--normalize`: Loudness normalize audio.
77
- - `--trim`: Trim silence.
78
- - `--freeze_EN_bert`: Freeze English BERT.
79
- - `--freeze_JP_bert`: Freeze Japanese BERT.
80
- - `--freeze_ZH_bert`: Freeze Chinese BERT.
81
- - `--freeze_style`: Freeze style vector.
82
- - `--freeze_decoder`: Freeze decoder.
83
- - `--use_jp_extra`: Use JP-Extra model.
84
- - `--val_per_lang`: Validation data per language (default: 0).
85
- - `--log_interval`: Log interval (default: 200).
86
- - `--yomi_error`: How to handle yomi errors (default: `raise`: raise an error after preprocessing all texts, `skip`: skip the texts with errors, `use`: use the texts with errors by ignoring unknown characters).
87
-
88
- ## 3. Train
89
-
90
- Training settings are automatically loaded from the above process.
91
-
92
- If NOT using JP-Extra model:
93
- ```bash
94
- python train_ms.py [--repo_id <username>/<repo_name>]
95
- ```
96
-
97
- If using JP-Extra model:
98
- ```bash
99
- python train_ms_jp_extra.py [--repo_id <username>/<repo_name>] [--skip_default_style]
100
- ```
101
-
102
- Optional:
103
- - `--repo_id`: Hugging Face repository ID to upload the trained model to. You should have logged in using `huggingface-cli login` before running this command.
104
- - `--skip_default_style`: Skip making the default style vector. Use this if you want to resume training (since the default style vector is already made).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/README_en.md DELETED
@@ -1,127 +0,0 @@
1
- # This English README is for 1.x versions. WIP for 2.x versions.
2
-
3
- # Style-Bert-VITS2
4
-
5
- Bert-VITS2 with more controllable voice styles.
6
-
7
- https://github.com/litagin02/Style-Bert-VITS2/assets/139731664/b907c1b8-43aa-46e6-b03f-f6362f5a5a1e
8
-
9
- [Zenn Commentary Article (translated)](Style-Bert-VITS2_en.md) ([original](https://zenn.dev/litagin/articles/034819a5256ff4))
10
-
11
- [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](http://colab.research.google.com/github/litagin02/Style-Bert-VITS2/blob/master/colab.ipynb)
12
-
13
- Online demo: https://huggingface.co/spaces/litagin/Style-Bert-VITS2-JVNV
14
-
15
- This repository is based on [Bert-VITS2](https://github.com/fishaudio/Bert-VITS2) v2.1, so many thanks to the original author!
16
-
17
- - [Update History](docs/CHANGELOG.md)
18
-
19
- **Overview**
20
-
21
- - Based on Bert-VITS2 v2.1, which generates emotionally rich voices from entered text, this version allows free control of emotions and speaking styles, including intensity.
22
- - Easy to install and train for people without Git or Python (for Windows users), much is borrowed from [EasyBertVits2](https://github.com/Zuntan03/EasyBertVits2/). Training on Google Colab is also supported: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](http://colab.research.google.com/github/litagin02/Style-Bert-VITS2/blob/master/colab.ipynb)
23
- - If used only for voice synthesis, it can operate on CPU without a graphics card.
24
- - Also includes an API server for integration with others (PR by [@darai0512](https://github.com/darai0512), thank you).
25
- - Originally, Bert-VITS2's strength was to read "happy text happily, sad text sadly", so even without using the added style specification in this fork, you can generate emotionally rich voices.
26
-
27
-
28
- ## How to Use
29
-
30
- <!-- For more details, please refer to [here](docs/tutorial.md). -->
31
-
32
- ### Operating Environment
33
-
34
- We have confirmed the operation in Windows Command Prompt, WSL2, and Linux (Ubuntu Desktop) for each UI and API Server (please be creative with path specifications in WSL).
35
-
36
- ### Installation
37
-
38
- #### For Those Unfamiliar with Git or Python
39
-
40
- Assuming Windows:
41
-
42
- 1. Download and unzip [this zip file](https://github.com/litagin02/Style-Bert-VITS2/releases/download/1.3/Style-Bert-VITS2.zip).
43
- - If you have a graphics card, double-click `Install-Style-Bert-VITS2.bat`.
44
- - If you don't have a graphics card, double-click `Install-Style-Bert-VITS2-CPU.bat`.
45
- 2. Wait for the necessary environment to install automatically.
46
- 3. After that, if the WebUI for voice synthesis launches automatically, the installation is successful. The default model will be downloaded, so you can play with it immediately.
47
-
48
- For updates, please double-click `Update-Style-Bert-VITS2.bat`.
49
-
50
- #### For Those Familiar with Git and Python
51
-
52
- ```bash
53
- git clone https://github.com/litagin02/Style-Bert-VITS2.git
54
- cd Style-Bert-VITS2
55
- python -m venv venv
56
- venv\Scripts\activate
57
- pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
58
- pip install -r requirements.txt
59
- python initialize.py # Download necessary models and default TTS model
60
- ```
61
- Don't forget the last step.
62
-
63
- ### Voice Synthesis
64
- Double-click `App.bat` or run `python app.py` to launch the WebUI. The default model is downloaded during installation, so you can use it even if you haven't trained it.
65
-
66
- The structure of the model files required for voice synthesis is as follows (you don't need to place them manually):
67
-
68
- ```
69
- model_assets
70
- ├── your_model
71
- │ ├── config.json
72
- │ ├── your_model_file1.safetensors
73
- │ ├── your_model_file2.safetensors
74
- │ ├── ...
75
- │ └── style_vectors.npy
76
- └── another_model
77
- ├── ...
78
- ```
79
-
80
- For inference, `config.json`, `*.safetensors`, and `style_vectors.npy` are necessary. If you want to share a model, please share these three files.
81
-
82
- Among them, `style_vectors.npy` is a file necessary to control the style. By default, the average style "Neutral" is generated during training.
83
- If you want to use multiple styles for more detailed control, please refer to "Generating Styles" below (even with only the average style, if the training data is emotionally rich, sufficiently emotionally rich voices can be generated).
84
-
85
- ### Training
86
-
87
- Double-click Train.bat or run `python webui_train.py` to launch the WebUI.
88
-
89
- ### Generating Styles
90
- For those who want to use styles other than the default "Neutral".
91
-
92
- - Double-click `Style.bat` or run `python webui_style_vectors.py` to launch the WebUI.
93
- - It is independent of training, so you can do it even during training, and you can redo it any number of times after training is complete (preprocessing must be finished).
94
- - For more details on the specifications of the style, please refer to [clustering.ipynb](../clustering.ipynb).
95
-
96
- ### Dataset Creation
97
-
98
- - Double-click `Dataset.bat` or run `python webui_dataset.py` to launch the WebUI for creating datasets from audio files. You can use this tool to learn from audio files only.
99
-
100
- Note: If you want to manually correct the dataset, remove noise, etc., you may find [Aivis](https://github.com/tsukumijima/Aivis) or its Windows-compatible dataset part [Aivis Dataset](https://github.com/litagin02/Aivis-Dataset) useful. However, if there are many files, etc., it may be sufficient to simply cut out and create a dataset with this tool.
101
-
102
- Please experiment to see what kind of dataset is best.
103
-
104
- ### API Server
105
- Run `python server_fastapi.py` in the constructed environment to launch the API server.
106
- Please check the API specification after launching at `/docs`.
107
-
108
- By default, CORS settings are allowed for all domains.
109
- As much as possible, change the value of server.origins in `config.yml` and limit it to trusted domains (if you delete the key, you can disable the CORS settings).
110
-
111
- ### Merging
112
- You can create a new model by mixing two models in terms of "voice", "emotional expression", and "tempo".
113
- Double-click `Merge.bat` or run `python webui_merge.py` to launch the WebUI.
114
-
115
- ## Relation to Bert-VITS2 v2.1
116
- Basically, it's just a slight modification of the Bert-VITS2 v2.1 model structure. The [pre-trained model](https://huggingface.co/litagin/Style-Bert-VITS2-1.0-base) is also essentially the same as Bert-VITS2 v2.1 (unnecessary weights have been removed and converted to safetensors).
117
-
118
- The differences are as follows:
119
-
120
- - Like [EasyBertVits2](https://github.com/Zuntan03/EasyBertVits2), it is easy to use even for people who do not know Python or Git.
121
- - Changed the model for emotional embedding (from 1024-dimensional [wav2vec2-large-robust-12-ft-emotion-msp-dim](https://huggingface.co/audeering/wav2vec2-large-robust-12-ft-emotion-msp-dim) to 256-dimensional [wespeaker-voxceleb-resnet34-LM](https://huggingface.co/pyannote/wespeaker-voxceleb-resnet34-LM), which is more for speaker identification than emotional embedding)
122
- - Removed vector quantization from embeddings and replaced it with just a fully connected layer.
123
- - By creating a style vector file `style_vectors.npy`, you can generate voices using that style and continuously specify the strength of the effect.
124
- - Various WebUIs created
125
- - Support for bf16 training
126
- - Support for safetensors format, defaulting to using safetensors
127
- - Other minor bug fixes and refactoring
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/Style-Bert-VITS2_en.md DELETED
@@ -1,207 +0,0 @@
1
- # Announcements
2
-
3
- * I uploaded a tutorial video explaining Style-Bert-VITS2, which can be found on [YouTube](https://www.youtube-nocookie.com/embed/aTUSzgDl1iY).
4
-
5
- * I frequently visit the「AI声づくり研究会」 (AI Voice Creation Research Group) Discord server.
6
-
7
- # Overview
8
-
9
- On February 1, 2024, a Japanese-specialized version of the Chinese open-source text-to-speech (TTS) model Bert-VITS2, called [Bert-VITS2 JP-Extra](https://github.com/fishaudio/Bert-VITS2/releases/tag/JP-Exta), was released. My modified version, [Style-Bert-VITS2](https://github.com/litagin02/Style-Bert-VITS2), now supports the JP-Extra version as of February 3.
10
-
11
- You can try out the model using the [online demo](https://huggingface.co/spaces/litagin/Style-Bert-VITS2-JVNV).
12
-
13
- This version improves the naturalness of Japanese pronunciation, accent, and intonation, while reducing clarity issues and instability during training. If you only need Japanese TTS and don't require English or Chinese, using the JP-Extra version is highly recommended.
14
-
15
- This article discusses the differences between the JP-Extra version and the [previous 2.1-2.3 structures](https://zenn.dev/litagin/articles/8c6edcf6b6fcd6), as well as how Style-Bert-VITS2 further modifies the model.
16
-
17
- # Disclaimer
18
-
19
- I have not formally studied machine learning, voice AI, or Japanese language processing, so there may be inaccuracies in the article.
20
-
21
- # Short Summary
22
-
23
- Compared to other versions, (Style-)Bert-VITS2 JP-Extra:
24
-
25
- - Fixes bugs in the Japanese reading and accent acquisition parts of the original version (thanks to my contributions ✌)
26
- - Increases the amount of Japanese training data used for the pre-trained model (approximately 800 hours for Japanese only)
27
- - Removes Chinese and English components to focus on Japanese performance
28
- - Implements voice control using prompts with CLAP, as in version 2.2 (although it doesn't seem very practical, similar to 2.2)
29
- - Uses the new WavLM-based discriminator from version 2.3 to improve naturalness
30
- - Removes the duration discriminator to avoid unstable phoneme intervals, as seen in version 2.3
31
- - In Style-Bert-VITS2, the seemingly ineffective CLAP-based emotion embedding is removed and replaced with a simple fully connected layer for style embedding, as in the previous version
32
- - Style-Bert-VITS2 also allows for (some) manual control of accents
33
-
34
- These changes significantly improve the naturalness of Japanese pronunciation and accents, increase clarity, and reduce the impression of "Japanese spoken by a foreigner" that was present in earlier versions.
35
-
36
- Below I will write a little about these changes from a layman's perspective.
37
-
38
- # Increase in Japanese Training Data
39
-
40
- According to the [Bert-VITS2 JP-Extra release page](https://github.com/fishaudio/Bert-VITS2/releases/tag/JP-Exta);
41
-
42
- > 3. "the amount of Japanese training data has been increased several times, now up to approximately 800 hours for a single language"
43
-
44
- The increase in data (along with the fixes to Japanese processing bugs) may contribute more to the improvement in naturalness than the model structure refinements, although this is not certain without further experimentation.
45
-
46
- # Japanese Language Processing
47
-
48
- The following section is not directly related to the main topic of model structure, so feel free to skip it if you are not interested.
49
-
50
- In a previous article, I mentioned that the original version had bugs in the Japanese processing part, and that Style-Bert-VITS2 fixed them. The current (Style-)Bert-VITS2 JP-Extra incorporates those fixes. Here, I will explain precisely what kind of processing is performed on Japanese text.
51
-
52
- ## Overview of Japanese Processing in Japanese TTS Models
53
-
54
- In Japanese TTS, the input Japanese text is typically converted into a phoneme sequence, a process called grapheme-to-phoneme (g2p). Both during training and inference, the phoneme sequence obtained from the g2p process is fed into the model as input (in addition to the original Japanese text via BERT, which is a unique feature of Bert-VITS2).
55
-
56
- ## Example
57
-
58
- The [pyopenjtalk](https://github.com/r9y9/pyopenjtalk) library, which has become a de facto standard for Japanese phoneme processing and is used in Bert-VITS2, provides a g2p function. For example:
59
-
60
- ```python
61
- >>> import pyopenjtalk
62
- >>> pyopenjtalk.g2p("おはよう!元気ですか?")
63
- 'o h a y o o pau g e N k i d e s U k a'
64
- ```
65
-
66
- The function returns a space-separated list of phonemes for the input text.
67
-
68
- ## Limitations of pyopenjtalk's Default g2p
69
-
70
- While `pyopenjtalk.g2p` is convenient, it has some limitations:
71
-
72
- 1. It only returns a simple phoneme sequence without any accent information.
73
- 2. All punctuation marks and symbols like "!?" in the input text are treated as pause phonemes (`pau`), so "私は……そう思う……。" and "私は!!!!そう思う!!!" are not distinguished.
74
-
75
- ### g2p Considering Accents
76
-
77
- Accents are an important issue in Japanese TTS. Unlike English or Chinese, each word in Japanese has a correct accent, and incorrect accents can cause significant unnaturalness. Therefore, it is desirable to correctly learn the accent information in addition to the phonemes and, if possible, to enable manual accent specification for TTS.
78
-
79
- There are various approaches to incorporating accent information into the model. For example, [ESPNet](https://github.com/espnet/espnet), which allows for various voice-related training tasks, provides the [following g2p functions](https://github.com/espnet/espnet/blob/59733c2f1a962575667f6887e87fcdf04e06afc3/egs2/jvs/tts1/run.sh#L29-L49) for Japanese:
80
-
81
- - `pyopenjtalk`: Uses the default `pyopenjtalk.g2p` function without accent information
82
- - `pyopenjtalk_accent`: Inserts accent information using `0` for low and `1` for high pitch after each phoneme
83
- - `pyopenjtalk_prosody`: Inserts `[` for pitch rise and `]` for pitch fall as part of the phoneme symbols
84
- - `pyopenjtalk_kana`: Outputs katakana instead of phonemes
85
- - `pyopenjtalk_phone`: Outputs phonemes with stress and tone marks
86
-
87
- The choice of which g2p function to use varies among libraries, and it is unclear which one is the most common. For example, [COEIROINK](https://coeiroink.com/) uses `pyopenjtalk_prosody`.
88
-
89
- However, **all of these g2p functions have the second limitation mentioned above, where the type and number of symbols in the input text are not distinguished**. We desire the model to read "私は……そう思う……。" with a lack of confidence and "私は!!!!そう思う!!!" as shouting loudly, but this is not possible with these functions.
90
-
91
- In Bert-VITS2, accent information is fed into the model separately from the phoneme sequence under the name `tones`. This assigns the numbers 0 or 1 to each phoneme in the phoneme sequence. For Japanese, it looks like this:
92
-
93
- ```
94
- おはよう!!!ございます?
95
- → (o: 0), (h: 1), (a: 1), (y: 1), (o: 1), (o: 1), (!, 0), (!, 0), (!, 0), (g: 0) (o: 0), (z: 1) (a: 1), (i: 1), (m: 1), (a: 1), (s: 0), (u: 0), (?, 0)
96
- ```
97
-
98
- The low (0) and high (1) values are assigned to each phoneme, and this sequence of values is fed into the model separately from the phoneme sequence. Furthermore, as in the example above, **the symbols in the text are treated as phonemes themselves, distinguishing their type and number**.
99
-
100
- Implementing such a g2p function might be easy for experts in the Japanese TTS field, but lacking such knowledge, I took the following approach:
101
-
102
- 1. First, obtain a phoneme sequence with pitch rise and fall symbols using `pyopenjtalk_prosody` from ESPNet (however, the information about symbols like "!" and "…" is lost)
103
- 2. Use this to create a list of phoneme-accent pairs with the symbols completely removed
104
- 3. Separately create a phoneme sequence (without accent information) that includes the symbols
105
- 4. Combine the two results to obtain the desired output
106
-
107
- It might be possible to perform these operations using `pyopenjtalk` alone, but there are some difficulties:
108
-
109
- - In pyopenjtalk (OpenJTalk), obtaining accent information seems to always require extracting full context labels from the text (`pyopenjtalk.extract_fullcontext`), but the information about the type and number of symbols in the text is already lost at the full context label stage (so it is fundamentally impossible to obtain the desired result by parsing the full context labels)
110
-
111
- On the other hand, for step 3 above, the `pyopenjtalk.run_frontend` function obtains the reading in `pron` while preserving the type and number of symbols, as follows:
112
-
113
- As you can see, the `pron` part of the `pyopenjtalk.run_frontend` output preserves the type and number of symbols, so converting this to a phoneme sequence would accomplish step 3.
114
-
115
- Then, it's just a matter of writing processing code to combine the two results.
116
-
117
- For more details (and for my own reference), please refer to the well-commented source code.
118
-
119
- I actively welcome suggestions on how to simplify this process.
120
-
121
- ## Previously Existing Bugs
122
-
123
- Previous versions of Bert-VITS2 did not use the above method and had the following bugs:
124
-
125
- 1. When converting the reading result of `pyopenjtalk.run_frontend` to a phoneme list, the katakana reading was further processed by `pyopenjtalk.g2p`, causing issues.
126
- 2. The accent acquisition method was inaccurate, and the information was reset at word boundaries. For example, the correct accent for "私は思う" is "ワ➚タシワ オ➚モ➘ウ", but it became "ワ➚タシ➘ワ オ➚モ➘ウ" (due to the separate processing of "私" and "は").
127
-
128
- Regarding the first bug, further applying `pyopenjtalk.g2p` to the reading "シャリョオ" of "車両" results in "シャリヨオ":
129
-
130
- This behavior of `pyopenjtalk.g2p` (whether intentional or a bug) affected the subsequent accent processing, causing all accents after words like "車両" or "思う" to become "0".
131
-
132
- (I am unsure whether this behavior of `pyopenjtalk.g2p` is intended or a bug)
133
-
134
- # Changes in Model Structure
135
-
136
- The main idea of "inputting not only the phoneme sequence but also semantic information obtained from BERT to enable content-aware reading" remains unchanged. However, there are some differences between the JP-Extra version and the existing 2.1-2.3 models, which will be discussed in this section.
137
-
138
- ## Basic Framework
139
-
140
- Please refer to the [previous article](https://zenn.dev/litagin/articles/7179bb40f1f3a1).
141
-
142
- To summarize, the voice generation (generator) part of (Style-)Bert-VITS2 consists of the following components:
143
-
144
- - TextEncoder (receives text and returns various information)
145
- - DurationPredictor (returns phoneme intervals, i.e., the duration of each phoneme)
146
- - StochasticDurationPredictor (adds randomness to DurationPredictor?)
147
- - Flow (contains voice tone information, especially pitch)
148
- - Decoder (synthesizes the final voice output using various information; also contains voice tone information)
149
-
150
- Furthermore, since the model uses a GAN for training, both the Generator (voice generation) and the Discriminator (distinguishes between real and generated voices) are trained. The following components correspond to the files saved during actual training:
151
-
152
- - Generator: Has the above structure and generates voice from text. Saved in the `G_1000.pth` file. Only this is required for inference.
153
- - MultiPeriodDiscriminator: I lack the knowledge to explain this. Saved in the `D_1000.pth` file. It is the main discriminator and is apparently used in HiFi-GAN and other models.
154
- - DurationDiscriminator: Apparently a discriminator for phoneme intervals (output of DurationPredictor, etc). Saved in the `DUR_1000.pth` file.
155
- - **WavLMDiscriminator**: Will be discussed in more detail later. Saved in the `WD_1000.pth` file. It seems to be a discriminator using the [WavLM](https://arxiv.org/abs/2110.13900) SSL model for voice.
156
-
157
- The original JP-Extra version roughly follows the structure of Bert-VITS2 ver 2.3, with the addition of output control using CLAP prompts from ver 2.2.
158
-
159
- The important structural points are as follows:
160
-
161
- 1. Use of WavLMDiscriminator introduced in ver 2.3
162
- 2. Removal of DurationDiscriminator
163
- 3. Increase of `gin_channels` parameter from 256 in 2.1 and 2.2 to 512, as in 2.3
164
- 4. Voice tone control using CLAP prompts
165
-
166
- ### 1. WavLMDiscriminator
167
-
168
- I the knowledge and ability to provide a full explanation, so only the understood points will be discussed.
169
-
170
- In the machine learning field, **SSL (Self-Supervised Learning) models**, which are trained on large amounts of unlabeled data, seem to be useful. These models are used as a base for downstream tasks.
171
-
172
- In the voice field, the following models might be well-known:
173
-
174
- - [HuBERT](https://arxiv.org/abs/2106.07447)
175
- - [ContentVec](https://arxiv.org/abs/2204.09224)
176
- - [wav2vec 2.0](https://arxiv.org/abs/2006.11477)
177
- - [WavLM](https://arxiv.org/abs/2110.13900)
178
-
179
- The **WavLM** model, specifically [microsoft/wavlm-base-plus](https://huggingface.co/microsoft/wavlm-base-plus), was introduced in Bert-VITS2 ver 2.3 and is also used in the JP-Extra version.
180
-
181
- Although I do not fully understand the details, using the WavLM SSL model as a discriminator seems to improve the quality of the discriminator and, consequently, the quality of the generated voice. The `WD_*` files that started appearing in pre-trained models and during training in ver 2.3 and (Style-)Bert-VITS2 JP-Extra correspond to this model.
182
-
183
- ### 2. Removal of DurationDiscriminator
184
-
185
- (Style-)Bert-VITS2 had been using DurationDiscriminator for some time, but since ver 2.3 (possibly due to compatibility with WavLMDiscriminator?), there have been issues with phoneme intervals becoming slightly unstable (sounding stretched or not stabilizing during training).
186
-
187
- Considering this, the JP-Extra version does not use this component (so the `DUR_0` pre-trained model is no longer required).
188
-
189
- As a result, you might get a slight impression of faster speech, but overall, the phoneme intervals seem to have settled down. The presence or absence of this DurationDiscriminator can be easily changed in the settings, so experimenting with it might yield some insights.
190
-
191
- ### 3. Addition of gin_channels
192
-
193
- I can only provide impressions on this change, which was made in the original ver 2.3. There is a parameter called `gin_channels` that collectively determines the dimensions of the hidden layers in the model, and it was increased from 256 to 512.
194
-
195
- In the previous comments on Bert-VITS2 2.3, I had the impression that increasing this value might have added a slight inability to fully train the model. However, considering the success of the JP-Extra version (which may have benefited from an increase in the amount of data used for pre-training), increasing the dimensions might have been a good change in the end (although this cannot be stated with certainty without experimenting with 256).
196
-
197
- ### 4. CLAP
198
-
199
- This feature was introduced in the original Bert-VITS2 ver 2.2 (and removed in ver 2.3). It uses the [CLAP](https://huggingface.co/laion/clap-htsat-fused) model, which is trained on audio-text pairs, to attempt to control the output voice using text prompts (e.g., `Happy`).
200
-
201
- Specifically, an embedding related to the CLAP model (which can extract feature vectors from both audio and text) is added to the TextEncoder part.
202
-
203
- To be honest, while this may have been effective at the pre-trained model level, its effect seems to almost disappear when fine-tuning the model for practical use, and voice control using prompts is hardly possible, based on my experience.
204
-
205
- # Conclusion
206
-
207
- I encourage everyone to use Style-Bert-VITS2! It comes with tools for creating datasets and does not require Python environment setup for installation. As long as you have a GPU, you can easily train the model. Let's create our own tts models!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/paperspace.md DELETED
@@ -1,86 +0,0 @@
1
- # Paperspace gradient で学習する
2
-
3
- 詳しいコマンドの叩き方は[こちら](CLI.md)を参照してください。
4
-
5
- ## 事前準備
6
- - Paperspace のアカウントを作成し必要なら課金する
7
- - Projectを作る
8
- - NotebookはStart from Scratchを選択して空いてるGPUマシンを選ぶ
9
-
10
- ## 使い方
11
-
12
- 以下では次のような方針でやっています。
13
-
14
- - `/storage/`は永続ストレージなので、事前学習モデルとかを含めてリポジトリをクローンするとよい。
15
- - `/notebooks/`はノートブックごとに変わるストレージなので(同一ノートブック違うランタイムだと共有されるらしい)、データセットやその結果を保存する。ただ容量が多い場合はあふれる可能性があるので`/tmp/`に保存するとよいかもしれない。
16
- - hugging faceアカウントを作り、(プライベートな)リポジトリを作って、学習元データを置いたり、学習結果を随時アップロードする。
17
-
18
- ### 1. 環境を作る
19
-
20
- 以下はデフォルトの`Start from Scratch`で作成した環境の場合。[Dockerfile.train](../Dockerfile.train)を使ったカスタムイメージをするとPythonの環境構築の手間がちょっと省けるので、それを使いたい人は`Advanced Options / Container / Name`に[`litagin/mygradient:latest`](https://hub.docker.com/r/litagin/mygradient/tags)を指定すると使えます(pipの箇所が不要になる等)。
21
-
22
- まずは永続ストレージにgit clone
23
- ```bash
24
- mkdir -p /storage/sbv2
25
- cd /storage/sbv2
26
- git clone https://github.com/litagin02/Style-Bert-VITS2.git
27
- ```
28
- 環境構築(デフォルトはPyTorch 1.x系、Python 3.9の模様)
29
- ```bash
30
- cd /storage/sbv2/Style-Bert-VITS2
31
- pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 && pip install -r requirements.txt
32
- ```
33
- 事前学習済みモデル等のダウンロード、またパスを`/notebooks/`以下のものに設定
34
- ```bash
35
- python initialize.py --skip_jvnv --dataset_root /notebooks/Data --assets_root /notebooks/model_assets
36
- ```
37
-
38
- ### 2. データセットの準備
39
- 以下では`username/voices`というデータセットリポジトリにある`Foo.zip`というデータセットを使うことを想定しています。
40
- ```bash
41
- cd /notebooks
42
- huggingface-cli login # 事前にトークンが必要
43
- huggingface-cli download username/voices Foo.zip --repo-type dataset --local-dir .
44
- ```
45
-
46
- - zipファイル中身が既に`raw`と`esd.list`があるデータ(スライス・書き起こし済み)の場合
47
- ```bash
48
- mkdir -p Data/Foo
49
- unzip Foo.zip -d Data/Foo
50
- rm Foo.zip
51
- cd /storage/sbv2/Style-Bert-VITS2
52
- ```
53
-
54
- - zipファイルが音声ファイルのみの場合
55
- ```bash
56
- mkdir inputs
57
- unzip Foo.zip -d inputs
58
- cd /storage/sbv2/Style-Bert-VITS2
59
- python slice.py --model_name Foo -i /notebooks/inputs
60
- python transcribe.py --model_name Foo --use_hf_whisper
61
- ```
62
-
63
- それが終わったら、以下のコマンドで一括前処理を行う(パラメータは各自お好み、バッチサイズ5か6でVRAM 16GBギリくらい)。
64
- ```bash
65
- python preprocess_all.py --model_name Foo -b 5 -e 300 --use_jp_extra
66
- ```
67
-
68
- ### 3. 学習
69
-
70
- Hugging faceの`username/sbv2-private`というモデルリポジトリに学習済みモデルをアップロードすることを想定しています。事前に`huggingface-cli login`でログインしておくこと。
71
- ```bash
72
- python train_ms_jp_extra.py --repo_id username/sbv2-private
73
- ```
74
- (JP-Extraでない場合は`train_ms.py`を使う)
75
-
76
- ### 4. 学習再開
77
-
78
- Notebooksの時間制限が切れてから別Notebooksで同じモデルを学習を再開する場合(環境構築は必要)。
79
- ```bash
80
- huggingface-cli login
81
- cd /notebooks
82
- huggingface-cli download username/sbv2-private --include "Data/Foo/*" --local-dir .
83
- cd /storage/sbv2/Style-Bert-VITS2
84
- python train_ms_jp_extra.py --repo_id username/sbv2-private --skip_default_style
85
- ```
86
- 前回の設定が残っているので特に前処理等は不要。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
gen_yaml.py DELETED
@@ -1,34 +0,0 @@
1
- import argparse
2
- import os
3
- import shutil
4
-
5
- import yaml
6
-
7
-
8
- parser = argparse.ArgumentParser(
9
- description="config.ymlの生成。あらかじめ前準備をしたデータをバッチファイルなどで連続で学習する時にtrain_ms.pyより前に使用する。"
10
- )
11
- # そうしないと最後の前準備したデータで学習してしまう
12
- parser.add_argument("--model_name", type=str, help="Model name", required=True)
13
- parser.add_argument(
14
- "--dataset_path",
15
- type=str,
16
- help="Dataset path(example: Data\\your_model_name)",
17
- required=True,
18
- )
19
- args = parser.parse_args()
20
-
21
-
22
- def gen_yaml(model_name, dataset_path):
23
- if not os.path.exists("config.yml"):
24
- shutil.copy(src="default_config.yml", dst="config.yml")
25
- with open("config.yml", "r", encoding="utf-8") as f:
26
- yml_data = yaml.safe_load(f)
27
- yml_data["model_name"] = model_name
28
- yml_data["dataset_path"] = dataset_path
29
- with open("config.yml", "w", encoding="utf-8") as f:
30
- yaml.dump(yml_data, f, allow_unicode=True)
31
-
32
-
33
- if __name__ == "__main__":
34
- gen_yaml(args.model_name, args.dataset_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
gradio_tabs/dataset.py DELETED
@@ -1,248 +0,0 @@
1
- import gradio as gr
2
-
3
- from style_bert_vits2.logging import logger
4
- from style_bert_vits2.utils.subprocess import run_script_with_log
5
-
6
-
7
- def do_slice(
8
- model_name: str,
9
- min_sec: float,
10
- max_sec: float,
11
- min_silence_dur_ms: int,
12
- time_suffix: bool,
13
- input_dir: str,
14
- ):
15
- if model_name == "":
16
- return "Error: モデル名を入力してください。"
17
- logger.info("Start slicing...")
18
- cmd = [
19
- "slice.py",
20
- "--model_name",
21
- model_name,
22
- "--min_sec",
23
- str(min_sec),
24
- "--max_sec",
25
- str(max_sec),
26
- "--min_silence_dur_ms",
27
- str(min_silence_dur_ms),
28
- ]
29
- if time_suffix:
30
- cmd.append("--time_suffix")
31
- if input_dir != "":
32
- cmd += ["--input_dir", input_dir]
33
- # onnxの警告が出るので無視する
34
- success, message = run_script_with_log(cmd, ignore_warning=True)
35
- if not success:
36
- return f"Error: {message}"
37
- return "音声のスライスが完了しました。"
38
-
39
-
40
- def do_transcribe(
41
- model_name,
42
- whisper_model,
43
- compute_type,
44
- language,
45
- initial_prompt,
46
- device,
47
- use_hf_whisper,
48
- batch_size,
49
- num_beams,
50
- ):
51
- if model_name == "":
52
- return "Error: モデル名を入力してください。"
53
-
54
- cmd = [
55
- "transcribe.py",
56
- "--model_name",
57
- model_name,
58
- "--model",
59
- whisper_model,
60
- "--compute_type",
61
- compute_type,
62
- "--device",
63
- device,
64
- "--language",
65
- language,
66
- "--initial_prompt",
67
- f'"{initial_prompt}"',
68
- "--num_beams",
69
- str(num_beams),
70
- ]
71
- if use_hf_whisper:
72
- cmd.append("--use_hf_whisper")
73
- cmd.extend(["--batch_size", str(batch_size)])
74
- success, message = run_script_with_log(cmd)
75
- if not success:
76
- return f"Error: {message}. エラーメッセージが空の場合、何も問題がない可能性があるので、書き起こしファイルをチェックして問題なければ無視してください。"
77
-
78
-
79
- how_to_md = """
80
- Style-Bert-VITS2の学習用データセットを作成するためのツールです。以下の2つからなります。
81
-
82
- - 与えられた音声からちょうどいい長さの発話区間を切り取りスライス
83
- - 音声に対して文字起こし
84
-
85
- このうち両方を使ってもよいし、スライスする必要がない場合は後者のみを使ってもよいです。
86
-
87
- ## 必要なもの
88
-
89
- 学習したい音声が入ったwavファイルいくつか。
90
- 合計時間がある程度はあったほうがいいかも、10分とかでも大丈夫だったとの報告あり。単一ファイルでも良いし複数ファイルでもよい。
91
-
92
- ## スライス使い方
93
- 1. `inputs`フォルダにwavファイルをすべて入れる
94
- 2. `モデル名`を入力して、設定を必要なら調整して`音声のスライス`ボタンを押す
95
- 3. 出来上がった音声ファイルたちは`Data/{モデル名}/raw`に保存される
96
-
97
- ## 書き起こし使い方
98
-
99
- 1. 書き起こしたい音声ファイルのあるフォルダを指定(デフォルトは`Data/{モデル名}/raw`なのでスライス後に行う場合は省略してよい)
100
- 2. 設定を必要なら調整してボタンを押す
101
- 3. 書き起こしファイルは`Data/{モデル名}/esd.list`に保存される
102
-
103
- ## 注意
104
-
105
- - 長すぎる秒数(12-15秒くらいより長い?)のwavファイルは学習に用いられないようです。また短すぎてもあまりよくない可能性もあります。
106
- - 書き起こしの結果をどれだけ修正すればいいかはデータセットに依存しそうです。
107
- - 手動で書き起こしをいろいろ修正したり結果を細かく確認したい場合は、[Aivis Dataset](https://github.com/litagin02/Aivis-Dataset)もおすすめします。書き起こし部分もかなり工夫されています。ですがファイル数が多い場合などは、このツールで簡易的に切り出してデータセットを作るだけでも十分という気もしています。
108
- """
109
-
110
-
111
- def create_dataset_app() -> gr.Blocks:
112
- with gr.Blocks() as app:
113
- with gr.Accordion("使い方", open=False):
114
- gr.Markdown(how_to_md)
115
- model_name = gr.Textbox(
116
- label="モデル名を入力してください(話者名としても使われます)。"
117
- )
118
- with gr.Accordion("音声のスライス"):
119
- with gr.Row():
120
- with gr.Column():
121
- input_dir = gr.Textbox(
122
- label="元音声の入っているフォルダパス",
123
- value="inputs",
124
- info="下記フォルダにwavファイルを入れておいてください",
125
- )
126
- min_sec = gr.Slider(
127
- minimum=0,
128
- maximum=10,
129
- value=2,
130
- step=0.5,
131
- label="この秒数未満は切り捨てる",
132
- )
133
- max_sec = gr.Slider(
134
- minimum=0,
135
- maximum=15,
136
- value=12,
137
- step=0.5,
138
- label="この秒数以上は切り捨てる",
139
- )
140
- min_silence_dur_ms = gr.Slider(
141
- minimum=0,
142
- maximum=2000,
143
- value=700,
144
- step=100,
145
- label="無音とみなして区切る最小の無音の長さ(ms)",
146
- )
147
- time_suffix = gr.Checkbox(
148
- value=False,
149
- label="WAVファイル名の末尾に元ファイルの時間範囲を付与する",
150
- )
151
- slice_button = gr.Button("スライスを実行")
152
- result1 = gr.Textbox(label="結果")
153
- with gr.Row():
154
- with gr.Column():
155
- whisper_model = gr.Dropdown(
156
- [
157
- "tiny",
158
- "base",
159
- "small",
160
- "medium",
161
- "large",
162
- "large-v2",
163
- "large-v3",
164
- ],
165
- label="Whisperモデル",
166
- value="large-v3",
167
- )
168
- use_hf_whisper = gr.Checkbox(
169
- label="HuggingFaceのWhisperを使う(速度が速いがVRAMを多く使う)",
170
- )
171
- compute_type = gr.Dropdown(
172
- [
173
- "int8",
174
- "int8_float32",
175
- "int8_float16",
176
- "int8_bfloat16",
177
- "int16",
178
- "float16",
179
- "bfloat16",
180
- "float32",
181
- ],
182
- label="計算精度",
183
- value="bfloat16",
184
- )
185
- batch_size = gr.Slider(
186
- minimum=1,
187
- maximum=128,
188
- value=16,
189
- step=1,
190
- label="バッチサイズ",
191
- info="大きくすると速度が速くなるがVRAMを多く使う",
192
- visible=False,
193
- )
194
- device = gr.Radio(["cuda", "cpu"], label="デバイス", value="cuda")
195
- language = gr.Dropdown(["ja", "en", "zh"], value="ja", label="言語")
196
- initial_prompt = gr.Textbox(
197
- label="初期プロンプト",
198
- value="こんにちは。元気、ですかー?ふふっ、私は……ちゃんと元気だよ!",
199
- info="このように書き起こしてほしいという例文(句読点の入れ方・笑い方・固有名詞等)",
200
- )
201
- num_beams = gr.Slider(
202
- minimum=1,
203
- maximum=10,
204
- value=1,
205
- step=1,
206
- label="ビームサーチのビーム数",
207
- info="小さいほど速度が上がる(以前は5)",
208
- )
209
- transcribe_button = gr.Button("音声の文字起こし")
210
- result2 = gr.Textbox(label="結果")
211
- slice_button.click(
212
- do_slice,
213
- inputs=[
214
- model_name,
215
- min_sec,
216
- max_sec,
217
- min_silence_dur_ms,
218
- time_suffix,
219
- input_dir,
220
- ],
221
- outputs=[result1],
222
- )
223
- transcribe_button.click(
224
- do_transcribe,
225
- inputs=[
226
- model_name,
227
- whisper_model,
228
- compute_type,
229
- language,
230
- initial_prompt,
231
- device,
232
- use_hf_whisper,
233
- batch_size,
234
- num_beams,
235
- ],
236
- outputs=[result2],
237
- )
238
- use_hf_whisper.change(
239
- lambda x: (
240
- gr.update(visible=x),
241
- gr.update(visible=not x),
242
- gr.update(visible=not x),
243
- ),
244
- inputs=[use_hf_whisper],
245
- outputs=[batch_size, compute_type, device],
246
- )
247
-
248
- return app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
gradio_tabs/inference.py DELETED
@@ -1,468 +0,0 @@
1
- import datetime
2
- import json
3
- from typing import Optional
4
-
5
- import gradio as gr
6
-
7
- from style_bert_vits2.constants import (
8
- DEFAULT_ASSIST_TEXT_WEIGHT,
9
- DEFAULT_LENGTH,
10
- DEFAULT_LINE_SPLIT,
11
- DEFAULT_NOISE,
12
- DEFAULT_NOISEW,
13
- DEFAULT_SDP_RATIO,
14
- DEFAULT_SPLIT_INTERVAL,
15
- DEFAULT_STYLE,
16
- DEFAULT_STYLE_WEIGHT,
17
- GRADIO_THEME,
18
- Languages,
19
- )
20
- from style_bert_vits2.logging import logger
21
- from style_bert_vits2.models.infer import InvalidToneError
22
- from style_bert_vits2.nlp.japanese import pyopenjtalk_worker as pyopenjtalk
23
- from style_bert_vits2.nlp.japanese.g2p_utils import g2kata_tone, kata_tone2phone_tone
24
- from style_bert_vits2.nlp.japanese.normalizer import normalize_text
25
- from style_bert_vits2.tts_model import TTSModelHolder
26
-
27
-
28
- # pyopenjtalk_worker を起動
29
- ## pyopenjtalk_worker は TCP ソケットサーバーのため、ここで起動する
30
- pyopenjtalk.initialize_worker()
31
-
32
- # Web UI での学習時の無駄な GPU VRAM 消費を避けるため、あえてここでは BERT モデルの事前ロードを行わない
33
- # データセットの BERT 特徴量は事前に bert_gen.py により抽出されているため、学習時に BERT モデルをロードしておく必要はない
34
- # BERT モデルの事前ロードは「ロード」ボタン押下時に実行される TTSModelHolder.get_model_for_gradio() 内で行われる
35
- # Web UI での学習時、音声合成タブの「ロード」ボタンを押さなければ、BERT モデルが VRAM にロードされていない状態で学習を開始できる
36
-
37
- languages = [lang.value for lang in Languages]
38
-
39
- initial_text = "こんにちは、初めまして。あなたの名前はなんていうの?"
40
-
41
- examples = [
42
- [initial_text, "JP"],
43
- [
44
- """あなたがそんなこと言うなんて、私はとっても嬉しい。
45
- あなたがそんなこと言うなんて、私はとっても怒ってる。
46
- あなたがそんなこと言うなんて、私はとっても驚いてる。
47
- あなたがそんなこと言うなんて、私はとっても辛い。""",
48
- "JP",
49
- ],
50
- [ # ChatGPTに考えてもらった告白セリフ
51
- """私、ずっと前からあなたのことを見てきました。あなたの笑顔、優しさ、強さに、心惹かれていたんです。
52
- 友達として過ごす中で、あなたのことがだんだんと特別な存在になっていくのがわかりました。
53
- えっと、私、あなたのことが好きです!もしよければ、私と付き合ってくれませんか?""",
54
- "JP",
55
- ],
56
- [ # 夏目漱石『吾輩は猫である』
57
- """吾輩は猫である。名前はまだ無い。
58
- どこで生れたかとんと見当がつかぬ。なんでも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。
59
- 吾輩はここで初めて人間というものを見た。しかもあとで聞くと、それは書生という、人間中で一番獰悪な種族であったそうだ。
60
- この書生というのは時々我々を捕まえて煮て食うという話である。""",
61
- "JP",
62
- ],
63
- [ # 梶井基次郎『桜の樹の下には』
64
- """桜の樹の下には屍体が埋まっている!これは信じていいことなんだよ。
65
- 何故って、桜の花があんなにも見事に咲くなんて信じられないことじゃないか。俺はあの美しさが信じられないので、このにさんにち不安だった。
66
- しかしいま、やっとわかるときが来た。桜の樹の下には屍体が埋まっている。これは信じていいことだ。""",
67
- "JP",
68
- ],
69
- [ # ChatGPTと考えた、感情を表すセリフ
70
- """やったー!テストで満点取れた!私とっても嬉しいな!
71
- どうして私の意見を無視するの?許せない!ムカつく!あんたなんか死ねばいいのに。
72
- あはははっ!この漫画めっちゃ笑える、見てよこれ、ふふふ、あはは。
73
- あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しい。""",
74
- "JP",
75
- ],
76
- [ # 上の丁寧語バージョン
77
- """やりました!テストで満点取れましたよ!私とっても嬉しいです!
78
- どうして私の意見を無視するんですか?許せません!ムカつきます!あんたなんか死んでください。
79
- あはははっ!この漫画めっちゃ笑えます、見てくださいこれ、ふふふ、あはは。
80
- あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しいです。""",
81
- "JP",
82
- ],
83
- [ # ChatGPTに考えてもらった音声合成の説明文章
84
- """音声合成は、機械学習を活用して、テキストから人の声を再現する技術です。この技術は、言語の構造を解析し、それに基づいて音声を生成します。
85
- この分野の最新の研究成果を使うと、よ��自然で表現豊かな音声の生成が可能である。深層学習の応用により、感情やアクセントを含む声質の微妙な変化も再現することが出来る。""",
86
- "JP",
87
- ],
88
- [
89
- "Speech synthesis is the artificial production of human speech. A computer system used for this purpose is called a speech synthesizer, and can be implemented in software or hardware products.",
90
- "EN",
91
- ],
92
- [
93
- "语音合成是人工制造人类语音。用于此目的的计算机系统称为语音合成器,可以通过软件或硬件产品实现。",
94
- "ZH",
95
- ],
96
- ]
97
-
98
- initial_md = """
99
- - Ver 2.3で追加されたエディターのほうが実際に読み上げさせるには使いやすいかもしれません。`Editor.bat`か`python server_editor.py --inbrowser`で起動できます。
100
-
101
- - 初期からある[jvnvのモデル](https://huggingface.co/litagin/style_bert_vits2_jvnv)は、[JVNVコーパス(言語音声と非言語音声を持つ日本語感情音声コーパス)](https://sites.google.com/site/shinnosuketakamichi/research-topics/jvnv_corpus)で学習されたモデルです。ライセンスは[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/deed.ja)です。
102
- """
103
-
104
- how_to_md = """
105
- 下のように`model_assets`ディレクトリの中にモデルファイルたちを置いてください。
106
- ```
107
- model_assets
108
- ├── your_model
109
- │ ├── config.json
110
- │ ├── your_model_file1.safetensors
111
- │ ├── your_model_file2.safetensors
112
- │ ├── ...
113
- │ └── style_vectors.npy
114
- └── another_model
115
- ├── ...
116
- ```
117
- 各モデルにはファイルたちが必要です:
118
- - `config.json`:学習時の設定ファイル
119
- - `*.safetensors`:学習済みモデルファイル(1つ以上が必要、複数可)
120
- - `style_vectors.npy`:スタイルベクトルファイル
121
-
122
- 上2つは`Train.bat`による学習で自動的に正しい位置に保存されます。`style_vectors.npy`は`Style.bat`を実行して指示に従って生成してください。
123
- """
124
-
125
- style_md = f"""
126
- - プリセットまたは音声ファイルから読み上げの声音・感情・スタイルのようなものを制御できます。
127
- - デフォルトの{DEFAULT_STYLE}でも、十分に読み上げる文に応じた感情で感情豊かに読み上げられます。このスタイル制御は、それを重み付きで上書きするような感じです。
128
- - 強さを大きくしすぎると発音が変になったり声にならなかったりと崩壊することがあります。
129
- - どのくらいに強さがいいかはモデルやスタイルによって異なるようです。
130
- - 音声ファイルを入力する場合は、学習データと似た声音の話者(特に同じ性別)でないとよい効果が出ないかもしれません。
131
- """
132
-
133
-
134
- def make_interactive():
135
- return gr.update(interactive=True, value="音声合成")
136
-
137
-
138
- def make_non_interactive():
139
- return gr.update(interactive=False, value="音声合成(モデルをロードしてください)")
140
-
141
-
142
- def gr_util(item):
143
- if item == "プリセットから選ぶ":
144
- return (gr.update(visible=True), gr.Audio(visible=False, value=None))
145
- else:
146
- return (gr.update(visible=False), gr.update(visible=True))
147
-
148
-
149
- def create_inference_app(model_holder: TTSModelHolder) -> gr.Blocks:
150
- def tts_fn(
151
- model_name,
152
- model_path,
153
- text,
154
- language,
155
- reference_audio_path,
156
- sdp_ratio,
157
- noise_scale,
158
- noise_scale_w,
159
- length_scale,
160
- line_split,
161
- split_interval,
162
- assist_text,
163
- assist_text_weight,
164
- use_assist_text,
165
- style,
166
- style_weight,
167
- kata_tone_json_str,
168
- use_tone,
169
- speaker,
170
- pitch_scale,
171
- intonation_scale,
172
- ):
173
- model_holder.get_model(model_name, model_path)
174
- assert model_holder.current_model is not None
175
-
176
- wrong_tone_message = ""
177
- kata_tone: Optional[list[tuple[str, int]]] = None
178
- if use_tone and kata_tone_json_str != "":
179
- if language != "JP":
180
- logger.warning("Only Japanese is supported for tone generation.")
181
- wrong_tone_message = "アクセント指定は現在日本語のみ対応しています。"
182
- if line_split:
183
- logger.warning("Tone generation is not supported for line split.")
184
- wrong_tone_message = (
185
- "アクセント指定は改行で分けて生成を使わない場合のみ対応しています。"
186
- )
187
- try:
188
- kata_tone = []
189
- json_data = json.loads(kata_tone_json_str)
190
- # tupleを使うように変換
191
- for kana, tone in json_data:
192
- assert isinstance(kana, str) and tone in (0, 1), f"{kana}, {tone}"
193
- kata_tone.append((kana, tone))
194
- except Exception as e:
195
- logger.warning(f"Error occurred when parsing kana_tone_json: {e}")
196
- wrong_tone_message = f"アクセント指定が不正です: {e}"
197
- kata_tone = None
198
-
199
- # toneは実際に音声合成に代入される際のみnot Noneになる
200
- tone: Optional[list[int]] = None
201
- if kata_tone is not None:
202
- phone_tone = kata_tone2phone_tone(kata_tone)
203
- tone = [t for _, t in phone_tone]
204
-
205
- speaker_id = model_holder.current_model.spk2id[speaker]
206
-
207
- start_time = datetime.datetime.now()
208
-
209
- try:
210
- sr, audio = model_holder.current_model.infer(
211
- text=text,
212
- language=language,
213
- reference_audio_path=reference_audio_path,
214
- sdp_ratio=sdp_ratio,
215
- noise=noise_scale,
216
- noise_w=noise_scale_w,
217
- length=length_scale,
218
- line_split=line_split,
219
- split_interval=split_interval,
220
- assist_text=assist_text,
221
- assist_text_weight=assist_text_weight,
222
- use_assist_text=use_assist_text,
223
- style=style,
224
- style_weight=style_weight,
225
- given_tone=tone,
226
- speaker_id=speaker_id,
227
- pitch_scale=pitch_scale,
228
- intonation_scale=intonation_scale,
229
- )
230
- except InvalidToneError as e:
231
- logger.error(f"Tone error: {e}")
232
- return f"Error: アクセント指定が不正です:\n{e}", None, kata_tone_json_str
233
- except ValueError as e:
234
- logger.error(f"Value error: {e}")
235
- return f"Error: {e}", None, kata_tone_json_str
236
-
237
- end_time = datetime.datetime.now()
238
- duration = (end_time - start_time).total_seconds()
239
-
240
- if tone is None and language == "JP":
241
- # アクセント指定に使えるようにアクセント情報を返す
242
- norm_text = normalize_text(text)
243
- kata_tone = g2kata_tone(norm_text)
244
- kata_tone_json_str = json.dumps(kata_tone, ensure_ascii=False)
245
- elif tone is None:
246
- kata_tone_json_str = ""
247
- message = f"Success, time: {duration} seconds."
248
- if wrong_tone_message != "":
249
- message = wrong_tone_message + "\n" + message
250
- return message, (sr, audio), kata_tone_json_str
251
-
252
- model_names = model_holder.model_names
253
- if len(model_names) == 0:
254
- logger.error(
255
- f"モデルが見つかりませんでした。{model_holder.root_dir}にモデルを置いてください。"
256
- )
257
- with gr.Blocks() as app:
258
- gr.Markdown(
259
- f"Error: モデルが見つかりませんでした。{model_holder.root_dir}にモデルを置いてください。"
260
- )
261
- return app
262
- initial_id = 0
263
- initial_pth_files = [
264
- str(f) for f in model_holder.model_files_dict[model_names[initial_id]]
265
- ]
266
-
267
- with gr.Blocks(theme=GRADIO_THEME) as app:
268
- gr.Markdown(initial_md)
269
- with gr.Accordion(label="使い方", open=False):
270
- gr.Markdown(how_to_md)
271
- with gr.Row():
272
- with gr.Column():
273
- with gr.Row():
274
- with gr.Column(scale=3):
275
- model_name = gr.Dropdown(
276
- label="モデル一覧",
277
- choices=model_names,
278
- value=model_names[initial_id],
279
- )
280
- model_path = gr.Dropdown(
281
- label="モデルファイル",
282
- choices=initial_pth_files,
283
- value=initial_pth_files[0],
284
- )
285
- refresh_button = gr.Button("更新", scale=1, visible=True)
286
- load_button = gr.Button("ロード", scale=1, variant="primary")
287
- text_input = gr.TextArea(label="テキスト", value=initial_text)
288
- pitch_scale = gr.Slider(
289
- minimum=0.8,
290
- maximum=1.5,
291
- value=1,
292
- step=0.05,
293
- label="音高(1以外では音質劣化)",
294
- )
295
- intonation_scale = gr.Slider(
296
- minimum=0,
297
- maximum=2,
298
- value=1,
299
- step=0.1,
300
- label="抑揚(1以外では音質劣化)",
301
- )
302
-
303
- line_split = gr.Checkbox(
304
- label="改行で分けて生成(分けたほうが感情が乗ります)",
305
- value=DEFAULT_LINE_SPLIT,
306
- )
307
- split_interval = gr.Slider(
308
- minimum=0.0,
309
- maximum=2,
310
- value=DEFAULT_SPLIT_INTERVAL,
311
- step=0.1,
312
- label="改行ごとに挟む無音の長さ(秒)",
313
- )
314
- line_split.change(
315
- lambda x: (gr.Slider(visible=x)),
316
- inputs=[line_split],
317
- outputs=[split_interval],
318
- )
319
- tone = gr.Textbox(
320
- label="アクセント調整(数値は 0=低 か1=高 のみ)",
321
- info="改行で分けない場合のみ使えます。万能ではありません。",
322
- )
323
- use_tone = gr.Checkbox(label="アクセント調整を使う", value=False)
324
- use_tone.change(
325
- lambda x: (gr.Checkbox(value=False) if x else gr.Checkbox()),
326
- inputs=[use_tone],
327
- outputs=[line_split],
328
- )
329
- language = gr.Dropdown(choices=languages, value="JP", label="Language")
330
- speaker = gr.Dropdown(label="話者")
331
- with gr.Accordion(label="詳細設定", open=False):
332
- sdp_ratio = gr.Slider(
333
- minimum=0,
334
- maximum=1,
335
- value=DEFAULT_SDP_RATIO,
336
- step=0.1,
337
- label="SDP Ratio",
338
- )
339
- noise_scale = gr.Slider(
340
- minimum=0.1,
341
- maximum=2,
342
- value=DEFAULT_NOISE,
343
- step=0.1,
344
- label="Noise",
345
- )
346
- noise_scale_w = gr.Slider(
347
- minimum=0.1,
348
- maximum=2,
349
- value=DEFAULT_NOISEW,
350
- step=0.1,
351
- label="Noise_W",
352
- )
353
- length_scale = gr.Slider(
354
- minimum=0.1,
355
- maximum=2,
356
- value=DEFAULT_LENGTH,
357
- step=0.1,
358
- label="Length",
359
- )
360
- use_assist_text = gr.Checkbox(
361
- label="Assist textを使う", value=False
362
- )
363
- assist_text = gr.Textbox(
364
- label="Assist text",
365
- placeholder="どうして私の意見を無視するの?許せない、ムカつく!死ねばいいのに。",
366
- info="このテキストの読み上げと似た声音・感情になりやすくなります。ただ抑揚やテンポ等が犠牲になる傾向があります。",
367
- visible=False,
368
- )
369
- assist_text_weight = gr.Slider(
370
- minimum=0,
371
- maximum=1,
372
- value=DEFAULT_ASSIST_TEXT_WEIGHT,
373
- step=0.1,
374
- label="Assist textの強さ",
375
- visible=False,
376
- )
377
- use_assist_text.change(
378
- lambda x: (gr.Textbox(visible=x), gr.Slider(visible=x)),
379
- inputs=[use_assist_text],
380
- outputs=[assist_text, assist_text_weight],
381
- )
382
- with gr.Column():
383
- with gr.Accordion("スタイルについて詳細", open=False):
384
- gr.Markdown(style_md)
385
- style_mode = gr.Radio(
386
- ["プリセットから選ぶ", "音声ファイルを入力"],
387
- label="スタイルの指定方法",
388
- value="プリセットから選ぶ",
389
- )
390
- style = gr.Dropdown(
391
- label=f"スタイル({DEFAULT_STYLE}が平均スタイル)",
392
- choices=["モデルをロードしてください"],
393
- value="モデルをロードしてください",
394
- )
395
- style_weight = gr.Slider(
396
- minimum=0,
397
- maximum=50,
398
- value=DEFAULT_STYLE_WEIGHT,
399
- step=0.1,
400
- label="スタイルの強さ",
401
- )
402
- ref_audio_path = gr.Audio(
403
- label="参照音声", type="filepath", visible=False
404
- )
405
- tts_button = gr.Button(
406
- "音声合成(モデルをロードしてください)",
407
- variant="primary",
408
- interactive=False,
409
- )
410
- text_output = gr.Textbox(label="情報")
411
- audio_output = gr.Audio(label="結果")
412
- with gr.Accordion("テキスト例", open=False):
413
- gr.Examples(examples, inputs=[text_input, language])
414
-
415
- tts_button.click(
416
- tts_fn,
417
- inputs=[
418
- model_name,
419
- model_path,
420
- text_input,
421
- language,
422
- ref_audio_path,
423
- sdp_ratio,
424
- noise_scale,
425
- noise_scale_w,
426
- length_scale,
427
- line_split,
428
- split_interval,
429
- assist_text,
430
- assist_text_weight,
431
- use_assist_text,
432
- style,
433
- style_weight,
434
- tone,
435
- use_tone,
436
- speaker,
437
- pitch_scale,
438
- intonation_scale,
439
- ],
440
- outputs=[text_output, audio_output, tone],
441
- )
442
-
443
- model_name.change(
444
- model_holder.update_model_files_for_gradio,
445
- inputs=[model_name],
446
- outputs=[model_path],
447
- )
448
-
449
- model_path.change(make_non_interactive, outputs=[tts_button])
450
-
451
- refresh_button.click(
452
- model_holder.update_model_names_for_gradio,
453
- outputs=[model_name, model_path, tts_button],
454
- )
455
-
456
- load_button.click(
457
- model_holder.get_model_for_gradio,
458
- inputs=[model_name, model_path],
459
- outputs=[style, tts_button, speaker],
460
- )
461
-
462
- style_mode.change(
463
- gr_util,
464
- inputs=[style_mode],
465
- outputs=[style, ref_audio_path],
466
- )
467
-
468
- return app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
gradio_tabs/merge.py DELETED
@@ -1,501 +0,0 @@
1
- import json
2
- import os
3
- from pathlib import Path
4
-
5
- import gradio as gr
6
- import numpy as np
7
- import torch
8
- import yaml
9
- from safetensors import safe_open
10
- from safetensors.torch import save_file
11
-
12
- from style_bert_vits2.constants import DEFAULT_STYLE, GRADIO_THEME
13
- from style_bert_vits2.logging import logger
14
- from style_bert_vits2.tts_model import TTSModel, TTSModelHolder
15
-
16
-
17
- voice_keys = ["dec"]
18
- voice_pitch_keys = ["flow"]
19
- speech_style_keys = ["enc_p"]
20
- tempo_keys = ["sdp", "dp"]
21
-
22
- device = "cuda" if torch.cuda.is_available() else "cpu"
23
-
24
- # Get path settings
25
- with open(os.path.join("configs", "paths.yml"), "r", encoding="utf-8") as f:
26
- path_config: dict[str, str] = yaml.safe_load(f.read())
27
- # dataset_root = path_config["dataset_root"]
28
- assets_root = path_config["assets_root"]
29
-
30
-
31
- def merge_style(model_name_a, model_name_b, weight, output_name, style_triple_list):
32
- """
33
- style_triple_list: list[(model_aでのスタイル名, model_bでのスタイル名, 出力するスタイル名)]
34
- """
35
- # 新スタイル名リストにNeutralが含まれているか確認し、Neutralを先頭に持ってくる
36
- if any(triple[2] == DEFAULT_STYLE for triple in style_triple_list):
37
- # 存在する場合、リストをソート
38
- sorted_list = sorted(style_triple_list, key=lambda x: x[2] != DEFAULT_STYLE)
39
- else:
40
- # 存在しない場合、エラーを発生
41
- raise ValueError(f"No element with {DEFAULT_STYLE} output style name found.")
42
-
43
- style_vectors_a = np.load(
44
- os.path.join(assets_root, model_name_a, "style_vectors.npy")
45
- ) # (style_num_a, 256)
46
- style_vectors_b = np.load(
47
- os.path.join(assets_root, model_name_b, "style_vectors.npy")
48
- ) # (style_num_b, 256)
49
- with open(
50
- os.path.join(assets_root, model_name_a, "config.json"), "r", encoding="utf-8"
51
- ) as f:
52
- config_a = json.load(f)
53
- with open(
54
- os.path.join(assets_root, model_name_b, "config.json"), "r", encoding="utf-8"
55
- ) as f:
56
- config_b = json.load(f)
57
- style2id_a = config_a["data"]["style2id"]
58
- style2id_b = config_b["data"]["style2id"]
59
- new_style_vecs = []
60
- new_style2id = {}
61
- for style_a, style_b, style_out in sorted_list:
62
- if style_a not in style2id_a:
63
- logger.error(f"{style_a} is not in {model_name_a}.")
64
- raise ValueError(f"{style_a} は {model_name_a} にありません。")
65
- if style_b not in style2id_b:
66
- logger.error(f"{style_b} is not in {model_name_b}.")
67
- raise ValueError(f"{style_b} は {model_name_b} にありません。")
68
- new_style = (
69
- style_vectors_a[style2id_a[style_a]] * (1 - weight)
70
- + style_vectors_b[style2id_b[style_b]] * weight
71
- )
72
- new_style_vecs.append(new_style)
73
- new_style2id[style_out] = len(new_style_vecs) - 1
74
- new_style_vecs = np.array(new_style_vecs)
75
-
76
- output_style_path = os.path.join(assets_root, output_name, "style_vectors.npy")
77
- np.save(output_style_path, new_style_vecs)
78
-
79
- new_config = config_a.copy()
80
- new_config["data"]["num_styles"] = len(new_style2id)
81
- new_config["data"]["style2id"] = new_style2id
82
- new_config["model_name"] = output_name
83
- with open(
84
- os.path.join(assets_root, output_name, "config.json"), "w", encoding="utf-8"
85
- ) as f:
86
- json.dump(new_config, f, indent=2, ensure_ascii=False)
87
-
88
- # recipe.jsonを読み込んで、style_triple_listを追記
89
- info_path = os.path.join(assets_root, output_name, "recipe.json")
90
- if os.path.exists(info_path):
91
- with open(info_path, "r", encoding="utf-8") as f:
92
- info = json.load(f)
93
- else:
94
- info = {}
95
- info["style_triple_list"] = style_triple_list
96
- with open(info_path, "w", encoding="utf-8") as f:
97
- json.dump(info, f, indent=2, ensure_ascii=False)
98
-
99
- return output_style_path, list(new_style2id.keys())
100
-
101
-
102
- def lerp_tensors(t, v0, v1):
103
- return v0 * (1 - t) + v1 * t
104
-
105
-
106
- def slerp_tensors(t, v0, v1, dot_thres=0.998):
107
- device = v0.device
108
- v0c = v0.cpu().numpy()
109
- v1c = v1.cpu().numpy()
110
-
111
- dot = np.sum(v0c * v1c / (np.linalg.norm(v0c) * np.linalg.norm(v1c)))
112
-
113
- if abs(dot) > dot_thres:
114
- return lerp_tensors(t, v0, v1)
115
-
116
- th0 = np.arccos(dot)
117
- sin_th0 = np.sin(th0)
118
- th_t = th0 * t
119
-
120
- return torch.from_numpy(
121
- v0c * np.sin(th0 - th_t) / sin_th0 + v1c * np.sin(th_t) / sin_th0
122
- ).to(device)
123
-
124
-
125
- def merge_models(
126
- model_path_a,
127
- model_path_b,
128
- voice_weight,
129
- voice_pitch_weight,
130
- speech_style_weight,
131
- tempo_weight,
132
- output_name,
133
- use_slerp_instead_of_lerp,
134
- ):
135
- """model Aを起点に、model Bの各要素を重み付けしてマージする。
136
- safetensors形式を前提とする。"""
137
- model_a_weight = {}
138
- with safe_open(model_path_a, framework="pt", device="cpu") as f:
139
- for k in f.keys():
140
- model_a_weight[k] = f.get_tensor(k)
141
-
142
- model_b_weight = {}
143
- with safe_open(model_path_b, framework="pt", device="cpu") as f:
144
- for k in f.keys():
145
- model_b_weight[k] = f.get_tensor(k)
146
-
147
- merged_model_weight = model_a_weight.copy()
148
-
149
- for key in model_a_weight.keys():
150
- if any([key.startswith(prefix) for prefix in voice_keys]):
151
- weight = voice_weight
152
- elif any([key.startswith(prefix) for prefix in voice_pitch_keys]):
153
- weight = voice_pitch_weight
154
- elif any([key.startswith(prefix) for prefix in speech_style_keys]):
155
- weight = speech_style_weight
156
- elif any([key.startswith(prefix) for prefix in tempo_keys]):
157
- weight = tempo_weight
158
- else:
159
- continue
160
- merged_model_weight[key] = (
161
- slerp_tensors if use_slerp_instead_of_lerp else lerp_tensors
162
- )(weight, model_a_weight[key], model_b_weight[key])
163
-
164
- merged_model_path = os.path.join(
165
- assets_root, output_name, f"{output_name}.safetensors"
166
- )
167
- os.makedirs(os.path.dirname(merged_model_path), exist_ok=True)
168
- save_file(merged_model_weight, merged_model_path)
169
-
170
- info = {
171
- "model_a": model_path_a,
172
- "model_b": model_path_b,
173
- "voice_weight": voice_weight,
174
- "voice_pitch_weight": voice_pitch_weight,
175
- "speech_style_weight": speech_style_weight,
176
- "tempo_weight": tempo_weight,
177
- }
178
- with open(
179
- os.path.join(assets_root, output_name, "recipe.json"), "w", encoding="utf-8"
180
- ) as f:
181
- json.dump(info, f, indent=2, ensure_ascii=False)
182
- return merged_model_path
183
-
184
-
185
- def merge_models_gr(
186
- model_name_a,
187
- model_path_a,
188
- model_name_b,
189
- model_path_b,
190
- output_name,
191
- voice_weight,
192
- voice_pitch_weight,
193
- speech_style_weight,
194
- tempo_weight,
195
- use_slerp_instead_of_lerp,
196
- ):
197
- if output_name == "":
198
- return "Error: 新しいモデル名を入力してください。"
199
- merged_model_path = merge_models(
200
- model_path_a,
201
- model_path_b,
202
- voice_weight,
203
- voice_pitch_weight,
204
- speech_style_weight,
205
- tempo_weight,
206
- output_name,
207
- use_slerp_instead_of_lerp,
208
- )
209
- return f"Success: モデルを{merged_model_path}に保存しました。"
210
-
211
-
212
- def merge_style_gr(
213
- model_name_a,
214
- model_name_b,
215
- weight,
216
- output_name,
217
- style_triple_list_str: str,
218
- ):
219
- if output_name == "":
220
- return "Error: 新しいモデル名を入力してください。", None
221
- style_triple_list = []
222
- for line in style_triple_list_str.split("\n"):
223
- if not line:
224
- continue
225
- style_triple = line.split(",")
226
- if len(style_triple) != 3:
227
- logger.error(f"Invalid style triple: {line}")
228
- return (
229
- f"Error: スタイルを3つのカンマ区切りで入力してください:\n{line}",
230
- None,
231
- )
232
- style_a, style_b, style_out = style_triple
233
- style_a = style_a.strip()
234
- style_b = style_b.strip()
235
- style_out = style_out.strip()
236
- style_triple_list.append((style_a, style_b, style_out))
237
- try:
238
- new_style_path, new_styles = merge_style(
239
- model_name_a, model_name_b, weight, output_name, style_triple_list
240
- )
241
- except ValueError as e:
242
- return f"Error: {e}"
243
- return f"Success: スタイルを{new_style_path}に保存しました。", gr.Dropdown(
244
- choices=new_styles, value=new_styles[0]
245
- )
246
-
247
-
248
- def simple_tts(model_name, text, style=DEFAULT_STYLE, style_weight=1.0):
249
- model_path = os.path.join(assets_root, model_name, f"{model_name}.safetensors")
250
- config_path = os.path.join(assets_root, model_name, "config.json")
251
- style_vec_path = os.path.join(assets_root, model_name, "style_vectors.npy")
252
-
253
- model = TTSModel(Path(model_path), Path(config_path), Path(style_vec_path), device)
254
- return model.infer(text, style=style, style_weight=style_weight)
255
-
256
-
257
- def update_two_model_names_dropdown(model_holder: TTSModelHolder):
258
- new_names, new_files, _ = model_holder.update_model_names_for_gradio()
259
- return new_names, new_files, new_names, new_files
260
-
261
-
262
- def load_styles_gr(model_name_a, model_name_b):
263
- config_path_a = os.path.join(assets_root, model_name_a, "config.json")
264
- with open(config_path_a, "r", encoding="utf-8") as f:
265
- config_a = json.load(f)
266
- styles_a = list(config_a["data"]["style2id"].keys())
267
-
268
- config_path_b = os.path.join(assets_root, model_name_b, "config.json")
269
- with open(config_path_b, "r", encoding="utf-8") as f:
270
- config_b = json.load(f)
271
- styles_b = list(config_b["data"]["style2id"].keys())
272
-
273
- return (
274
- gr.Textbox(value=", ".join(styles_a)),
275
- gr.Textbox(value=", ".join(styles_b)),
276
- gr.TextArea(
277
- label="スタイルのマージリスト",
278
- placeholder=f"{DEFAULT_STYLE}, {DEFAULT_STYLE},{DEFAULT_STYLE}\nAngry, Angry, Angry",
279
- value="\n".join(
280
- f"{sty_a}, {sty_b}, {sty_a if sty_a != sty_b else ''}{sty_b}"
281
- for sty_a in styles_a
282
- for sty_b in styles_b
283
- ),
284
- ),
285
- )
286
-
287
-
288
- initial_md = """
289
- ## 使い方
290
-
291
- 1. マージしたい2つのモデルを選択してください(`model_assets`フォルダの中から選ばれます)。
292
- 2. マージ後のモデルの名前を入力してください。
293
- 3. マージ後のモデルの声質・話し方・話す速さを調整してください。
294
- 4. 「モデルファイルのマージ」ボタンを押してください(safetensorsファイルがマージされる)。
295
- 5. スタイルベクトルファイルも生成する必要があるので、指示に従ってマージ方法を入力後、「スタイルのマージ」ボタンを押してください。
296
-
297
- 以上でマージは完了で、`model_assets/マージ後のモデル名`にマージ後のモデルが保存され、音声合成のときに使えます。
298
-
299
- また`model_asses/マージ後のモデル名/recipe.json`には、マージの配合レシピが記録されます(推論にはいらないので配合メモ用です)。
300
-
301
- 一番下にマージしたモデルによる簡易的な音声合成機能もつけています。
302
-
303
- ## 注意
304
- 1.x系と2.x-JP-Extraのモデルマージは失敗するようです。
305
- """
306
-
307
- style_merge_md = f"""
308
- ## スタイルベクトルのマージ
309
-
310
- 1行に「モデルAのスタイル名, モデルBのスタイル名, 左の2つを混ぜて出力するスタイル名」
311
- という形式で入力してください。例えば、
312
- ```
313
- {DEFAULT_STYLE}, {DEFAULT_STYLE}, {DEFAULT_STYLE}
314
- Happy, Surprise, HappySurprise
315
- ```
316
- と入力すると、マージ後のスタイルベクトルは、
317
- - `{DEFAULT_STYLE}`: モデルAの`{DEFAULT_STYLE}`とモデルBの`{DEFAULT_STYLE}`を混ぜたもの
318
- - `HappySurprise`: モデルAの`Happy`とモデルBの`Surprise`を混ぜたもの
319
- の2つになります。
320
-
321
- ### 注意
322
- - 必ず「{DEFAULT_STYLE}」という名前のスタイルを作ってください。これは、マージ後のモデルの平均スタイルになります。
323
- - 構造上の相性の関係で、スタイルベクトルを混ぜる重みは、上の「話し方」と同じ比率で混ぜられます。例えば「話し方」が0のときはモデルAのみしか使われません。
324
- """
325
-
326
-
327
- def create_merge_app(model_holder: TTSModelHolder) -> gr.Blocks:
328
- model_names = model_holder.model_names
329
- if len(model_names) == 0:
330
- logger.error(
331
- f"モデルが見つかりませんでした。{assets_root}にモデルを置いてください。"
332
- )
333
- with gr.Blocks() as app:
334
- gr.Markdown(
335
- f"Error: モデルが見つかりませんでした。{assets_root}にモデルを置いてください。"
336
- )
337
- return app
338
- initial_id = 0
339
- initial_model_files = model_holder.model_files_dict[model_names[initial_id]]
340
-
341
- with gr.Blocks(theme=GRADIO_THEME) as app:
342
- gr.Markdown(
343
- "2つのStyle-Bert-VITS2モデルから、声質・話し方・話す速さを取り替えたり混ぜたりできます。"
344
- )
345
- with gr.Accordion(label="使い方", open=False):
346
- gr.Markdown(initial_md)
347
- with gr.Row():
348
- with gr.Column(scale=3):
349
- model_name_a = gr.Dropdown(
350
- label="モデルA",
351
- choices=model_names,
352
- value=model_names[initial_id],
353
- )
354
- model_path_a = gr.Dropdown(
355
- label="モデルファイル",
356
- choices=initial_model_files,
357
- value=initial_model_files[0],
358
- )
359
- with gr.Column(scale=3):
360
- model_name_b = gr.Dropdown(
361
- label="モデルB",
362
- choices=model_names,
363
- value=model_names[initial_id],
364
- )
365
- model_path_b = gr.Dropdown(
366
- label="モデルファイル",
367
- choices=initial_model_files,
368
- value=initial_model_files[0],
369
- )
370
- refresh_button = gr.Button("更新", scale=1, visible=True)
371
- with gr.Column(variant="panel"):
372
- new_name = gr.Textbox(label="新しいモデル名", placeholder="new_model")
373
- with gr.Row():
374
- voice_slider = gr.Slider(
375
- label="声質",
376
- value=0,
377
- minimum=0,
378
- maximum=1,
379
- step=0.1,
380
- )
381
- voice_pitch_slider = gr.Slider(
382
- label="声の高さ",
383
- value=0,
384
- minimum=0,
385
- maximum=1,
386
- step=0.1,
387
- )
388
- speech_style_slider = gr.Slider(
389
- label="話し方(抑揚・感情表現等)",
390
- value=0,
391
- minimum=0,
392
- maximum=1,
393
- step=0.1,
394
- )
395
- tempo_slider = gr.Slider(
396
- label="話す速さ・リズム・テンポ",
397
- value=0,
398
- minimum=0,
399
- maximum=1,
400
- step=0.1,
401
- )
402
- use_slerp_instead_of_lerp = gr.Checkbox(
403
- label="線形補完のかわりに球面線形補完を使う",
404
- value=False,
405
- )
406
- with gr.Column(variant="panel"):
407
- gr.Markdown("## モデルファイル(safetensors)のマージ")
408
- model_merge_button = gr.Button(
409
- "モデルファイルのマージ", variant="primary"
410
- )
411
- info_model_merge = gr.Textbox(label="情報")
412
- with gr.Column(variant="panel"):
413
- gr.Markdown(style_merge_md)
414
- with gr.Row():
415
- load_style_button = gr.Button("スタイル一覧をロード", scale=1)
416
- styles_a = gr.Textbox(label="モデルAのスタイル一覧")
417
- styles_b = gr.Textbox(label="モデルBのスタイル一覧")
418
- style_triple_list = gr.TextArea(
419
- label="スタイルのマージリスト",
420
- placeholder=f"{DEFAULT_STYLE}, {DEFAULT_STYLE},{DEFAULT_STYLE}\nAngry, Angry, Angry",
421
- value=f"{DEFAULT_STYLE}, {DEFAULT_STYLE}, {DEFAULT_STYLE}",
422
- )
423
- style_merge_button = gr.Button("スタイルのマージ", variant="primary")
424
- info_style_merge = gr.Textbox(label="情報")
425
-
426
- text_input = gr.TextArea(
427
- label="テキスト", value="これはテストです。聞こえていますか?"
428
- )
429
- style = gr.Dropdown(
430
- label="スタイル",
431
- choices=["スタイルをマージしてください"],
432
- value="スタイルをマージしてください",
433
- )
434
- emotion_weight = gr.Slider(
435
- minimum=0,
436
- maximum=50,
437
- value=1,
438
- step=0.1,
439
- label="スタイルの強さ",
440
- )
441
- tts_button = gr.Button("音声合成", variant="primary")
442
- audio_output = gr.Audio(label="結果")
443
-
444
- model_name_a.change(
445
- model_holder.update_model_files_for_gradio,
446
- inputs=[model_name_a],
447
- outputs=[model_path_a],
448
- )
449
- model_name_b.change(
450
- model_holder.update_model_files_for_gradio,
451
- inputs=[model_name_b],
452
- outputs=[model_path_b],
453
- )
454
-
455
- refresh_button.click(
456
- lambda: update_two_model_names_dropdown(model_holder),
457
- outputs=[model_name_a, model_path_a, model_name_b, model_path_b],
458
- )
459
-
460
- load_style_button.click(
461
- load_styles_gr,
462
- inputs=[model_name_a, model_name_b],
463
- outputs=[styles_a, styles_b, style_triple_list],
464
- )
465
-
466
- model_merge_button.click(
467
- merge_models_gr,
468
- inputs=[
469
- model_name_a,
470
- model_path_a,
471
- model_name_b,
472
- model_path_b,
473
- new_name,
474
- voice_slider,
475
- voice_pitch_slider,
476
- speech_style_slider,
477
- tempo_slider,
478
- use_slerp_instead_of_lerp,
479
- ],
480
- outputs=[info_model_merge],
481
- )
482
-
483
- style_merge_button.click(
484
- merge_style_gr,
485
- inputs=[
486
- model_name_a,
487
- model_name_b,
488
- speech_style_slider,
489
- new_name,
490
- style_triple_list,
491
- ],
492
- outputs=[info_style_merge, style],
493
- )
494
-
495
- tts_button.click(
496
- simple_tts,
497
- inputs=[new_name, text_input, style, emotion_weight],
498
- outputs=[audio_output],
499
- )
500
-
501
- return app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
gradio_tabs/style_vectors.py DELETED
@@ -1,470 +0,0 @@
1
- import json
2
- import os
3
- import shutil
4
- from pathlib import Path
5
-
6
- import gradio as gr
7
- import matplotlib.pyplot as plt
8
- import numpy as np
9
- import yaml
10
- from scipy.spatial.distance import pdist, squareform
11
- from sklearn.cluster import DBSCAN, AgglomerativeClustering, KMeans
12
- from sklearn.manifold import TSNE
13
- from umap import UMAP
14
-
15
- from config import config
16
- from style_bert_vits2.constants import DEFAULT_STYLE, GRADIO_THEME
17
- from style_bert_vits2.logging import logger
18
-
19
-
20
- # Get path settings
21
- with open(os.path.join("configs", "paths.yml"), "r", encoding="utf-8") as f:
22
- path_config: dict[str, str] = yaml.safe_load(f.read())
23
- dataset_root = Path(path_config["dataset_root"])
24
- # assets_root = path_config["assets_root"]
25
-
26
- MAX_CLUSTER_NUM = 10
27
- MAX_AUDIO_NUM = 10
28
-
29
- tsne = TSNE(n_components=2, random_state=42, metric="cosine")
30
- umap = UMAP(n_components=2, random_state=42, metric="cosine", n_jobs=1, min_dist=0.0)
31
-
32
- wav_files: list[Path] = []
33
- x = np.array([])
34
- x_reduced = None
35
- y_pred = np.array([])
36
- mean = np.array([])
37
- centroids = []
38
-
39
-
40
- def load(model_name: str, reduction_method: str):
41
- global wav_files, x, x_reduced, mean
42
- # wavs_dir = os.path.join(dataset_root, model_name, "wavs")
43
- wavs_dir = dataset_root / model_name / "wavs"
44
- # style_vector_files = [
45
- # os.path.join(wavs_dir, f) for f in os.listdir(wavs_dir) if f.endswith(".npy")
46
- # ]
47
- style_vector_files = [f for f in wavs_dir.rglob("*.npy") if f.is_file()]
48
- # foo.wav.npy -> foo.wav
49
- wav_files = [f.with_suffix("") for f in style_vector_files]
50
- logger.info(f"Found {len(style_vector_files)} style vectors in {wavs_dir}")
51
- style_vectors = [np.load(f) for f in style_vector_files]
52
- x = np.array(style_vectors)
53
- mean = np.mean(x, axis=0)
54
- if reduction_method == "t-SNE":
55
- x_reduced = tsne.fit_transform(x)
56
- elif reduction_method == "UMAP":
57
- x_reduced = umap.fit_transform(x)
58
- else:
59
- raise ValueError("Invalid reduction method")
60
- x_reduced = np.asarray(x_reduced)
61
- plt.figure(figsize=(6, 6))
62
- plt.scatter(x_reduced[:, 0], x_reduced[:, 1])
63
- return plt
64
-
65
-
66
- def do_clustering(n_clusters=4, method="KMeans"):
67
- global centroids, x_reduced, y_pred
68
- if method == "KMeans":
69
- model = KMeans(n_clusters=n_clusters, random_state=42, n_init="auto")
70
- y_pred = model.fit_predict(x)
71
- elif method == "Agglomerative":
72
- model = AgglomerativeClustering(n_clusters=n_clusters)
73
- y_pred = model.fit_predict(x)
74
- elif method == "KMeans after reduction":
75
- assert x_reduced is not None
76
- model = KMeans(n_clusters=n_clusters, random_state=42, n_init="auto")
77
- y_pred = model.fit_predict(x_reduced)
78
- elif method == "Agglomerative after reduction":
79
- assert x_reduced is not None
80
- model = AgglomerativeClustering(n_clusters=n_clusters)
81
- y_pred = model.fit_predict(x_reduced)
82
- else:
83
- raise ValueError("Invalid method")
84
-
85
- centroids = []
86
- for i in range(n_clusters):
87
- centroids.append(np.mean(x[y_pred == i], axis=0))
88
-
89
- return y_pred, centroids
90
-
91
-
92
- def do_dbscan(eps=2.5, min_samples=15):
93
- global centroids, x_reduced, y_pred
94
- model = DBSCAN(eps=eps, min_samples=min_samples)
95
- assert x_reduced is not None
96
- y_pred = model.fit_predict(x_reduced)
97
- n_clusters = max(y_pred) + 1
98
- centroids = []
99
- for i in range(n_clusters):
100
- centroids.append(np.mean(x[y_pred == i], axis=0))
101
- return y_pred, centroids
102
-
103
-
104
- def representative_wav_files(cluster_id, num_files=1):
105
- # y_predの中でcluster_indexに関するメドイドを探す
106
- cluster_indices = np.where(y_pred == cluster_id)[0]
107
- cluster_vectors = x[cluster_indices]
108
- # クラスタ内の全ベクトル間の距離を計算
109
- distances = pdist(cluster_vectors)
110
- distance_matrix = squareform(distances)
111
-
112
- # 各ベクトルと他の全ベクトルとの平均距離を計算
113
- mean_distances = distance_matrix.mean(axis=1)
114
-
115
- # 平均距離が最も小さい順にnum_files個のインデックスを取得
116
- closest_indices = np.argsort(mean_distances)[:num_files]
117
-
118
- return cluster_indices[closest_indices]
119
-
120
-
121
- def do_dbscan_gradio(eps=2.5, min_samples=15):
122
- global x_reduced, centroids
123
-
124
- y_pred, centroids = do_dbscan(eps, min_samples)
125
-
126
- assert x_reduced is not None
127
-
128
- cmap = plt.get_cmap("tab10")
129
- plt.figure(figsize=(6, 6))
130
- for i in range(max(y_pred) + 1):
131
- plt.scatter(
132
- x_reduced[y_pred == i, 0],
133
- x_reduced[y_pred == i, 1],
134
- color=cmap(i),
135
- label=f"Style {i + 1}",
136
- )
137
- # Noise cluster (-1) is black
138
- plt.scatter(
139
- x_reduced[y_pred == -1, 0],
140
- x_reduced[y_pred == -1, 1],
141
- color="black",
142
- label="Noise",
143
- )
144
- plt.legend()
145
-
146
- n_clusters = max(y_pred) + 1
147
-
148
- if n_clusters > MAX_CLUSTER_NUM:
149
- # raise ValueError(f"The number of clusters is too large: {n_clusters}")
150
- return [
151
- plt,
152
- gr.Slider(maximum=MAX_CLUSTER_NUM),
153
- f"クラスタ数が多すぎます、パラメータを変えてみてください。: {n_clusters}",
154
- ] + [gr.Audio(visible=False)] * MAX_AUDIO_NUM
155
-
156
- elif n_clusters == 0:
157
- return [
158
- plt,
159
- gr.Slider(maximum=MAX_CLUSTER_NUM),
160
- "クラスタが数が0です。パラメータを変えてみてください。",
161
- ] + [gr.Audio(visible=False)] * MAX_AUDIO_NUM
162
-
163
- return [plt, gr.Slider(maximum=n_clusters, value=1), n_clusters] + [
164
- gr.Audio(visible=False)
165
- ] * MAX_AUDIO_NUM
166
-
167
-
168
- def representative_wav_files_gradio(cluster_id, num_files=1):
169
- cluster_id = cluster_id - 1 # UIでは1から始まるので0からにする
170
- closest_indices = representative_wav_files(cluster_id, num_files)
171
- actual_num_files = len(closest_indices) # ファイル数が少ないときのため
172
- return [
173
- gr.Audio(wav_files[i], visible=True, label=str(wav_files[i]))
174
- for i in closest_indices
175
- ] + [gr.update(visible=False)] * (MAX_AUDIO_NUM - actual_num_files)
176
-
177
-
178
- def do_clustering_gradio(n_clusters=4, method="KMeans"):
179
- global x_reduced, centroids
180
- y_pred, centroids = do_clustering(n_clusters, method)
181
-
182
- assert x_reduced is not None
183
- cmap = plt.get_cmap("tab10")
184
- plt.figure(figsize=(6, 6))
185
- for i in range(n_clusters):
186
- plt.scatter(
187
- x_reduced[y_pred == i, 0],
188
- x_reduced[y_pred == i, 1],
189
- color=cmap(i),
190
- label=f"Style {i + 1}",
191
- )
192
- plt.legend()
193
-
194
- return [plt, gr.Slider(maximum=n_clusters, value=1)] + [
195
- gr.Audio(visible=False)
196
- ] * MAX_AUDIO_NUM
197
-
198
-
199
- def save_style_vectors_from_clustering(model_name, style_names_str: str):
200
- """centerとcentroidsを保存する"""
201
- result_dir = os.path.join(config.assets_root, model_name)
202
- os.makedirs(result_dir, exist_ok=True)
203
- style_vectors = np.stack([mean] + centroids)
204
- style_vector_path = os.path.join(result_dir, "style_vectors.npy")
205
- if os.path.exists(style_vector_path):
206
- logger.info(f"Backup {style_vector_path} to {style_vector_path}.bak")
207
- shutil.copy(style_vector_path, f"{style_vector_path}.bak")
208
- np.save(style_vector_path, style_vectors)
209
- logger.success(f"Saved style vectors to {style_vector_path}")
210
-
211
- # config.jsonの更新
212
- config_path = os.path.join(result_dir, "config.json")
213
- if not os.path.exists(config_path):
214
- return f"{config_path}が存在しません。"
215
- style_names = [name.strip() for name in style_names_str.split(",")]
216
- style_name_list = [DEFAULT_STYLE] + style_names
217
- if len(style_name_list) != len(centroids) + 1:
218
- return f"スタイルの数が合いません。`,`で正しく{len(centroids)}個に区切られているか確認してください: {style_names_str}"
219
- if len(set(style_names)) != len(style_names):
220
- return "スタイル名が重複しています。"
221
-
222
- logger.info(f"Backup {config_path} to {config_path}.bak")
223
- shutil.copy(config_path, f"{config_path}.bak")
224
- with open(config_path, "r", encoding="utf-8") as f:
225
- json_dict = json.load(f)
226
- json_dict["data"]["num_styles"] = len(style_name_list)
227
- style_dict = {name: i for i, name in enumerate(style_name_list)}
228
- json_dict["data"]["style2id"] = style_dict
229
- with open(config_path, "w", encoding="utf-8") as f:
230
- json.dump(json_dict, f, indent=2, ensure_ascii=False)
231
- logger.success(f"Updated {config_path}")
232
- return f"成功!\n{style_vector_path}に保存し{config_path}を更新しました。"
233
-
234
-
235
- def save_style_vectors_from_files(
236
- model_name, audio_files_str: str, style_names_str: str
237
- ):
238
- """音声ファイルからスタイルベクトルを作成して保存する"""
239
- global mean
240
- if len(x) == 0:
241
- return "Error: スタイルベクトルを読み込んでください。"
242
- mean = np.mean(x, axis=0)
243
-
244
- result_dir = os.path.join(config.assets_root, model_name)
245
- os.makedirs(result_dir, exist_ok=True)
246
- audio_files = [name.strip() for name in audio_files_str.split(",")]
247
- style_names = [name.strip() for name in style_names_str.split(",")]
248
- if len(audio_files) != len(style_names):
249
- return f"音声ファイルとスタイル名の数が合いません。`,`で正しく{len(style_names)}個に区切られているか確認してください: {audio_files_str}と{style_names_str}"
250
- style_name_list = [DEFAULT_STYLE] + style_names
251
- if len(set(style_names)) != len(style_names):
252
- return "スタイル名が重複しています。"
253
- style_vectors = [mean]
254
-
255
- wavs_dir = os.path.join(dataset_root, model_name, "wavs")
256
- for audio_file in audio_files:
257
- path = os.path.join(wavs_dir, audio_file)
258
- if not os.path.exists(path):
259
- return f"{path}が存在しません。"
260
- style_vectors.append(np.load(f"{path}.npy"))
261
- style_vectors = np.stack(style_vectors)
262
- assert len(style_name_list) == len(style_vectors)
263
- style_vector_path = os.path.join(result_dir, "style_vectors.npy")
264
- if os.path.exists(style_vector_path):
265
- logger.info(f"Backup {style_vector_path} to {style_vector_path}.bak")
266
- shutil.copy(style_vector_path, f"{style_vector_path}.bak")
267
- np.save(style_vector_path, style_vectors)
268
-
269
- # config.jsonの更新
270
- config_path = os.path.join(result_dir, "config.json")
271
- if not os.path.exists(config_path):
272
- return f"{config_path}が存在しません。"
273
- logger.info(f"Backup {config_path} to {config_path}.bak")
274
- shutil.copy(config_path, f"{config_path}.bak")
275
-
276
- with open(config_path, "r", encoding="utf-8") as f:
277
- json_dict = json.load(f)
278
- json_dict["data"]["num_styles"] = len(style_name_list)
279
- style_dict = {name: i for i, name in enumerate(style_name_list)}
280
- json_dict["data"]["style2id"] = style_dict
281
-
282
- with open(config_path, "w", encoding="utf-8") as f:
283
- json.dump(json_dict, f, indent=2, ensure_ascii=False)
284
- return f"成功!\n{style_vector_path}に保存し{config_path}を更新しました。"
285
-
286
-
287
- how_to_md = f"""
288
- Style-Bert-VITS2でこまかくスタイルを指定して音声合成するには、モデルごとにスタイルベクトルのファイル`style_vectors.npy`を手動で作成する必要があります。
289
-
290
- ただし、学習の過程で自動的に平均スタイル「{DEFAULT_STYLE}」のみは作成されるので、それをそのまま使うこともできます(その場合はこのWebUIは使いません)。
291
-
292
- このプロセスは学習とは全く関係がないので、何回でも独立して繰り返して試せます。また学習中にもたぶん軽いので動くはずです。
293
-
294
- ## 方法
295
-
296
- - 方法1: 音声ファイルを自動でスタイル別に分け、その各スタイルの平均を取って保存
297
- - 方法2: スタイルを代表する音声ファイルを手動で選んで、その音声のスタイルベクトルを保存
298
- - 方法3: 自分でもっと頑張ってこだわって作る(JVNVコーパスなど、もともとスタイルラベル等が利用可能な場合はこれがよいかも)
299
- """
300
-
301
- method1 = f"""
302
- 学習の時に取り出したスタイルベクトルを読み込んで、可視化を見ながらスタイルを分けていきます。
303
-
304
- 手順:
305
- 1. 図を眺める
306
- 2. スタイル数を決める(平均スタイルを除く)
307
- 3. スタイル分けを行って結果を確認
308
- 4. スタイルの名前を決めて保存
309
-
310
-
311
- 詳細: スタイルベクトル(256次元)たちを適当なアルゴリズムでクラスタリングして、各クラスタの中心のベクトル(と全体の平均ベクトル)を保存します。
312
-
313
- 平均スタイル({DEFAULT_STYLE})は自動的に保存されます。
314
- """
315
-
316
- dbscan_md = """
317
- DBSCANという方法でスタイル分けを行います。
318
- こちらの方が方法1よりも特徴がはっきり出るもののみを取り出せ、よいスタイルベクトルが作れるかもしれません。
319
- ただし事前にスタイル数は指定できません。
320
-
321
- パラメータ:
322
- - eps: この値より近い点同士をどんどん繋げて同じスタイル分類とする。小さいほどスタイル数が増え、大きいほどスタイル数が減る傾向。
323
- - min_samples: ある点をスタイルの核となる点とみなすために必要な近傍の点の数。小さいほどスタイル数が増え、大きいほどスタイル数が減る傾向。
324
-
325
- UMAPの場合はepsは0.3くらい、t-SNEの場合は2.5くらいがいいかもしれません。min_samplesはデータ数に依存するのでいろいろ試してみてください。
326
-
327
- 詳細:
328
- https://ja.wikipedia.org/wiki/DBSCAN
329
- """
330
-
331
-
332
- def create_style_vectors_app():
333
- with gr.Blocks(theme=GRADIO_THEME) as app:
334
- with gr.Accordion("使い方", open=False):
335
- gr.Markdown(how_to_md)
336
- with gr.Row():
337
- model_name = gr.Textbox(placeholder="your_model_name", label="モデル名")
338
- reduction_method = gr.Radio(
339
- choices=["UMAP", "t-SNE"],
340
- label="次元削減方法",
341
- info="v 1.3以前はt-SNEでしたがUMAPのほうがよい可能性もあります。",
342
- value="UMAP",
343
- )
344
- load_button = gr.Button("スタイルベクトルを読み込む", variant="primary")
345
- output = gr.Plot(label="音声スタイルの可視化")
346
- load_button.click(load, inputs=[model_name, reduction_method], outputs=[output])
347
- with gr.Tab("方法1: スタイル分けを自動で行う"):
348
- with gr.Tab("スタイル分け1"):
349
- n_clusters = gr.Slider(
350
- minimum=2,
351
- maximum=10,
352
- step=1,
353
- value=4,
354
- label="作るスタイルの数(平均スタイルを除く)",
355
- info="上の図を見ながらスタイルの数を試行錯誤してください。",
356
- )
357
- c_method = gr.Radio(
358
- choices=[
359
- "Agglomerative after reduction",
360
- "KMeans after reduction",
361
- "Agglomerative",
362
- "KMeans",
363
- ],
364
- label="アルゴリズム",
365
- info="分類する(クラスタリング)アルゴリズムを選択します。いろいろ試してみてください。",
366
- value="Agglomerative after reduction",
367
- )
368
- c_button = gr.Button("スタイル分けを実行")
369
- with gr.Tab("スタイル分け2: DBSCAN"):
370
- gr.Markdown(dbscan_md)
371
- eps = gr.Slider(
372
- minimum=0.1,
373
- maximum=10,
374
- step=0.01,
375
- value=0.3,
376
- label="eps",
377
- )
378
- min_samples = gr.Slider(
379
- minimum=1,
380
- maximum=50,
381
- step=1,
382
- value=15,
383
- label="min_samples",
384
- )
385
- with gr.Row():
386
- dbscan_button = gr.Button("スタイル分けを実行")
387
- num_styles_result = gr.Textbox(label="スタイル数")
388
- gr.Markdown("スタイル分けの結果")
389
- gr.Markdown(
390
- "注意: もともと256次元なものをを2次元に落としているので、正確なベクトルの位置関係ではありません。"
391
- )
392
- with gr.Row():
393
- gr_plot = gr.Plot()
394
- with gr.Column():
395
- with gr.Row():
396
- cluster_index = gr.Slider(
397
- minimum=1,
398
- maximum=MAX_CLUSTER_NUM,
399
- step=1,
400
- value=1,
401
- label="スタイル番号",
402
- info="選択したスタイルの代表音声を表示します。",
403
- )
404
- num_files = gr.Slider(
405
- minimum=1,
406
- maximum=MAX_AUDIO_NUM,
407
- step=1,
408
- value=5,
409
- label="代表音声の数をいくつ表示するか",
410
- )
411
- get_audios_button = gr.Button("代表音声を取得")
412
- with gr.Row():
413
- audio_list = []
414
- for i in range(MAX_AUDIO_NUM):
415
- audio_list.append(gr.Audio(visible=False, show_label=True))
416
- c_button.click(
417
- do_clustering_gradio,
418
- inputs=[n_clusters, c_method],
419
- outputs=[gr_plot, cluster_index] + audio_list,
420
- )
421
- dbscan_button.click(
422
- do_dbscan_gradio,
423
- inputs=[eps, min_samples],
424
- outputs=[gr_plot, cluster_index, num_styles_result] + audio_list,
425
- )
426
- get_audios_button.click(
427
- representative_wav_files_gradio,
428
- inputs=[cluster_index, num_files],
429
- outputs=audio_list,
430
- )
431
- gr.Markdown("結果が良さそうなら、これを保存します。")
432
- style_names = gr.Textbox(
433
- "Angry, Sad, Happy",
434
- label="スタイルの名前",
435
- info=f"スタイルの名前を`,`で区切って入力してください(日本語可)。例: `Angry, Sad, Happy`や`怒り, 悲しみ, 喜び`など。平均音声は{DEFAULT_STYLE}として自動的に保存されます。",
436
- )
437
- with gr.Row():
438
- save_button1 = gr.Button("スタイルベクトルを保存", variant="primary")
439
- info2 = gr.Textbox(label="保存結果")
440
-
441
- save_button1.click(
442
- save_style_vectors_from_clustering,
443
- inputs=[model_name, style_names],
444
- outputs=[info2],
445
- )
446
- with gr.Tab("方法2: 手動でスタイルを選ぶ"):
447
- gr.Markdown(
448
- "下のテキスト欄に、各スタイルの代表音声のファイル名を`,`区切りで、その横に対応するスタイル名を`,`区切りで入力してください。"
449
- )
450
- gr.Markdown("例: `angry.wav, sad.wav, happy.wav`と`Angry, Sad, Happy`")
451
- gr.Markdown(
452
- f"注意: {DEFAULT_STYLE}スタイルは自動的に保存されます、手動では{DEFAULT_STYLE}という名前のスタイルは指定しないでください。"
453
- )
454
- with gr.Row():
455
- audio_files_text = gr.Textbox(
456
- label="音声ファイル名", placeholder="angry.wav, sad.wav, happy.wav"
457
- )
458
- style_names_text = gr.Textbox(
459
- label="スタイル名", placeholder="Angry, Sad, Happy"
460
- )
461
- with gr.Row():
462
- save_button2 = gr.Button("スタイルベクトルを保存", variant="primary")
463
- info2 = gr.Textbox(label="保存結果")
464
- save_button2.click(
465
- save_style_vectors_from_files,
466
- inputs=[model_name, audio_files_text, style_names_text],
467
- outputs=[info2],
468
- )
469
-
470
- return app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
gradio_tabs/train.py DELETED
@@ -1,785 +0,0 @@
1
- import json
2
- import os
3
- import shutil
4
- import socket
5
- import subprocess
6
- import sys
7
- import time
8
- import webbrowser
9
- from datetime import datetime
10
- from multiprocessing import cpu_count
11
- from pathlib import Path
12
-
13
- import gradio as gr
14
- import yaml
15
-
16
- from style_bert_vits2.logging import logger
17
- from style_bert_vits2.utils.stdout_wrapper import SAFE_STDOUT
18
- from style_bert_vits2.utils.subprocess import run_script_with_log, second_elem_of
19
-
20
-
21
- logger_handler = None
22
- tensorboard_executed = False
23
-
24
- # Get path settings
25
- with open(os.path.join("configs", "paths.yml"), "r", encoding="utf-8") as f:
26
- path_config: dict[str, str] = yaml.safe_load(f.read())
27
- dataset_root = Path(path_config["dataset_root"])
28
-
29
-
30
- def get_path(model_name: str) -> tuple[Path, Path, Path, Path, Path]:
31
- assert model_name != "", "モデル名は空にできません"
32
- dataset_path = dataset_root / model_name
33
- lbl_path = dataset_path / "esd.list"
34
- train_path = dataset_path / "train.list"
35
- val_path = dataset_path / "val.list"
36
- config_path = dataset_path / "config.json"
37
- return dataset_path, lbl_path, train_path, val_path, config_path
38
-
39
-
40
- def initialize(
41
- model_name: str,
42
- batch_size: int,
43
- epochs: int,
44
- save_every_steps: int,
45
- freeze_EN_bert: bool,
46
- freeze_JP_bert: bool,
47
- freeze_ZH_bert: bool,
48
- freeze_style: bool,
49
- freeze_decoder: bool,
50
- use_jp_extra: bool,
51
- log_interval: int,
52
- ):
53
- global logger_handler
54
- dataset_path, _, train_path, val_path, config_path = get_path(model_name)
55
-
56
- # 前処理のログをファイルに保存する
57
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
58
- file_name = f"preprocess_{timestamp}.log"
59
- if logger_handler is not None:
60
- logger.remove(logger_handler)
61
- logger_handler = logger.add(os.path.join(dataset_path, file_name))
62
-
63
- logger.info(
64
- f"Step 1: start initialization...\nmodel_name: {model_name}, batch_size: {batch_size}, epochs: {epochs}, save_every_steps: {save_every_steps}, freeze_ZH_bert: {freeze_ZH_bert}, freeze_JP_bert: {freeze_JP_bert}, freeze_EN_bert: {freeze_EN_bert}, freeze_style: {freeze_style}, freeze_decoder: {freeze_decoder}, use_jp_extra: {use_jp_extra}"
65
- )
66
-
67
- default_config_path = (
68
- "configs/config.json" if not use_jp_extra else "configs/config_jp_extra.json"
69
- )
70
-
71
- with open(default_config_path, "r", encoding="utf-8") as f:
72
- config = json.load(f)
73
- config["model_name"] = model_name
74
- config["data"]["training_files"] = str(train_path)
75
- config["data"]["validation_files"] = str(val_path)
76
- config["train"]["batch_size"] = batch_size
77
- config["train"]["epochs"] = epochs
78
- config["train"]["eval_interval"] = save_every_steps
79
- config["train"]["log_interval"] = log_interval
80
-
81
- config["train"]["freeze_EN_bert"] = freeze_EN_bert
82
- config["train"]["freeze_JP_bert"] = freeze_JP_bert
83
- config["train"]["freeze_ZH_bert"] = freeze_ZH_bert
84
- config["train"]["freeze_style"] = freeze_style
85
- config["train"]["freeze_decoder"] = freeze_decoder
86
-
87
- config["train"]["bf16_run"] = False # デフォルトでFalseのはずだが念のため
88
-
89
- # 今はデフォルトであるが、以前は非JP-Extra版になくバグの原因になるので念のため
90
- config["data"]["use_jp_extra"] = use_jp_extra
91
-
92
- model_path = dataset_path / "models"
93
- if model_path.exists():
94
- logger.warning(
95
- f"Step 1: {model_path} already exists, so copy it to backup to {model_path}_backup"
96
- )
97
- shutil.copytree(
98
- src=model_path,
99
- dst=dataset_path / "models_backup",
100
- dirs_exist_ok=True,
101
- )
102
- shutil.rmtree(model_path)
103
- pretrained_dir = Path("pretrained" if not use_jp_extra else "pretrained_jp_extra")
104
- try:
105
- shutil.copytree(
106
- src=pretrained_dir,
107
- dst=model_path,
108
- )
109
- except FileNotFoundError:
110
- logger.error(f"Step 1: {pretrained_dir} folder not found.")
111
- return False, f"Step 1, Error: {pretrained_dir}フォルダが見つかりません。"
112
-
113
- with open(config_path, "w", encoding="utf-8") as f:
114
- json.dump(config, f, indent=2, ensure_ascii=False)
115
- if not Path("config.yml").exists():
116
- shutil.copy(src="default_config.yml", dst="config.yml")
117
- with open("config.yml", "r", encoding="utf-8") as f:
118
- yml_data = yaml.safe_load(f)
119
- yml_data["model_name"] = model_name
120
- yml_data["dataset_path"] = str(dataset_path)
121
- with open("config.yml", "w", encoding="utf-8") as f:
122
- yaml.dump(yml_data, f, allow_unicode=True)
123
- logger.success("Step 1: initialization finished.")
124
- return True, "Step 1, Success: 初期設定が完了しました"
125
-
126
-
127
- def resample(model_name: str, normalize: bool, trim: bool, num_processes: int):
128
- logger.info("Step 2: start resampling...")
129
- dataset_path, _, _, _, _ = get_path(model_name)
130
- input_dir = dataset_path / "raw"
131
- output_dir = dataset_path / "wavs"
132
- cmd = [
133
- "resample.py",
134
- "-i",
135
- str(input_dir),
136
- "-o",
137
- str(output_dir),
138
- "--num_processes",
139
- str(num_processes),
140
- "--sr",
141
- "44100",
142
- ]
143
- if normalize:
144
- cmd.append("--normalize")
145
- if trim:
146
- cmd.append("--trim")
147
- success, message = run_script_with_log(cmd)
148
- if not success:
149
- logger.error("Step 2: resampling failed.")
150
- return False, f"Step 2, Error: 音声ファイルの前処理に失敗しました:\n{message}"
151
- elif message:
152
- logger.warning("Step 2: resampling finished with stderr.")
153
- return True, f"Step 2, Success: 音声ファイルの前処理が完了しました:\n{message}"
154
- logger.success("Step 2: resampling finished.")
155
- return True, "Step 2, Success: 音声ファイルの前処理が完了しました"
156
-
157
-
158
- def preprocess_text(
159
- model_name: str, use_jp_extra: bool, val_per_lang: int, yomi_error: str
160
- ):
161
- logger.info("Step 3: start preprocessing text...")
162
- _, lbl_path, train_path, val_path, config_path = get_path(model_name)
163
- if not lbl_path.exists():
164
- logger.error(f"Step 3: {lbl_path} not found.")
165
- return False, f"Step 3, Error: 書き起こしファイル {lbl_path} が見つかりません。"
166
-
167
- cmd = [
168
- "preprocess_text.py",
169
- "--config-path",
170
- str(config_path),
171
- "--transcription-path",
172
- str(lbl_path),
173
- "--train-path",
174
- str(train_path),
175
- "--val-path",
176
- str(val_path),
177
- "--val-per-lang",
178
- str(val_per_lang),
179
- "--yomi_error",
180
- yomi_error,
181
- "--correct_path", # 音声ファイルのパスを正しいパスに修正する
182
- ]
183
- if use_jp_extra:
184
- cmd.append("--use_jp_extra")
185
- success, message = run_script_with_log(cmd)
186
- if not success:
187
- logger.error("Step 3: preprocessing text failed.")
188
- return (
189
- False,
190
- f"Step 3, Error: 書き起こしファイルの前処理に失敗しました:\n{message}",
191
- )
192
- elif message:
193
- logger.warning("Step 3: preprocessing text finished with stderr.")
194
- return (
195
- True,
196
- f"Step 3, Success: 書き起こしファイルの前処理が完了しました:\n{message}",
197
- )
198
- logger.success("Step 3: preprocessing text finished.")
199
- return True, "Step 3, Success: 書き起こしファイルの前処理が完了しました"
200
-
201
-
202
- def bert_gen(model_name: str):
203
- logger.info("Step 4: start bert_gen...")
204
- _, _, _, _, config_path = get_path(model_name)
205
- success, message = run_script_with_log(
206
- ["bert_gen.py", "--config", str(config_path)]
207
- )
208
- if not success:
209
- logger.error("Step 4: bert_gen failed.")
210
- return False, f"Step 4, Error: BERT特徴ファイルの生成に失敗しました:\n{message}"
211
- elif message:
212
- logger.warning("Step 4: bert_gen finished with stderr.")
213
- return (
214
- True,
215
- f"Step 4, Success: BERT特徴ファイルの生成が完了しました:\n{message}",
216
- )
217
- logger.success("Step 4: bert_gen finished.")
218
- return True, "Step 4, Success: BERT特徴ファイルの生成が完了しました"
219
-
220
-
221
- def style_gen(model_name: str, num_processes: int):
222
- logger.info("Step 5: start style_gen...")
223
- _, _, _, _, config_path = get_path(model_name)
224
- success, message = run_script_with_log(
225
- [
226
- "style_gen.py",
227
- "--config",
228
- str(config_path),
229
- "--num_processes",
230
- str(num_processes),
231
- ]
232
- )
233
- if not success:
234
- logger.error("Step 5: style_gen failed.")
235
- return (
236
- False,
237
- f"Step 5, Error: スタイル特徴ファイルの生成に失敗しました:\n{message}",
238
- )
239
- elif message:
240
- logger.warning("Step 5: style_gen finished with stderr.")
241
- return (
242
- True,
243
- f"Step 5, Success: スタイル特徴ファイルの生成が完了しました:\n{message}",
244
- )
245
- logger.success("Step 5: style_gen finished.")
246
- return True, "Step 5, Success: スタイル特徴ファイルの生成が完了しました"
247
-
248
-
249
- def preprocess_all(
250
- model_name: str,
251
- batch_size: int,
252
- epochs: int,
253
- save_every_steps: int,
254
- num_processes: int,
255
- normalize: bool,
256
- trim: bool,
257
- freeze_EN_bert: bool,
258
- freeze_JP_bert: bool,
259
- freeze_ZH_bert: bool,
260
- freeze_style: bool,
261
- freeze_decoder: bool,
262
- use_jp_extra: bool,
263
- val_per_lang: int,
264
- log_interval: int,
265
- yomi_error: str,
266
- ):
267
- if model_name == "":
268
- return False, "Error: モデル名を入力してください"
269
- success, message = initialize(
270
- model_name=model_name,
271
- batch_size=batch_size,
272
- epochs=epochs,
273
- save_every_steps=save_every_steps,
274
- freeze_EN_bert=freeze_EN_bert,
275
- freeze_JP_bert=freeze_JP_bert,
276
- freeze_ZH_bert=freeze_ZH_bert,
277
- freeze_style=freeze_style,
278
- freeze_decoder=freeze_decoder,
279
- use_jp_extra=use_jp_extra,
280
- log_interval=log_interval,
281
- )
282
- if not success:
283
- return False, message
284
- success, message = resample(
285
- model_name=model_name,
286
- normalize=normalize,
287
- trim=trim,
288
- num_processes=num_processes,
289
- )
290
- if not success:
291
- return False, message
292
-
293
- success, message = preprocess_text(
294
- model_name=model_name,
295
- use_jp_extra=use_jp_extra,
296
- val_per_lang=val_per_lang,
297
- yomi_error=yomi_error,
298
- )
299
- if not success:
300
- return False, message
301
- success, message = bert_gen(
302
- model_name=model_name
303
- ) # bert_genは重いのでプロセス数いじらない
304
- if not success:
305
- return False, message
306
- success, message = style_gen(model_name=model_name, num_processes=num_processes)
307
- if not success:
308
- return False, message
309
- logger.success("Success: All preprocess finished!")
310
- return (
311
- True,
312
- "Success: 全ての前処理が完了しました。ターミナルを確認しておかしいところがないか確認するのをおすすめします。",
313
- )
314
-
315
-
316
- def train(
317
- model_name: str,
318
- skip_style: bool = False,
319
- use_jp_extra: bool = True,
320
- speedup: bool = False,
321
- ):
322
- dataset_path, _, _, _, config_path = get_path(model_name)
323
- # 学習再開の場合を考えて念のためconfig.ymlの名前等を更新
324
- with open("config.yml", "r", encoding="utf-8") as f:
325
- yml_data = yaml.safe_load(f)
326
- yml_data["model_name"] = model_name
327
- yml_data["dataset_path"] = str(dataset_path)
328
- with open("config.yml", "w", encoding="utf-8") as f:
329
- yaml.dump(yml_data, f, allow_unicode=True)
330
-
331
- train_py = "train_ms.py" if not use_jp_extra else "train_ms_jp_extra.py"
332
- cmd = [train_py, "--config", str(config_path), "--model", str(dataset_path)]
333
- if skip_style:
334
- cmd.append("--skip_default_style")
335
- if speedup:
336
- cmd.append("--speedup")
337
- success, message = run_script_with_log(cmd, ignore_warning=True)
338
- if not success:
339
- logger.error("Train failed.")
340
- return False, f"Error: 学習に失敗しました:\n{message}"
341
- elif message:
342
- logger.warning("Train finished with stderr.")
343
- return True, f"Success: 学習が完了しました:\n{message}"
344
- logger.success("Train finished.")
345
- return True, "Success: 学習が完了しました"
346
-
347
-
348
- def wait_for_tensorboard(port: int = 6006, timeout: float = 10):
349
- start_time = time.time()
350
- while True:
351
- try:
352
- with socket.create_connection(("localhost", port), timeout=1):
353
- return True # ポートが開いている場合
354
- except OSError:
355
- pass # ポートがまだ開いていない場合
356
-
357
- if time.time() - start_time > timeout:
358
- return False # タイムアウト
359
-
360
- time.sleep(0.1)
361
-
362
-
363
- def run_tensorboard(model_name: str):
364
- global tensorboard_executed
365
- if not tensorboard_executed:
366
- python = sys.executable
367
- tensorboard_cmd = [
368
- python,
369
- "-m",
370
- "tensorboard.main",
371
- "--logdir",
372
- f"Data/{model_name}/models",
373
- ]
374
- subprocess.Popen(
375
- tensorboard_cmd,
376
- stdout=SAFE_STDOUT, # type: ignore
377
- stderr=SAFE_STDOUT, # type: ignore
378
- )
379
- yield gr.Button("起動中…")
380
- if wait_for_tensorboard():
381
- tensorboard_executed = True
382
- else:
383
- logger.error("Tensorboard did not start in the expected time.")
384
- webbrowser.open("http://localhost:6006")
385
- yield gr.Button("Tensorboardを開く")
386
-
387
-
388
- how_to_md = """
389
- ## 使い方
390
-
391
- - データを準備して、モデル名を入力して、必要なら設定を調整してから、「自動前処理を実行」ボタンを押してください。進捗状況等はターミナルに表示されます。
392
-
393
- - 各ステップごとに実行する場合は「手動前処理」を使ってください(基本的には自動でいいはず)。
394
-
395
- - 前処理が終わったら、「学習を開始する」ボタンを押すと学習が開始されます。
396
-
397
- - 途中から学習を再開する場合は、モデル名を入力してから「学習を開始する」を押せばよいです。
398
-
399
- 注意: 標準スタイル以外のスタイルを音声合成で使うには、スタイルベクトルファイル`style_vectors.npy`を作る必要があります。これは、`Style.bat`を実行してそこで作成してください。
400
- 動作は軽いはずなので、学習中でも実行でき、何度でも繰り返して試せます。
401
-
402
- ## JP-Extra版について
403
-
404
- 元とするモデル構造として [Bert-VITS2 Japanese-Extra](https://github.com/fishaudio/Bert-VITS2/releases/tag/JP-Exta) を使うことができます。
405
- 日本語のアクセントやイントネーションや自然性が上がる傾向にありますが、英語と中国語は話せなくなります。
406
- """
407
-
408
- prepare_md = """
409
- まず音声データ(wavファイルで1ファイルが2-12秒程度の、長すぎず短すぎない発話のものをいくつか)と、書き起こしテキストを用意してください。
410
-
411
- それを次のように配置します。
412
- ```
413
- ├── Data
414
- │ ├── {モデルの名前}
415
- │ │ ├── esd.list
416
- │ │ ├── raw
417
- │ │ │ ├── ****.wav
418
- │ │ │ ├── ****.wav
419
- │ │ │ ├── ...
420
- ```
421
-
422
- wavファイル名やモデルの名前は空白を含まない半角で、wavファイルの拡張子は小文字`.wav`である必要があります。
423
- `raw` フォルダにはすべてのwavファイルを入れ、`esd.list` ファイルには、以下のフォーマットで各wavファイルの情報を記述してください。
424
- ```
425
- ****.wav|{話者名}|{言語ID、ZHかJPかEN}|{書き起こしテキスト}
426
- ```
427
-
428
- 例:
429
- ```
430
- wav_number1.wav|hanako|JP|こんにちは、聞こえて、いますか?
431
- wav_next.wav|taro|JP|はい、聞こえています……。
432
- english_teacher.wav|Mary|EN|How are you? I'm fine, thank you, and you?
433
- ...
434
- ```
435
- 日本語話者の単一話者データセットでも構いません。
436
-
437
- - 音声ファイルはrawフォルダの直下でなくてもサブフォルダに入れても構いません。その場合は、`esd.list`の最初には`raw`からの相対パスを記述してください。
438
- """
439
-
440
-
441
- def create_train_app():
442
- with gr.Blocks().queue() as app:
443
- with gr.Accordion("使い方", open=False):
444
- gr.Markdown(how_to_md)
445
- with gr.Accordion(label="データの前準備", open=False):
446
- gr.Markdown(prepare_md)
447
- model_name = gr.Textbox(label="モデル名")
448
- gr.Markdown("### 自動前処理")
449
- with gr.Row(variant="panel"):
450
- with gr.Column():
451
- use_jp_extra = gr.Checkbox(
452
- label="JP-Extra版を使う(日本語の性能が上がるが英語と中国語は話せなくなる)",
453
- value=True,
454
- )
455
- batch_size = gr.Slider(
456
- label="バッチサイズ",
457
- info="学習速度が遅い場合は小さくして試し、VRAMに余裕があれば大きくしてください。JP-Extra版でのVRAM使用量目安: 1: 6GB, 2: 8GB, 3: 10GB, 4: 12GB",
458
- value=2,
459
- minimum=1,
460
- maximum=64,
461
- step=1,
462
- )
463
- epochs = gr.Slider(
464
- label="エポック数",
465
- info="100もあれば十分そうだけどもっと回すと質が上がるかもしれない",
466
- value=100,
467
- minimum=10,
468
- maximum=1000,
469
- step=10,
470
- )
471
- save_every_steps = gr.Slider(
472
- label="何ステップごとに結果を保存するか",
473
- info="エポック数とは違うことに注意",
474
- value=1000,
475
- minimum=100,
476
- maximum=10000,
477
- step=100,
478
- )
479
- normalize = gr.Checkbox(
480
- label="音声の音量を正規化する(音量の大小が揃っていない場合など)",
481
- value=False,
482
- )
483
- trim = gr.Checkbox(
484
- label="音声の最初と最後の無音を取り除く",
485
- value=False,
486
- )
487
- yomi_error = gr.Radio(
488
- label="書き起こしが読めないファイルの扱い",
489
- choices=[
490
- ("エラー出たらテキスト前処理が終わった時点で中断", "raise"),
491
- ("読めないファイルは使わず続行", "skip"),
492
- ("読めないファイルも無理やり読んで学習に使う", "use"),
493
- ],
494
- value="raise",
495
- )
496
- with gr.Accordion("詳細設定", open=False):
497
- num_processes = gr.Slider(
498
- label="プロセス数",
499
- info="前処理時の並列処理プロセス数、前処理でフリーズしたら下げてください",
500
- value=cpu_count() // 2,
501
- minimum=1,
502
- maximum=cpu_count(),
503
- step=1,
504
- )
505
- val_per_lang = gr.Slider(
506
- label="検証データ数",
507
- info="学習には使われず、tensorboardで元音声と合成音声を比較するためのもの",
508
- value=0,
509
- minimum=0,
510
- maximum=100,
511
- step=1,
512
- )
513
- log_interval = gr.Slider(
514
- label="Tensorboardのログ出力間隔",
515
- info="Tensorboardで詳しく見たい人は小さめにしてください",
516
- value=200,
517
- minimum=10,
518
- maximum=1000,
519
- step=10,
520
- )
521
- gr.Markdown("学習時に特定の部分を凍結させるかどうか")
522
- freeze_EN_bert = gr.Checkbox(
523
- label="英語bert部分を凍結",
524
- value=False,
525
- )
526
- freeze_JP_bert = gr.Checkbox(
527
- label="日本語bert部分を凍結",
528
- value=False,
529
- )
530
- freeze_ZH_bert = gr.Checkbox(
531
- label="中国語bert部分を凍結",
532
- value=False,
533
- )
534
- freeze_style = gr.Checkbox(
535
- label="スタイル部分を凍結",
536
- value=False,
537
- )
538
- freeze_decoder = gr.Checkbox(
539
- label="デコーダ部分を凍結",
540
- value=False,
541
- )
542
-
543
- with gr.Column():
544
- preprocess_button = gr.Button(
545
- value="自動前処理を実行", variant="primary"
546
- )
547
- info_all = gr.Textbox(label="状況")
548
- with gr.Accordion(open=False, label="手動前処理"):
549
- with gr.Row(variant="panel"):
550
- with gr.Column():
551
- gr.Markdown(value="#### Step 1: 設定ファイルの生成")
552
- use_jp_extra_manual = gr.Checkbox(
553
- label="JP-Extra版を使う",
554
- value=True,
555
- )
556
- batch_size_manual = gr.Slider(
557
- label="バッチサイズ",
558
- value=2,
559
- minimum=1,
560
- maximum=64,
561
- step=1,
562
- )
563
- epochs_manual = gr.Slider(
564
- label="エポック数",
565
- value=100,
566
- minimum=1,
567
- maximum=1000,
568
- step=1,
569
- )
570
- save_every_steps_manual = gr.Slider(
571
- label="何ステップごとに結果を保存するか",
572
- value=1000,
573
- minimum=100,
574
- maximum=10000,
575
- step=100,
576
- )
577
- log_interval_manual = gr.Slider(
578
- label="Tensorboardのログ出力間隔",
579
- value=200,
580
- minimum=10,
581
- maximum=1000,
582
- step=10,
583
- )
584
- freeze_EN_bert_manual = gr.Checkbox(
585
- label="英語bert部分を凍結",
586
- value=False,
587
- )
588
- freeze_JP_bert_manual = gr.Checkbox(
589
- label="日本語bert部分を凍結",
590
- value=False,
591
- )
592
- freeze_ZH_bert_manual = gr.Checkbox(
593
- label="中国語bert部分を凍結",
594
- value=False,
595
- )
596
- freeze_style_manual = gr.Checkbox(
597
- label="スタイル部分を凍結",
598
- value=False,
599
- )
600
- freeze_decoder_manual = gr.Checkbox(
601
- label="デコーダ部分を凍結",
602
- value=False,
603
- )
604
- with gr.Column():
605
- generate_config_btn = gr.Button(value="実行", variant="primary")
606
- info_init = gr.Textbox(label="状況")
607
- with gr.Row(variant="panel"):
608
- with gr.Column():
609
- gr.Markdown(value="#### Step 2: 音声ファイルの前処理")
610
- num_processes_resample = gr.Slider(
611
- label="プロセス数",
612
- value=cpu_count() // 2,
613
- minimum=1,
614
- maximum=cpu_count(),
615
- step=1,
616
- )
617
- normalize_resample = gr.Checkbox(
618
- label="音声の音量を正規化する",
619
- value=False,
620
- )
621
- trim_resample = gr.Checkbox(
622
- label="音声の最初と最後の無音を取り除く",
623
- value=False,
624
- )
625
- with gr.Column():
626
- resample_btn = gr.Button(value="実行", variant="primary")
627
- info_resample = gr.Textbox(label="状況")
628
- with gr.Row(variant="panel"):
629
- with gr.Column():
630
- gr.Markdown(value="#### Step 3: 書き起こしファイルの前処理")
631
- val_per_lang_manual = gr.Slider(
632
- label="検証データ数",
633
- value=0,
634
- minimum=0,
635
- maximum=100,
636
- step=1,
637
- )
638
- yomi_error_manual = gr.Radio(
639
- label="書き起こしが読めないファイルの扱い",
640
- choices=[
641
- ("エラー出たらテキスト前処理が終わった時点で中断", "raise"),
642
- ("読めないファイルは使わず続行", "skip"),
643
- ("読めないファイルも無理やり読んで学習に使う", "use"),
644
- ],
645
- value="raise",
646
- )
647
- with gr.Column():
648
- preprocess_text_btn = gr.Button(value="実行", variant="primary")
649
- info_preprocess_text = gr.Textbox(label="状況")
650
- with gr.Row(variant="panel"):
651
- with gr.Column():
652
- gr.Markdown(value="#### Step 4: BERT特徴ファイルの生成")
653
- with gr.Column():
654
- bert_gen_btn = gr.Button(value="実行", variant="primary")
655
- info_bert = gr.Textbox(label="状況")
656
- with gr.Row(variant="panel"):
657
- with gr.Column():
658
- gr.Markdown(value="#### Step 5: スタイル特徴ファイルの生成")
659
- num_processes_style = gr.Slider(
660
- label="プロセス数",
661
- value=cpu_count() // 2,
662
- minimum=1,
663
- maximum=cpu_count(),
664
- step=1,
665
- )
666
- with gr.Column():
667
- style_gen_btn = gr.Button(value="実行", variant="primary")
668
- info_style = gr.Textbox(label="状況")
669
- gr.Markdown("## 学習")
670
- with gr.Row():
671
- skip_style = gr.Checkbox(
672
- label="スタイルファイルの生成をスキップする",
673
- info="学習再開の場合の場合はチェックしてください",
674
- value=False,
675
- )
676
- use_jp_extra_train = gr.Checkbox(
677
- label="JP-Extra版を使う",
678
- value=True,
679
- )
680
- speedup = gr.Checkbox(
681
- label="ログ等をスキップして学習を高速化する",
682
- value=False,
683
- visible=False, # Experimental
684
- )
685
- train_btn = gr.Button(value="学習を開始する", variant="primary")
686
- tensorboard_btn = gr.Button(value="Tensorboardを開く")
687
- gr.Markdown(
688
- "進捗はターミナルで確認してください。結果は指定したステップごとに随時保存されており、また学習を途中から再開することもできます。学習を終了するには単にターミナルを終了してください。"
689
- )
690
- info_train = gr.Textbox(label="状況")
691
-
692
- preprocess_button.click(
693
- second_elem_of(preprocess_all),
694
- inputs=[
695
- model_name,
696
- batch_size,
697
- epochs,
698
- save_every_steps,
699
- num_processes,
700
- normalize,
701
- trim,
702
- freeze_EN_bert,
703
- freeze_JP_bert,
704
- freeze_ZH_bert,
705
- freeze_style,
706
- freeze_decoder,
707
- use_jp_extra,
708
- val_per_lang,
709
- log_interval,
710
- yomi_error,
711
- ],
712
- outputs=[info_all],
713
- )
714
-
715
- # Manual preprocess
716
- generate_config_btn.click(
717
- second_elem_of(initialize),
718
- inputs=[
719
- model_name,
720
- batch_size_manual,
721
- epochs_manual,
722
- save_every_steps_manual,
723
- freeze_EN_bert_manual,
724
- freeze_JP_bert_manual,
725
- freeze_ZH_bert_manual,
726
- freeze_style_manual,
727
- freeze_decoder_manual,
728
- use_jp_extra_manual,
729
- log_interval_manual,
730
- ],
731
- outputs=[info_init],
732
- )
733
- resample_btn.click(
734
- second_elem_of(resample),
735
- inputs=[
736
- model_name,
737
- normalize_resample,
738
- trim_resample,
739
- num_processes_resample,
740
- ],
741
- outputs=[info_resample],
742
- )
743
- preprocess_text_btn.click(
744
- second_elem_of(preprocess_text),
745
- inputs=[
746
- model_name,
747
- use_jp_extra_manual,
748
- val_per_lang_manual,
749
- yomi_error_manual,
750
- ],
751
- outputs=[info_preprocess_text],
752
- )
753
- bert_gen_btn.click(
754
- second_elem_of(bert_gen),
755
- inputs=[model_name],
756
- outputs=[info_bert],
757
- )
758
- style_gen_btn.click(
759
- second_elem_of(style_gen),
760
- inputs=[model_name, num_processes_style],
761
- outputs=[info_style],
762
- )
763
-
764
- # Train
765
- train_btn.click(
766
- second_elem_of(train),
767
- inputs=[model_name, skip_style, use_jp_extra_train, speedup],
768
- outputs=[info_train],
769
- )
770
- tensorboard_btn.click(
771
- run_tensorboard, inputs=[model_name], outputs=[tensorboard_btn]
772
- )
773
-
774
- use_jp_extra.change(
775
- lambda x: gr.Checkbox(value=x),
776
- inputs=[use_jp_extra],
777
- outputs=[use_jp_extra_train],
778
- )
779
- use_jp_extra_manual.change(
780
- lambda x: gr.Checkbox(value=x),
781
- inputs=[use_jp_extra_manual],
782
- outputs=[use_jp_extra_train],
783
- )
784
-
785
- return app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
infer.py DELETED
@@ -1,314 +0,0 @@
1
- import torch
2
-
3
- import commons
4
- import utils
5
- from models import SynthesizerTrn
6
- from models_jp_extra import SynthesizerTrn as SynthesizerTrnJPExtra
7
- from text import cleaned_text_to_sequence, get_bert
8
- from text.cleaner import clean_text
9
- from text.symbols import symbols
10
- from common.log import logger
11
-
12
-
13
- class InvalidToneError(ValueError):
14
- pass
15
-
16
-
17
- def get_net_g(model_path: str, version: str, device: str, hps):
18
- if version.endswith("JP-Extra"):
19
- logger.info("Using JP-Extra model")
20
- net_g = SynthesizerTrnJPExtra(
21
- len(symbols),
22
- hps.data.filter_length // 2 + 1,
23
- hps.train.segment_size // hps.data.hop_length,
24
- n_speakers=hps.data.n_speakers,
25
- **hps.model,
26
- ).to(device)
27
- else:
28
- logger.info("Using normal model")
29
- net_g = SynthesizerTrn(
30
- len(symbols),
31
- hps.data.filter_length // 2 + 1,
32
- hps.train.segment_size // hps.data.hop_length,
33
- n_speakers=hps.data.n_speakers,
34
- **hps.model,
35
- ).to(device)
36
- net_g.state_dict()
37
- _ = net_g.eval()
38
- if model_path.endswith(".pth") or model_path.endswith(".pt"):
39
- _ = utils.load_checkpoint(model_path, net_g, None, skip_optimizer=True)
40
- elif model_path.endswith(".safetensors"):
41
- _ = utils.load_safetensors(model_path, net_g, True)
42
- else:
43
- raise ValueError(f"Unknown model format: {model_path}")
44
- return net_g
45
-
46
-
47
- def get_text(
48
- text,
49
- language_str,
50
- hps,
51
- device,
52
- assist_text=None,
53
- assist_text_weight=0.7,
54
- given_tone=None,
55
- ):
56
- use_jp_extra = hps.version.endswith("JP-Extra")
57
- # 推論のときにのみ呼び出されるので、raise_yomi_errorはFalseに設定
58
- norm_text, phone, tone, word2ph = clean_text(
59
- text, language_str, use_jp_extra, raise_yomi_error=False
60
- )
61
- if given_tone is not None:
62
- if len(given_tone) != len(phone):
63
- raise InvalidToneError(
64
- f"Length of given_tone ({len(given_tone)}) != length of phone ({len(phone)})"
65
- )
66
- tone = given_tone
67
- phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
68
-
69
- if hps.data.add_blank:
70
- phone = commons.intersperse(phone, 0)
71
- tone = commons.intersperse(tone, 0)
72
- language = commons.intersperse(language, 0)
73
- for i in range(len(word2ph)):
74
- word2ph[i] = word2ph[i] * 2
75
- word2ph[0] += 1
76
- bert_ori = get_bert(
77
- norm_text,
78
- word2ph,
79
- language_str,
80
- device,
81
- assist_text,
82
- assist_text_weight,
83
- )
84
- del word2ph
85
- assert bert_ori.shape[-1] == len(phone), phone
86
-
87
- if language_str == "ZH":
88
- bert = bert_ori
89
- ja_bert = torch.zeros(1024, len(phone))
90
- en_bert = torch.zeros(1024, len(phone))
91
- elif language_str == "JP":
92
- bert = torch.zeros(1024, len(phone))
93
- ja_bert = bert_ori
94
- en_bert = torch.zeros(1024, len(phone))
95
- elif language_str == "EN":
96
- bert = torch.zeros(1024, len(phone))
97
- ja_bert = torch.zeros(1024, len(phone))
98
- en_bert = bert_ori
99
- else:
100
- raise ValueError("language_str should be ZH, JP or EN")
101
-
102
- assert bert.shape[-1] == len(
103
- phone
104
- ), f"Bert seq len {bert.shape[-1]} != {len(phone)}"
105
-
106
- phone = torch.LongTensor(phone)
107
- tone = torch.LongTensor(tone)
108
- language = torch.LongTensor(language)
109
- return bert, ja_bert, en_bert, phone, tone, language
110
-
111
-
112
- def infer(
113
- text,
114
- style_vec,
115
- sdp_ratio,
116
- noise_scale,
117
- noise_scale_w,
118
- length_scale,
119
- sid: int, # In the original Bert-VITS2, its speaker_name: str, but here it's id
120
- language,
121
- hps,
122
- net_g,
123
- device,
124
- skip_start=False,
125
- skip_end=False,
126
- assist_text=None,
127
- assist_text_weight=0.7,
128
- given_tone=None,
129
- ):
130
- is_jp_extra = hps.version.endswith("JP-Extra")
131
- bert, ja_bert, en_bert, phones, tones, lang_ids = get_text(
132
- text,
133
- language,
134
- hps,
135
- device,
136
- assist_text=assist_text,
137
- assist_text_weight=assist_text_weight,
138
- given_tone=given_tone,
139
- )
140
- if skip_start:
141
- phones = phones[3:]
142
- tones = tones[3:]
143
- lang_ids = lang_ids[3:]
144
- bert = bert[:, 3:]
145
- ja_bert = ja_bert[:, 3:]
146
- en_bert = en_bert[:, 3:]
147
- if skip_end:
148
- phones = phones[:-2]
149
- tones = tones[:-2]
150
- lang_ids = lang_ids[:-2]
151
- bert = bert[:, :-2]
152
- ja_bert = ja_bert[:, :-2]
153
- en_bert = en_bert[:, :-2]
154
- with torch.no_grad():
155
- x_tst = phones.to(device).unsqueeze(0)
156
- tones = tones.to(device).unsqueeze(0)
157
- lang_ids = lang_ids.to(device).unsqueeze(0)
158
- bert = bert.to(device).unsqueeze(0)
159
- ja_bert = ja_bert.to(device).unsqueeze(0)
160
- en_bert = en_bert.to(device).unsqueeze(0)
161
- x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device)
162
- style_vec = torch.from_numpy(style_vec).to(device).unsqueeze(0)
163
- del phones
164
- sid_tensor = torch.LongTensor([sid]).to(device)
165
- if is_jp_extra:
166
- output = net_g.infer(
167
- x_tst,
168
- x_tst_lengths,
169
- sid_tensor,
170
- tones,
171
- lang_ids,
172
- ja_bert,
173
- style_vec=style_vec,
174
- sdp_ratio=sdp_ratio,
175
- noise_scale=noise_scale,
176
- noise_scale_w=noise_scale_w,
177
- length_scale=length_scale,
178
- )
179
- else:
180
- output = net_g.infer(
181
- x_tst,
182
- x_tst_lengths,
183
- sid_tensor,
184
- tones,
185
- lang_ids,
186
- bert,
187
- ja_bert,
188
- en_bert,
189
- style_vec=style_vec,
190
- sdp_ratio=sdp_ratio,
191
- noise_scale=noise_scale,
192
- noise_scale_w=noise_scale_w,
193
- length_scale=length_scale,
194
- )
195
- audio = output[0][0, 0].data.cpu().float().numpy()
196
- del (
197
- x_tst,
198
- tones,
199
- lang_ids,
200
- bert,
201
- x_tst_lengths,
202
- sid_tensor,
203
- ja_bert,
204
- en_bert,
205
- style_vec,
206
- ) # , emo
207
- if torch.cuda.is_available():
208
- torch.cuda.empty_cache()
209
- return audio
210
-
211
-
212
- def infer_multilang(
213
- text,
214
- style_vec,
215
- sdp_ratio,
216
- noise_scale,
217
- noise_scale_w,
218
- length_scale,
219
- sid,
220
- language,
221
- hps,
222
- net_g,
223
- device,
224
- skip_start=False,
225
- skip_end=False,
226
- ):
227
- bert, ja_bert, en_bert, phones, tones, lang_ids = [], [], [], [], [], []
228
- # emo = get_emo_(reference_audio, emotion, sid)
229
- # if isinstance(reference_audio, np.ndarray):
230
- # emo = get_clap_audio_feature(reference_audio, device)
231
- # else:
232
- # emo = get_clap_text_feature(emotion, device)
233
- # emo = torch.squeeze(emo, dim=1)
234
- for idx, (txt, lang) in enumerate(zip(text, language)):
235
- _skip_start = (idx != 0) or (skip_start and idx == 0)
236
- _skip_end = (idx != len(language) - 1) or skip_end
237
- (
238
- temp_bert,
239
- temp_ja_bert,
240
- temp_en_bert,
241
- temp_phones,
242
- temp_tones,
243
- temp_lang_ids,
244
- ) = get_text(txt, lang, hps, device)
245
- if _skip_start:
246
- temp_bert = temp_bert[:, 3:]
247
- temp_ja_bert = temp_ja_bert[:, 3:]
248
- temp_en_bert = temp_en_bert[:, 3:]
249
- temp_phones = temp_phones[3:]
250
- temp_tones = temp_tones[3:]
251
- temp_lang_ids = temp_lang_ids[3:]
252
- if _skip_end:
253
- temp_bert = temp_bert[:, :-2]
254
- temp_ja_bert = temp_ja_bert[:, :-2]
255
- temp_en_bert = temp_en_bert[:, :-2]
256
- temp_phones = temp_phones[:-2]
257
- temp_tones = temp_tones[:-2]
258
- temp_lang_ids = temp_lang_ids[:-2]
259
- bert.append(temp_bert)
260
- ja_bert.append(temp_ja_bert)
261
- en_bert.append(temp_en_bert)
262
- phones.append(temp_phones)
263
- tones.append(temp_tones)
264
- lang_ids.append(temp_lang_ids)
265
- bert = torch.concatenate(bert, dim=1)
266
- ja_bert = torch.concatenate(ja_bert, dim=1)
267
- en_bert = torch.concatenate(en_bert, dim=1)
268
- phones = torch.concatenate(phones, dim=0)
269
- tones = torch.concatenate(tones, dim=0)
270
- lang_ids = torch.concatenate(lang_ids, dim=0)
271
- with torch.no_grad():
272
- x_tst = phones.to(device).unsqueeze(0)
273
- tones = tones.to(device).unsqueeze(0)
274
- lang_ids = lang_ids.to(device).unsqueeze(0)
275
- bert = bert.to(device).unsqueeze(0)
276
- ja_bert = ja_bert.to(device).unsqueeze(0)
277
- en_bert = en_bert.to(device).unsqueeze(0)
278
- # emo = emo.to(device).unsqueeze(0)
279
- x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device)
280
- del phones
281
- speakers = torch.LongTensor([hps.data.spk2id[sid]]).to(device)
282
- audio = (
283
- net_g.infer(
284
- x_tst,
285
- x_tst_lengths,
286
- speakers,
287
- tones,
288
- lang_ids,
289
- bert,
290
- ja_bert,
291
- en_bert,
292
- style_vec=style_vec,
293
- sdp_ratio=sdp_ratio,
294
- noise_scale=noise_scale,
295
- noise_scale_w=noise_scale_w,
296
- length_scale=length_scale,
297
- )[0][0, 0]
298
- .data.cpu()
299
- .float()
300
- .numpy()
301
- )
302
- del (
303
- x_tst,
304
- tones,
305
- lang_ids,
306
- bert,
307
- x_tst_lengths,
308
- speakers,
309
- ja_bert,
310
- en_bert,
311
- ) # , emo
312
- if torch.cuda.is_available():
313
- torch.cuda.empty_cache()
314
- return audio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
inputs/.gitignore DELETED
@@ -1,2 +0,0 @@
1
- *
2
- !.gitignore
 
 
 
library.ipynb DELETED
@@ -1,138 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "metadata": {},
6
- "source": [
7
- "# Style-Bert-VITS2ライブラリの使用例\n",
8
- "\n",
9
- "`pip install style-bert-vits2`を使った、jupyter notebookでの使用例です。Google colab等でも動きます。"
10
- ]
11
- },
12
- {
13
- "cell_type": "code",
14
- "execution_count": null,
15
- "metadata": {},
16
- "outputs": [],
17
- "source": [
18
- "# PyTorch環境の構築(ない場合)\n",
19
- "# 参照: https://pytorch.org/get-started/locally/\n",
20
- "\n",
21
- "!pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118"
22
- ]
23
- },
24
- {
25
- "cell_type": "code",
26
- "execution_count": null,
27
- "metadata": {
28
- "id": "LLrngKcQEAyP"
29
- },
30
- "outputs": [],
31
- "source": [
32
- "# style-bert-vits2のインストール\n",
33
- "\n",
34
- "!pip install style-bert-vits2"
35
- ]
36
- },
37
- {
38
- "cell_type": "code",
39
- "execution_count": null,
40
- "metadata": {
41
- "id": "9xRtfUg5EZkx"
42
- },
43
- "outputs": [],
44
- "source": [
45
- "# BERTモデルをロード(ローカルに手動でダウンロードする必要はありません)\n",
46
- "\n",
47
- "from style_bert_vits2.nlp import bert_models\n",
48
- "from style_bert_vits2.constants import Languages\n",
49
- "\n",
50
- "\n",
51
- "bert_models.load_model(Languages.JP, \"ku-nlp/deberta-v2-large-japanese-char-wwm\")\n",
52
- "bert_models.load_tokenizer(Languages.JP, \"ku-nlp/deberta-v2-large-japanese-char-wwm\")\n",
53
- "# bert_models.load_model(Languages.EN, \"microsoft/deberta-v3-large\")\n",
54
- "# bert_models.load_tokenizer(Languages.EN, \"microsoft/deberta-v3-large\")\n",
55
- "# bert_models.load_model(Languages.ZH, \"hfl/chinese-roberta-wwm-ext-large\")\n",
56
- "# bert_models.load_tokenizer(Languages.ZH, \"hfl/chinese-roberta-wwm-ext-large\")"
57
- ]
58
- },
59
- {
60
- "cell_type": "code",
61
- "execution_count": null,
62
- "metadata": {
63
- "id": "q2V9d3HyFAr_"
64
- },
65
- "outputs": [],
66
- "source": [
67
- "# Hugging Faceから試しにデフォルトモデルをダウンロードしてみて、それを音声合成に使ってみる\n",
68
- "# model_assetsディレクトリにダウンロードされます\n",
69
- "\n",
70
- "from pathlib import Path\n",
71
- "from huggingface_hub import hf_hub_download\n",
72
- "\n",
73
- "\n",
74
- "model_file = \"jvnv-F1-jp/jvnv-F1-jp_e160_s14000.safetensors\"\n",
75
- "config_file = \"jvnv-F1-jp/config.json\"\n",
76
- "style_file = \"jvnv-F1-jp/style_vectors.npy\"\n",
77
- "\n",
78
- "for file in [model_file, config_file, style_file]:\n",
79
- " print(file)\n",
80
- " hf_hub_download(\n",
81
- " \"litagin/style_bert_vits2_jvnv\",\n",
82
- " file,\n",
83
- " local_dir=\"model_assets\"\n",
84
- " )"
85
- ]
86
- },
87
- {
88
- "cell_type": "code",
89
- "execution_count": null,
90
- "metadata": {
91
- "id": "hJa31MEUFhe4"
92
- },
93
- "outputs": [],
94
- "source": [
95
- "# 上でダウンロードしたモデルファイルを指定して音声合成のテスト\n",
96
- "\n",
97
- "from style_bert_vits2.tts_model import TTSModel\n",
98
- "\n",
99
- "assets_root = Path(\"model_assets\")\n",
100
- "\n",
101
- "model = TTSModel(\n",
102
- " model_path=assets_root / model_file,\n",
103
- " config_path=assets_root / config_file,\n",
104
- " style_vec_path=assets_root / style_file,\n",
105
- " device=\"cpu\"\n",
106
- ")"
107
- ]
108
- },
109
- {
110
- "cell_type": "code",
111
- "execution_count": null,
112
- "metadata": {
113
- "id": "Gal0tqrtGXZx"
114
- },
115
- "outputs": [],
116
- "source": [
117
- "from IPython.display import Audio, display\n",
118
- "\n",
119
- "sr, audio = model.infer(text=\"こんにちは\")\n",
120
- "display(Audio(audio, rate=sr))"
121
- ]
122
- }
123
- ],
124
- "metadata": {
125
- "colab": {
126
- "provenance": []
127
- },
128
- "kernelspec": {
129
- "display_name": "Python 3",
130
- "name": "python3"
131
- },
132
- "language_info": {
133
- "name": "python"
134
- }
135
- },
136
- "nbformat": 4,
137
- "nbformat_minor": 0
138
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
losses.py DELETED
@@ -1,153 +0,0 @@
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, 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 DELETED
@@ -1,148 +0,0 @@
1
- import warnings
2
-
3
- import torch
4
- import torch.utils.data
5
- from librosa.filters import mel as librosa_mel_fn
6
-
7
-
8
- # warnings.simplefilter(action='ignore', category=FutureWarning)
9
- warnings.filterwarnings(action="ignore")
10
- MAX_WAV_VALUE = 32768.0
11
-
12
-
13
- def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
14
- """
15
- PARAMS
16
- ------
17
- C: compression factor
18
- """
19
- return torch.log(torch.clamp(x, min=clip_val) * C)
20
-
21
-
22
- def dynamic_range_decompression_torch(x, C=1):
23
- """
24
- PARAMS
25
- ------
26
- C: compression factor used to compress
27
- """
28
- return torch.exp(x) / C
29
-
30
-
31
- def spectral_normalize_torch(magnitudes):
32
- output = dynamic_range_compression_torch(magnitudes)
33
- return output
34
-
35
-
36
- def spectral_de_normalize_torch(magnitudes):
37
- output = dynamic_range_decompression_torch(magnitudes)
38
- return output
39
-
40
-
41
- mel_basis = {}
42
- hann_window = {}
43
-
44
-
45
- def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
46
- if torch.min(y) < -1.0:
47
- print("min value is ", torch.min(y))
48
- if torch.max(y) > 1.0:
49
- print("max value is ", torch.max(y))
50
-
51
- global hann_window
52
- dtype_device = str(y.dtype) + "_" + str(y.device)
53
- wnsize_dtype_device = str(win_size) + "_" + dtype_device
54
- if wnsize_dtype_device not in hann_window:
55
- hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
56
- dtype=y.dtype, device=y.device
57
- )
58
-
59
- y = torch.nn.functional.pad(
60
- y.unsqueeze(1),
61
- (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
62
- mode="reflect",
63
- )
64
- y = y.squeeze(1)
65
-
66
- spec = torch.stft(
67
- y,
68
- n_fft,
69
- hop_length=hop_size,
70
- win_length=win_size,
71
- window=hann_window[wnsize_dtype_device],
72
- center=center,
73
- pad_mode="reflect",
74
- normalized=False,
75
- onesided=True,
76
- return_complex=False,
77
- )
78
-
79
- spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
80
- return spec
81
-
82
-
83
- def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
84
- global mel_basis
85
- dtype_device = str(spec.dtype) + "_" + str(spec.device)
86
- fmax_dtype_device = str(fmax) + "_" + dtype_device
87
- if fmax_dtype_device not in mel_basis:
88
- mel = librosa_mel_fn(
89
- sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax
90
- )
91
- mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
92
- dtype=spec.dtype, device=spec.device
93
- )
94
- spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
95
- spec = spectral_normalize_torch(spec)
96
- return spec
97
-
98
-
99
- def mel_spectrogram_torch(
100
- y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False
101
- ):
102
- if torch.min(y) < -1.0:
103
- print("min value is ", torch.min(y))
104
- if torch.max(y) > 1.0:
105
- print("max value is ", torch.max(y))
106
-
107
- global mel_basis, hann_window
108
- dtype_device = str(y.dtype) + "_" + str(y.device)
109
- fmax_dtype_device = str(fmax) + "_" + dtype_device
110
- wnsize_dtype_device = str(win_size) + "_" + dtype_device
111
- if fmax_dtype_device not in mel_basis:
112
- mel = librosa_mel_fn(
113
- sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax
114
- )
115
- mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
116
- dtype=y.dtype, device=y.device
117
- )
118
- if wnsize_dtype_device not in hann_window:
119
- hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
120
- dtype=y.dtype, device=y.device
121
- )
122
-
123
- y = torch.nn.functional.pad(
124
- y.unsqueeze(1),
125
- (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
126
- mode="reflect",
127
- )
128
- y = y.squeeze(1)
129
-
130
- spec = torch.stft(
131
- y,
132
- n_fft,
133
- hop_length=hop_size,
134
- win_length=win_size,
135
- window=hann_window[wnsize_dtype_device],
136
- center=center,
137
- pad_mode="reflect",
138
- normalized=False,
139
- onesided=True,
140
- return_complex=False,
141
- )
142
-
143
- spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
144
-
145
- spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
146
- spec = spectral_normalize_torch(spec)
147
-
148
- return spec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models.py DELETED
@@ -1,1024 +0,0 @@
1
- import math
2
- import warnings
3
-
4
- import torch
5
- from torch import nn
6
- from torch.nn import Conv1d, Conv2d, ConvTranspose1d
7
- from torch.nn import functional as F
8
- from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
9
-
10
- import attentions
11
- import commons
12
- import modules
13
- import monotonic_align
14
- from commons import get_padding, init_weights
15
- from text import num_languages, num_tones, symbols
16
-
17
-
18
- class DurationDiscriminator(nn.Module): # vits2
19
- def __init__(
20
- self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0
21
- ):
22
- super().__init__()
23
-
24
- self.in_channels = in_channels
25
- self.filter_channels = filter_channels
26
- self.kernel_size = kernel_size
27
- self.p_dropout = p_dropout
28
- self.gin_channels = gin_channels
29
-
30
- self.drop = nn.Dropout(p_dropout)
31
- self.conv_1 = nn.Conv1d(
32
- in_channels, filter_channels, kernel_size, padding=kernel_size // 2
33
- )
34
- self.norm_1 = modules.LayerNorm(filter_channels)
35
- self.conv_2 = nn.Conv1d(
36
- filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
37
- )
38
- self.norm_2 = modules.LayerNorm(filter_channels)
39
- self.dur_proj = nn.Conv1d(1, filter_channels, 1)
40
-
41
- self.pre_out_conv_1 = nn.Conv1d(
42
- 2 * filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
43
- )
44
- self.pre_out_norm_1 = modules.LayerNorm(filter_channels)
45
- self.pre_out_conv_2 = nn.Conv1d(
46
- filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
47
- )
48
- self.pre_out_norm_2 = modules.LayerNorm(filter_channels)
49
-
50
- if gin_channels != 0:
51
- self.cond = nn.Conv1d(gin_channels, in_channels, 1)
52
-
53
- self.output_layer = nn.Sequential(nn.Linear(filter_channels, 1), nn.Sigmoid())
54
-
55
- def forward_probability(self, x, x_mask, dur, g=None):
56
- dur = self.dur_proj(dur)
57
- x = torch.cat([x, dur], dim=1)
58
- x = self.pre_out_conv_1(x * x_mask)
59
- x = torch.relu(x)
60
- x = self.pre_out_norm_1(x)
61
- x = self.drop(x)
62
- x = self.pre_out_conv_2(x * x_mask)
63
- x = torch.relu(x)
64
- x = self.pre_out_norm_2(x)
65
- x = self.drop(x)
66
- x = x * x_mask
67
- x = x.transpose(1, 2)
68
- output_prob = self.output_layer(x)
69
- return output_prob
70
-
71
- def forward(self, x, x_mask, dur_r, dur_hat, g=None):
72
- x = torch.detach(x)
73
- if g is not None:
74
- g = torch.detach(g)
75
- x = x + self.cond(g)
76
- x = self.conv_1(x * x_mask)
77
- x = torch.relu(x)
78
- x = self.norm_1(x)
79
- x = self.drop(x)
80
- x = self.conv_2(x * x_mask)
81
- x = torch.relu(x)
82
- x = self.norm_2(x)
83
- x = self.drop(x)
84
-
85
- output_probs = []
86
- for dur in [dur_r, dur_hat]:
87
- output_prob = self.forward_probability(x, x_mask, dur, g)
88
- output_probs.append(output_prob)
89
-
90
- return output_probs
91
-
92
-
93
- class TransformerCouplingBlock(nn.Module):
94
- def __init__(
95
- self,
96
- channels,
97
- hidden_channels,
98
- filter_channels,
99
- n_heads,
100
- n_layers,
101
- kernel_size,
102
- p_dropout,
103
- n_flows=4,
104
- gin_channels=0,
105
- share_parameter=False,
106
- ):
107
- super().__init__()
108
- self.channels = channels
109
- self.hidden_channels = hidden_channels
110
- self.kernel_size = kernel_size
111
- self.n_layers = n_layers
112
- self.n_flows = n_flows
113
- self.gin_channels = gin_channels
114
-
115
- self.flows = nn.ModuleList()
116
-
117
- self.wn = (
118
- attentions.FFT(
119
- hidden_channels,
120
- filter_channels,
121
- n_heads,
122
- n_layers,
123
- kernel_size,
124
- p_dropout,
125
- isflow=True,
126
- gin_channels=self.gin_channels,
127
- )
128
- if share_parameter
129
- else None
130
- )
131
-
132
- for i in range(n_flows):
133
- self.flows.append(
134
- modules.TransformerCouplingLayer(
135
- channels,
136
- hidden_channels,
137
- kernel_size,
138
- n_layers,
139
- n_heads,
140
- p_dropout,
141
- filter_channels,
142
- mean_only=True,
143
- wn_sharing_parameter=self.wn,
144
- gin_channels=self.gin_channels,
145
- )
146
- )
147
- self.flows.append(modules.Flip())
148
-
149
- def forward(self, x, x_mask, g=None, reverse=False):
150
- if not reverse:
151
- for flow in self.flows:
152
- x, _ = flow(x, x_mask, g=g, reverse=reverse)
153
- else:
154
- for flow in reversed(self.flows):
155
- x = flow(x, x_mask, g=g, reverse=reverse)
156
- return x
157
-
158
-
159
- class StochasticDurationPredictor(nn.Module):
160
- def __init__(
161
- self,
162
- in_channels,
163
- filter_channels,
164
- kernel_size,
165
- p_dropout,
166
- n_flows=4,
167
- gin_channels=0,
168
- ):
169
- super().__init__()
170
- filter_channels = in_channels # it needs to be removed from future version.
171
- self.in_channels = in_channels
172
- self.filter_channels = filter_channels
173
- self.kernel_size = kernel_size
174
- self.p_dropout = p_dropout
175
- self.n_flows = n_flows
176
- self.gin_channels = gin_channels
177
-
178
- self.log_flow = modules.Log()
179
- self.flows = nn.ModuleList()
180
- self.flows.append(modules.ElementwiseAffine(2))
181
- for i in range(n_flows):
182
- self.flows.append(
183
- modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
184
- )
185
- self.flows.append(modules.Flip())
186
-
187
- self.post_pre = nn.Conv1d(1, filter_channels, 1)
188
- self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
189
- self.post_convs = modules.DDSConv(
190
- filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
191
- )
192
- self.post_flows = nn.ModuleList()
193
- self.post_flows.append(modules.ElementwiseAffine(2))
194
- for i in range(4):
195
- self.post_flows.append(
196
- modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
197
- )
198
- self.post_flows.append(modules.Flip())
199
-
200
- self.pre = nn.Conv1d(in_channels, filter_channels, 1)
201
- self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
202
- self.convs = modules.DDSConv(
203
- filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
204
- )
205
- if gin_channels != 0:
206
- self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
207
-
208
- def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
209
- x = torch.detach(x)
210
- x = self.pre(x)
211
- if g is not None:
212
- g = torch.detach(g)
213
- x = x + self.cond(g)
214
- x = self.convs(x, x_mask)
215
- x = self.proj(x) * x_mask
216
-
217
- if not reverse:
218
- flows = self.flows
219
- assert w is not None
220
-
221
- logdet_tot_q = 0
222
- h_w = self.post_pre(w)
223
- h_w = self.post_convs(h_w, x_mask)
224
- h_w = self.post_proj(h_w) * x_mask
225
- e_q = (
226
- torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype)
227
- * x_mask
228
- )
229
- z_q = e_q
230
- for flow in self.post_flows:
231
- z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
232
- logdet_tot_q += logdet_q
233
- z_u, z1 = torch.split(z_q, [1, 1], 1)
234
- u = torch.sigmoid(z_u) * x_mask
235
- z0 = (w - u) * x_mask
236
- logdet_tot_q += torch.sum(
237
- (F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2]
238
- )
239
- logq = (
240
- torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q**2)) * x_mask, [1, 2])
241
- - logdet_tot_q
242
- )
243
-
244
- logdet_tot = 0
245
- z0, logdet = self.log_flow(z0, x_mask)
246
- logdet_tot += logdet
247
- z = torch.cat([z0, z1], 1)
248
- for flow in flows:
249
- z, logdet = flow(z, x_mask, g=x, reverse=reverse)
250
- logdet_tot = logdet_tot + logdet
251
- nll = (
252
- torch.sum(0.5 * (math.log(2 * math.pi) + (z**2)) * x_mask, [1, 2])
253
- - logdet_tot
254
- )
255
- return nll + logq # [b]
256
- else:
257
- flows = list(reversed(self.flows))
258
- flows = flows[:-2] + [flows[-1]] # remove a useless vflow
259
- z = (
260
- torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype)
261
- * noise_scale
262
- )
263
- for flow in flows:
264
- z = flow(z, x_mask, g=x, reverse=reverse)
265
- z0, z1 = torch.split(z, [1, 1], 1)
266
- logw = z0
267
- return logw
268
-
269
-
270
- class DurationPredictor(nn.Module):
271
- def __init__(
272
- self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0
273
- ):
274
- super().__init__()
275
-
276
- self.in_channels = in_channels
277
- self.filter_channels = filter_channels
278
- self.kernel_size = kernel_size
279
- self.p_dropout = p_dropout
280
- self.gin_channels = gin_channels
281
-
282
- self.drop = nn.Dropout(p_dropout)
283
- self.conv_1 = nn.Conv1d(
284
- in_channels, filter_channels, kernel_size, padding=kernel_size // 2
285
- )
286
- self.norm_1 = modules.LayerNorm(filter_channels)
287
- self.conv_2 = nn.Conv1d(
288
- filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
289
- )
290
- self.norm_2 = modules.LayerNorm(filter_channels)
291
- self.proj = nn.Conv1d(filter_channels, 1, 1)
292
-
293
- if gin_channels != 0:
294
- self.cond = nn.Conv1d(gin_channels, in_channels, 1)
295
-
296
- def forward(self, x, x_mask, g=None):
297
- x = torch.detach(x)
298
- if g is not None:
299
- g = torch.detach(g)
300
- x = x + self.cond(g)
301
- x = self.conv_1(x * x_mask)
302
- x = torch.relu(x)
303
- x = self.norm_1(x)
304
- x = self.drop(x)
305
- x = self.conv_2(x * x_mask)
306
- x = torch.relu(x)
307
- x = self.norm_2(x)
308
- x = self.drop(x)
309
- x = self.proj(x * x_mask)
310
- return x * x_mask
311
-
312
-
313
- class TextEncoder(nn.Module):
314
- def __init__(
315
- self,
316
- n_vocab,
317
- out_channels,
318
- hidden_channels,
319
- filter_channels,
320
- n_heads,
321
- n_layers,
322
- kernel_size,
323
- p_dropout,
324
- n_speakers,
325
- gin_channels=0,
326
- ):
327
- super().__init__()
328
- self.n_vocab = n_vocab
329
- self.out_channels = out_channels
330
- self.hidden_channels = hidden_channels
331
- self.filter_channels = filter_channels
332
- self.n_heads = n_heads
333
- self.n_layers = n_layers
334
- self.kernel_size = kernel_size
335
- self.p_dropout = p_dropout
336
- self.gin_channels = gin_channels
337
- self.emb = nn.Embedding(len(symbols), hidden_channels)
338
- nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
339
- self.tone_emb = nn.Embedding(num_tones, hidden_channels)
340
- nn.init.normal_(self.tone_emb.weight, 0.0, hidden_channels**-0.5)
341
- self.language_emb = nn.Embedding(num_languages, hidden_channels)
342
- nn.init.normal_(self.language_emb.weight, 0.0, hidden_channels**-0.5)
343
- self.bert_proj = nn.Conv1d(1024, hidden_channels, 1)
344
- self.ja_bert_proj = nn.Conv1d(1024, hidden_channels, 1)
345
- self.en_bert_proj = nn.Conv1d(1024, hidden_channels, 1)
346
- self.style_proj = nn.Linear(256, hidden_channels)
347
-
348
- self.encoder = attentions.Encoder(
349
- hidden_channels,
350
- filter_channels,
351
- n_heads,
352
- n_layers,
353
- kernel_size,
354
- p_dropout,
355
- gin_channels=self.gin_channels,
356
- )
357
- self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
358
-
359
- def forward(
360
- self,
361
- x,
362
- x_lengths,
363
- tone,
364
- language,
365
- bert,
366
- ja_bert,
367
- en_bert,
368
- style_vec,
369
- sid,
370
- g=None,
371
- ):
372
- bert_emb = self.bert_proj(bert).transpose(1, 2)
373
- ja_bert_emb = self.ja_bert_proj(ja_bert).transpose(1, 2)
374
- en_bert_emb = self.en_bert_proj(en_bert).transpose(1, 2)
375
- style_emb = self.style_proj(style_vec.unsqueeze(1))
376
-
377
- x = (
378
- self.emb(x)
379
- + self.tone_emb(tone)
380
- + self.language_emb(language)
381
- + bert_emb
382
- + ja_bert_emb
383
- + en_bert_emb
384
- + style_emb
385
- ) * math.sqrt(
386
- self.hidden_channels
387
- ) # [b, t, h]
388
- x = torch.transpose(x, 1, -1) # [b, h, t]
389
- x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
390
- x.dtype
391
- )
392
-
393
- x = self.encoder(x * x_mask, x_mask, g=g)
394
- stats = self.proj(x) * x_mask
395
-
396
- m, logs = torch.split(stats, self.out_channels, dim=1)
397
- return x, m, logs, x_mask
398
-
399
-
400
- class ResidualCouplingBlock(nn.Module):
401
- def __init__(
402
- self,
403
- channels,
404
- hidden_channels,
405
- kernel_size,
406
- dilation_rate,
407
- n_layers,
408
- n_flows=4,
409
- gin_channels=0,
410
- ):
411
- super().__init__()
412
- self.channels = channels
413
- self.hidden_channels = hidden_channels
414
- self.kernel_size = kernel_size
415
- self.dilation_rate = dilation_rate
416
- self.n_layers = n_layers
417
- self.n_flows = n_flows
418
- self.gin_channels = gin_channels
419
-
420
- self.flows = nn.ModuleList()
421
- for i in range(n_flows):
422
- self.flows.append(
423
- modules.ResidualCouplingLayer(
424
- channels,
425
- hidden_channels,
426
- kernel_size,
427
- dilation_rate,
428
- n_layers,
429
- gin_channels=gin_channels,
430
- mean_only=True,
431
- )
432
- )
433
- self.flows.append(modules.Flip())
434
-
435
- def forward(self, x, x_mask, g=None, reverse=False):
436
- if not reverse:
437
- for flow in self.flows:
438
- x, _ = flow(x, x_mask, g=g, reverse=reverse)
439
- else:
440
- for flow in reversed(self.flows):
441
- x = flow(x, x_mask, g=g, reverse=reverse)
442
- return x
443
-
444
-
445
- class PosteriorEncoder(nn.Module):
446
- def __init__(
447
- self,
448
- in_channels,
449
- out_channels,
450
- hidden_channels,
451
- kernel_size,
452
- dilation_rate,
453
- n_layers,
454
- gin_channels=0,
455
- ):
456
- super().__init__()
457
- self.in_channels = in_channels
458
- self.out_channels = out_channels
459
- self.hidden_channels = hidden_channels
460
- self.kernel_size = kernel_size
461
- self.dilation_rate = dilation_rate
462
- self.n_layers = n_layers
463
- self.gin_channels = gin_channels
464
-
465
- self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
466
- self.enc = modules.WN(
467
- hidden_channels,
468
- kernel_size,
469
- dilation_rate,
470
- n_layers,
471
- gin_channels=gin_channels,
472
- )
473
- self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
474
-
475
- def forward(self, x, x_lengths, g=None):
476
- x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
477
- x.dtype
478
- )
479
- x = self.pre(x) * x_mask
480
- x = self.enc(x, x_mask, g=g)
481
- stats = self.proj(x) * x_mask
482
- m, logs = torch.split(stats, self.out_channels, dim=1)
483
- z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
484
- return z, m, logs, x_mask
485
-
486
-
487
- class Generator(torch.nn.Module):
488
- def __init__(
489
- self,
490
- initial_channel,
491
- resblock,
492
- resblock_kernel_sizes,
493
- resblock_dilation_sizes,
494
- upsample_rates,
495
- upsample_initial_channel,
496
- upsample_kernel_sizes,
497
- gin_channels=0,
498
- ):
499
- super(Generator, self).__init__()
500
- self.num_kernels = len(resblock_kernel_sizes)
501
- self.num_upsamples = len(upsample_rates)
502
- self.conv_pre = Conv1d(
503
- initial_channel, upsample_initial_channel, 7, 1, padding=3
504
- )
505
- resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
506
-
507
- self.ups = nn.ModuleList()
508
- for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
509
- self.ups.append(
510
- weight_norm(
511
- ConvTranspose1d(
512
- upsample_initial_channel // (2**i),
513
- upsample_initial_channel // (2 ** (i + 1)),
514
- k,
515
- u,
516
- padding=(k - u) // 2,
517
- )
518
- )
519
- )
520
-
521
- self.resblocks = nn.ModuleList()
522
- for i in range(len(self.ups)):
523
- ch = upsample_initial_channel // (2 ** (i + 1))
524
- for j, (k, d) in enumerate(
525
- zip(resblock_kernel_sizes, resblock_dilation_sizes)
526
- ):
527
- self.resblocks.append(resblock(ch, k, d))
528
-
529
- self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
530
- self.ups.apply(init_weights)
531
-
532
- if gin_channels != 0:
533
- self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
534
-
535
- def forward(self, x, g=None):
536
- x = self.conv_pre(x)
537
- if g is not None:
538
- x = x + self.cond(g)
539
-
540
- for i in range(self.num_upsamples):
541
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
542
- x = self.ups[i](x)
543
- xs = None
544
- for j in range(self.num_kernels):
545
- if xs is None:
546
- xs = self.resblocks[i * self.num_kernels + j](x)
547
- else:
548
- xs += self.resblocks[i * self.num_kernels + j](x)
549
- x = xs / self.num_kernels
550
- x = F.leaky_relu(x)
551
- x = self.conv_post(x)
552
- x = torch.tanh(x)
553
-
554
- return x
555
-
556
- def remove_weight_norm(self):
557
- print("Removing weight norm...")
558
- for layer in self.ups:
559
- remove_weight_norm(layer)
560
- for layer in self.resblocks:
561
- layer.remove_weight_norm()
562
-
563
-
564
- class DiscriminatorP(torch.nn.Module):
565
- def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
566
- super(DiscriminatorP, self).__init__()
567
- self.period = period
568
- self.use_spectral_norm = use_spectral_norm
569
- norm_f = weight_norm if use_spectral_norm is False else spectral_norm
570
- self.convs = nn.ModuleList(
571
- [
572
- norm_f(
573
- Conv2d(
574
- 1,
575
- 32,
576
- (kernel_size, 1),
577
- (stride, 1),
578
- padding=(get_padding(kernel_size, 1), 0),
579
- )
580
- ),
581
- norm_f(
582
- Conv2d(
583
- 32,
584
- 128,
585
- (kernel_size, 1),
586
- (stride, 1),
587
- padding=(get_padding(kernel_size, 1), 0),
588
- )
589
- ),
590
- norm_f(
591
- Conv2d(
592
- 128,
593
- 512,
594
- (kernel_size, 1),
595
- (stride, 1),
596
- padding=(get_padding(kernel_size, 1), 0),
597
- )
598
- ),
599
- norm_f(
600
- Conv2d(
601
- 512,
602
- 1024,
603
- (kernel_size, 1),
604
- (stride, 1),
605
- padding=(get_padding(kernel_size, 1), 0),
606
- )
607
- ),
608
- norm_f(
609
- Conv2d(
610
- 1024,
611
- 1024,
612
- (kernel_size, 1),
613
- 1,
614
- padding=(get_padding(kernel_size, 1), 0),
615
- )
616
- ),
617
- ]
618
- )
619
- self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
620
-
621
- def forward(self, x):
622
- fmap = []
623
-
624
- # 1d to 2d
625
- b, c, t = x.shape
626
- if t % self.period != 0: # pad first
627
- n_pad = self.period - (t % self.period)
628
- x = F.pad(x, (0, n_pad), "reflect")
629
- t = t + n_pad
630
- x = x.view(b, c, t // self.period, self.period)
631
-
632
- for layer in self.convs:
633
- x = layer(x)
634
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
635
- fmap.append(x)
636
- x = self.conv_post(x)
637
- fmap.append(x)
638
- x = torch.flatten(x, 1, -1)
639
-
640
- return x, fmap
641
-
642
-
643
- class DiscriminatorS(torch.nn.Module):
644
- def __init__(self, use_spectral_norm=False):
645
- super(DiscriminatorS, self).__init__()
646
- norm_f = weight_norm if use_spectral_norm is False else spectral_norm
647
- self.convs = nn.ModuleList(
648
- [
649
- norm_f(Conv1d(1, 16, 15, 1, padding=7)),
650
- norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
651
- norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
652
- norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
653
- norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
654
- norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
655
- ]
656
- )
657
- self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
658
-
659
- def forward(self, x):
660
- fmap = []
661
-
662
- for layer in self.convs:
663
- x = layer(x)
664
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
665
- fmap.append(x)
666
- x = self.conv_post(x)
667
- fmap.append(x)
668
- x = torch.flatten(x, 1, -1)
669
-
670
- return x, fmap
671
-
672
-
673
- class MultiPeriodDiscriminator(torch.nn.Module):
674
- def __init__(self, use_spectral_norm=False):
675
- super(MultiPeriodDiscriminator, self).__init__()
676
- periods = [2, 3, 5, 7, 11]
677
-
678
- discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
679
- discs = discs + [
680
- DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
681
- ]
682
- self.discriminators = nn.ModuleList(discs)
683
-
684
- def forward(self, y, y_hat):
685
- y_d_rs = []
686
- y_d_gs = []
687
- fmap_rs = []
688
- fmap_gs = []
689
- for i, d in enumerate(self.discriminators):
690
- y_d_r, fmap_r = d(y)
691
- y_d_g, fmap_g = d(y_hat)
692
- y_d_rs.append(y_d_r)
693
- y_d_gs.append(y_d_g)
694
- fmap_rs.append(fmap_r)
695
- fmap_gs.append(fmap_g)
696
-
697
- return y_d_rs, y_d_gs, fmap_rs, fmap_gs
698
-
699
-
700
- class ReferenceEncoder(nn.Module):
701
- """
702
- inputs --- [N, Ty/r, n_mels*r] mels
703
- outputs --- [N, ref_enc_gru_size]
704
- """
705
-
706
- def __init__(self, spec_channels, gin_channels=0):
707
- super().__init__()
708
- self.spec_channels = spec_channels
709
- ref_enc_filters = [32, 32, 64, 64, 128, 128]
710
- K = len(ref_enc_filters)
711
- filters = [1] + ref_enc_filters
712
- convs = [
713
- weight_norm(
714
- nn.Conv2d(
715
- in_channels=filters[i],
716
- out_channels=filters[i + 1],
717
- kernel_size=(3, 3),
718
- stride=(2, 2),
719
- padding=(1, 1),
720
- )
721
- )
722
- for i in range(K)
723
- ]
724
- self.convs = nn.ModuleList(convs)
725
- # self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)]) # noqa: E501
726
-
727
- out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K)
728
- self.gru = nn.GRU(
729
- input_size=ref_enc_filters[-1] * out_channels,
730
- hidden_size=256 // 2,
731
- batch_first=True,
732
- )
733
- self.proj = nn.Linear(128, gin_channels)
734
-
735
- def forward(self, inputs, mask=None):
736
- N = inputs.size(0)
737
- out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs]
738
- for conv in self.convs:
739
- out = conv(out)
740
- # out = wn(out)
741
- out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K]
742
-
743
- out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
744
- T = out.size(1)
745
- N = out.size(0)
746
- out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
747
-
748
- self.gru.flatten_parameters()
749
- memory, out = self.gru(out) # out --- [1, N, 128]
750
-
751
- return self.proj(out.squeeze(0))
752
-
753
- def calculate_channels(self, L, kernel_size, stride, pad, n_convs):
754
- for i in range(n_convs):
755
- L = (L - kernel_size + 2 * pad) // stride + 1
756
- return L
757
-
758
-
759
- class SynthesizerTrn(nn.Module):
760
- """
761
- Synthesizer for Training
762
- """
763
-
764
- def __init__(
765
- self,
766
- n_vocab,
767
- spec_channels,
768
- segment_size,
769
- inter_channels,
770
- hidden_channels,
771
- filter_channels,
772
- n_heads,
773
- n_layers,
774
- kernel_size,
775
- p_dropout,
776
- resblock,
777
- resblock_kernel_sizes,
778
- resblock_dilation_sizes,
779
- upsample_rates,
780
- upsample_initial_channel,
781
- upsample_kernel_sizes,
782
- n_speakers=256,
783
- gin_channels=256,
784
- use_sdp=True,
785
- n_flow_layer=4,
786
- n_layers_trans_flow=4,
787
- flow_share_parameter=False,
788
- use_transformer_flow=True,
789
- **kwargs,
790
- ):
791
- super().__init__()
792
- self.n_vocab = n_vocab
793
- self.spec_channels = spec_channels
794
- self.inter_channels = inter_channels
795
- self.hidden_channels = hidden_channels
796
- self.filter_channels = filter_channels
797
- self.n_heads = n_heads
798
- self.n_layers = n_layers
799
- self.kernel_size = kernel_size
800
- self.p_dropout = p_dropout
801
- self.resblock = resblock
802
- self.resblock_kernel_sizes = resblock_kernel_sizes
803
- self.resblock_dilation_sizes = resblock_dilation_sizes
804
- self.upsample_rates = upsample_rates
805
- self.upsample_initial_channel = upsample_initial_channel
806
- self.upsample_kernel_sizes = upsample_kernel_sizes
807
- self.segment_size = segment_size
808
- self.n_speakers = n_speakers
809
- self.gin_channels = gin_channels
810
- self.n_layers_trans_flow = n_layers_trans_flow
811
- self.use_spk_conditioned_encoder = kwargs.get(
812
- "use_spk_conditioned_encoder", True
813
- )
814
- self.use_sdp = use_sdp
815
- self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False)
816
- self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01)
817
- self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6)
818
- self.current_mas_noise_scale = self.mas_noise_scale_initial
819
- if self.use_spk_conditioned_encoder and gin_channels > 0:
820
- self.enc_gin_channels = gin_channels
821
- self.enc_p = TextEncoder(
822
- n_vocab,
823
- inter_channels,
824
- hidden_channels,
825
- filter_channels,
826
- n_heads,
827
- n_layers,
828
- kernel_size,
829
- p_dropout,
830
- self.n_speakers,
831
- gin_channels=self.enc_gin_channels,
832
- )
833
- self.dec = Generator(
834
- inter_channels,
835
- resblock,
836
- resblock_kernel_sizes,
837
- resblock_dilation_sizes,
838
- upsample_rates,
839
- upsample_initial_channel,
840
- upsample_kernel_sizes,
841
- gin_channels=gin_channels,
842
- )
843
- self.enc_q = PosteriorEncoder(
844
- spec_channels,
845
- inter_channels,
846
- hidden_channels,
847
- 5,
848
- 1,
849
- 16,
850
- gin_channels=gin_channels,
851
- )
852
- if use_transformer_flow:
853
- self.flow = TransformerCouplingBlock(
854
- inter_channels,
855
- hidden_channels,
856
- filter_channels,
857
- n_heads,
858
- n_layers_trans_flow,
859
- 5,
860
- p_dropout,
861
- n_flow_layer,
862
- gin_channels=gin_channels,
863
- share_parameter=flow_share_parameter,
864
- )
865
- else:
866
- self.flow = ResidualCouplingBlock(
867
- inter_channels,
868
- hidden_channels,
869
- 5,
870
- 1,
871
- n_flow_layer,
872
- gin_channels=gin_channels,
873
- )
874
- self.sdp = StochasticDurationPredictor(
875
- hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels
876
- )
877
- self.dp = DurationPredictor(
878
- hidden_channels, 256, 3, 0.5, gin_channels=gin_channels
879
- )
880
-
881
- if n_speakers >= 1:
882
- self.emb_g = nn.Embedding(n_speakers, gin_channels)
883
- else:
884
- self.ref_enc = ReferenceEncoder(spec_channels, gin_channels)
885
-
886
- def forward(
887
- self,
888
- x,
889
- x_lengths,
890
- y,
891
- y_lengths,
892
- sid,
893
- tone,
894
- language,
895
- bert,
896
- ja_bert,
897
- en_bert,
898
- style_vec,
899
- ):
900
- if self.n_speakers > 0:
901
- g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
902
- else:
903
- g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
904
- x, m_p, logs_p, x_mask = self.enc_p(
905
- x, x_lengths, tone, language, bert, ja_bert, en_bert, style_vec, sid, g=g
906
- )
907
- z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
908
- z_p = self.flow(z, y_mask, g=g)
909
-
910
- with torch.no_grad():
911
- # negative cross-entropy
912
- s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
913
- neg_cent1 = torch.sum(
914
- -0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True
915
- ) # [b, 1, t_s]
916
- neg_cent2 = torch.matmul(
917
- -0.5 * (z_p**2).transpose(1, 2), s_p_sq_r
918
- ) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
919
- neg_cent3 = torch.matmul(
920
- z_p.transpose(1, 2), (m_p * s_p_sq_r)
921
- ) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
922
- neg_cent4 = torch.sum(
923
- -0.5 * (m_p**2) * s_p_sq_r, [1], keepdim=True
924
- ) # [b, 1, t_s]
925
- neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
926
- if self.use_noise_scaled_mas:
927
- epsilon = (
928
- torch.std(neg_cent)
929
- * torch.randn_like(neg_cent)
930
- * self.current_mas_noise_scale
931
- )
932
- neg_cent = neg_cent + epsilon
933
-
934
- attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
935
- attn = (
936
- monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1))
937
- .unsqueeze(1)
938
- .detach()
939
- )
940
-
941
- w = attn.sum(2)
942
-
943
- l_length_sdp = self.sdp(x, x_mask, w, g=g)
944
- l_length_sdp = l_length_sdp / torch.sum(x_mask)
945
-
946
- logw_ = torch.log(w + 1e-6) * x_mask
947
- logw = self.dp(x, x_mask, g=g)
948
- # logw_sdp = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=1.0)
949
- l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(
950
- x_mask
951
- ) # for averaging
952
- # l_length_sdp += torch.sum((logw_sdp - logw_) ** 2, [1, 2]) / torch.sum(x_mask)
953
-
954
- l_length = l_length_dp + l_length_sdp
955
-
956
- # expand prior
957
- m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
958
- logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
959
-
960
- z_slice, ids_slice = commons.rand_slice_segments(
961
- z, y_lengths, self.segment_size
962
- )
963
- o = self.dec(z_slice, g=g)
964
- return (
965
- o,
966
- l_length,
967
- attn,
968
- ids_slice,
969
- x_mask,
970
- y_mask,
971
- (z, z_p, m_p, logs_p, m_q, logs_q),
972
- (x, logw, logw_),
973
- )
974
-
975
- def infer(
976
- self,
977
- x,
978
- x_lengths,
979
- sid,
980
- tone,
981
- language,
982
- bert,
983
- ja_bert,
984
- en_bert,
985
- style_vec,
986
- noise_scale=0.667,
987
- length_scale=1,
988
- noise_scale_w=0.8,
989
- max_len=None,
990
- sdp_ratio=0,
991
- y=None,
992
- ):
993
- # x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert)
994
- # g = self.gst(y)
995
- if self.n_speakers > 0:
996
- g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
997
- else:
998
- g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
999
- x, m_p, logs_p, x_mask = self.enc_p(
1000
- x, x_lengths, tone, language, bert, ja_bert, en_bert, style_vec, sid, g=g
1001
- )
1002
- logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (
1003
- sdp_ratio
1004
- ) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio)
1005
- w = torch.exp(logw) * x_mask * length_scale
1006
- w_ceil = torch.ceil(w)
1007
- y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
1008
- y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(
1009
- x_mask.dtype
1010
- )
1011
- attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
1012
- attn = commons.generate_path(w_ceil, attn_mask)
1013
-
1014
- m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(
1015
- 1, 2
1016
- ) # [b, t', t], [b, t, d] -> [b, d, t']
1017
- logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(
1018
- 1, 2
1019
- ) # [b, t', t], [b, t, d] -> [b, d, t']
1020
-
1021
- z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
1022
- z = self.flow(z_p, y_mask, g=g, reverse=True)
1023
- o = self.dec((z * y_mask)[:, :, :max_len], g=g)
1024
- return o, attn, y_mask, (z, z_p, m_p, logs_p)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models_jp_extra.py DELETED
@@ -1,1071 +0,0 @@
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
-
18
- class DurationDiscriminator(nn.Module): # vits2
19
- def __init__(
20
- self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0
21
- ):
22
- super().__init__()
23
-
24
- self.in_channels = in_channels
25
- self.filter_channels = filter_channels
26
- self.kernel_size = kernel_size
27
- self.p_dropout = p_dropout
28
- self.gin_channels = gin_channels
29
-
30
- self.drop = nn.Dropout(p_dropout)
31
- self.conv_1 = nn.Conv1d(
32
- in_channels, filter_channels, kernel_size, padding=kernel_size // 2
33
- )
34
- self.norm_1 = modules.LayerNorm(filter_channels)
35
- self.conv_2 = nn.Conv1d(
36
- filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
37
- )
38
- self.norm_2 = modules.LayerNorm(filter_channels)
39
- self.dur_proj = nn.Conv1d(1, filter_channels, 1)
40
-
41
- self.LSTM = nn.LSTM(
42
- 2 * filter_channels, filter_channels, batch_first=True, bidirectional=True
43
- )
44
-
45
- if gin_channels != 0:
46
- self.cond = nn.Conv1d(gin_channels, in_channels, 1)
47
-
48
- self.output_layer = nn.Sequential(
49
- nn.Linear(2 * filter_channels, 1), nn.Sigmoid()
50
- )
51
-
52
- def forward_probability(self, x, dur):
53
- dur = self.dur_proj(dur)
54
- x = torch.cat([x, dur], dim=1)
55
- x = x.transpose(1, 2)
56
- x, _ = self.LSTM(x)
57
- output_prob = self.output_layer(x)
58
- return output_prob
59
-
60
- def forward(self, x, x_mask, dur_r, dur_hat, g=None):
61
- x = torch.detach(x)
62
- if g is not None:
63
- g = torch.detach(g)
64
- x = x + self.cond(g)
65
- x = self.conv_1(x * x_mask)
66
- x = torch.relu(x)
67
- x = self.norm_1(x)
68
- x = self.drop(x)
69
- x = self.conv_2(x * x_mask)
70
- x = torch.relu(x)
71
- x = self.norm_2(x)
72
- x = self.drop(x)
73
-
74
- output_probs = []
75
- for dur in [dur_r, dur_hat]:
76
- output_prob = self.forward_probability(x, dur)
77
- output_probs.append(output_prob)
78
-
79
- return output_probs
80
-
81
-
82
- class TransformerCouplingBlock(nn.Module):
83
- def __init__(
84
- self,
85
- channels,
86
- hidden_channels,
87
- filter_channels,
88
- n_heads,
89
- n_layers,
90
- kernel_size,
91
- p_dropout,
92
- n_flows=4,
93
- gin_channels=0,
94
- share_parameter=False,
95
- ):
96
- super().__init__()
97
- self.channels = channels
98
- self.hidden_channels = hidden_channels
99
- self.kernel_size = kernel_size
100
- self.n_layers = n_layers
101
- self.n_flows = n_flows
102
- self.gin_channels = gin_channels
103
-
104
- self.flows = nn.ModuleList()
105
-
106
- self.wn = (
107
- attentions.FFT(
108
- hidden_channels,
109
- filter_channels,
110
- n_heads,
111
- n_layers,
112
- kernel_size,
113
- p_dropout,
114
- isflow=True,
115
- gin_channels=self.gin_channels,
116
- )
117
- if share_parameter
118
- else None
119
- )
120
-
121
- for i in range(n_flows):
122
- self.flows.append(
123
- modules.TransformerCouplingLayer(
124
- channels,
125
- hidden_channels,
126
- kernel_size,
127
- n_layers,
128
- n_heads,
129
- p_dropout,
130
- filter_channels,
131
- mean_only=True,
132
- wn_sharing_parameter=self.wn,
133
- gin_channels=self.gin_channels,
134
- )
135
- )
136
- self.flows.append(modules.Flip())
137
-
138
- def forward(self, x, x_mask, g=None, reverse=False):
139
- if not reverse:
140
- for flow in self.flows:
141
- x, _ = flow(x, x_mask, g=g, reverse=reverse)
142
- else:
143
- for flow in reversed(self.flows):
144
- x = flow(x, x_mask, g=g, reverse=reverse)
145
- return x
146
-
147
-
148
- class StochasticDurationPredictor(nn.Module):
149
- def __init__(
150
- self,
151
- in_channels,
152
- filter_channels,
153
- kernel_size,
154
- p_dropout,
155
- n_flows=4,
156
- gin_channels=0,
157
- ):
158
- super().__init__()
159
- filter_channels = in_channels # it needs to be removed from future version.
160
- self.in_channels = in_channels
161
- self.filter_channels = filter_channels
162
- self.kernel_size = kernel_size
163
- self.p_dropout = p_dropout
164
- self.n_flows = n_flows
165
- self.gin_channels = gin_channels
166
-
167
- self.log_flow = modules.Log()
168
- self.flows = nn.ModuleList()
169
- self.flows.append(modules.ElementwiseAffine(2))
170
- for i in range(n_flows):
171
- self.flows.append(
172
- modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
173
- )
174
- self.flows.append(modules.Flip())
175
-
176
- self.post_pre = nn.Conv1d(1, filter_channels, 1)
177
- self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
178
- self.post_convs = modules.DDSConv(
179
- filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
180
- )
181
- self.post_flows = nn.ModuleList()
182
- self.post_flows.append(modules.ElementwiseAffine(2))
183
- for i in range(4):
184
- self.post_flows.append(
185
- modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
186
- )
187
- self.post_flows.append(modules.Flip())
188
-
189
- self.pre = nn.Conv1d(in_channels, filter_channels, 1)
190
- self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
191
- self.convs = modules.DDSConv(
192
- filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
193
- )
194
- if gin_channels != 0:
195
- self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
196
-
197
- def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
198
- x = torch.detach(x)
199
- x = self.pre(x)
200
- if g is not None:
201
- g = torch.detach(g)
202
- x = x + self.cond(g)
203
- x = self.convs(x, x_mask)
204
- x = self.proj(x) * x_mask
205
-
206
- if not reverse:
207
- flows = self.flows
208
- assert w is not None
209
-
210
- logdet_tot_q = 0
211
- h_w = self.post_pre(w)
212
- h_w = self.post_convs(h_w, x_mask)
213
- h_w = self.post_proj(h_w) * x_mask
214
- e_q = (
215
- torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype)
216
- * x_mask
217
- )
218
- z_q = e_q
219
- for flow in self.post_flows:
220
- z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
221
- logdet_tot_q += logdet_q
222
- z_u, z1 = torch.split(z_q, [1, 1], 1)
223
- u = torch.sigmoid(z_u) * x_mask
224
- z0 = (w - u) * x_mask
225
- logdet_tot_q += torch.sum(
226
- (F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2]
227
- )
228
- logq = (
229
- torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q**2)) * x_mask, [1, 2])
230
- - logdet_tot_q
231
- )
232
-
233
- logdet_tot = 0
234
- z0, logdet = self.log_flow(z0, x_mask)
235
- logdet_tot += logdet
236
- z = torch.cat([z0, z1], 1)
237
- for flow in flows:
238
- z, logdet = flow(z, x_mask, g=x, reverse=reverse)
239
- logdet_tot = logdet_tot + logdet
240
- nll = (
241
- torch.sum(0.5 * (math.log(2 * math.pi) + (z**2)) * x_mask, [1, 2])
242
- - logdet_tot
243
- )
244
- return nll + logq # [b]
245
- else:
246
- flows = list(reversed(self.flows))
247
- flows = flows[:-2] + [flows[-1]] # remove a useless vflow
248
- z = (
249
- torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype)
250
- * noise_scale
251
- )
252
- for flow in flows:
253
- z = flow(z, x_mask, g=x, reverse=reverse)
254
- z0, z1 = torch.split(z, [1, 1], 1)
255
- logw = z0
256
- return logw
257
-
258
-
259
- class DurationPredictor(nn.Module):
260
- def __init__(
261
- self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0
262
- ):
263
- super().__init__()
264
-
265
- self.in_channels = in_channels
266
- self.filter_channels = filter_channels
267
- self.kernel_size = kernel_size
268
- self.p_dropout = p_dropout
269
- self.gin_channels = gin_channels
270
-
271
- self.drop = nn.Dropout(p_dropout)
272
- self.conv_1 = nn.Conv1d(
273
- in_channels, filter_channels, kernel_size, padding=kernel_size // 2
274
- )
275
- self.norm_1 = modules.LayerNorm(filter_channels)
276
- self.conv_2 = nn.Conv1d(
277
- filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
278
- )
279
- self.norm_2 = modules.LayerNorm(filter_channels)
280
- self.proj = nn.Conv1d(filter_channels, 1, 1)
281
-
282
- if gin_channels != 0:
283
- self.cond = nn.Conv1d(gin_channels, in_channels, 1)
284
-
285
- def forward(self, x, x_mask, g=None):
286
- x = torch.detach(x)
287
- if g is not None:
288
- g = torch.detach(g)
289
- x = x + self.cond(g)
290
- x = self.conv_1(x * x_mask)
291
- x = torch.relu(x)
292
- x = self.norm_1(x)
293
- x = self.drop(x)
294
- x = self.conv_2(x * x_mask)
295
- x = torch.relu(x)
296
- x = self.norm_2(x)
297
- x = self.drop(x)
298
- x = self.proj(x * x_mask)
299
- return x * x_mask
300
-
301
-
302
- class Bottleneck(nn.Sequential):
303
- def __init__(self, in_dim, hidden_dim):
304
- c_fc1 = nn.Linear(in_dim, hidden_dim, bias=False)
305
- c_fc2 = nn.Linear(in_dim, hidden_dim, bias=False)
306
- super().__init__(*[c_fc1, c_fc2])
307
-
308
-
309
- class Block(nn.Module):
310
- def __init__(self, in_dim, hidden_dim) -> None:
311
- super().__init__()
312
- self.norm = nn.LayerNorm(in_dim)
313
- self.mlp = MLP(in_dim, hidden_dim)
314
-
315
- def forward(self, x: torch.Tensor) -> torch.Tensor:
316
- x = x + self.mlp(self.norm(x))
317
- return x
318
-
319
-
320
- class MLP(nn.Module):
321
- def __init__(self, in_dim, hidden_dim):
322
- super().__init__()
323
- self.c_fc1 = nn.Linear(in_dim, hidden_dim, bias=False)
324
- self.c_fc2 = nn.Linear(in_dim, hidden_dim, bias=False)
325
- self.c_proj = nn.Linear(hidden_dim, in_dim, bias=False)
326
-
327
- def forward(self, x: torch.Tensor):
328
- x = F.silu(self.c_fc1(x)) * self.c_fc2(x)
329
- x = self.c_proj(x)
330
- return x
331
-
332
-
333
- class TextEncoder(nn.Module):
334
- def __init__(
335
- self,
336
- n_vocab,
337
- out_channels,
338
- hidden_channels,
339
- filter_channels,
340
- n_heads,
341
- n_layers,
342
- kernel_size,
343
- p_dropout,
344
- gin_channels=0,
345
- ):
346
- super().__init__()
347
- self.n_vocab = n_vocab
348
- self.out_channels = out_channels
349
- self.hidden_channels = hidden_channels
350
- self.filter_channels = filter_channels
351
- self.n_heads = n_heads
352
- self.n_layers = n_layers
353
- self.kernel_size = kernel_size
354
- self.p_dropout = p_dropout
355
- self.gin_channels = gin_channels
356
- self.emb = nn.Embedding(len(symbols), hidden_channels)
357
- nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
358
- self.tone_emb = nn.Embedding(num_tones, hidden_channels)
359
- nn.init.normal_(self.tone_emb.weight, 0.0, hidden_channels**-0.5)
360
- self.language_emb = nn.Embedding(num_languages, hidden_channels)
361
- nn.init.normal_(self.language_emb.weight, 0.0, hidden_channels**-0.5)
362
- self.bert_proj = nn.Conv1d(1024, hidden_channels, 1)
363
-
364
- # Remove emo_vq since it's not working well.
365
- self.style_proj = nn.Linear(256, hidden_channels)
366
-
367
- self.encoder = attentions.Encoder(
368
- hidden_channels,
369
- filter_channels,
370
- n_heads,
371
- n_layers,
372
- kernel_size,
373
- p_dropout,
374
- gin_channels=self.gin_channels,
375
- )
376
- self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
377
-
378
- def forward(self, x, x_lengths, tone, language, bert, style_vec, g=None):
379
- bert_emb = self.bert_proj(bert).transpose(1, 2)
380
- style_emb = self.style_proj(style_vec.unsqueeze(1))
381
- x = (
382
- self.emb(x)
383
- + self.tone_emb(tone)
384
- + self.language_emb(language)
385
- + bert_emb
386
- + style_emb
387
- ) * math.sqrt(
388
- self.hidden_channels
389
- ) # [b, t, h]
390
- x = torch.transpose(x, 1, -1) # [b, h, t]
391
- x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
392
- x.dtype
393
- )
394
-
395
- x = self.encoder(x * x_mask, x_mask, g=g)
396
- stats = self.proj(x) * x_mask
397
-
398
- m, logs = torch.split(stats, self.out_channels, dim=1)
399
- return x, m, logs, x_mask
400
-
401
-
402
- class ResidualCouplingBlock(nn.Module):
403
- def __init__(
404
- self,
405
- channels,
406
- hidden_channels,
407
- kernel_size,
408
- dilation_rate,
409
- n_layers,
410
- n_flows=4,
411
- gin_channels=0,
412
- ):
413
- super().__init__()
414
- self.channels = channels
415
- self.hidden_channels = hidden_channels
416
- self.kernel_size = kernel_size
417
- self.dilation_rate = dilation_rate
418
- self.n_layers = n_layers
419
- self.n_flows = n_flows
420
- self.gin_channels = gin_channels
421
-
422
- self.flows = nn.ModuleList()
423
- for i in range(n_flows):
424
- self.flows.append(
425
- modules.ResidualCouplingLayer(
426
- channels,
427
- hidden_channels,
428
- kernel_size,
429
- dilation_rate,
430
- n_layers,
431
- gin_channels=gin_channels,
432
- mean_only=True,
433
- )
434
- )
435
- self.flows.append(modules.Flip())
436
-
437
- def forward(self, x, x_mask, g=None, reverse=False):
438
- if not reverse:
439
- for flow in self.flows:
440
- x, _ = flow(x, x_mask, g=g, reverse=reverse)
441
- else:
442
- for flow in reversed(self.flows):
443
- x = flow(x, x_mask, g=g, reverse=reverse)
444
- return x
445
-
446
-
447
- class PosteriorEncoder(nn.Module):
448
- def __init__(
449
- self,
450
- in_channels,
451
- out_channels,
452
- hidden_channels,
453
- kernel_size,
454
- dilation_rate,
455
- n_layers,
456
- gin_channels=0,
457
- ):
458
- super().__init__()
459
- self.in_channels = in_channels
460
- self.out_channels = out_channels
461
- self.hidden_channels = hidden_channels
462
- self.kernel_size = kernel_size
463
- self.dilation_rate = dilation_rate
464
- self.n_layers = n_layers
465
- self.gin_channels = gin_channels
466
-
467
- self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
468
- self.enc = modules.WN(
469
- hidden_channels,
470
- kernel_size,
471
- dilation_rate,
472
- n_layers,
473
- gin_channels=gin_channels,
474
- )
475
- self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
476
-
477
- def forward(self, x, x_lengths, g=None):
478
- x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
479
- x.dtype
480
- )
481
- x = self.pre(x) * x_mask
482
- x = self.enc(x, x_mask, g=g)
483
- stats = self.proj(x) * x_mask
484
- m, logs = torch.split(stats, self.out_channels, dim=1)
485
- z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
486
- return z, m, logs, x_mask
487
-
488
-
489
- class Generator(torch.nn.Module):
490
- def __init__(
491
- self,
492
- initial_channel,
493
- resblock,
494
- resblock_kernel_sizes,
495
- resblock_dilation_sizes,
496
- upsample_rates,
497
- upsample_initial_channel,
498
- upsample_kernel_sizes,
499
- gin_channels=0,
500
- ):
501
- super(Generator, self).__init__()
502
- self.num_kernels = len(resblock_kernel_sizes)
503
- self.num_upsamples = len(upsample_rates)
504
- self.conv_pre = Conv1d(
505
- initial_channel, upsample_initial_channel, 7, 1, padding=3
506
- )
507
- resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
508
-
509
- self.ups = nn.ModuleList()
510
- for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
511
- self.ups.append(
512
- weight_norm(
513
- ConvTranspose1d(
514
- upsample_initial_channel // (2**i),
515
- upsample_initial_channel // (2 ** (i + 1)),
516
- k,
517
- u,
518
- padding=(k - u) // 2,
519
- )
520
- )
521
- )
522
-
523
- self.resblocks = nn.ModuleList()
524
- for i in range(len(self.ups)):
525
- ch = upsample_initial_channel // (2 ** (i + 1))
526
- for j, (k, d) in enumerate(
527
- zip(resblock_kernel_sizes, resblock_dilation_sizes)
528
- ):
529
- self.resblocks.append(resblock(ch, k, d))
530
-
531
- self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
532
- self.ups.apply(init_weights)
533
-
534
- if gin_channels != 0:
535
- self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
536
-
537
- def forward(self, x, g=None):
538
- x = self.conv_pre(x)
539
- if g is not None:
540
- x = x + self.cond(g)
541
-
542
- for i in range(self.num_upsamples):
543
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
544
- x = self.ups[i](x)
545
- xs = None
546
- for j in range(self.num_kernels):
547
- if xs is None:
548
- xs = self.resblocks[i * self.num_kernels + j](x)
549
- else:
550
- xs += self.resblocks[i * self.num_kernels + j](x)
551
- x = xs / self.num_kernels
552
- x = F.leaky_relu(x)
553
- x = self.conv_post(x)
554
- x = torch.tanh(x)
555
-
556
- return x
557
-
558
- def remove_weight_norm(self):
559
- print("Removing weight norm...")
560
- for layer in self.ups:
561
- remove_weight_norm(layer)
562
- for layer in self.resblocks:
563
- layer.remove_weight_norm()
564
-
565
-
566
- class DiscriminatorP(torch.nn.Module):
567
- def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
568
- super(DiscriminatorP, self).__init__()
569
- self.period = period
570
- self.use_spectral_norm = use_spectral_norm
571
- norm_f = weight_norm if use_spectral_norm is False else spectral_norm
572
- self.convs = nn.ModuleList(
573
- [
574
- norm_f(
575
- Conv2d(
576
- 1,
577
- 32,
578
- (kernel_size, 1),
579
- (stride, 1),
580
- padding=(get_padding(kernel_size, 1), 0),
581
- )
582
- ),
583
- norm_f(
584
- Conv2d(
585
- 32,
586
- 128,
587
- (kernel_size, 1),
588
- (stride, 1),
589
- padding=(get_padding(kernel_size, 1), 0),
590
- )
591
- ),
592
- norm_f(
593
- Conv2d(
594
- 128,
595
- 512,
596
- (kernel_size, 1),
597
- (stride, 1),
598
- padding=(get_padding(kernel_size, 1), 0),
599
- )
600
- ),
601
- norm_f(
602
- Conv2d(
603
- 512,
604
- 1024,
605
- (kernel_size, 1),
606
- (stride, 1),
607
- padding=(get_padding(kernel_size, 1), 0),
608
- )
609
- ),
610
- norm_f(
611
- Conv2d(
612
- 1024,
613
- 1024,
614
- (kernel_size, 1),
615
- 1,
616
- padding=(get_padding(kernel_size, 1), 0),
617
- )
618
- ),
619
- ]
620
- )
621
- self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
622
-
623
- def forward(self, x):
624
- fmap = []
625
-
626
- # 1d to 2d
627
- b, c, t = x.shape
628
- if t % self.period != 0: # pad first
629
- n_pad = self.period - (t % self.period)
630
- x = F.pad(x, (0, n_pad), "reflect")
631
- t = t + n_pad
632
- x = x.view(b, c, t // self.period, self.period)
633
-
634
- for layer in self.convs:
635
- x = layer(x)
636
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
637
- fmap.append(x)
638
- x = self.conv_post(x)
639
- fmap.append(x)
640
- x = torch.flatten(x, 1, -1)
641
-
642
- return x, fmap
643
-
644
-
645
- class DiscriminatorS(torch.nn.Module):
646
- def __init__(self, use_spectral_norm=False):
647
- super(DiscriminatorS, self).__init__()
648
- norm_f = weight_norm if use_spectral_norm is False else spectral_norm
649
- self.convs = nn.ModuleList(
650
- [
651
- norm_f(Conv1d(1, 16, 15, 1, padding=7)),
652
- norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
653
- norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
654
- norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
655
- norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
656
- norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
657
- ]
658
- )
659
- self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
660
-
661
- def forward(self, x):
662
- fmap = []
663
-
664
- for layer in self.convs:
665
- x = layer(x)
666
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
667
- fmap.append(x)
668
- x = self.conv_post(x)
669
- fmap.append(x)
670
- x = torch.flatten(x, 1, -1)
671
-
672
- return x, fmap
673
-
674
-
675
- class MultiPeriodDiscriminator(torch.nn.Module):
676
- def __init__(self, use_spectral_norm=False):
677
- super(MultiPeriodDiscriminator, self).__init__()
678
- periods = [2, 3, 5, 7, 11]
679
-
680
- discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
681
- discs = discs + [
682
- DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
683
- ]
684
- self.discriminators = nn.ModuleList(discs)
685
-
686
- def forward(self, y, y_hat):
687
- y_d_rs = []
688
- y_d_gs = []
689
- fmap_rs = []
690
- fmap_gs = []
691
- for i, d in enumerate(self.discriminators):
692
- y_d_r, fmap_r = d(y)
693
- y_d_g, fmap_g = d(y_hat)
694
- y_d_rs.append(y_d_r)
695
- y_d_gs.append(y_d_g)
696
- fmap_rs.append(fmap_r)
697
- fmap_gs.append(fmap_g)
698
-
699
- return y_d_rs, y_d_gs, fmap_rs, fmap_gs
700
-
701
-
702
- class WavLMDiscriminator(nn.Module):
703
- """docstring for Discriminator."""
704
-
705
- def __init__(
706
- self, slm_hidden=768, slm_layers=13, initial_channel=64, use_spectral_norm=False
707
- ):
708
- super(WavLMDiscriminator, self).__init__()
709
- norm_f = weight_norm if use_spectral_norm == False else spectral_norm
710
- self.pre = norm_f(
711
- Conv1d(slm_hidden * slm_layers, initial_channel, 1, 1, padding=0)
712
- )
713
-
714
- self.convs = nn.ModuleList(
715
- [
716
- norm_f(
717
- nn.Conv1d(
718
- initial_channel, initial_channel * 2, kernel_size=5, padding=2
719
- )
720
- ),
721
- norm_f(
722
- nn.Conv1d(
723
- initial_channel * 2,
724
- initial_channel * 4,
725
- kernel_size=5,
726
- padding=2,
727
- )
728
- ),
729
- norm_f(
730
- nn.Conv1d(initial_channel * 4, initial_channel * 4, 5, 1, padding=2)
731
- ),
732
- ]
733
- )
734
-
735
- self.conv_post = norm_f(Conv1d(initial_channel * 4, 1, 3, 1, padding=1))
736
-
737
- def forward(self, x):
738
- x = self.pre(x)
739
-
740
- fmap = []
741
- for l in self.convs:
742
- x = l(x)
743
- x = F.leaky_relu(x, modules.LRELU_SLOPE)
744
- fmap.append(x)
745
- x = self.conv_post(x)
746
- x = torch.flatten(x, 1, -1)
747
-
748
- return x
749
-
750
-
751
- class ReferenceEncoder(nn.Module):
752
- """
753
- inputs --- [N, Ty/r, n_mels*r] mels
754
- outputs --- [N, ref_enc_gru_size]
755
- """
756
-
757
- def __init__(self, spec_channels, gin_channels=0):
758
- super().__init__()
759
- self.spec_channels = spec_channels
760
- ref_enc_filters = [32, 32, 64, 64, 128, 128]
761
- K = len(ref_enc_filters)
762
- filters = [1] + ref_enc_filters
763
- convs = [
764
- weight_norm(
765
- nn.Conv2d(
766
- in_channels=filters[i],
767
- out_channels=filters[i + 1],
768
- kernel_size=(3, 3),
769
- stride=(2, 2),
770
- padding=(1, 1),
771
- )
772
- )
773
- for i in range(K)
774
- ]
775
- self.convs = nn.ModuleList(convs)
776
- # self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)]) # noqa: E501
777
-
778
- out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K)
779
- self.gru = nn.GRU(
780
- input_size=ref_enc_filters[-1] * out_channels,
781
- hidden_size=256 // 2,
782
- batch_first=True,
783
- )
784
- self.proj = nn.Linear(128, gin_channels)
785
-
786
- def forward(self, inputs, mask=None):
787
- N = inputs.size(0)
788
- out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs]
789
- for conv in self.convs:
790
- out = conv(out)
791
- # out = wn(out)
792
- out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K]
793
-
794
- out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
795
- T = out.size(1)
796
- N = out.size(0)
797
- out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
798
-
799
- self.gru.flatten_parameters()
800
- memory, out = self.gru(out) # out --- [1, N, 128]
801
-
802
- return self.proj(out.squeeze(0))
803
-
804
- def calculate_channels(self, L, kernel_size, stride, pad, n_convs):
805
- for i in range(n_convs):
806
- L = (L - kernel_size + 2 * pad) // stride + 1
807
- return L
808
-
809
-
810
- class SynthesizerTrn(nn.Module):
811
- """
812
- Synthesizer for Training
813
- """
814
-
815
- def __init__(
816
- self,
817
- n_vocab,
818
- spec_channels,
819
- segment_size,
820
- inter_channels,
821
- hidden_channels,
822
- filter_channels,
823
- n_heads,
824
- n_layers,
825
- kernel_size,
826
- p_dropout,
827
- resblock,
828
- resblock_kernel_sizes,
829
- resblock_dilation_sizes,
830
- upsample_rates,
831
- upsample_initial_channel,
832
- upsample_kernel_sizes,
833
- n_speakers=256,
834
- gin_channels=256,
835
- use_sdp=True,
836
- n_flow_layer=4,
837
- n_layers_trans_flow=6,
838
- flow_share_parameter=False,
839
- use_transformer_flow=True,
840
- **kwargs
841
- ):
842
- super().__init__()
843
- self.n_vocab = n_vocab
844
- self.spec_channels = spec_channels
845
- self.inter_channels = inter_channels
846
- self.hidden_channels = hidden_channels
847
- self.filter_channels = filter_channels
848
- self.n_heads = n_heads
849
- self.n_layers = n_layers
850
- self.kernel_size = kernel_size
851
- self.p_dropout = p_dropout
852
- self.resblock = resblock
853
- self.resblock_kernel_sizes = resblock_kernel_sizes
854
- self.resblock_dilation_sizes = resblock_dilation_sizes
855
- self.upsample_rates = upsample_rates
856
- self.upsample_initial_channel = upsample_initial_channel
857
- self.upsample_kernel_sizes = upsample_kernel_sizes
858
- self.segment_size = segment_size
859
- self.n_speakers = n_speakers
860
- self.gin_channels = gin_channels
861
- self.n_layers_trans_flow = n_layers_trans_flow
862
- self.use_spk_conditioned_encoder = kwargs.get(
863
- "use_spk_conditioned_encoder", True
864
- )
865
- self.use_sdp = use_sdp
866
- self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False)
867
- self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01)
868
- self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6)
869
- self.current_mas_noise_scale = self.mas_noise_scale_initial
870
- if self.use_spk_conditioned_encoder and gin_channels > 0:
871
- self.enc_gin_channels = gin_channels
872
- self.enc_p = TextEncoder(
873
- n_vocab,
874
- inter_channels,
875
- hidden_channels,
876
- filter_channels,
877
- n_heads,
878
- n_layers,
879
- kernel_size,
880
- p_dropout,
881
- gin_channels=self.enc_gin_channels,
882
- )
883
- self.dec = Generator(
884
- inter_channels,
885
- resblock,
886
- resblock_kernel_sizes,
887
- resblock_dilation_sizes,
888
- upsample_rates,
889
- upsample_initial_channel,
890
- upsample_kernel_sizes,
891
- gin_channels=gin_channels,
892
- )
893
- self.enc_q = PosteriorEncoder(
894
- spec_channels,
895
- inter_channels,
896
- hidden_channels,
897
- 5,
898
- 1,
899
- 16,
900
- gin_channels=gin_channels,
901
- )
902
- if use_transformer_flow:
903
- self.flow = TransformerCouplingBlock(
904
- inter_channels,
905
- hidden_channels,
906
- filter_channels,
907
- n_heads,
908
- n_layers_trans_flow,
909
- 5,
910
- p_dropout,
911
- n_flow_layer,
912
- gin_channels=gin_channels,
913
- share_parameter=flow_share_parameter,
914
- )
915
- else:
916
- self.flow = ResidualCouplingBlock(
917
- inter_channels,
918
- hidden_channels,
919
- 5,
920
- 1,
921
- n_flow_layer,
922
- gin_channels=gin_channels,
923
- )
924
- self.sdp = StochasticDurationPredictor(
925
- hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels
926
- )
927
- self.dp = DurationPredictor(
928
- hidden_channels, 256, 3, 0.5, gin_channels=gin_channels
929
- )
930
-
931
- if n_speakers >= 1:
932
- self.emb_g = nn.Embedding(n_speakers, gin_channels)
933
- else:
934
- self.ref_enc = ReferenceEncoder(spec_channels, gin_channels)
935
-
936
- def forward(
937
- self,
938
- x,
939
- x_lengths,
940
- y,
941
- y_lengths,
942
- sid,
943
- tone,
944
- language,
945
- bert,
946
- style_vec,
947
- ):
948
- if self.n_speakers > 0:
949
- g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
950
- else:
951
- g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
952
- x, m_p, logs_p, x_mask = self.enc_p(
953
- x, x_lengths, tone, language, bert, style_vec, g=g
954
- )
955
- z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
956
- z_p = self.flow(z, y_mask, g=g)
957
-
958
- with torch.no_grad():
959
- # negative cross-entropy
960
- s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
961
- neg_cent1 = torch.sum(
962
- -0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True
963
- ) # [b, 1, t_s]
964
- neg_cent2 = torch.matmul(
965
- -0.5 * (z_p**2).transpose(1, 2), s_p_sq_r
966
- ) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
967
- neg_cent3 = torch.matmul(
968
- z_p.transpose(1, 2), (m_p * s_p_sq_r)
969
- ) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
970
- neg_cent4 = torch.sum(
971
- -0.5 * (m_p**2) * s_p_sq_r, [1], keepdim=True
972
- ) # [b, 1, t_s]
973
- neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
974
- if self.use_noise_scaled_mas:
975
- epsilon = (
976
- torch.std(neg_cent)
977
- * torch.randn_like(neg_cent)
978
- * self.current_mas_noise_scale
979
- )
980
- neg_cent = neg_cent + epsilon
981
-
982
- attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
983
- attn = (
984
- monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1))
985
- .unsqueeze(1)
986
- .detach()
987
- )
988
-
989
- w = attn.sum(2)
990
-
991
- l_length_sdp = self.sdp(x, x_mask, w, g=g)
992
- l_length_sdp = l_length_sdp / torch.sum(x_mask)
993
-
994
- logw_ = torch.log(w + 1e-6) * x_mask
995
- logw = self.dp(x, x_mask, g=g)
996
- # logw_sdp = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=1.0)
997
- l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(
998
- x_mask
999
- ) # for averaging
1000
- # l_length_sdp += torch.sum((logw_sdp - logw_) ** 2, [1, 2]) / torch.sum(x_mask)
1001
-
1002
- l_length = l_length_dp + l_length_sdp
1003
-
1004
- # expand prior
1005
- m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
1006
- logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
1007
-
1008
- z_slice, ids_slice = commons.rand_slice_segments(
1009
- z, y_lengths, self.segment_size
1010
- )
1011
- o = self.dec(z_slice, g=g)
1012
- return (
1013
- o,
1014
- l_length,
1015
- attn,
1016
- ids_slice,
1017
- x_mask,
1018
- y_mask,
1019
- (z, z_p, m_p, logs_p, m_q, logs_q),
1020
- (x, logw, logw_), # , logw_sdp),
1021
- g,
1022
- )
1023
-
1024
- def infer(
1025
- self,
1026
- x,
1027
- x_lengths,
1028
- sid,
1029
- tone,
1030
- language,
1031
- bert,
1032
- style_vec,
1033
- noise_scale=0.667,
1034
- length_scale=1,
1035
- noise_scale_w=0.8,
1036
- max_len=None,
1037
- sdp_ratio=0,
1038
- y=None,
1039
- ):
1040
- # x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert)
1041
- # g = self.gst(y)
1042
- if self.n_speakers > 0:
1043
- g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
1044
- else:
1045
- g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
1046
- x, m_p, logs_p, x_mask = self.enc_p(
1047
- x, x_lengths, tone, language, bert, style_vec, g=g
1048
- )
1049
- logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (
1050
- sdp_ratio
1051
- ) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio)
1052
- w = torch.exp(logw) * x_mask * length_scale
1053
- w_ceil = torch.ceil(w)
1054
- y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
1055
- y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(
1056
- x_mask.dtype
1057
- )
1058
- attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
1059
- attn = commons.generate_path(w_ceil, attn_mask)
1060
-
1061
- m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(
1062
- 1, 2
1063
- ) # [b, t', t], [b, t, d] -> [b, d, t']
1064
- logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(
1065
- 1, 2
1066
- ) # [b, t', t], [b, t, d] -> [b, d, t']
1067
-
1068
- z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
1069
- z = self.flow(z_p, y_mask, g=g, reverse=True)
1070
- o = self.dec((z * y_mask)[:, :, :max_len], g=g)
1071
- return o, attn, y_mask, (z, z_p, m_p, logs_p)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
modules.py DELETED
@@ -1,581 +0,0 @@
1
- import math
2
- import warnings
3
-
4
- import torch
5
- from torch import nn
6
- from torch.nn import Conv1d
7
- from torch.nn import functional as F
8
- from torch.nn.utils import remove_weight_norm, weight_norm
9
-
10
- import commons
11
- from attentions import Encoder
12
- from commons import get_padding, init_weights
13
- from transforms import piecewise_rational_quadratic_transform
14
-
15
- LRELU_SLOPE = 0.1
16
-
17
-
18
- class LayerNorm(nn.Module):
19
- def __init__(self, channels, eps=1e-5):
20
- super().__init__()
21
- self.channels = channels
22
- self.eps = eps
23
-
24
- self.gamma = nn.Parameter(torch.ones(channels))
25
- self.beta = nn.Parameter(torch.zeros(channels))
26
-
27
- def forward(self, x):
28
- x = x.transpose(1, -1)
29
- x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
30
- return x.transpose(1, -1)
31
-
32
-
33
- class ConvReluNorm(nn.Module):
34
- def __init__(
35
- self,
36
- in_channels,
37
- hidden_channels,
38
- out_channels,
39
- kernel_size,
40
- n_layers,
41
- p_dropout,
42
- ):
43
- super().__init__()
44
- self.in_channels = in_channels
45
- self.hidden_channels = hidden_channels
46
- self.out_channels = out_channels
47
- self.kernel_size = kernel_size
48
- self.n_layers = n_layers
49
- self.p_dropout = p_dropout
50
- assert n_layers > 1, "Number of layers should be larger than 0."
51
-
52
- self.conv_layers = nn.ModuleList()
53
- self.norm_layers = nn.ModuleList()
54
- self.conv_layers.append(
55
- nn.Conv1d(
56
- in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
57
- )
58
- )
59
- self.norm_layers.append(LayerNorm(hidden_channels))
60
- self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
61
- for _ in range(n_layers - 1):
62
- self.conv_layers.append(
63
- nn.Conv1d(
64
- hidden_channels,
65
- hidden_channels,
66
- kernel_size,
67
- padding=kernel_size // 2,
68
- )
69
- )
70
- self.norm_layers.append(LayerNorm(hidden_channels))
71
- self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
72
- self.proj.weight.data.zero_()
73
- self.proj.bias.data.zero_()
74
-
75
- def forward(self, x, x_mask):
76
- x_org = x
77
- for i in range(self.n_layers):
78
- x = self.conv_layers[i](x * x_mask)
79
- x = self.norm_layers[i](x)
80
- x = self.relu_drop(x)
81
- x = x_org + self.proj(x)
82
- return x * x_mask
83
-
84
-
85
- class DDSConv(nn.Module):
86
- """
87
- Dialted and Depth-Separable Convolution
88
- """
89
-
90
- def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
91
- super().__init__()
92
- self.channels = channels
93
- self.kernel_size = kernel_size
94
- self.n_layers = n_layers
95
- self.p_dropout = p_dropout
96
-
97
- self.drop = nn.Dropout(p_dropout)
98
- self.convs_sep = nn.ModuleList()
99
- self.convs_1x1 = nn.ModuleList()
100
- self.norms_1 = nn.ModuleList()
101
- self.norms_2 = nn.ModuleList()
102
- for i in range(n_layers):
103
- dilation = kernel_size**i
104
- padding = (kernel_size * dilation - dilation) // 2
105
- self.convs_sep.append(
106
- nn.Conv1d(
107
- channels,
108
- channels,
109
- kernel_size,
110
- groups=channels,
111
- dilation=dilation,
112
- padding=padding,
113
- )
114
- )
115
- self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
116
- self.norms_1.append(LayerNorm(channels))
117
- self.norms_2.append(LayerNorm(channels))
118
-
119
- def forward(self, x, x_mask, g=None):
120
- if g is not None:
121
- x = x + g
122
- for i in range(self.n_layers):
123
- y = self.convs_sep[i](x * x_mask)
124
- y = self.norms_1[i](y)
125
- y = F.gelu(y)
126
- y = self.convs_1x1[i](y)
127
- y = self.norms_2[i](y)
128
- y = F.gelu(y)
129
- y = self.drop(y)
130
- x = x + y
131
- return x * x_mask
132
-
133
-
134
- class WN(torch.nn.Module):
135
- def __init__(
136
- self,
137
- hidden_channels,
138
- kernel_size,
139
- dilation_rate,
140
- n_layers,
141
- gin_channels=0,
142
- p_dropout=0,
143
- ):
144
- super(WN, self).__init__()
145
- assert kernel_size % 2 == 1
146
- self.hidden_channels = hidden_channels
147
- self.kernel_size = (kernel_size,)
148
- self.dilation_rate = dilation_rate
149
- self.n_layers = n_layers
150
- self.gin_channels = gin_channels
151
- self.p_dropout = p_dropout
152
-
153
- self.in_layers = torch.nn.ModuleList()
154
- self.res_skip_layers = torch.nn.ModuleList()
155
- self.drop = nn.Dropout(p_dropout)
156
-
157
- if gin_channels != 0:
158
- cond_layer = torch.nn.Conv1d(
159
- gin_channels, 2 * hidden_channels * n_layers, 1
160
- )
161
- self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
162
-
163
- for i in range(n_layers):
164
- dilation = dilation_rate**i
165
- padding = int((kernel_size * dilation - dilation) / 2)
166
- in_layer = torch.nn.Conv1d(
167
- hidden_channels,
168
- 2 * hidden_channels,
169
- kernel_size,
170
- dilation=dilation,
171
- padding=padding,
172
- )
173
- in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
174
- self.in_layers.append(in_layer)
175
-
176
- # last one is not necessary
177
- if i < n_layers - 1:
178
- res_skip_channels = 2 * hidden_channels
179
- else:
180
- res_skip_channels = hidden_channels
181
-
182
- res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
183
- res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
184
- self.res_skip_layers.append(res_skip_layer)
185
-
186
- def forward(self, x, x_mask, g=None, **kwargs):
187
- output = torch.zeros_like(x)
188
- n_channels_tensor = torch.IntTensor([self.hidden_channels])
189
-
190
- if g is not None:
191
- g = self.cond_layer(g)
192
-
193
- for i in range(self.n_layers):
194
- x_in = self.in_layers[i](x)
195
- if g is not None:
196
- cond_offset = i * 2 * self.hidden_channels
197
- g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
198
- else:
199
- g_l = torch.zeros_like(x_in)
200
-
201
- acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
202
- acts = self.drop(acts)
203
-
204
- res_skip_acts = self.res_skip_layers[i](acts)
205
- if i < self.n_layers - 1:
206
- res_acts = res_skip_acts[:, : self.hidden_channels, :]
207
- x = (x + res_acts) * x_mask
208
- output = output + res_skip_acts[:, self.hidden_channels :, :]
209
- else:
210
- output = output + res_skip_acts
211
- return output * x_mask
212
-
213
- def remove_weight_norm(self):
214
- if self.gin_channels != 0:
215
- torch.nn.utils.remove_weight_norm(self.cond_layer)
216
- for l in self.in_layers:
217
- torch.nn.utils.remove_weight_norm(l)
218
- for l in self.res_skip_layers:
219
- torch.nn.utils.remove_weight_norm(l)
220
-
221
-
222
- class ResBlock1(torch.nn.Module):
223
- def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
224
- super(ResBlock1, self).__init__()
225
- self.convs1 = nn.ModuleList(
226
- [
227
- weight_norm(
228
- Conv1d(
229
- channels,
230
- channels,
231
- kernel_size,
232
- 1,
233
- dilation=dilation[0],
234
- padding=get_padding(kernel_size, dilation[0]),
235
- )
236
- ),
237
- weight_norm(
238
- Conv1d(
239
- channels,
240
- channels,
241
- kernel_size,
242
- 1,
243
- dilation=dilation[1],
244
- padding=get_padding(kernel_size, dilation[1]),
245
- )
246
- ),
247
- weight_norm(
248
- Conv1d(
249
- channels,
250
- channels,
251
- kernel_size,
252
- 1,
253
- dilation=dilation[2],
254
- padding=get_padding(kernel_size, dilation[2]),
255
- )
256
- ),
257
- ]
258
- )
259
- self.convs1.apply(init_weights)
260
-
261
- self.convs2 = nn.ModuleList(
262
- [
263
- weight_norm(
264
- Conv1d(
265
- channels,
266
- channels,
267
- kernel_size,
268
- 1,
269
- dilation=1,
270
- padding=get_padding(kernel_size, 1),
271
- )
272
- ),
273
- weight_norm(
274
- Conv1d(
275
- channels,
276
- channels,
277
- kernel_size,
278
- 1,
279
- dilation=1,
280
- padding=get_padding(kernel_size, 1),
281
- )
282
- ),
283
- weight_norm(
284
- Conv1d(
285
- channels,
286
- channels,
287
- kernel_size,
288
- 1,
289
- dilation=1,
290
- padding=get_padding(kernel_size, 1),
291
- )
292
- ),
293
- ]
294
- )
295
- self.convs2.apply(init_weights)
296
-
297
- def forward(self, x, x_mask=None):
298
- for c1, c2 in zip(self.convs1, self.convs2):
299
- xt = F.leaky_relu(x, LRELU_SLOPE)
300
- if x_mask is not None:
301
- xt = xt * x_mask
302
- xt = c1(xt)
303
- xt = F.leaky_relu(xt, LRELU_SLOPE)
304
- if x_mask is not None:
305
- xt = xt * x_mask
306
- xt = c2(xt)
307
- x = xt + x
308
- if x_mask is not None:
309
- x = x * x_mask
310
- return x
311
-
312
- def remove_weight_norm(self):
313
- for l in self.convs1:
314
- remove_weight_norm(l)
315
- for l in self.convs2:
316
- remove_weight_norm(l)
317
-
318
-
319
- class ResBlock2(torch.nn.Module):
320
- def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
321
- super(ResBlock2, self).__init__()
322
- self.convs = nn.ModuleList(
323
- [
324
- weight_norm(
325
- Conv1d(
326
- channels,
327
- channels,
328
- kernel_size,
329
- 1,
330
- dilation=dilation[0],
331
- padding=get_padding(kernel_size, dilation[0]),
332
- )
333
- ),
334
- weight_norm(
335
- Conv1d(
336
- channels,
337
- channels,
338
- kernel_size,
339
- 1,
340
- dilation=dilation[1],
341
- padding=get_padding(kernel_size, dilation[1]),
342
- )
343
- ),
344
- ]
345
- )
346
- self.convs.apply(init_weights)
347
-
348
- def forward(self, x, x_mask=None):
349
- for c in self.convs:
350
- xt = F.leaky_relu(x, LRELU_SLOPE)
351
- if x_mask is not None:
352
- xt = xt * x_mask
353
- xt = c(xt)
354
- x = xt + x
355
- if x_mask is not None:
356
- x = x * x_mask
357
- return x
358
-
359
- def remove_weight_norm(self):
360
- for l in self.convs:
361
- remove_weight_norm(l)
362
-
363
-
364
- class Log(nn.Module):
365
- def forward(self, x, x_mask, reverse=False, **kwargs):
366
- if not reverse:
367
- y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
368
- logdet = torch.sum(-y, [1, 2])
369
- return y, logdet
370
- else:
371
- x = torch.exp(x) * x_mask
372
- return x
373
-
374
-
375
- class Flip(nn.Module):
376
- def forward(self, x, *args, reverse=False, **kwargs):
377
- x = torch.flip(x, [1])
378
- if not reverse:
379
- logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
380
- return x, logdet
381
- else:
382
- return x
383
-
384
-
385
- class ElementwiseAffine(nn.Module):
386
- def __init__(self, channels):
387
- super().__init__()
388
- self.channels = channels
389
- self.m = nn.Parameter(torch.zeros(channels, 1))
390
- self.logs = nn.Parameter(torch.zeros(channels, 1))
391
-
392
- def forward(self, x, x_mask, reverse=False, **kwargs):
393
- if not reverse:
394
- y = self.m + torch.exp(self.logs) * x
395
- y = y * x_mask
396
- logdet = torch.sum(self.logs * x_mask, [1, 2])
397
- return y, logdet
398
- else:
399
- x = (x - self.m) * torch.exp(-self.logs) * x_mask
400
- return x
401
-
402
-
403
- class ResidualCouplingLayer(nn.Module):
404
- def __init__(
405
- self,
406
- channels,
407
- hidden_channels,
408
- kernel_size,
409
- dilation_rate,
410
- n_layers,
411
- p_dropout=0,
412
- gin_channels=0,
413
- mean_only=False,
414
- ):
415
- assert channels % 2 == 0, "channels should be divisible by 2"
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.half_channels = channels // 2
423
- self.mean_only = mean_only
424
-
425
- self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
426
- self.enc = WN(
427
- hidden_channels,
428
- kernel_size,
429
- dilation_rate,
430
- n_layers,
431
- p_dropout=p_dropout,
432
- gin_channels=gin_channels,
433
- )
434
- self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
435
- self.post.weight.data.zero_()
436
- self.post.bias.data.zero_()
437
-
438
- def forward(self, x, x_mask, g=None, reverse=False):
439
- x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
440
- h = self.pre(x0) * x_mask
441
- h = self.enc(h, x_mask, g=g)
442
- stats = self.post(h) * x_mask
443
- if not self.mean_only:
444
- m, logs = torch.split(stats, [self.half_channels] * 2, 1)
445
- else:
446
- m = stats
447
- logs = torch.zeros_like(m)
448
-
449
- if not reverse:
450
- x1 = m + x1 * torch.exp(logs) * x_mask
451
- x = torch.cat([x0, x1], 1)
452
- logdet = torch.sum(logs, [1, 2])
453
- return x, logdet
454
- else:
455
- x1 = (x1 - m) * torch.exp(-logs) * x_mask
456
- x = torch.cat([x0, x1], 1)
457
- return x
458
-
459
-
460
- class ConvFlow(nn.Module):
461
- def __init__(
462
- self,
463
- in_channels,
464
- filter_channels,
465
- kernel_size,
466
- n_layers,
467
- num_bins=10,
468
- tail_bound=5.0,
469
- ):
470
- super().__init__()
471
- self.in_channels = in_channels
472
- self.filter_channels = filter_channels
473
- self.kernel_size = kernel_size
474
- self.n_layers = n_layers
475
- self.num_bins = num_bins
476
- self.tail_bound = tail_bound
477
- self.half_channels = in_channels // 2
478
-
479
- self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
480
- self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
481
- self.proj = nn.Conv1d(
482
- filter_channels, self.half_channels * (num_bins * 3 - 1), 1
483
- )
484
- self.proj.weight.data.zero_()
485
- self.proj.bias.data.zero_()
486
-
487
- def forward(self, x, x_mask, g=None, reverse=False):
488
- x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
489
- h = self.pre(x0)
490
- h = self.convs(h, x_mask, g=g)
491
- h = self.proj(h) * x_mask
492
-
493
- b, c, t = x0.shape
494
- h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
495
-
496
- unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
497
- unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
498
- self.filter_channels
499
- )
500
- unnormalized_derivatives = h[..., 2 * self.num_bins :]
501
-
502
- x1, logabsdet = piecewise_rational_quadratic_transform(
503
- x1,
504
- unnormalized_widths,
505
- unnormalized_heights,
506
- unnormalized_derivatives,
507
- inverse=reverse,
508
- tails="linear",
509
- tail_bound=self.tail_bound,
510
- )
511
-
512
- x = torch.cat([x0, x1], 1) * x_mask
513
- logdet = torch.sum(logabsdet * x_mask, [1, 2])
514
- if not reverse:
515
- return x, logdet
516
- else:
517
- return x
518
-
519
-
520
- class TransformerCouplingLayer(nn.Module):
521
- def __init__(
522
- self,
523
- channels,
524
- hidden_channels,
525
- kernel_size,
526
- n_layers,
527
- n_heads,
528
- p_dropout=0,
529
- filter_channels=0,
530
- mean_only=False,
531
- wn_sharing_parameter=None,
532
- gin_channels=0,
533
- ):
534
- assert channels % 2 == 0, "channels should be divisible by 2"
535
- super().__init__()
536
- self.channels = channels
537
- self.hidden_channels = hidden_channels
538
- self.kernel_size = kernel_size
539
- self.n_layers = n_layers
540
- self.half_channels = channels // 2
541
- self.mean_only = mean_only
542
-
543
- self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
544
- self.enc = (
545
- Encoder(
546
- hidden_channels,
547
- filter_channels,
548
- n_heads,
549
- n_layers,
550
- kernel_size,
551
- p_dropout,
552
- isflow=True,
553
- gin_channels=gin_channels,
554
- )
555
- if wn_sharing_parameter is None
556
- else wn_sharing_parameter
557
- )
558
- self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
559
- self.post.weight.data.zero_()
560
- self.post.bias.data.zero_()
561
-
562
- def forward(self, x, x_mask, g=None, reverse=False):
563
- x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
564
- h = self.pre(x0) * x_mask
565
- h = self.enc(h, x_mask, g=g)
566
- stats = self.post(h) * x_mask
567
- if not self.mean_only:
568
- m, logs = torch.split(stats, [self.half_channels] * 2, 1)
569
- else:
570
- m = stats
571
- logs = torch.zeros_like(m)
572
-
573
- if not reverse:
574
- x1 = m + x1 * torch.exp(logs) * x_mask
575
- x = torch.cat([x0, x1], 1)
576
- logdet = torch.sum(logs, [1, 2])
577
- return x, logdet
578
- else:
579
- x1 = (x1 - m) * torch.exp(-logs) * x_mask
580
- x = torch.cat([x0, x1], 1)
581
- return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
monotonic_align/__init__.py DELETED
@@ -1,16 +0,0 @@
1
- from numpy import zeros, int32, float32
2
- from torch import from_numpy
3
-
4
- from .core import maximum_path_jit
5
-
6
-
7
- def maximum_path(neg_cent, mask):
8
- device = neg_cent.device
9
- dtype = neg_cent.dtype
10
- neg_cent = neg_cent.data.cpu().numpy().astype(float32)
11
- path = zeros(neg_cent.shape, dtype=int32)
12
-
13
- t_t_max = mask.sum(1)[:, 0].data.cpu().numpy().astype(int32)
14
- t_s_max = mask.sum(2)[:, 0].data.cpu().numpy().astype(int32)
15
- maximum_path_jit(path, neg_cent, t_t_max, t_s_max)
16
- return from_numpy(path).to(device=device, dtype=dtype)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
monotonic_align/core.py DELETED
@@ -1,46 +0,0 @@
1
- import numba
2
-
3
-
4
- @numba.jit(
5
- numba.void(
6
- numba.int32[:, :, ::1],
7
- numba.float32[:, :, ::1],
8
- numba.int32[::1],
9
- numba.int32[::1],
10
- ),
11
- nopython=True,
12
- nogil=True,
13
- )
14
- def maximum_path_jit(paths, values, t_ys, t_xs):
15
- b = paths.shape[0]
16
- max_neg_val = -1e9
17
- for i in range(int(b)):
18
- path = paths[i]
19
- value = values[i]
20
- t_y = t_ys[i]
21
- t_x = t_xs[i]
22
-
23
- v_prev = v_cur = 0.0
24
- index = t_x - 1
25
-
26
- for y in range(t_y):
27
- for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
28
- if x == y:
29
- v_cur = max_neg_val
30
- else:
31
- v_cur = value[y - 1, x]
32
- if x == 0:
33
- if y == 0:
34
- v_prev = 0.0
35
- else:
36
- v_prev = max_neg_val
37
- else:
38
- v_prev = value[y - 1, x - 1]
39
- value[y, x] += max(v_prev, v_cur)
40
-
41
- for y in range(t_y - 1, -1, -1):
42
- path[y, index] = 1
43
- if index != 0 and (
44
- index == y or value[y - 1, index] < value[y - 1, index - 1]
45
- ):
46
- index = index - 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
preprocess_all.py DELETED
@@ -1,113 +0,0 @@
1
- import argparse
2
- from multiprocessing import cpu_count
3
-
4
- from gradio_tabs.train import preprocess_all
5
- from style_bert_vits2.nlp.japanese import pyopenjtalk_worker
6
- from style_bert_vits2.nlp.japanese.user_dict import update_dict
7
-
8
-
9
- # このプロセスからはワーカーを起動して辞書を使いたいので、ここで初期化
10
- pyopenjtalk_worker.initialize_worker()
11
-
12
- # dict_data/ 以下の辞書データを pyopenjtalk に適用
13
- update_dict()
14
-
15
- if __name__ == "__main__":
16
- parser = argparse.ArgumentParser()
17
- parser.add_argument(
18
- "--model_name", "-m", type=str, help="Model name", required=True
19
- )
20
- parser.add_argument("--batch_size", "-b", type=int, help="Batch size", default=2)
21
- parser.add_argument("--epochs", "-e", type=int, help="Epochs", default=100)
22
- parser.add_argument(
23
- "--save_every_steps",
24
- "-s",
25
- type=int,
26
- help="Save every steps",
27
- default=1000,
28
- )
29
- parser.add_argument(
30
- "--num_processes",
31
- type=int,
32
- help="Number of processes",
33
- default=cpu_count() // 2,
34
- )
35
- parser.add_argument(
36
- "--normalize",
37
- action="store_true",
38
- help="Loudness normalize audio",
39
- )
40
- parser.add_argument(
41
- "--trim",
42
- action="store_true",
43
- help="Trim silence",
44
- )
45
- parser.add_argument(
46
- "--freeze_EN_bert",
47
- action="store_true",
48
- help="Freeze English BERT",
49
- )
50
- parser.add_argument(
51
- "--freeze_JP_bert",
52
- action="store_true",
53
- help="Freeze Japanese BERT",
54
- )
55
- parser.add_argument(
56
- "--freeze_ZH_bert",
57
- action="store_true",
58
- help="Freeze Chinese BERT",
59
- )
60
- parser.add_argument(
61
- "--freeze_style",
62
- action="store_true",
63
- help="Freeze style vector",
64
- )
65
- parser.add_argument(
66
- "--freeze_decoder",
67
- action="store_true",
68
- help="Freeze decoder",
69
- )
70
- parser.add_argument(
71
- "--use_jp_extra",
72
- action="store_true",
73
- help="Use JP-Extra model",
74
- )
75
- parser.add_argument(
76
- "--val_per_lang",
77
- type=int,
78
- help="Validation per language",
79
- default=0,
80
- )
81
- parser.add_argument(
82
- "--log_interval",
83
- type=int,
84
- help="Log interval",
85
- default=200,
86
- )
87
- parser.add_argument(
88
- "--yomi_error",
89
- type=str,
90
- help="Yomi error. Options: raise, skip, use",
91
- default="raise",
92
- )
93
-
94
- args = parser.parse_args()
95
-
96
- preprocess_all(
97
- model_name=args.model_name,
98
- batch_size=args.batch_size,
99
- epochs=args.epochs,
100
- save_every_steps=args.save_every_steps,
101
- num_processes=args.num_processes,
102
- normalize=args.normalize,
103
- trim=args.trim,
104
- freeze_EN_bert=args.freeze_EN_bert,
105
- freeze_JP_bert=args.freeze_JP_bert,
106
- freeze_ZH_bert=args.freeze_ZH_bert,
107
- freeze_style=args.freeze_style,
108
- freeze_decoder=args.freeze_decoder,
109
- use_jp_extra=args.use_jp_extra,
110
- val_per_lang=args.val_per_lang,
111
- log_interval=args.log_interval,
112
- yomi_error=args.yomi_error,
113
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
preprocess_text.py DELETED
@@ -1,254 +0,0 @@
1
- import argparse
2
- import json
3
- from collections import defaultdict
4
- from pathlib import Path
5
- from random import shuffle
6
- from typing import Optional
7
-
8
- from tqdm import tqdm
9
-
10
- from config import Preprocess_text_config, config
11
- from style_bert_vits2.logging import logger
12
- from style_bert_vits2.nlp import clean_text
13
- from style_bert_vits2.nlp.japanese import pyopenjtalk_worker
14
- from style_bert_vits2.nlp.japanese.user_dict import update_dict
15
- from style_bert_vits2.utils.stdout_wrapper import SAFE_STDOUT
16
-
17
-
18
- # このプロセスからはワーカーを起動して辞書を使いたいので、ここで初期化
19
- pyopenjtalk_worker.initialize_worker()
20
-
21
- # dict_data/ 以下の辞書データを pyopenjtalk に適用
22
- update_dict()
23
-
24
-
25
- preprocess_text_config: Preprocess_text_config = config.preprocess_text_config
26
-
27
-
28
- # Count lines for tqdm
29
- def count_lines(file_path: Path):
30
- with file_path.open("r", encoding="utf-8") as file:
31
- return sum(1 for _ in file)
32
-
33
-
34
- def write_error_log(error_log_path: Path, line: str, error: Exception):
35
- with error_log_path.open("a", encoding="utf-8") as error_log:
36
- error_log.write(f"{line.strip()}\n{error}\n\n")
37
-
38
-
39
- def process_line(
40
- line: str,
41
- transcription_path: Path,
42
- correct_path: bool,
43
- use_jp_extra: bool,
44
- yomi_error: str,
45
- ):
46
- splitted_line = line.strip().split("|")
47
- if len(splitted_line) != 4:
48
- raise ValueError(f"Invalid line format: {line.strip()}")
49
- utt, spk, language, text = splitted_line
50
- norm_text, phones, tones, word2ph = clean_text(
51
- text=text,
52
- language=language, # type: ignore
53
- use_jp_extra=use_jp_extra,
54
- raise_yomi_error=(yomi_error != "use"),
55
- )
56
- if correct_path:
57
- utt = str(transcription_path.parent / "wavs" / utt)
58
-
59
- return "{}|{}|{}|{}|{}|{}|{}\n".format(
60
- utt,
61
- spk,
62
- language,
63
- norm_text,
64
- " ".join(phones),
65
- " ".join([str(i) for i in tones]),
66
- " ".join([str(i) for i in word2ph]),
67
- )
68
-
69
-
70
- def preprocess(
71
- transcription_path: Path,
72
- cleaned_path: Optional[Path],
73
- train_path: Path,
74
- val_path: Path,
75
- config_path: Path,
76
- val_per_lang: int,
77
- max_val_total: int,
78
- # clean: bool,
79
- use_jp_extra: bool,
80
- yomi_error: str,
81
- correct_path: bool,
82
- ):
83
- assert yomi_error in ["raise", "skip", "use"]
84
- if cleaned_path == "" or cleaned_path is None:
85
- cleaned_path = transcription_path.with_name(
86
- transcription_path.name + ".cleaned"
87
- )
88
-
89
- error_log_path = transcription_path.parent / "text_error.log"
90
- if error_log_path.exists():
91
- error_log_path.unlink()
92
- error_count = 0
93
-
94
- total_lines = count_lines(transcription_path)
95
-
96
- # transcription_path から 1行ずつ読み込んで文章処理して cleaned_path に書き込む
97
- with (
98
- transcription_path.open("r", encoding="utf-8") as trans_file,
99
- cleaned_path.open("w", encoding="utf-8") as out_file,
100
- ):
101
- for line in tqdm(trans_file, file=SAFE_STDOUT, total=total_lines):
102
- try:
103
- processed_line = process_line(
104
- line,
105
- transcription_path,
106
- correct_path,
107
- use_jp_extra,
108
- yomi_error,
109
- )
110
- out_file.write(processed_line)
111
- except Exception as e:
112
- logger.error(
113
- f"An error occurred at line:\n{line.strip()}\n{e}", encoding="utf-8"
114
- )
115
- write_error_log(error_log_path, line, e)
116
- error_count += 1
117
-
118
- transcription_path = cleaned_path
119
-
120
- # 各話者ごとのlineの辞書
121
- spk_utt_map: dict[str, list[str]] = defaultdict(list)
122
-
123
- # 話者からIDへの写像
124
- spk_id_map: dict[str, int] = {}
125
-
126
- # 話者ID
127
- current_sid: int = 0
128
-
129
- # 音源ファイルのチェックや、spk_id_mapの作成
130
- with transcription_path.open("r", encoding="utf-8") as f:
131
- audio_paths: set[str] = set()
132
- count_same = 0
133
- count_not_found = 0
134
- for line in f.readlines():
135
- utt, spk = line.strip().split("|")[:2]
136
- if utt in audio_paths:
137
- logger.warning(f"Same audio file appears multiple times: {utt}")
138
- count_same += 1
139
- continue
140
- if not Path(utt).is_file():
141
- logger.warning(f"Audio not found: {utt}")
142
- count_not_found += 1
143
- continue
144
- audio_paths.add(utt)
145
- spk_utt_map[spk].append(line)
146
-
147
- # 新しい話者が出てきたら話者IDを割り当て、current_sidを1増やす
148
- if spk not in spk_id_map.keys():
149
- spk_id_map[spk] = current_sid
150
- current_sid += 1
151
- if count_same > 0 or count_not_found > 0:
152
- logger.warning(
153
- f"Total repeated audios: {count_same}, Total number of audio not found: {count_not_found}"
154
- )
155
-
156
- train_list: list[str] = []
157
- val_list: list[str] = []
158
-
159
- # 各話者ごとにシャッフルして、val_per_lang個をval_listに、残りをtrain_listに追加
160
- for spk, utts in spk_utt_map.items():
161
- shuffle(utts)
162
- val_list += utts[:val_per_lang]
163
- train_list += utts[val_per_lang:]
164
-
165
- shuffle(val_list)
166
- if len(val_list) > max_val_total:
167
- train_list += val_list[max_val_total:]
168
- val_list = val_list[:max_val_total]
169
-
170
- with train_path.open("w", encoding="utf-8") as f:
171
- for line in train_list:
172
- f.write(line)
173
-
174
- with val_path.open("w", encoding="utf-8") as f:
175
- for line in val_list:
176
- f.write(line)
177
-
178
- with config_path.open("r", encoding="utf-8") as f:
179
- json_config = json.load(f)
180
-
181
- json_config["data"]["spk2id"] = spk_id_map
182
- json_config["data"]["n_speakers"] = len(spk_id_map)
183
-
184
- with config_path.open("w", encoding="utf-8") as f:
185
- json.dump(json_config, f, indent=2, ensure_ascii=False)
186
- if error_count > 0:
187
- if yomi_error == "skip":
188
- logger.warning(
189
- f"An error occurred in {error_count} lines. Proceed with lines without errors. Please check {error_log_path} for details."
190
- )
191
- else:
192
- # yom_error == "raise"と"use"の場合。
193
- # "use"の場合は、そもそもyomi_error = Falseで処理しているので、
194
- # ここが実行されるのは他の例外のときなので、エラーをraiseする。
195
- logger.error(
196
- f"An error occurred in {error_count} lines. Please check {error_log_path} for details."
197
- )
198
- raise Exception(
199
- f"An error occurred in {error_count} lines. Please check `Data/you_model_name/text_error.log` file for details."
200
- )
201
- # 何故か{error_log_path}をraiseすると文字コードエラーが起きるので上のように書いている
202
- else:
203
- logger.info(
204
- "Training set and validation set generation from texts is complete!"
205
- )
206
-
207
-
208
- if __name__ == "__main__":
209
- parser = argparse.ArgumentParser()
210
- parser.add_argument(
211
- "--transcription-path", default=preprocess_text_config.transcription_path
212
- )
213
- parser.add_argument("--cleaned-path", default=preprocess_text_config.cleaned_path)
214
- parser.add_argument("--train-path", default=preprocess_text_config.train_path)
215
- parser.add_argument("--val-path", default=preprocess_text_config.val_path)
216
- parser.add_argument("--config-path", default=preprocess_text_config.config_path)
217
-
218
- # 「話者ごと」のバリデーションデータ数、言語ごとではない!
219
- # 元のコードや設定ファイルでval_per_langとなっていたので名前をそのままにしている
220
- parser.add_argument(
221
- "--val-per-lang",
222
- default=preprocess_text_config.val_per_lang,
223
- help="Number of validation data per SPEAKER, not per language (due to compatibility with the original code).",
224
- )
225
- parser.add_argument("--max-val-total", default=preprocess_text_config.max_val_total)
226
- parser.add_argument("--use_jp_extra", action="store_true")
227
- parser.add_argument("--yomi_error", default="raise")
228
- parser.add_argument("--correct_path", action="store_true")
229
-
230
- args = parser.parse_args()
231
-
232
- transcription_path = Path(args.transcription_path)
233
- cleaned_path = Path(args.cleaned_path) if args.cleaned_path else None
234
- train_path = Path(args.train_path)
235
- val_path = Path(args.val_path)
236
- config_path = Path(args.config_path)
237
- val_per_lang = int(args.val_per_lang)
238
- max_val_total = int(args.max_val_total)
239
- use_jp_extra: bool = args.use_jp_extra
240
- yomi_error: str = args.yomi_error
241
- correct_path: bool = args.correct_path
242
-
243
- preprocess(
244
- transcription_path=transcription_path,
245
- cleaned_path=cleaned_path,
246
- train_path=train_path,
247
- val_path=val_path,
248
- config_path=config_path,
249
- val_per_lang=val_per_lang,
250
- max_val_total=max_val_total,
251
- use_jp_extra=use_jp_extra,
252
- yomi_error=yomi_error,
253
- correct_path=correct_path,
254
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
pyproject.toml DELETED
@@ -1,129 +0,0 @@
1
- [build-system]
2
- requires = ["hatchling"]
3
- build-backend = "hatchling.build"
4
-
5
- [project]
6
- name = "style-bert-vits2"
7
- dynamic = ["version"]
8
- description = 'Style-Bert-VITS2: Bert-VITS2 with more controllable voice styles.'
9
- readme = "README.md"
10
- requires-python = ">=3.9"
11
- license = "AGPL-3.0"
12
- keywords = []
13
- authors = [
14
- { name = "litagin02", email = "139731664+litagin02@users.noreply.github.com" },
15
- ]
16
- classifiers = [
17
- "Development Status :: 4 - Beta",
18
- "Programming Language :: Python",
19
- "Programming Language :: Python :: 3.9",
20
- "Programming Language :: Python :: 3.10",
21
- "Programming Language :: Python :: 3.11",
22
- "Programming Language :: Python :: Implementation :: CPython",
23
- ]
24
- dependencies = [
25
- 'cmudict',
26
- 'cn2an',
27
- 'g2p_en',
28
- 'jieba',
29
- 'loguru',
30
- 'num2words',
31
- 'numba',
32
- 'numpy',
33
- 'pydantic>=2.0',
34
- 'pyopenjtalk-dict',
35
- 'pypinyin',
36
- 'pyworld-prebuilt',
37
- 'safetensors',
38
- 'torch>=2.1',
39
- 'transformers',
40
- ]
41
-
42
- [project.urls]
43
- Documentation = "https://github.com/litagin02/Style-Bert-VITS2#readme"
44
- Issues = "https://github.com/litagin02/Style-Bert-VITS2/issues"
45
- Source = "https://github.com/litagin02/Style-Bert-VITS2"
46
-
47
- [tool.hatch.version]
48
- path = "style_bert_vits2/constants.py"
49
-
50
- [tool.hatch.build.targets.sdist]
51
- only-include = [
52
- ".vscode",
53
- "dict_data/default.csv",
54
- "docs",
55
- "style_bert_vits2",
56
- "tests",
57
- "LGPL_LICENSE",
58
- "LICENSE",
59
- "pyproject.toml",
60
- "README.md",
61
- ]
62
- exclude = [
63
- ".git",
64
- ".gitignore",
65
- ".gitattributes",
66
- ]
67
-
68
- [tool.hatch.build.targets.wheel]
69
- packages = ["style_bert_vits2"]
70
-
71
- [tool.hatch.envs.test]
72
- dependencies = [
73
- "coverage[toml]>=6.5",
74
- "pytest",
75
- ]
76
- [tool.hatch.envs.test.scripts]
77
- # Usage: `hatch run test:test`
78
- test = "pytest {args:tests}"
79
- # Usage: `hatch run test:coverage`
80
- test-cov = "coverage run -m pytest {args:tests}"
81
- # Usage: `hatch run test:cov-report`
82
- cov-report = [
83
- "- coverage combine",
84
- "coverage report",
85
- ]
86
- # Usage: `hatch run test:cov`
87
- cov = [
88
- "test-cov",
89
- "cov-report",
90
- ]
91
-
92
- [tool.hatch.envs.style]
93
- detached = true
94
- dependencies = [
95
- "black",
96
- "isort",
97
- ]
98
- [tool.hatch.envs.style.scripts]
99
- check = [
100
- "black --check --diff .",
101
- "isort --check-only --diff --profile black --gitignore --lai 2 . --sg \"Data/*\" --sg \"inputs/*\" --sg \"model_assets/*\" --sg \"static/*\"",
102
- ]
103
- fmt = [
104
- "black .",
105
- "isort --profile black --gitignore --lai 2 . --sg \"Data/*\" --sg \"inputs/*\" --sg \"model_assets/*\" --sg \"static/*\"",
106
- "check",
107
- ]
108
-
109
- [[tool.hatch.envs.test.matrix]]
110
- python = ["3.9", "3.10", "3.11"]
111
-
112
- [tool.coverage.run]
113
- source_pkgs = ["style_bert_vits2", "tests"]
114
- branch = true
115
- parallel = true
116
- omit = [
117
- "style_bert_vits2/constants.py",
118
- ]
119
-
120
- [tool.coverage.paths]
121
- style_bert_vits2 = ["style_bert_vits2", "*/style-bert-vits2/style_bert_vits2"]
122
- tests = ["tests", "*/style-bert-vits2/tests"]
123
-
124
- [tool.coverage.report]
125
- exclude_lines = [
126
- "no cov",
127
- "if __name__ == .__main__.:",
128
- "if TYPE_CHECKING:",
129
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
re_matching.py DELETED
@@ -1,81 +0,0 @@
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)