litagin commited on
Commit
83d190a
1 Parent(s): a2a4aef
This view is limited to 50 files because it contains too many changes.   See raw diff
.dockerignore CHANGED
@@ -3,23 +3,16 @@
3
 
4
  *
5
 
 
 
6
  !/bert/deberta-v2-large-japanese-char-wwm/
7
- !/common/
8
  !/configs/
9
  !/dict_data/default.csv
10
  !/model_assets/
11
- !/monotonic_align/
12
- !/text/
13
 
14
- !/attentions.py
15
- !/commons.py
16
  !/config.py
17
  !/default_config.yml
18
- !/infer.py
19
- !/models.py
20
- !/models_jp_extra.py
21
- !/modules.py
22
  !/requirements.txt
23
  !/server_editor.py
24
- !/transforms.py
25
- !/utils.py
 
3
 
4
  *
5
 
6
+ !/style_bert_vits2/
7
+
8
  !/bert/deberta-v2-large-japanese-char-wwm/
 
9
  !/configs/
10
  !/dict_data/default.csv
11
  !/model_assets/
12
+ !/static/
 
13
 
 
 
14
  !/config.py
15
  !/default_config.yml
16
+ !/initialize.py
 
 
 
17
  !/requirements.txt
18
  !/server_editor.py
 
 
.gitignore CHANGED
@@ -28,7 +28,6 @@ venv/
28
 
29
  safetensors.ipynb
30
  *.wav
31
- /static/
32
 
33
  # pyopenjtalk's dictionary
34
  *.dic
 
28
 
29
  safetensors.ipynb
30
  *.wav
 
31
 
32
  # pyopenjtalk's dictionary
33
  *.dic
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 CHANGED
@@ -20,4 +20,4 @@ COPY --chown=user . $HOME/app
20
  RUN pip install --no-cache-dir -r $HOME/app/requirements.txt
21
 
22
  # 必要に応じて制限を変更してください
23
- CMD ["python", "server_editor.py", "--line_length", "50", "--line_count", "3","--port", "7860"]
 
20
  RUN pip install --no-cache-dir -r $HOME/app/requirements.txt
21
 
22
  # 必要に応じて制限を変更してください
23
+ CMD ["python", "server_editor.py", "--line_length", "50", "--line_count", "3", "--skip_static_files", "--skip_default_models"]
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==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 --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 --inbroser
6
- venv\Scripts\python server_editor.py --inbrowser
7
-
8
- if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
9
-
10
- popd
11
- pause
 
 
 
 
 
 
 
 
 
 
 
 
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,500 +0,0 @@
1
- import argparse
2
- import datetime
3
- import json
4
- import os
5
- import sys
6
- from pathlib import Path
7
- from typing import Optional
8
-
9
- import gradio as gr
10
- import torch
11
- import yaml
12
-
13
- from common.constants import (
14
- DEFAULT_ASSIST_TEXT_WEIGHT,
15
- DEFAULT_LENGTH,
16
- DEFAULT_LINE_SPLIT,
17
- DEFAULT_NOISE,
18
- DEFAULT_NOISEW,
19
- DEFAULT_SDP_RATIO,
20
- DEFAULT_SPLIT_INTERVAL,
21
- DEFAULT_STYLE,
22
- DEFAULT_STYLE_WEIGHT,
23
- GRADIO_THEME,
24
- LATEST_VERSION,
25
- Languages,
26
- )
27
- from common.log import logger
28
- from common.tts_model import ModelHolder
29
- from infer import InvalidToneError
30
- from text.japanese import g2kata_tone, kata_tone2phone_tone, text_normalize
31
-
32
- # Get path settings
33
- with open(os.path.join("configs", "paths.yml"), "r", encoding="utf-8") as f:
34
- path_config: dict[str, str] = yaml.safe_load(f.read())
35
- # dataset_root = path_config["dataset_root"]
36
- assets_root = path_config["assets_root"]
37
-
38
- languages = [l.value for l in Languages]
39
-
40
-
41
- def tts_fn(
42
- model_name,
43
- model_path,
44
- text,
45
- language,
46
- reference_audio_path,
47
- sdp_ratio,
48
- noise_scale,
49
- noise_scale_w,
50
- length_scale,
51
- line_split,
52
- split_interval,
53
- assist_text,
54
- assist_text_weight,
55
- use_assist_text,
56
- style,
57
- style_weight,
58
- kata_tone_json_str,
59
- use_tone,
60
- speaker,
61
- pitch_scale,
62
- intonation_scale,
63
- ):
64
- model_holder.load_model_gr(model_name, model_path)
65
-
66
- wrong_tone_message = ""
67
- kata_tone: Optional[list[tuple[str, int]]] = None
68
- if use_tone and kata_tone_json_str != "":
69
- if language != "JP":
70
- logger.warning("Only Japanese is supported for tone generation.")
71
- wrong_tone_message = "アクセント指定は現在日本語のみ対応しています。"
72
- if line_split:
73
- logger.warning("Tone generation is not supported for line split.")
74
- wrong_tone_message = (
75
- "アクセント指定は改行で分けて生成を使わない場合のみ対応しています。"
76
- )
77
- try:
78
- kata_tone = []
79
- json_data = json.loads(kata_tone_json_str)
80
- # tupleを使うように変換
81
- for kana, tone in json_data:
82
- assert isinstance(kana, str) and tone in (0, 1), f"{kana}, {tone}"
83
- kata_tone.append((kana, tone))
84
- except Exception as e:
85
- logger.warning(f"Error occurred when parsing kana_tone_json: {e}")
86
- wrong_tone_message = f"アクセント指定が不正です: {e}"
87
- kata_tone = None
88
-
89
- # toneは実際に音声合成に代入される際のみnot Noneになる
90
- tone: Optional[list[int]] = None
91
- if kata_tone is not None:
92
- phone_tone = kata_tone2phone_tone(kata_tone)
93
- tone = [t for _, t in phone_tone]
94
-
95
- speaker_id = model_holder.current_model.spk2id[speaker]
96
-
97
- start_time = datetime.datetime.now()
98
-
99
- try:
100
- sr, audio = model_holder.current_model.infer(
101
- text=text,
102
- language=language,
103
- reference_audio_path=reference_audio_path,
104
- sdp_ratio=sdp_ratio,
105
- noise=noise_scale,
106
- noisew=noise_scale_w,
107
- length=length_scale,
108
- line_split=line_split,
109
- split_interval=split_interval,
110
- assist_text=assist_text,
111
- assist_text_weight=assist_text_weight,
112
- use_assist_text=use_assist_text,
113
- style=style,
114
- style_weight=style_weight,
115
- given_tone=tone,
116
- sid=speaker_id,
117
- pitch_scale=pitch_scale,
118
- intonation_scale=intonation_scale,
119
- )
120
- except InvalidToneError as e:
121
- logger.error(f"Tone error: {e}")
122
- return f"Error: アクセント指定が不正です:\n{e}", None, kata_tone_json_str
123
- except ValueError as e:
124
- logger.error(f"Value error: {e}")
125
- return f"Error: {e}", None, kata_tone_json_str
126
-
127
- end_time = datetime.datetime.now()
128
- duration = (end_time - start_time).total_seconds()
129
-
130
- if tone is None and language == "JP":
131
- # アクセント指定に使えるようにアクセント情報を返す
132
- norm_text = text_normalize(text)
133
- kata_tone = g2kata_tone(norm_text)
134
- kata_tone_json_str = json.dumps(kata_tone, ensure_ascii=False)
135
- elif tone is None:
136
- kata_tone_json_str = ""
137
- message = f"Success, time: {duration} seconds."
138
- if wrong_tone_message != "":
139
- message = wrong_tone_message + "\n" + message
140
- return message, (sr, audio), kata_tone_json_str
141
-
142
-
143
- initial_text = "こんにちは、初めまして。あなたの名前はなんていうの?"
144
-
145
- examples = [
146
- [initial_text, "JP"],
147
- [
148
- """あなたがそんなこと言うなんて、私はとっても嬉しい。
149
- あなたがそんなこと言うなんて、私はとっても怒ってる。
150
- あなたがそんなこと言うなんて、私はとっても驚いてる。
151
- あなたがそんなこと言うなんて、私はとっても辛い。""",
152
- "JP",
153
- ],
154
- [ # ChatGPTに考えてもらった告白セリフ
155
- """私、ずっと前からあなたのことを見てきました。あなたの笑顔、優しさ、強さに、心惹かれていたんです。
156
- 友達として過ごす中で、あなたのことがだんだんと特別な存在になっていくのがわかりました。
157
- えっと、私、あなたのことが好きです!もしよければ、私と付き合ってくれませんか?""",
158
- "JP",
159
- ],
160
- [ # 夏目漱石『吾輩は猫である』
161
- """吾輩は猫である。名前はまだ無い。
162
- どこで生れたかとんと見当がつかぬ。なんでも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。
163
- 吾輩はここで初めて人間というものを見た。しかもあとで聞くと、それは書生という、人間中で一番獰悪な種族であったそうだ。
164
- この書生というのは時々我々を捕まえて煮て食うという話である。""",
165
- "JP",
166
- ],
167
- [ # 梶井基次郎『桜の樹の下には』
168
- """桜の樹の下には屍体が埋まっている!これは信じていいことなんだよ。
169
- 何故って、桜の花があんなにも見事に咲くなんて信じられないことじゃないか。俺はあの美しさが信じられないので、このにさんにち不安だった。
170
- しかしいま、やっとわかるときが来た。桜の樹の下には屍体が埋まっている。これは信じていいことだ。""",
171
- "JP",
172
- ],
173
- [ # ChatGPTと考えた、感情を表すセリフ
174
- """やったー!テストで満点取れた!私とっても嬉しいな!
175
- どうして私の意見を無視するの?許せない!ムカつく!あんたなんか死ねばいいのに。
176
- あはははっ!この漫画めっちゃ笑える、見てよこれ、ふふふ、あはは。
177
- あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しい。""",
178
- "JP",
179
- ],
180
- [ # 上の丁寧語バージョン
181
- """やりました!テストで満点取れましたよ!私とっても嬉しいです!
182
- どうして私の意見を無視するんですか?許せません!ムカつきます!あんたなんか死んでください。
183
- あはははっ!この漫画めっちゃ笑えます、見てくださいこれ、ふふふ、あはは。
184
- あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しいです。""",
185
- "JP",
186
- ],
187
- [ # ChatGPTに考えてもらった音声合成の説明文章
188
- """音声合成は、機械学習を活用して、テキストから人の声を再現する技術です。この技術は、言語の構造を解析し、それに基づいて音声を生成します。
189
- この分野の最新の研究成果を使うと、より自然で表現豊かな音声の生成が可能である。深層学習の応用により、感情やアクセントを含む声質の微妙な変化も再現することが出来る。""",
190
- "JP",
191
- ],
192
- [
193
- "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.",
194
- "EN",
195
- ],
196
- [
197
- "语音合成是人工制造人类语音。用于此目的的计算机系统称为语音合成器,可以通过软件或硬件产品实现。",
198
- "ZH",
199
- ],
200
- ]
201
-
202
- initial_md = f"""
203
- # Style-Bert-VITS2 ver {LATEST_VERSION} 音声合成
204
-
205
- - Ver 2.3で追加されたエディターのほうが実際に読み上げさせるには使いやすいかもしれません。`Editor.bat`か`python server_editor.py`で起動できます。
206
-
207
- - 初期からある[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)です。
208
- """
209
-
210
- how_to_md = """
211
- 下のように`model_assets`ディレクトリの中にモデルファイルたちを置いてください。
212
- ```
213
- model_assets
214
- ├── your_model
215
- │ ├── config.json
216
- │ ├── your_model_file1.safetensors
217
- │ ├── your_model_file2.safetensors
218
- │ ├── ...
219
- │ └── style_vectors.npy
220
- └── another_model
221
- ├── ...
222
- ```
223
- 各モデルにはファイルたちが必要です:
224
- - `config.json`:学習時の設定ファイル
225
- - `*.safetensors`:学習済みモデルファイル(1つ以上が必要、複数可)
226
- - `style_vectors.npy`:スタイルベクトルファイル
227
-
228
- 上2つは`Train.bat`による学習で自動的に正しい位置に保存されます。`style_vectors.npy`は`Style.bat`を実行して指示に従って生成してください。
229
- """
230
-
231
- style_md = f"""
232
- - プリセットまたは音声ファイルから読み上げの声音・感情・スタイルのようなものを制御できます。
233
- - デフォルトの{DEFAULT_STYLE}でも、十分に読み上げる文に応じた感情で感情豊かに読み上げられます。このスタイル制御は、それを重み付きで上書きするような感じです。
234
- - 強さを大きくしすぎると発音が変になったり声にならなかったりと崩壊することがあります。
235
- - どのくらいに強さがいいかはモデルやスタイルによって異なるようです。
236
- - 音声ファイルを入力する場合は、学習データと似た声音の話者(特に同じ性別)でないとよい効果が出ないかもしれません。
237
- """
238
-
239
-
240
- def make_interactive():
241
- return gr.update(interactive=True, value="音声合成")
242
-
243
-
244
- def make_non_interactive():
245
- return gr.update(interactive=False, value="音声合成(モデルをロードしてください)")
246
-
247
-
248
- def gr_util(item):
249
- if item == "プリセットから選ぶ":
250
- return (gr.update(visible=True), gr.Audio(visible=False, value=None))
251
- else:
252
- return (gr.update(visible=False), gr.update(visible=True))
253
-
254
-
255
- if __name__ == "__main__":
256
- parser = argparse.ArgumentParser()
257
- parser.add_argument("--cpu", action="store_true", help="Use CPU instead of GPU")
258
- parser.add_argument(
259
- "--dir", "-d", type=str, help="Model directory", default=assets_root
260
- )
261
- parser.add_argument(
262
- "--share", action="store_true", help="Share this app publicly", default=False
263
- )
264
- parser.add_argument(
265
- "--server-name",
266
- type=str,
267
- default=None,
268
- help="Server name for Gradio app",
269
- )
270
- parser.add_argument(
271
- "--no-autolaunch",
272
- action="store_true",
273
- default=False,
274
- help="Do not launch app automatically",
275
- )
276
- args = parser.parse_args()
277
- model_dir = Path(args.dir)
278
-
279
- if args.cpu:
280
- device = "cpu"
281
- else:
282
- device = "cuda" if torch.cuda.is_available() else "cpu"
283
-
284
- model_holder = ModelHolder(model_dir, device)
285
-
286
- model_names = model_holder.model_names
287
- if len(model_names) == 0:
288
- logger.error(
289
- f"モデルが見つかりませんでした。{model_dir}にモデルを置いてください。"
290
- )
291
- sys.exit(1)
292
- initial_id = 0
293
- initial_pth_files = model_holder.model_files_dict[model_names[initial_id]]
294
-
295
- with gr.Blocks(theme=GRADIO_THEME) as app:
296
- gr.Markdown(initial_md)
297
- with gr.Accordion(label="使い方", open=False):
298
- gr.Markdown(how_to_md)
299
- with gr.Row():
300
- with gr.Column():
301
- with gr.Row():
302
- with gr.Column(scale=3):
303
- model_name = gr.Dropdown(
304
- label="モデル一覧",
305
- choices=model_names,
306
- value=model_names[initial_id],
307
- )
308
- model_path = gr.Dropdown(
309
- label="モデルファイル",
310
- choices=initial_pth_files,
311
- value=initial_pth_files[0],
312
- )
313
- refresh_button = gr.Button("更新", scale=1, visible=True)
314
- load_button = gr.Button("ロード", scale=1, variant="primary")
315
- text_input = gr.TextArea(label="テキスト", value=initial_text)
316
- pitch_scale = gr.Slider(
317
- minimum=0.8,
318
- maximum=1.5,
319
- value=1,
320
- step=0.05,
321
- label="音程(1以外では音質劣化)",
322
- visible=False, # pyworldが必要
323
- )
324
- intonation_scale = gr.Slider(
325
- minimum=0,
326
- maximum=2,
327
- value=1,
328
- step=0.1,
329
- label="抑揚(1以外では音質劣化)",
330
- visible=False, # pyworldが必要
331
- )
332
-
333
- line_split = gr.Checkbox(
334
- label="改行で分けて生成(分けたほうが感情が乗ります)",
335
- value=DEFAULT_LINE_SPLIT,
336
- )
337
- split_interval = gr.Slider(
338
- minimum=0.0,
339
- maximum=2,
340
- value=DEFAULT_SPLIT_INTERVAL,
341
- step=0.1,
342
- label="改行ごとに挟む無音の長さ(秒)",
343
- )
344
- line_split.change(
345
- lambda x: (gr.Slider(visible=x)),
346
- inputs=[line_split],
347
- outputs=[split_interval],
348
- )
349
- tone = gr.Textbox(
350
- label="アクセント調整(数値は 0=低 か1=高 のみ)",
351
- info="改行で分けない場合のみ使えます。万能ではありません。",
352
- )
353
- use_tone = gr.Checkbox(label="アクセント調整を使う", value=False)
354
- use_tone.change(
355
- lambda x: (gr.Checkbox(value=False) if x else gr.Checkbox()),
356
- inputs=[use_tone],
357
- outputs=[line_split],
358
- )
359
- language = gr.Dropdown(choices=languages, value="JP", label="Language")
360
- speaker = gr.Dropdown(label="話者")
361
- with gr.Accordion(label="詳細設定", open=False):
362
- sdp_ratio = gr.Slider(
363
- minimum=0,
364
- maximum=1,
365
- value=DEFAULT_SDP_RATIO,
366
- step=0.1,
367
- label="SDP Ratio",
368
- )
369
- noise_scale = gr.Slider(
370
- minimum=0.1,
371
- maximum=2,
372
- value=DEFAULT_NOISE,
373
- step=0.1,
374
- label="Noise",
375
- )
376
- noise_scale_w = gr.Slider(
377
- minimum=0.1,
378
- maximum=2,
379
- value=DEFAULT_NOISEW,
380
- step=0.1,
381
- label="Noise_W",
382
- )
383
- length_scale = gr.Slider(
384
- minimum=0.1,
385
- maximum=2,
386
- value=DEFAULT_LENGTH,
387
- step=0.1,
388
- label="Length",
389
- )
390
- use_assist_text = gr.Checkbox(
391
- label="Assist textを使う", value=False
392
- )
393
- assist_text = gr.Textbox(
394
- label="Assist text",
395
- placeholder="どうして私の意見を無視するの?許せない、ムカつく!死ねばいいのに。",
396
- info="このテキストの読み上げと似た声音・感情になりやすくなります。ただ抑揚やテンポ等が犠牲になる傾向があります。",
397
- visible=False,
398
- )
399
- assist_text_weight = gr.Slider(
400
- minimum=0,
401
- maximum=1,
402
- value=DEFAULT_ASSIST_TEXT_WEIGHT,
403
- step=0.1,
404
- label="Assist textの強さ",
405
- visible=False,
406
- )
407
- use_assist_text.change(
408
- lambda x: (gr.Textbox(visible=x), gr.Slider(visible=x)),
409
- inputs=[use_assist_text],
410
- outputs=[assist_text, assist_text_weight],
411
- )
412
- with gr.Column():
413
- with gr.Accordion("スタイルについて詳細", open=False):
414
- gr.Markdown(style_md)
415
- style_mode = gr.Radio(
416
- ["プリセットから選ぶ", "音声ファイルを入力"],
417
- label="スタイルの指定方法",
418
- value="プリセットから選ぶ",
419
- )
420
- style = gr.Dropdown(
421
- label=f"スタイル({DEFAULT_STYLE}が平均スタイル)",
422
- choices=["モデルをロードしてください"],
423
- value="モデルをロードしてください",
424
- )
425
- style_weight = gr.Slider(
426
- minimum=0,
427
- maximum=50,
428
- value=DEFAULT_STYLE_WEIGHT,
429
- step=0.1,
430
- label="スタイルの強さ",
431
- )
432
- ref_audio_path = gr.Audio(
433
- label="参照音声", type="filepath", visible=False
434
- )
435
- tts_button = gr.Button(
436
- "音声合成(モデルをロードしてください)",
437
- variant="primary",
438
- interactive=False,
439
- )
440
- text_output = gr.Textbox(label="情報")
441
- audio_output = gr.Audio(label="結果")
442
- with gr.Accordion("テキスト例", open=False):
443
- gr.Examples(examples, inputs=[text_input, language])
444
-
445
- tts_button.click(
446
- tts_fn,
447
- inputs=[
448
- model_name,
449
- model_path,
450
- text_input,
451
- language,
452
- ref_audio_path,
453
- sdp_ratio,
454
- noise_scale,
455
- noise_scale_w,
456
- length_scale,
457
- line_split,
458
- split_interval,
459
- assist_text,
460
- assist_text_weight,
461
- use_assist_text,
462
- style,
463
- style_weight,
464
- tone,
465
- use_tone,
466
- speaker,
467
- pitch_scale,
468
- intonation_scale,
469
- ],
470
- outputs=[text_output, audio_output, tone],
471
- )
472
-
473
- model_name.change(
474
- model_holder.update_model_files_gr,
475
- inputs=[model_name],
476
- outputs=[model_path],
477
- )
478
-
479
- model_path.change(make_non_interactive, outputs=[tts_button])
480
-
481
- refresh_button.click(
482
- model_holder.update_model_names_gr,
483
- outputs=[model_name, model_path, tts_button],
484
- )
485
-
486
- load_button.click(
487
- model_holder.load_model_gr,
488
- inputs=[model_name, model_path],
489
- outputs=[style, tts_button, speaker],
490
- )
491
-
492
- style_mode.change(
493
- gr_util,
494
- inputs=[style_mode],
495
- outputs=[style, ref_audio_path],
496
- )
497
-
498
- app.launch(
499
- inbrowser=not args.no_autolaunch, share=args.share, server_name=args.server_name
500
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bert/bert_models.json DELETED
@@ -1,14 +0,0 @@
1
- {
2
- "deberta-v2-large-japanese-char-wwm": {
3
- "repo_id": "ku-nlp/deberta-v2-large-japanese-char-wwm",
4
- "files": ["pytorch_model.bin"]
5
- },
6
- "chinese-roberta-wwm-ext-large": {
7
- "repo_id": "hfl/chinese-roberta-wwm-ext-large",
8
- "files": ["pytorch_model.bin"]
9
- },
10
- "deberta-v3-large": {
11
- "repo_id": "microsoft/deberta-v3-large",
12
- "files": ["spm.model", "pytorch_model.bin"]
13
- }
14
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bert_gen.py DELETED
@@ -1,85 +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
- import commons
9
- import utils
10
- from common.log import logger
11
- from common.stdout_wrapper import SAFE_STDOUT
12
- from config import config
13
- from text import cleaned_text_to_sequence, get_bert
14
-
15
-
16
- def process_line(x):
17
- line, add_blank = x
18
- device = config.bert_gen_config.device
19
- if config.bert_gen_config.use_multi_device:
20
- rank = mp.current_process()._identity
21
- rank = rank[0] if len(rank) > 0 else 0
22
- if torch.cuda.is_available():
23
- gpu_id = rank % torch.cuda.device_count()
24
- device = torch.device(f"cuda:{gpu_id}")
25
- else:
26
- device = torch.device("cpu")
27
- wav_path, _, language_str, text, phones, tone, word2ph = line.strip().split("|")
28
- phone = phones.split(" ")
29
- tone = [int(i) for i in tone.split(" ")]
30
- word2ph = [int(i) for i in word2ph.split(" ")]
31
- word2ph = [i for i in word2ph]
32
- phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
33
-
34
- if add_blank:
35
- phone = commons.intersperse(phone, 0)
36
- tone = commons.intersperse(tone, 0)
37
- language = commons.intersperse(language, 0)
38
- for i in range(len(word2ph)):
39
- word2ph[i] = word2ph[i] * 2
40
- word2ph[0] += 1
41
-
42
- bert_path = wav_path.replace(".WAV", ".wav").replace(".wav", ".bert.pt")
43
-
44
- try:
45
- bert = torch.load(bert_path)
46
- assert bert.shape[-1] == len(phone)
47
- except Exception:
48
- bert = get_bert(text, word2ph, language_str, device)
49
- assert bert.shape[-1] == len(phone)
50
- torch.save(bert, bert_path)
51
-
52
-
53
- preprocess_text_config = config.preprocess_text_config
54
-
55
- if __name__ == "__main__":
56
- parser = argparse.ArgumentParser()
57
- parser.add_argument(
58
- "-c", "--config", type=str, default=config.bert_gen_config.config_path
59
- )
60
- parser.add_argument(
61
- "--num_processes", type=int, default=config.bert_gen_config.num_processes
62
- )
63
- args, _ = parser.parse_known_args()
64
- config_path = args.config
65
- hps = utils.get_hparams_from_file(config_path)
66
- lines = []
67
- with open(hps.data.training_files, encoding="utf-8") as f:
68
- lines.extend(f.readlines())
69
-
70
- with open(hps.data.validation_files, encoding="utf-8") as f:
71
- lines.extend(f.readlines())
72
- add_blank = [hps.data.add_blank] * len(lines)
73
-
74
- if len(lines) != 0:
75
- num_processes = args.num_processes
76
- with ThreadPoolExecutor(max_workers=num_processes) as executor:
77
- _ = list(
78
- tqdm(
79
- executor.map(process_line, zip(lines, add_blank)),
80
- total=len(lines),
81
- file=SAFE_STDOUT,
82
- )
83
- )
84
-
85
- 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,410 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "metadata": {},
6
- "source": [
7
- "# Style-Bert-VITS2 (ver 2.3) の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上に構築します。グラボモードが有効になっていることを確認し、以下のセルを順に実行してください。"
30
- ]
31
- },
32
- {
33
- "cell_type": "code",
34
- "execution_count": null,
35
- "metadata": {},
36
- "outputs": [],
37
- "source": [
38
- "#@title このセルを実行して環境構築してください。\n",
39
- "#@markdown 最後に赤文字でエラーや警告が出ても何故かうまくいくみたいです。\n",
40
- "\n",
41
- "!git clone https://github.com/litagin02/Style-Bert-VITS2.git\n",
42
- "%cd Style-Bert-VITS2/\n",
43
- "!pip install -r requirements.txt\n",
44
- "!apt install libcublas11\n",
45
- "!python initialize.py --skip_jvnv"
46
- ]
47
- },
48
- {
49
- "cell_type": "code",
50
- "execution_count": null,
51
- "metadata": {},
52
- "outputs": [],
53
- "source": [
54
- "# Google driveを使う方はこちらを実行してください。\n",
55
- "\n",
56
- "from google.colab import drive\n",
57
- "drive.mount(\"/content/drive\")"
58
- ]
59
- },
60
- {
61
- "cell_type": "markdown",
62
- "metadata": {},
63
- "source": [
64
- "## 1. 初期設定\n",
65
- "\n",
66
- "学習とその結果を保存するディレクトリ名を指定します。\n",
67
- "Google driveの場合はそのまま実行、カスタマイズしたい方は変更して実行してください。"
68
- ]
69
- },
70
- {
71
- "cell_type": "code",
72
- "execution_count": 1,
73
- "metadata": {},
74
- "outputs": [],
75
- "source": [
76
- "# 学習に必要なファイルや途中経過が保存されるディレクトリ\n",
77
- "dataset_root = \"/content/drive/MyDrive/Style-Bert-VITS2/Data\"\n",
78
- "\n",
79
- "# 学習結果(音声合成に必要なファイルたち)が保存されるディレクトリ\n",
80
- "assets_root = \"/content/drive/MyDrive/Style-Bert-VITS2/model_assets\"\n",
81
- "\n",
82
- "import yaml\n",
83
- "\n",
84
- "\n",
85
- "with open(\"configs/paths.yml\", \"w\", encoding=\"utf-8\") as f:\n",
86
- " yaml.dump({\"dataset_root\": dataset_root, \"assets_root\": assets_root}, f)"
87
- ]
88
- },
89
- {
90
- "cell_type": "markdown",
91
- "metadata": {},
92
- "source": [
93
- "## 2. 学習に使うデータ準備\n",
94
- "\n",
95
- "すでに音声ファイル(1ファイル2-12秒程度)とその書き起こしデータがある場合は2.2を、ない場合は2.1を実行してください。"
96
- ]
97
- },
98
- {
99
- "cell_type": "markdown",
100
- "metadata": {},
101
- "source": [
102
- "### 2.1 音声ファイルからのデータセットの作成(ある人はスキップ可)\n",
103
- "\n",
104
- "音声ファイル(1ファイル2-12秒程度)とその書き起こしのデータセットを持っていない方は、(日本語の)音声ファイルのみから以下の手順でデータセットを作成することができます。Google drive上の`Style-Bert-VITS2/inputs/`フォルダに音声ファイル(wavファイル形式、1ファイルでも複数ファイルでも可)を置いて、下を実行すると、データセットが作られ、自動的に正しい場所へ配置されます。"
105
- ]
106
- },
107
- {
108
- "cell_type": "code",
109
- "execution_count": null,
110
- "metadata": {},
111
- "outputs": [],
112
- "source": [
113
- "# 元となる音声ファイル(wav形式)を入れるディレクトリ\n",
114
- "input_dir = \"/content/drive/MyDrive/Style-Bert-VITS2/inputs\"\n",
115
- "# モデル名(話者名)を入力\n",
116
- "model_name = \"your_model_name\"\n",
117
- "\n",
118
- "# こういうふうに書き起こして欲しいという例文(句読点の入れ方・笑い方や固有名詞等)\n",
119
- "initial_prompt = \"こんにちは。元気、ですかー?ふふっ、私は……ちゃんと元気だよ!\"\n",
120
- "\n",
121
- "!python slice.py -i {input_dir} -o {dataset_root}/{model_name}/raw\n",
122
- "!python transcribe.py -i {dataset_root}/{model_name}/raw -o {dataset_root}/{model_name}/esd.list --speaker_name {model_name} --compute_type float16 --initial_prompt {initial_prompt}"
123
- ]
124
- },
125
- {
126
- "cell_type": "markdown",
127
- "metadata": {},
128
- "source": [
129
- "成功したらそのまま3へ進んでください"
130
- ]
131
- },
132
- {
133
- "cell_type": "markdown",
134
- "metadata": {},
135
- "source": [
136
- "### 2.2 音声ファイルと書き起こしデータがすでにある場合\n",
137
- "\n",
138
- "指示に従って適切にデータセットを配置してください。\n",
139
- "\n",
140
- "次のセルを実行して、学習データをいれるフォルダ(1で設定した`dataset_root`)を作成します。"
141
- ]
142
- },
143
- {
144
- "cell_type": "code",
145
- "execution_count": 5,
146
- "metadata": {
147
- "id": "esCNJl704h52"
148
- },
149
- "outputs": [],
150
- "source": [
151
- "import os\n",
152
- "\n",
153
- "os.makedirs(dataset_root, exist_ok=True)"
154
- ]
155
- },
156
- {
157
- "cell_type": "markdown",
158
- "metadata": {},
159
- "source": [
160
- "次に、学習に必要なデータを、Google driveに作成された`Style-Bert-VITS2/Data`フォルダに配置します。\n",
161
- "\n",
162
- "まず音声データ(wavファイルで1ファイルが2-12秒程度の、長すぎず短すぎない発話のものをいくつか)と、書き起こしテキストを用意してください。wavファイル名やモデルの名前は空白を含まない半角で、wavファイルの拡張子は小文字`.wav`である必要があります。\n",
163
- "\n",
164
- "書き起こしテキストは、次の形式で記述してください。\n",
165
- "```\n",
166
- "****.wav|{話者名}|{言語ID、ZHかJPかEN}|{書き起こしテキスト}\n",
167
- "```\n",
168
- "\n",
169
- "例:\n",
170
- "```\n",
171
- "wav_number1.wav|hanako|JP|こんにちは、聞こえて、いますか?\n",
172
- "wav_next.wav|taro|JP|はい、聞こえています……。\n",
173
- "english_teacher.wav|Mary|EN|How are you? I'm fine, thank you, and you?\n",
174
- "...\n",
175
- "```\n",
176
- "日本語話者の単一話者データセットで構いません。\n",
177
- "\n",
178
- "### データセットの配置\n",
179
- "\n",
180
- "次にモデルの名前を適当に決めてください(空白を含まない半角英数字がよいです)。\n",
181
- "そして、書き起こしファイルを`esd.list`という名前で保存し、またwavファイルも`raw`というフォルダを作成し、あなたのGoogle Driveの中の(上で自動的に作られるはずの)`Data`フォルダのなかに、次のように配置します。\n",
182
- "```\n",
183
- "├── Data\n",
184
- "│ ├── {モデルの名前}\n",
185
- "│ │ ├── esd.list\n",
186
- "│ │ ├── raw\n",
187
- "│ │ │ ├── ****.wav\n",
188
- "│ │ │ ├── ****.wav\n",
189
- "│ │ │ ├── ...\n",
190
- "```"
191
- ]
192
- },
193
- {
194
- "cell_type": "markdown",
195
- "metadata": {
196
- "id": "5r85-W20ECcr"
197
- },
198
- "source": [
199
- "## 3. 学習の前処理\n",
200
- "\n",
201
- "次に学習の前処理を行います。必要なパラメータをここで指定します。次のセルに設定等を入力して実行してください。「~~かどうか」は`True`もしくは`False`を指定してください。"
202
- ]
203
- },
204
- {
205
- "cell_type": "code",
206
- "execution_count": 6,
207
- "metadata": {
208
- "id": "CXR7kjuF5GlE"
209
- },
210
- "outputs": [],
211
- "source": [
212
- "# 上でつけたフォルダの名前`Data/{model_name}/`\n",
213
- "model_name = \"your_model_name\"\n",
214
- "\n",
215
- "# JP-Extra (日本語特化版)を使うかどうか。日本語の能力が向上する代わりに英語と中国語は使えなくなります。\n",
216
- "use_jp_extra = True\n",
217
- "\n",
218
- "# 学習のバッチサイズ。VRAMのはみ出具合に応じて調整してください。\n",
219
- "batch_size = 4\n",
220
- "\n",
221
- "# 学習のエポック数(データセットを合計何周するか)。\n",
222
- "# 100ぐらいで十分かもしれませんが、もっと多くやると質が上がるのかもしれません。\n",
223
- "epochs = 100\n",
224
- "\n",
225
- "# 保存頻度。何ステップごとにモデルを保存するか。分からなければデフォルトのままで。\n",
226
- "save_every_steps = 1000\n",
227
- "\n",
228
- "# 音声ファイルの音量を正規化するかどうか\n",
229
- "normalize = False\n",
230
- "\n",
231
- "# 音声ファイルの開始・終了にある無音区間を削除するかどうか\n",
232
- "trim = False"
233
- ]
234
- },
235
- {
236
- "cell_type": "markdown",
237
- "metadata": {},
238
- "source": [
239
- "上のセルが実行されたら、次のセルを実行して学習の前処理を行います。"
240
- ]
241
- },
242
- {
243
- "cell_type": "code",
244
- "execution_count": null,
245
- "metadata": {
246
- "colab": {
247
- "base_uri": "https://localhost:8080/"
248
- },
249
- "id": "xMVaOIPLabV5",
250
- "outputId": "15fac868-9132-45d9-9f5f-365b6aeb67b0"
251
- },
252
- "outputs": [],
253
- "source": [
254
- "from webui_train import preprocess_all\n",
255
- "\n",
256
- "preprocess_all(\n",
257
- " model_name=model_name,\n",
258
- " batch_size=batch_size,\n",
259
- " epochs=epochs,\n",
260
- " save_every_steps=save_every_steps,\n",
261
- " num_processes=2,\n",
262
- " normalize=normalize,\n",
263
- " trim=trim,\n",
264
- " freeze_EN_bert=False,\n",
265
- " freeze_JP_bert=False,\n",
266
- " freeze_ZH_bert=False,\n",
267
- " freeze_style=False,\n",
268
- " freeze_decoder=False, # ここをTrueにするともしかしたら違う結果になるかもしれません。\n",
269
- " use_jp_extra=use_jp_extra,\n",
270
- " val_per_lang=0,\n",
271
- " log_interval=200,\n",
272
- ")"
273
- ]
274
- },
275
- {
276
- "cell_type": "markdown",
277
- "metadata": {},
278
- "source": [
279
- "## 4. 学習\n",
280
- "\n",
281
- "前処理が正常に終わったら、学習を行います。次のセルを実行すると学習が始まります。\n",
282
- "\n",
283
- "学習の結果は、上で指定した`save_every_steps`の間隔で、Google Driveの中の`Style-Bert-VITS2/Data/{モデルの名前}/model_assets/`フォルダに保存されます。\n",
284
- "\n",
285
- "このフォルダをダウンロードし、ローカルのStyle-Bert-VITS2の`model_assets`フォルダに上書きすれば、学習結果を使うことができます。"
286
- ]
287
- },
288
- {
289
- "cell_type": "code",
290
- "execution_count": null,
291
- "metadata": {
292
- "colab": {
293
- "base_uri": "https://localhost:8080/"
294
- },
295
- "id": "laieKrbEb6Ij",
296
- "outputId": "72238c88-f294-4ed9-84f6-84c1c17999ca"
297
- },
298
- "outputs": [],
299
- "source": [
300
- "# 上でつけたモデル名を入力。学習を途中からする場合はきちんとモデルが保存されているフォルダ名を入力。\n",
301
- "model_name = \"your_model_name\"\n",
302
- "\n",
303
- "\n",
304
- "import yaml\n",
305
- "from webui_train import get_path\n",
306
- "\n",
307
- "dataset_path, _, _, _, config_path = get_path(model_name)\n",
308
- "\n",
309
- "with open(\"default_config.yml\", \"r\", encoding=\"utf-8\") as f:\n",
310
- " yml_data = yaml.safe_load(f)\n",
311
- "yml_data[\"model_name\"] = model_name\n",
312
- "with open(\"config.yml\", \"w\", encoding=\"utf-8\") as f:\n",
313
- " yaml.dump(yml_data, f, allow_unicode=True)"
314
- ]
315
- },
316
- {
317
- "cell_type": "code",
318
- "execution_count": null,
319
- "metadata": {},
320
- "outputs": [],
321
- "source": [
322
- "# 日本語特化版を「使う」場合\n",
323
- "!python train_ms_jp_extra.py --config {config_path} --model {dataset_path} --assets_root {assets_root}"
324
- ]
325
- },
326
- {
327
- "cell_type": "code",
328
- "execution_count": null,
329
- "metadata": {},
330
- "outputs": [],
331
- "source": [
332
- "# 日本語特化版を「使わない」場合\n",
333
- "!python train_ms.py --config {config_path} --model {dataset_path} --assets_root {assets_root}"
334
- ]
335
- },
336
- {
337
- "cell_type": "code",
338
- "execution_count": null,
339
- "metadata": {
340
- "colab": {
341
- "base_uri": "https://localhost:8080/"
342
- },
343
- "id": "c7g0hrdeP1Tl",
344
- "outputId": "94f9a6f6-027f-4554-ce0c-60ac56251c22"
345
- },
346
- "outputs": [],
347
- "source": [
348
- "#@title 学習結果を試すならここから\n",
349
- "!python app.py --share --dir {assets_root}"
350
- ]
351
- },
352
- {
353
- "cell_type": "markdown",
354
- "metadata": {},
355
- "source": [
356
- "## 5. スタイル分け"
357
- ]
358
- },
359
- {
360
- "cell_type": "code",
361
- "execution_count": null,
362
- "metadata": {},
363
- "outputs": [],
364
- "source": [
365
- "!python webui_style_vectors.py --share"
366
- ]
367
- },
368
- {
369
- "cell_type": "markdown",
370
- "metadata": {},
371
- "source": [
372
- "## 6. マージ"
373
- ]
374
- },
375
- {
376
- "cell_type": "code",
377
- "execution_count": null,
378
- "metadata": {},
379
- "outputs": [],
380
- "source": [
381
- "!python webui_merge.py --share"
382
- ]
383
- }
384
- ],
385
- "metadata": {
386
- "accelerator": "GPU",
387
- "colab": {
388
- "gpuType": "T4",
389
- "provenance": []
390
- },
391
- "kernelspec": {
392
- "display_name": "Python 3",
393
- "name": "python3"
394
- },
395
- "language_info": {
396
- "codemirror_mode": {
397
- "name": "ipython",
398
- "version": 3
399
- },
400
- "file_extension": ".py",
401
- "mimetype": "text/x-python",
402
- "name": "python",
403
- "nbconvert_exporter": "python",
404
- "pygments_lexer": "ipython3",
405
- "version": "3.10.11"
406
- }
407
- },
408
- "nbformat": 4,
409
- "nbformat_minor": 0
410
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"
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,16 +0,0 @@
1
- """
2
- logger封装
3
- """
4
- from loguru import logger
5
-
6
- from .stdout_wrapper import SAFE_STDOUT
7
-
8
- # 移除所有默认的处理器
9
- logger.remove()
10
-
11
- # 自定义格式并添加到标准输出
12
- log_format = (
13
- "<g>{time:MM-DD HH:mm:ss}</g> |<lvl>{level:^8}</lvl>| {file}:{line} | {message}"
14
- )
15
-
16
- logger.add(SAFE_STDOUT, format=log_format, backtrace=True, diagnose=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
config.py CHANGED
@@ -2,14 +2,21 @@
2
  @Desc: 全局配置文件读取
3
  """
4
 
5
- import os
6
  import shutil
7
- from typing import Dict, List
 
8
 
9
  import torch
10
  import yaml
11
 
12
- from common.log import logger
 
 
 
 
 
 
 
13
 
14
  # If not cuda available, set possible devices to cpu
15
  cuda_available = torch.cuda.is_available()
@@ -19,17 +26,17 @@ class Resample_config:
19
  """重采样配置"""
20
 
21
  def __init__(self, in_dir: str, out_dir: str, sampling_rate: int = 44100):
22
- self.sampling_rate: int = sampling_rate # 目标采样率
23
- self.in_dir: str = in_dir # 待处理音频目录路径
24
- self.out_dir: str = out_dir # 重采样输出路径
25
 
26
  @classmethod
27
- def from_dict(cls, dataset_path: str, data: Dict[str, any]):
28
  """从字典中生成实例"""
29
 
30
  # 不检查路径是否有效,此逻辑在resample.py中处理
31
- data["in_dir"] = os.path.join(dataset_path, data["in_dir"])
32
- data["out_dir"] = os.path.join(dataset_path, data["out_dir"])
33
 
34
  return cls(**data)
35
 
@@ -48,39 +55,32 @@ class Preprocess_text_config:
48
  max_val_total: int = 10000,
49
  clean: bool = True,
50
  ):
51
- self.transcription_path: str = (
52
- transcription_path # 原始文本文件路径,文本格式应为{wav_path}|{speaker_name}|{language}|{text}。
53
- )
54
- self.cleaned_path: str = (
55
- cleaned_path # 数据清洗后文本路径,可以不填。不填则将在原始文本目录生成
56
- )
57
- self.train_path: str = (
58
- train_path # 训练集路径,可以不填。不填则将在原始文本目录生成
59
- )
60
- self.val_path: str = (
61
- val_path # 验证集路径,可以不填。不填则将在原始文本目录生成
62
- )
63
- self.config_path: str = config_path # 配置文件路径
64
- self.val_per_lang: int = val_per_lang # 每个speaker的验证集条数
65
- self.max_val_total: int = (
66
- max_val_total # 验证集最大条数,多于的会被截断并放到训练集中
67
- )
68
- self.clean: bool = clean # 是否进行数据清洗
69
 
70
  @classmethod
71
- def from_dict(cls, dataset_path: str, data: Dict[str, any]):
72
  """从字典中生成实例"""
73
 
74
- data["transcription_path"] = os.path.join(
75
- dataset_path, data["transcription_path"]
76
- )
77
  if data["cleaned_path"] == "" or data["cleaned_path"] is None:
78
- data["cleaned_path"] = None
79
  else:
80
- data["cleaned_path"] = os.path.join(dataset_path, data["cleaned_path"])
81
- data["train_path"] = os.path.join(dataset_path, data["train_path"])
82
- data["val_path"] = os.path.join(dataset_path, data["val_path"])
83
- data["config_path"] = os.path.join(dataset_path, data["config_path"])
84
 
85
  return cls(**data)
86
 
@@ -91,11 +91,11 @@ class Bert_gen_config:
91
  def __init__(
92
  self,
93
  config_path: str,
94
- num_processes: int = 2,
95
  device: str = "cuda",
96
  use_multi_device: bool = False,
97
  ):
98
- self.config_path = config_path
99
  self.num_processes = num_processes
100
  if not cuda_available:
101
  device = "cpu"
@@ -103,8 +103,8 @@ class Bert_gen_config:
103
  self.use_multi_device = use_multi_device
104
 
105
  @classmethod
106
- def from_dict(cls, dataset_path: str, data: Dict[str, any]):
107
- data["config_path"] = os.path.join(dataset_path, data["config_path"])
108
 
109
  return cls(**data)
110
 
@@ -118,15 +118,15 @@ class Style_gen_config:
118
  num_processes: int = 4,
119
  device: str = "cuda",
120
  ):
121
- self.config_path = config_path
122
  self.num_processes = num_processes
123
  if not cuda_available:
124
  device = "cpu"
125
  self.device = device
126
 
127
  @classmethod
128
- def from_dict(cls, dataset_path: str, data: Dict[str, any]):
129
- data["config_path"] = os.path.join(dataset_path, data["config_path"])
130
 
131
  return cls(**data)
132
 
@@ -137,7 +137,7 @@ class Train_ms_config:
137
  def __init__(
138
  self,
139
  config_path: str,
140
- env: Dict[str, any],
141
  # base: Dict[str, any],
142
  model_dir: str,
143
  num_workers: int,
@@ -146,16 +146,18 @@ class Train_ms_config:
146
  ):
147
  self.env = env # 需要加载的环境变量
148
  # self.base = base # 底模配置
149
- self.model_dir = model_dir # 训练模型存储目录,该路径为相对于dataset_path的路径,而非项目根目录
150
- self.config_path = config_path # 配置文件路径
 
 
151
  self.num_workers = num_workers # worker数量
152
  self.spec_cache = spec_cache # 是否启用spec缓存
153
  self.keep_ckpts = keep_ckpts # ckpt数量
154
 
155
  @classmethod
156
- def from_dict(cls, dataset_path: str, data: Dict[str, any]):
157
  # data["model"] = os.path.join(dataset_path, data["model"])
158
- data["config_path"] = os.path.join(dataset_path, data["config_path"])
159
 
160
  return cls(**data)
161
 
@@ -175,20 +177,18 @@ class Webui_config:
175
  ):
176
  if not cuda_available:
177
  device = "cpu"
178
- self.device: str = device
179
- self.model: str = model # 端口号
180
- self.config_path: str = config_path # 是否公开部署,对外网开放
181
- self.port: int = port # 是否开启debug模式
182
- self.share: bool = share # 模型路径
183
- self.debug: bool = debug # 配置文件路径
184
- self.language_identification_library: str = (
185
- language_identification_library # 语种识别库
186
- )
187
 
188
  @classmethod
189
- def from_dict(cls, dataset_path: str, data: Dict[str, any]):
190
- data["config_path"] = os.path.join(dataset_path, data["config_path"])
191
- data["model"] = os.path.join(dataset_path, data["model"])
192
  return cls(**data)
193
 
194
 
@@ -199,7 +199,7 @@ class Server_config:
199
  device: str = "cuda",
200
  limit: int = 100,
201
  language: str = "JP",
202
- origins: List[str] = None,
203
  ):
204
  self.port: int = port
205
  if not cuda_available:
@@ -207,10 +207,10 @@ class Server_config:
207
  self.device: str = device
208
  self.language: str = language
209
  self.limit: int = limit
210
- self.origins: List[str] = origins
211
 
212
  @classmethod
213
- def from_dict(cls, data: Dict[str, any]):
214
  return cls(**data)
215
 
216
 
@@ -222,32 +222,33 @@ class Translate_config:
222
  self.secret_key = secret_key
223
 
224
  @classmethod
225
- def from_dict(cls, data: Dict[str, any]):
226
  return cls(**data)
227
 
228
 
229
  class Config:
230
- def __init__(self, config_path: str, path_config: dict[str, str]):
231
- if not os.path.isfile(config_path) and os.path.isfile("default_config.yml"):
232
  shutil.copy(src="default_config.yml", dst=config_path)
233
  logger.info(
234
  f"A configuration file {config_path} has been generated based on the default configuration file default_config.yml."
235
  )
236
  logger.info(
237
- "If you have no special needs, please do not modify default_config.yml."
238
  )
239
  # sys.exit(0)
240
- with open(file=config_path, mode="r", encoding="utf-8") as file:
241
- yaml_config: Dict[str, any] = yaml.safe_load(file.read())
242
  model_name: str = yaml_config["model_name"]
243
  self.model_name: str = model_name
244
  if "dataset_path" in yaml_config:
245
- dataset_path = yaml_config["dataset_path"]
246
  else:
247
- dataset_path = os.path.join(path_config["dataset_root"], model_name)
248
- self.dataset_path: str = dataset_path
249
- self.assets_root: str = path_config["assets_root"]
250
- self.out_dir = os.path.join(self.assets_root, model_name)
 
251
  self.resample_config: Resample_config = Resample_config.from_dict(
252
  dataset_path, yaml_config["resample"]
253
  )
@@ -276,16 +277,31 @@ class Config:
276
  # )
277
 
278
 
279
- with open(os.path.join("configs", "paths.yml"), "r", encoding="utf-8") as f:
280
- path_config: dict[str, str] = yaml.safe_load(f.read())
281
- # Should contain the following keys:
282
- # - dataset_root: the root directory of the dataset, default to "Data"
283
- # - assets_root: the root directory of the assets, default to "model_assets"
 
 
 
 
 
 
 
 
 
 
 
 
284
 
 
 
 
 
 
 
 
 
285
 
286
- try:
287
- config = Config("config.yml", path_config)
288
- except (TypeError, KeyError):
289
- logger.warning("Old config.yml found. Replace it with default_config.yml.")
290
- shutil.copy(src="default_config.yml", dst="config.yml")
291
- config = Config("config.yml", path_config)
 
2
  @Desc: 全局配置文件读取
3
  """
4
 
 
5
  import shutil
6
+ from pathlib import Path
7
+ from typing import Any
8
 
9
  import torch
10
  import yaml
11
 
12
+ from style_bert_vits2.logging import logger
13
+
14
+
15
+ class PathConfig:
16
+ def __init__(self, dataset_root: str, assets_root: str):
17
+ self.dataset_root = Path(dataset_root)
18
+ self.assets_root = Path(assets_root)
19
+
20
 
21
  # If not cuda available, set possible devices to cpu
22
  cuda_available = torch.cuda.is_available()
 
26
  """重采样配置"""
27
 
28
  def __init__(self, in_dir: str, out_dir: str, sampling_rate: int = 44100):
29
+ self.sampling_rate = sampling_rate # 目标采样率
30
+ self.in_dir = Path(in_dir) # 待处理音频目录路径
31
+ self.out_dir = Path(out_dir) # 重采样输出路径
32
 
33
  @classmethod
34
+ def from_dict(cls, dataset_path: Path, data: dict[str, Any]):
35
  """从字典中生成实例"""
36
 
37
  # 不检查路径是否有效,此逻辑在resample.py中处理
38
+ data["in_dir"] = dataset_path / data["in_dir"]
39
+ data["out_dir"] = dataset_path / data["out_dir"]
40
 
41
  return cls(**data)
42
 
 
55
  max_val_total: int = 10000,
56
  clean: bool = True,
57
  ):
58
+ self.transcription_path = Path(transcription_path)
59
+ self.train_path = Path(train_path)
60
+ if cleaned_path == "" or cleaned_path is None:
61
+ self.cleaned_path = self.transcription_path.with_name(
62
+ self.transcription_path.name + ".cleaned"
63
+ )
64
+ else:
65
+ self.cleaned_path = Path(cleaned_path)
66
+ self.val_path = Path(val_path)
67
+ self.config_path = Path(config_path)
68
+ self.val_per_lang = val_per_lang
69
+ self.max_val_total = max_val_total
70
+ self.clean = clean
 
 
 
 
 
71
 
72
  @classmethod
73
+ def from_dict(cls, dataset_path: Path, data: dict[str, Any]):
74
  """从字典中生成实例"""
75
 
76
+ data["transcription_path"] = dataset_path / data["transcription_path"]
 
 
77
  if data["cleaned_path"] == "" or data["cleaned_path"] is None:
78
+ data["cleaned_path"] = ""
79
  else:
80
+ data["cleaned_path"] = dataset_path / data["cleaned_path"]
81
+ data["train_path"] = dataset_path / data["train_path"]
82
+ data["val_path"] = dataset_path / data["val_path"]
83
+ data["config_path"] = dataset_path / data["config_path"]
84
 
85
  return cls(**data)
86
 
 
91
  def __init__(
92
  self,
93
  config_path: str,
94
+ num_processes: int = 1,
95
  device: str = "cuda",
96
  use_multi_device: bool = False,
97
  ):
98
+ self.config_path = Path(config_path)
99
  self.num_processes = num_processes
100
  if not cuda_available:
101
  device = "cpu"
 
103
  self.use_multi_device = use_multi_device
104
 
105
  @classmethod
106
+ def from_dict(cls, dataset_path: Path, data: dict[str, Any]):
107
+ data["config_path"] = dataset_path / data["config_path"]
108
 
109
  return cls(**data)
110
 
 
118
  num_processes: int = 4,
119
  device: str = "cuda",
120
  ):
121
+ self.config_path = Path(config_path)
122
  self.num_processes = num_processes
123
  if not cuda_available:
124
  device = "cpu"
125
  self.device = device
126
 
127
  @classmethod
128
+ def from_dict(cls, dataset_path: Path, data: dict[str, Any]):
129
+ data["config_path"] = dataset_path / data["config_path"]
130
 
131
  return cls(**data)
132
 
 
137
  def __init__(
138
  self,
139
  config_path: str,
140
+ env: dict[str, Any],
141
  # base: Dict[str, any],
142
  model_dir: str,
143
  num_workers: int,
 
146
  ):
147
  self.env = env # 需要加载的环境变量
148
  # self.base = base # 底模配置
149
+ self.model_dir = Path(
150
+ model_dir
151
+ ) # 训练模型存储目录,该路径为相对于dataset_path的路径,而非项目根目录
152
+ self.config_path = Path(config_path) # 配置文件路径
153
  self.num_workers = num_workers # worker数量
154
  self.spec_cache = spec_cache # 是否启用spec缓存
155
  self.keep_ckpts = keep_ckpts # ckpt数量
156
 
157
  @classmethod
158
+ def from_dict(cls, dataset_path: Path, data: dict[str, Any]):
159
  # data["model"] = os.path.join(dataset_path, data["model"])
160
+ data["config_path"] = dataset_path / data["config_path"]
161
 
162
  return cls(**data)
163
 
 
177
  ):
178
  if not cuda_available:
179
  device = "cpu"
180
+ self.device = device
181
+ self.model = Path(model)
182
+ self.config_path = Path(config_path)
183
+ self.port: int = port
184
+ self.share: bool = share
185
+ self.debug: bool = debug
186
+ self.language_identification_library: str = language_identification_library
 
 
187
 
188
  @classmethod
189
+ def from_dict(cls, dataset_path: Path, data: dict[str, Any]):
190
+ data["config_path"] = dataset_path / data["config_path"]
191
+ data["model"] = dataset_path / data["model"]
192
  return cls(**data)
193
 
194
 
 
199
  device: str = "cuda",
200
  limit: int = 100,
201
  language: str = "JP",
202
+ origins: list[str] = ["*"],
203
  ):
204
  self.port: int = port
205
  if not cuda_available:
 
207
  self.device: str = device
208
  self.language: str = language
209
  self.limit: int = limit
210
+ self.origins: list[str] = origins
211
 
212
  @classmethod
213
+ def from_dict(cls, data: dict[str, Any]):
214
  return cls(**data)
215
 
216
 
 
222
  self.secret_key = secret_key
223
 
224
  @classmethod
225
+ def from_dict(cls, data: dict[str, Any]):
226
  return cls(**data)
227
 
228
 
229
  class Config:
230
+ def __init__(self, config_path: str, path_config: PathConfig):
231
+ if not Path(config_path).exists():
232
  shutil.copy(src="default_config.yml", dst=config_path)
233
  logger.info(
234
  f"A configuration file {config_path} has been generated based on the default configuration file default_config.yml."
235
  )
236
  logger.info(
237
+ "Please do not modify default_config.yml. Instead, modify config.yml."
238
  )
239
  # sys.exit(0)
240
+ with open(config_path, encoding="utf-8") as file:
241
+ yaml_config: dict[str, Any] = yaml.safe_load(file.read())
242
  model_name: str = yaml_config["model_name"]
243
  self.model_name: str = model_name
244
  if "dataset_path" in yaml_config:
245
+ dataset_path = Path(yaml_config["dataset_path"])
246
  else:
247
+ dataset_path = path_config.dataset_root / model_name
248
+ self.dataset_path = dataset_path
249
+ self.dataset_root = path_config.dataset_root
250
+ self.assets_root = path_config.assets_root
251
+ self.out_dir = self.assets_root / model_name
252
  self.resample_config: Resample_config = Resample_config.from_dict(
253
  dataset_path, yaml_config["resample"]
254
  )
 
277
  # )
278
 
279
 
280
+ # Load and initialize the configuration
281
+
282
+
283
+ def get_path_config() -> PathConfig:
284
+ path_config_path = Path("configs/paths.yml")
285
+ if not path_config_path.exists():
286
+ shutil.copy(src="configs/default_paths.yml", dst=path_config_path)
287
+ logger.info(
288
+ f"A configuration file {path_config_path} has been generated based on the default configuration file default_paths.yml."
289
+ )
290
+ logger.info(
291
+ "Please do not modify configs/default_paths.yml. Instead, modify configs/paths.yml."
292
+ )
293
+ with open(path_config_path, encoding="utf-8") as file:
294
+ path_config_dict: dict[str, str] = yaml.safe_load(file.read())
295
+ return PathConfig(**path_config_dict)
296
+
297
 
298
+ def get_config() -> Config:
299
+ path_config = get_path_config()
300
+ try:
301
+ config = Config("config.yml", path_config)
302
+ except (TypeError, KeyError):
303
+ logger.warning("Old config.yml found. Replace it with default_config.yml.")
304
+ shutil.copy(src="default_config.yml", dst="config.yml")
305
+ config = Config("config.yml", path_config)
306
 
307
+ return config
 
 
 
 
 
configs/config.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "model_name": "your_model_name",
3
  "train": {
4
  "log_interval": 200,
5
  "eval_interval": 1000,
@@ -24,8 +24,9 @@
24
  "freeze_encoder": false
25
  },
26
  "data": {
27
- "training_files": "Data/your_model_name/filelists/train.list",
28
- "validation_files": "Data/your_model_name/filelists/val.list",
 
29
  "max_wav_value": 32768.0,
30
  "sampling_rate": 44100,
31
  "filter_length": 2048,
@@ -68,5 +69,5 @@
68
  "use_spectral_norm": false,
69
  "gin_channels": 256
70
  },
71
- "version": "2.3"
72
  }
 
1
  {
2
+ "model_name": "Dummy",
3
  "train": {
4
  "log_interval": 200,
5
  "eval_interval": 1000,
 
24
  "freeze_encoder": false
25
  },
26
  "data": {
27
+ "use_jp_extra": false,
28
+ "training_files": "Data/Dummy/train.list",
29
+ "validation_files": "Data/Dummy/val.list",
30
  "max_wav_value": 32768.0,
31
  "sampling_rate": 44100,
32
  "filter_length": 2048,
 
69
  "use_spectral_norm": false,
70
  "gin_channels": 256
71
  },
72
+ "version": "2.5.0"
73
  }
configs/{configs_jp_extra.json → config_jp_extra.json} RENAMED
@@ -1,4 +1,5 @@
1
  {
 
2
  "train": {
3
  "log_interval": 200,
4
  "eval_interval": 1000,
@@ -27,8 +28,8 @@
27
  },
28
  "data": {
29
  "use_jp_extra": true,
30
- "training_files": "filelists/train.list",
31
- "validation_files": "filelists/val.list",
32
  "max_wav_value": 32768.0,
33
  "sampling_rate": 44100,
34
  "filter_length": 2048,
@@ -75,5 +76,5 @@
75
  "initial_channel": 64
76
  }
77
  },
78
- "version": "2.3-JP-Extra"
79
  }
 
1
  {
2
+ "model_name": "Dummy",
3
  "train": {
4
  "log_interval": 200,
5
  "eval_interval": 1000,
 
28
  },
29
  "data": {
30
  "use_jp_extra": true,
31
+ "training_files": "Data/Dummy/train.list",
32
+ "validation_files": "Data/Dummy/val.list",
33
  "max_wav_value": 32768.0,
34
  "sampling_rate": 44100,
35
  "filter_length": 2048,
 
76
  "initial_channel": 64
77
  }
78
  },
79
+ "version": "2.5.0-JP-Extra"
80
  }
configs/default_paths.yml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Root directory of the training dataset.
2
+ # The training dataset of {model_name} should be placed in {dataset_root}/{model_name}.
3
+ dataset_root: Data
4
+
5
+ # Root directory of the model assets (for inference).
6
+ # In training, the model assets will be saved to {assets_root}/{model_name},
7
+ # and in inference, we load all the models from {assets_root}.
8
+ assets_root: model_assets
data_utils.py DELETED
@@ -1,456 +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
- import commons
11
- from config import config
12
- from mel_processing import mel_spectrogram_torch, spectrogram_torch
13
- from text import cleaned_text_to_sequence
14
- from common.log import logger
15
- from utils import load_filepaths_and_text, load_wav_to_torch
16
-
17
- """Multi speaker version"""
18
-
19
-
20
- class TextAudioSpeakerLoader(torch.utils.data.Dataset):
21
- """
22
- 1) loads audio, speaker_id, text pairs
23
- 2) normalizes text and converts them to sequences of integers
24
- 3) computes spectrograms from audio files.
25
- """
26
-
27
- def __init__(self, audiopaths_sid_text, hparams):
28
- self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
29
- self.max_wav_value = hparams.max_wav_value
30
- self.sampling_rate = hparams.sampling_rate
31
- self.filter_length = hparams.filter_length
32
- self.hop_length = hparams.hop_length
33
- self.win_length = hparams.win_length
34
- self.sampling_rate = hparams.sampling_rate
35
- self.spk_map = hparams.spk2id
36
- self.hparams = hparams
37
- self.use_jp_extra = getattr(hparams, "use_jp_extra", False)
38
-
39
- self.use_mel_spec_posterior = getattr(
40
- hparams, "use_mel_posterior_encoder", False
41
- )
42
- if self.use_mel_spec_posterior:
43
- self.n_mel_channels = getattr(hparams, "n_mel_channels", 80)
44
-
45
- self.cleaned_text = getattr(hparams, "cleaned_text", False)
46
-
47
- self.add_blank = hparams.add_blank
48
- self.min_text_len = getattr(hparams, "min_text_len", 1)
49
- self.max_text_len = getattr(hparams, "max_text_len", 384)
50
-
51
- random.seed(1234)
52
- random.shuffle(self.audiopaths_sid_text)
53
- self._filter()
54
-
55
- def _filter(self):
56
- """
57
- Filter text & store spec lengths
58
- """
59
- # Store spectrogram lengths for Bucketing
60
- # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
61
- # spec_length = wav_length // hop_length
62
-
63
- audiopaths_sid_text_new = []
64
- lengths = []
65
- skipped = 0
66
- logger.info("Init dataset...")
67
- for _id, spk, language, text, phones, tone, word2ph in tqdm(
68
- self.audiopaths_sid_text, file=sys.stdout
69
- ):
70
- audiopath = f"{_id}"
71
- if self.min_text_len <= len(phones) and len(phones) <= self.max_text_len:
72
- phones = phones.split(" ")
73
- tone = [int(i) for i in tone.split(" ")]
74
- word2ph = [int(i) for i in word2ph.split(" ")]
75
- audiopaths_sid_text_new.append(
76
- [audiopath, spk, language, text, phones, tone, word2ph]
77
- )
78
- lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
79
- else:
80
- skipped += 1
81
- logger.info(
82
- "skipped: "
83
- + str(skipped)
84
- + ", total: "
85
- + str(len(self.audiopaths_sid_text))
86
- )
87
- self.audiopaths_sid_text = audiopaths_sid_text_new
88
- self.lengths = lengths
89
-
90
- def get_audio_text_speaker_pair(self, audiopath_sid_text):
91
- # separate filename, speaker_id and text
92
- audiopath, sid, language, text, phones, tone, word2ph = audiopath_sid_text
93
-
94
- bert, ja_bert, en_bert, phones, tone, language = self.get_text(
95
- text, word2ph, phones, tone, language, audiopath
96
- )
97
-
98
- spec, wav = self.get_audio(audiopath)
99
- sid = torch.LongTensor([int(self.spk_map[sid])])
100
- style_vec = torch.FloatTensor(np.load(f"{audiopath}.npy"))
101
- if self.use_jp_extra:
102
- return (phones, spec, wav, sid, tone, language, ja_bert, style_vec)
103
- else:
104
- return (
105
- phones,
106
- spec,
107
- wav,
108
- sid,
109
- tone,
110
- language,
111
- bert,
112
- ja_bert,
113
- en_bert,
114
- style_vec,
115
- )
116
-
117
- def get_audio(self, filename):
118
- audio, sampling_rate = load_wav_to_torch(filename)
119
- if sampling_rate != self.sampling_rate:
120
- raise ValueError(
121
- "{} {} SR doesn't match target {} SR".format(
122
- filename, sampling_rate, self.sampling_rate
123
- )
124
- )
125
- audio_norm = audio / self.max_wav_value
126
- audio_norm = audio_norm.unsqueeze(0)
127
- spec_filename = filename.replace(".wav", ".spec.pt")
128
- if self.use_mel_spec_posterior:
129
- spec_filename = spec_filename.replace(".spec.pt", ".mel.pt")
130
- try:
131
- spec = torch.load(spec_filename)
132
- except:
133
- if self.use_mel_spec_posterior:
134
- spec = mel_spectrogram_torch(
135
- audio_norm,
136
- self.filter_length,
137
- self.n_mel_channels,
138
- self.sampling_rate,
139
- self.hop_length,
140
- self.win_length,
141
- self.hparams.mel_fmin,
142
- self.hparams.mel_fmax,
143
- center=False,
144
- )
145
- else:
146
- spec = spectrogram_torch(
147
- audio_norm,
148
- self.filter_length,
149
- self.sampling_rate,
150
- self.hop_length,
151
- self.win_length,
152
- center=False,
153
- )
154
- spec = torch.squeeze(spec, 0)
155
- if config.train_ms_config.spec_cache:
156
- torch.save(spec, spec_filename)
157
- return spec, audio_norm
158
-
159
- def get_text(self, text, word2ph, phone, tone, language_str, wav_path):
160
- phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
161
- if self.add_blank:
162
- phone = commons.intersperse(phone, 0)
163
- tone = commons.intersperse(tone, 0)
164
- language = commons.intersperse(language, 0)
165
- for i in range(len(word2ph)):
166
- word2ph[i] = word2ph[i] * 2
167
- word2ph[0] += 1
168
- bert_path = wav_path.replace(".wav", ".bert.pt")
169
- try:
170
- bert_ori = torch.load(bert_path)
171
- assert bert_ori.shape[-1] == len(phone)
172
- except Exception as e:
173
- logger.warning("Bert load Failed")
174
- logger.warning(e)
175
-
176
- if language_str == "ZH":
177
- bert = bert_ori
178
- ja_bert = torch.zeros(1024, len(phone))
179
- en_bert = torch.zeros(1024, len(phone))
180
- elif language_str == "JP":
181
- bert = torch.zeros(1024, len(phone))
182
- ja_bert = bert_ori
183
- en_bert = torch.zeros(1024, len(phone))
184
- elif language_str == "EN":
185
- bert = torch.zeros(1024, len(phone))
186
- ja_bert = torch.zeros(1024, len(phone))
187
- en_bert = bert_ori
188
- phone = torch.LongTensor(phone)
189
- tone = torch.LongTensor(tone)
190
- language = torch.LongTensor(language)
191
- return bert, ja_bert, en_bert, phone, tone, language
192
-
193
- def get_sid(self, sid):
194
- sid = torch.LongTensor([int(sid)])
195
- return sid
196
-
197
- def __getitem__(self, index):
198
- return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
199
-
200
- def __len__(self):
201
- return len(self.audiopaths_sid_text)
202
-
203
-
204
- class TextAudioSpeakerCollate:
205
- """Zero-pads model inputs and targets"""
206
-
207
- def __init__(self, return_ids=False, use_jp_extra=False):
208
- self.return_ids = return_ids
209
- self.use_jp_extra = use_jp_extra
210
-
211
- def __call__(self, batch):
212
- """Collate's training batch from normalized text, audio and speaker identities
213
- PARAMS
214
- ------
215
- batch: [text_normalized, spec_normalized, wav_normalized, sid]
216
- """
217
- # Right zero-pad all one-hot text sequences to max input length
218
- _, ids_sorted_decreasing = torch.sort(
219
- torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True
220
- )
221
-
222
- max_text_len = max([len(x[0]) for x in batch])
223
- max_spec_len = max([x[1].size(1) for x in batch])
224
- max_wav_len = max([x[2].size(1) for x in batch])
225
-
226
- text_lengths = torch.LongTensor(len(batch))
227
- spec_lengths = torch.LongTensor(len(batch))
228
- wav_lengths = torch.LongTensor(len(batch))
229
- sid = torch.LongTensor(len(batch))
230
-
231
- text_padded = torch.LongTensor(len(batch), max_text_len)
232
- tone_padded = torch.LongTensor(len(batch), max_text_len)
233
- language_padded = torch.LongTensor(len(batch), max_text_len)
234
- # This is ZH bert if not use_jp_extra, JA bert if use_jp_extra
235
- bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
236
- if not self.use_jp_extra:
237
- ja_bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
238
- en_bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
239
- style_vec = torch.FloatTensor(len(batch), 256)
240
-
241
- spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
242
- wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
243
- text_padded.zero_()
244
- tone_padded.zero_()
245
- language_padded.zero_()
246
- spec_padded.zero_()
247
- wav_padded.zero_()
248
- bert_padded.zero_()
249
- if not self.use_jp_extra:
250
- ja_bert_padded.zero_()
251
- en_bert_padded.zero_()
252
- style_vec.zero_()
253
-
254
- for i in range(len(ids_sorted_decreasing)):
255
- row = batch[ids_sorted_decreasing[i]]
256
-
257
- text = row[0]
258
- text_padded[i, : text.size(0)] = text
259
- text_lengths[i] = text.size(0)
260
-
261
- spec = row[1]
262
- spec_padded[i, :, : spec.size(1)] = spec
263
- spec_lengths[i] = spec.size(1)
264
-
265
- wav = row[2]
266
- wav_padded[i, :, : wav.size(1)] = wav
267
- wav_lengths[i] = wav.size(1)
268
-
269
- sid[i] = row[3]
270
-
271
- tone = row[4]
272
- tone_padded[i, : tone.size(0)] = tone
273
-
274
- language = row[5]
275
- language_padded[i, : language.size(0)] = language
276
-
277
- bert = row[6]
278
- bert_padded[i, :, : bert.size(1)] = bert
279
-
280
- if self.use_jp_extra:
281
- style_vec[i, :] = row[7]
282
- else:
283
- ja_bert = row[7]
284
- ja_bert_padded[i, :, : ja_bert.size(1)] = ja_bert
285
-
286
- en_bert = row[8]
287
- en_bert_padded[i, :, : en_bert.size(1)] = en_bert
288
- style_vec[i, :] = row[9]
289
-
290
- if self.use_jp_extra:
291
- return (
292
- text_padded,
293
- text_lengths,
294
- spec_padded,
295
- spec_lengths,
296
- wav_padded,
297
- wav_lengths,
298
- sid,
299
- tone_padded,
300
- language_padded,
301
- bert_padded,
302
- style_vec,
303
- )
304
- else:
305
- return (
306
- text_padded,
307
- text_lengths,
308
- spec_padded,
309
- spec_lengths,
310
- wav_padded,
311
- wav_lengths,
312
- sid,
313
- tone_padded,
314
- language_padded,
315
- bert_padded,
316
- ja_bert_padded,
317
- en_bert_padded,
318
- style_vec,
319
- )
320
-
321
-
322
- class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
323
- """
324
- Maintain similar input lengths in a batch.
325
- Length groups are specified by boundaries.
326
- Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
327
-
328
- It removes samples which are not included in the boundaries.
329
- Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
330
- """
331
-
332
- def __init__(
333
- self,
334
- dataset,
335
- batch_size,
336
- boundaries,
337
- num_replicas=None,
338
- rank=None,
339
- shuffle=True,
340
- ):
341
- super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
342
- self.lengths = dataset.lengths
343
- self.batch_size = batch_size
344
- self.boundaries = boundaries
345
-
346
- self.buckets, self.num_samples_per_bucket = self._create_buckets()
347
- logger.info(f"Bucket info: {self.num_samples_per_bucket}")
348
- # logger.info(
349
- # f"Unused samples: {len(self.lengths) - sum(self.num_samples_per_bucket)}"
350
- # )
351
- # ↑マイナスになることあるし、別にこれは使われないサンプル数ではないようだ……
352
- # バケットの仕組みはよく分からない
353
-
354
- self.total_size = sum(self.num_samples_per_bucket)
355
- self.num_samples = self.total_size // self.num_replicas
356
-
357
- def _create_buckets(self):
358
- buckets = [[] for _ in range(len(self.boundaries) - 1)]
359
- for i in range(len(self.lengths)):
360
- length = self.lengths[i]
361
- idx_bucket = self._bisect(length)
362
- if idx_bucket != -1:
363
- buckets[idx_bucket].append(i)
364
-
365
- try:
366
- for i in range(len(buckets) - 1, 0, -1):
367
- if len(buckets[i]) == 0:
368
- buckets.pop(i)
369
- self.boundaries.pop(i + 1)
370
- assert all(len(bucket) > 0 for bucket in buckets)
371
- # When one bucket is not traversed
372
- except Exception as e:
373
- logger.info("Bucket warning ", e)
374
- for i in range(len(buckets) - 1, -1, -1):
375
- if len(buckets[i]) == 0:
376
- buckets.pop(i)
377
- self.boundaries.pop(i + 1)
378
-
379
- num_samples_per_bucket = []
380
- for i in range(len(buckets)):
381
- len_bucket = len(buckets[i])
382
- total_batch_size = self.num_replicas * self.batch_size
383
- rem = (
384
- total_batch_size - (len_bucket % total_batch_size)
385
- ) % total_batch_size
386
- num_samples_per_bucket.append(len_bucket + rem)
387
- return buckets, num_samples_per_bucket
388
-
389
- def __iter__(self):
390
- # deterministically shuffle based on epoch
391
- g = torch.Generator()
392
- g.manual_seed(self.epoch)
393
-
394
- indices = []
395
- if self.shuffle:
396
- for bucket in self.buckets:
397
- indices.append(torch.randperm(len(bucket), generator=g).tolist())
398
- else:
399
- for bucket in self.buckets:
400
- indices.append(list(range(len(bucket))))
401
-
402
- batches = []
403
- for i in range(len(self.buckets)):
404
- bucket = self.buckets[i]
405
- len_bucket = len(bucket)
406
- if len_bucket == 0:
407
- continue
408
- ids_bucket = indices[i]
409
- num_samples_bucket = self.num_samples_per_bucket[i]
410
-
411
- # add extra samples to make it evenly divisible
412
- rem = num_samples_bucket - len_bucket
413
- ids_bucket = (
414
- ids_bucket
415
- + ids_bucket * (rem // len_bucket)
416
- + ids_bucket[: (rem % len_bucket)]
417
- )
418
-
419
- # subsample
420
- ids_bucket = ids_bucket[self.rank :: self.num_replicas]
421
-
422
- # batching
423
- for j in range(len(ids_bucket) // self.batch_size):
424
- batch = [
425
- bucket[idx]
426
- for idx in ids_bucket[
427
- j * self.batch_size : (j + 1) * self.batch_size
428
- ]
429
- ]
430
- batches.append(batch)
431
-
432
- if self.shuffle:
433
- batch_ids = torch.randperm(len(batches), generator=g).tolist()
434
- batches = [batches[i] for i in batch_ids]
435
- self.batches = batches
436
-
437
- assert len(self.batches) * self.batch_size == self.num_samples
438
- return iter(self.batches)
439
-
440
- def _bisect(self, x, lo=0, hi=None):
441
- if hi is None:
442
- hi = len(self.boundaries) - 1
443
-
444
- if hi > lo:
445
- mid = (hi + lo) // 2
446
- if self.boundaries[mid] < x and x <= self.boundaries[mid + 1]:
447
- return mid
448
- elif x <= self.boundaries[mid]:
449
- return self._bisect(x, lo, mid)
450
- else:
451
- return self._bisect(x, mid + 1, hi)
452
- else:
453
- return -1
454
-
455
- def __len__(self):
456
- return self.num_samples // self.batch_size
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
default_config.yml CHANGED
@@ -22,7 +22,7 @@ preprocess_text:
22
 
23
  bert_gen:
24
  config_path: "config.json"
25
- num_processes: 2
26
  device: "cuda"
27
  use_multi_device: false
28
 
 
22
 
23
  bert_gen:
24
  config_path: "config.json"
25
+ num_processes: 1
26
  device: "cuda"
27
  use_multi_device: false
28
 
default_style.py DELETED
@@ -1,30 +0,0 @@
1
- import os
2
- from common.log import logger
3
- from common.constants import DEFAULT_STYLE
4
-
5
- import numpy as np
6
- import json
7
-
8
-
9
- def set_style_config(json_path, output_path):
10
- with open(json_path, "r", encoding="utf-8") as f:
11
- json_dict = json.load(f)
12
- json_dict["data"]["num_styles"] = 1
13
- json_dict["data"]["style2id"] = {DEFAULT_STYLE: 0}
14
- with open(output_path, "w", encoding="utf-8") as f:
15
- json.dump(json_dict, f, indent=2, ensure_ascii=False)
16
- logger.info(f"Save style config (only {DEFAULT_STYLE}) to {output_path}")
17
-
18
-
19
- def save_mean_vector(wav_dir, output_path):
20
- embs = []
21
- for file in os.listdir(wav_dir):
22
- if file.endswith(".npy"):
23
- xvec = np.load(os.path.join(wav_dir, file))
24
- embs.append(np.expand_dims(xvec, axis=0))
25
-
26
- x = np.concatenate(embs, axis=0) # (N, 256)
27
- mean = np.mean(x, axis=0) # (256,)
28
- only_mean = np.stack([mean]) # (1, 256)
29
- np.save(output_path, only_mean)
30
- logger.info(f"Saved mean style vector to {output_path}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dict_data/.gitignore DELETED
@@ -1,3 +0,0 @@
1
- *
2
- !.gitignore
3
- !default.csv
 
 
 
 
dict_data/default.csv CHANGED
@@ -1,3 +1,5 @@
1
  Bert,,,8609,名詞,固有名詞,一般,*,*,*,Bert,バアト,バアト,0/3,*
2
  VITS,,,8609,名詞,固有名詞,一般,*,*,*,VITS,ビッツ,ビッツ,0/3,*
3
- VITS2,,,8609,名詞,固有名詞,一般,*,*,*,VITS2,ビッツツウ,ビッツツウ,4/5,*
 
 
 
1
  Bert,,,8609,名詞,固有名詞,一般,*,*,*,Bert,バアト,バアト,0/3,*
2
  VITS,,,8609,名詞,固有名詞,一般,*,*,*,VITS,ビッツ,ビッツ,0/3,*
3
+ VITS二,,,8609,名詞,固有名詞,一般,*,*,*,VITS二,ビッツツー,ビッツツー,4/5,*
4
+ BertVITS,,,8609,名詞,固有名詞,一般,*,*,*,BertVITS,バアトビッツ,バアトビッツ,4/6,*
5
+ 担々麺,,,8609,名詞,固有名詞,一般,*,*,*,担々麺,タンタンメン,タンタンメン,3/6,*
docs/CHANGELOG.md DELETED
@@ -1,129 +0,0 @@
1
- # Changelog
2
-
3
- ## v2.3 (2024-02-25)
4
-
5
- ### 大きな変更
6
-
7
- #### ユーザー辞書機能
8
- あらかじめ辞書に固有名詞を追加することができ、それが学習時・音声合成時の読み取得部分に適応されます。辞書の追加・編集は次のエディタ経由で行ってください。
9
-
10
- 辞書部分の[実装](/text/user_dict/) は、中のREADMEにある通り、[VOICEVOX Editor](https://github.com/VOICEVOX/voicevox) のものを使っており、この部分のコードライセンスはLGPL-3.
11
-
12
- #### 音声合成専用エディタ
13
-
14
- 音声合成専用エディタを追加。今までのWebUIでできた機能のほか、次のような機能が使えます(つまり既存の日本語音声合成ソフトウェアのエディタを真似ました):
15
- - セリフ単位でキャラや設定を変更しながら原稿を作り、それを一括で生成したり、原稿を保存等したり読み込んだり
16
- - GUIよる分かりやすいアクセント調整
17
- - ユーザー辞書への単語追加や編集
18
-
19
- `Editor.bat`をダブルクリックか`python server_editor.py --inbrowser`で起動します。エディター部分は[こちらの別リポジトリ](https://github.com/litagin02/Style-Bert-VITS2-Editor)になります。フロントエンド初心者なのでプルリクや改善案等をお待ちしています。
20
-
21
- ### 改善
22
- - 学習時にデコーダー部分を凍結するオプションの追加。品質がもしかしたら上がるかもしれません。
23
- -
24
-
25
- ## v2.2 (2024-02-09)
26
-
27
- ### 変更・機能追加
28
- - bfloat16オプションはデメリットしか無さそうなので、常にオフで学習するよう変更
29
- - バッチサイズのデフォルトを4から2に変更。学習が遅い場合はバッチサイズを下げて試してみて、VRAMに余裕があれば上げてください。JP-Extra使用時でのバッチサイズごとのVRAM使用量目安は、1: 6GB, 2: 8GB, 3: 10GB, 4: 12GB くらいのようです。
30
- - 学習の際の検証データ数をデフォルトで0に変更し、また検証データ数を学習用WebUIで指定できるようにした
31
- - Tensorboardのログ間隔を学習用WebUIで指定できるようにした
32
- - UIのテーマを`common/constants.py`の`GRADIO_THEME`で指定できるようにした
33
-
34
- ### バグ修正
35
- - JP-Extra使用時にバッチサイズが1だと学習中にエラーが発生するバグを修正
36
- - 「こんにちは!?!?!?!?」等、感嘆符等の記号が連続すると学習・音声合成でエラーになるバグを修正
37
- - `—` (em dash, U+2014) や `―` (quotation dash, U+2015) 等のダッシュやハイフンの各種変種が、種類によって`-`(通常の半角ハイフン)に正規化されたりされていなかったりする処理を、全て正規化するように修正
38
-
39
- ## v2.1 (2024-02-07)
40
-
41
- ### 変更
42
- - 学習の際、デフォルトではbfloat16オプションを使わないよう変更(学習が発散したり質が下がることがある模様)
43
- - 学習の際のメモリ使用量を削減しようと頑張った
44
-
45
- ### バグ修正や改善
46
- - 学習WebUIからTensorboardのログを見れるように
47
- - 音声合成(やそのAPI)において、同時に別の話者が選択され音声合成がリクエストされた場合に発生するエラーを修正
48
- - モデルマージ時に、そのレシピを`recipe.json`ファイルへ保存するように変更
49
- - 「改行で分けて生成」がより感情が乗る旨の明記等、軽微な説明文の改善
50
- - 「`ーーそれは面白い`」や「`なるほど。ーーーそういうことか。`」等、長音記号の前が母音でない場合、長音記号`ー`でなくダッシュ`―`の勘違いだと思われるので、ダッシュ記号として処理するように変更
51
-
52
- ## v2.0.1 (2024-02-05)
53
-
54
- 軽微なバグ修正や改善
55
- - スタイルベクトルに`NaN`が含まれていた場合(主に音声ファイルが極端に短い場合に発生)、それを学習リストから除外するように修正
56
- - colabにマージの追加
57
- - 学習時のプログレスバーの表示がおかしかったのを修正
58
- - デフォルトの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ファイルとかがあったところ)においてダブルクリックしてください。
59
-
60
- ## v2.0 (2024-02-03)
61
-
62
- ### 大きい変更
63
- モデル構造に [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) 様に感謝します)
64
- - これにより、日本語の発音やアクセントや抑揚や自然性が向上する傾向があります
65
- - スタイルベクトルを使ったスタイルの操作は変わらず使えます
66
- - ただしJP-Extraでは英語と中国語の音声合成は(現状は)できません
67
- - 旧モデルも引き続き使うことができ、また旧モデルで学習することもできます
68
- - デフォルトのJVNVモデルは現在は旧verのままです
69
-
70
- ### 改善
71
- - `Merge.bat`で、声音マージを、より細かく「声質」と「声の高さ」の点でマージできるように。
72
-
73
- ### バグ修正
74
- - PyTorchのバージョンに由来するバグを修正(torchのバージョンを2.1.2に固定)
75
- - `―`(ダッシュ、長音記号ではない)が2連続すると学習・音声合成でエラーになるバグを修正
76
- - 「三円」等「ん+母音」のアクセントの仮名表記が「サネン」等になり、また偶にエラーが発生する問題を修正(「ん」の音素表記を内部的には「N」で統一)
77
-
78
- ## v1.3 (2024-01-09)
79
-
80
- ### 大きい変更
81
- - 元々のBert-VITS2に存在した、日本語の発音・アクセント処理部分のバグを修正・リファクタリング
82
- - `車両`が`シャリヨオ`、`思う`が`オモオ`、`見つける`が`ミッケル`等に発音・学習されており、その単語以降のアクセント情報が全て死んでいた
83
- - `私はそれを見る`のアクセントが`ワ➚タシ➘ワ ソ➚レ➘オ ミ➘ル`だったのを`ワ➚タシワ ソ➚レオ ミ➘ル`に修正
84
- - 学習・音声合成で無視されていたアルファベット・ギリシャ文字を無視しないように変更(基本はアルファベット読みだけど簡単な単語は読めるらしい、学習の際は念のためカタカナ等にしたほうがよいです)
85
- - 修正の影響で、前処理時に(今まで無視されていた)読めない漢字等で引っかかるようになりました。その場合は書き起こしを確認して修正するようにしてください。
86
- - アクセントを調整して音声合成できるように(完全に制御できるわけではないが改善される場合がある)。
87
-
88
- これまでのモデルもこれまで通り使え、アクセントや発音等が改善される可能性があります。新しいバージョンで学習し直すとより良くなる可能性もあります。が劇的に良くなるかは分かりません。
89
-
90
- ### 改善
91
- - `Dataset.bat`の音声スライスと書き起こしをよりカスタマイズできるように(スライスの秒数設定や書き起こしのWhisperモデル指定や言語指定等)
92
- - `Style.bat`のスタイル分けで、スタイルごとのサンプル音声を指定した数だけ複数再生できるように。また新しい次元削減方法(UMAP)と新しいスタイル分けの方法(DBSCAN)を追加(UMAPのほうがよくスタイルが分かれるかもしれません)
93
- - `App.bat`での音声合成時に複数話者モデルの場合に話者を指定できるように
94
- - colabの[ノートブック](http://colab.research.google.com/github/litagin02/Style-Bert-VITS2/blob/master/colab.ipynb)で、音声ファイルのみからデータセットを作成するオプション部分を追加
95
- - クラウド実行等の際にパスの指定をこちらでできるように、パスの設定を`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`なので、クラウド等でやる方はここを変更してください。
96
- - どのステップ数の出力がよいかの「一つの」指標として [SpeechMOS](https://github.com/tarepan/SpeechMOS) を使うスクリプトを追加:
97
- ```bash
98
- python speech_mos.py -m <model_name>
99
- ```
100
- ステップごとの自然性評価が表示され、`mos_results`フォルダの`mos_{model_name}.csv`と`mos_{model_name}.png`に結果が保存される。読み上げさせたい文章を変えたかったら中のファイルを弄って各自調整してください。あくまでアクセントや感情表現や抑揚を全く考えない基準での評価で、目安のひとつなので、実際に読み上げさせて選別するのが一番だと思います。
101
- - 学習時のウォームアップオプションを機能するように( [@kale4eat](https://github.com/kale4eat) 様によるPRです、ありがとうございます!)。前処理時に生成さ��る`config.json`の`train`の`warmup_epochs`を変更することで、ウォームアップのエポック数を変更できます。デフォルトは`0`で今までと同じ学習率の挙動です。
102
-
103
- ### その他
104
- - `Dataset.bat`の音声スライスでノーマライズ機能を削除(学習前処理で行えるため)
105
- - `Train.bat`の音量ノーマライズと無音切り詰めをデフォルトでオフに変更
106
- - 学習時の進捗を全体エポック数で表示し、学習全体の進捗を見やすいように( [@RedRayz](https://github.com/RedRayz) 様によるPRです、ありがとうございます!)
107
- - その他バグ修正等( [@tinjyuu](https://github.com/@tinjyuu) 様、 [@darai0512](https://github.com/darai0512) 様ありがとうございます!)
108
- - `config.json`にスタイル埋め込み部分を学習しない`freeze_style`オプションを追加(デフォルトは`false`)
109
-
110
- ### TIPS
111
- - 日本語学習の場合、`config.json`の`freeze_bert`と`freeze_en_bert`を`true`にしておくと、英語と中国語の発話能力が学習の過程で落ちないかもしれませんが、あまり比較していなので分かりません。
112
-
113
- ## v1.2 (2023-12-31)
114
-
115
- - グラボがないユーザーでの音声合成をサポート、`Install-Style-Bert-VITS2-CPU.bat`でインストール。
116
- - Google Colabでの学習をサポート、[ノートブック](http://colab.research.google.com/github/litagin02/Style-Bert-VITS2/blob/master/colab.ipynb)を追加
117
- - 音声合成のAPIサーバーを追加、`python server_fastapi.py`で起動します。API仕様は起動後に`/docs`にて確認ください。( [@darai0512](https://github.com/darai0512) 様によるPRです、ありがとうございます!)
118
- - 学習時に自動的にデフォルトスタイル Neutral を生成するように。特にスタイル指定が必要のない方は、学習したらそのまま音声合成を試せます。これまで通りスタイルを自分で作ることもできます。
119
- - マージ機能の新規追加: `Merge.bat`, `webui_merge.py`
120
- - 前処理のリサンプリング時に音声ファイルの開始・終了部分の無音を削除するオプションを追加(デフォルトでオン)
121
- - `スタイルテキスト (style text)`がスタイル指定と紛らわしかったので、`アシストテキスト (assist text)`に変更
122
- - その他コードのリファクタリング
123
-
124
- ## v1.1 (2023-12-29)
125
- - TrainとDatasetのWebUIの改良・調整(一括事前処理ボタン等)
126
- - 前処理のリサンプリング時に音量を正規化するオプションを追加(デフォルトでオン)
127
-
128
- ## v1.0 (2023-12-27)
129
- - 初版
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/CLI.md DELETED
@@ -1,96 +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==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 --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 wavs
28
- ```bash
29
- python slice.py --model_name <model_name> [-i <input_dir>] [-m <min_sec>] [-M <max_sec>]
30
- ```
31
-
32
- Required:
33
- - `model_name`: Name of the speaker (to be used as the name of the trained model).
34
-
35
- Optional:
36
- - `input_dir`: Path to the directory containing the audio files to slice (default: `inputs`)
37
- - `min_sec`: Minimum duration of the sliced audio files in seconds (default: 2).
38
- - `max_sec`: Maximum duration of the sliced audio files in seconds (default: 12).
39
-
40
- ### 1.2. Transcribe wavs
41
-
42
- ```bash
43
- python transcribe.py --model_name <model_name>
44
- ```
45
- Required:
46
- - `model_name`: Name of the speaker (to be used as the name of the trained model).
47
-
48
- Optional
49
- - `--initial_prompt`: Initial prompt to use for the transcription (default value is specific to Japanese).
50
- - `--device`: `cuda` or `cpu` (default: `cuda`).
51
- - `--language`: `jp`, `en`, or `en` (default: `jp`).
52
- - `--model`: Whisper model, default: `large-v3`
53
- - `--compute_type`: default: `bfloat16`
54
-
55
- ## 2. Preprocess
56
-
57
- ```bash
58
- 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]
59
- ```
60
-
61
- Required:
62
- - `model_name`: Name of the speaker (to be used as the name of the trained model).
63
-
64
- Optional:
65
- - `--batch_size`, `-b`: Batch size (default: 2).
66
- - `--epochs`, `-e`: Number of epochs (default: 100).
67
- - `--save_every_steps`, `-s`: Save every steps (default: 1000).
68
- - `--num_processes`: Number of processes (default: half of the number of CPU cores).
69
- - `--normalize`: Loudness normalize audio.
70
- - `--trim`: Trim silence.
71
- - `--freeze_EN_bert`: Freeze English BERT.
72
- - `--freeze_JP_bert`: Freeze Japanese BERT.
73
- - `--freeze_ZH_bert`: Freeze Chinese BERT.
74
- - `--freeze_style`: Freeze style vector.
75
- - `--freeze_decoder`: Freeze decoder.
76
- - `--use_jp_extra`: Use JP-Extra model.
77
- - `--val_per_lang`: Validation data per language (default: 0).
78
- - `--log_interval`: Log interval (default: 200).
79
-
80
- ## 3. Train
81
-
82
- Training settings are automatically loaded from the above process.
83
-
84
- If NOT using JP-Extra model:
85
- ```bash
86
- python train_ms.py [--repo_id <username>/<repo_name>]
87
- ```
88
-
89
- If using JP-Extra model:
90
- ```bash
91
- python train_ms_jp_extra.py [--repo_id <username>/<repo_name>] [--skip_default_style]
92
- ```
93
-
94
- Optional:
95
- - `--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.
96
- - `--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,125 +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
- [![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)
10
-
11
- Online demo: https://huggingface.co/spaces/litagin/Style-Bert-VITS2-JVNV
12
-
13
- This repository is based on [Bert-VITS2](https://github.com/fishaudio/Bert-VITS2) v2.1, so many thanks to the original author!
14
-
15
- - [Update History](docs/CHANGELOG.md)
16
-
17
- **Overview**
18
-
19
- - 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.
20
- - 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)
21
- - If used only for voice synthesis, it can operate on CPU without a graphics card.
22
- - Also includes an API server for integration with others (PR by [@darai0512](https://github.com/darai0512), thank you).
23
- - 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.
24
-
25
-
26
- ## How to Use
27
-
28
- <!-- For more details, please refer to [here](docs/tutorial.md). -->
29
-
30
- ### Operating Environment
31
-
32
- 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).
33
-
34
- ### Installation
35
-
36
- #### For Those Unfamiliar with Git or Python
37
-
38
- Assuming Windows:
39
-
40
- 1. Download and unzip [this zip file](https://github.com/litagin02/Style-Bert-VITS2/releases/download/1.3/Style-Bert-VITS2.zip).
41
- - If you have a graphics card, double-click `Install-Style-Bert-VITS2.bat`.
42
- - If you don't have a graphics card, double-click `Install-Style-Bert-VITS2-CPU.bat`.
43
- 2. Wait for the necessary environment to install automatically.
44
- 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.
45
-
46
- For updates, please double-click `Update-Style-Bert-VITS2.bat`.
47
-
48
- #### For Those Familiar with Git and Python
49
-
50
- ```bash
51
- git clone https://github.com/litagin02/Style-Bert-VITS2.git
52
- cd Style-Bert-VITS2
53
- python -m venv venv
54
- venv\Scripts\activate
55
- pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
56
- pip install -r requirements.txt
57
- python initialize.py # Download necessary models and default TTS model
58
- ```
59
- Don't forget the last step.
60
-
61
- ### Voice Synthesis
62
- 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.
63
-
64
- The structure of the model files required for voice synthesis is as follows (you don't need to place them manually):
65
-
66
- ```
67
- model_assets
68
- ├── your_model
69
- │ ├── config.json
70
- │ ├── your_model_file1.safetensors
71
- │ ├── your_model_file2.safetensors
72
- │ ├── ...
73
- │ └── style_vectors.npy
74
- └── another_model
75
- ├── ...
76
- ```
77
-
78
- For inference, `config.json`, `*.safetensors`, and `style_vectors.npy` are necessary. If you want to share a model, please share these three files.
79
-
80
- Among them, `style_vectors.npy` is a file necessary to control the style. By default, the average style "Neutral" is generated during training.
81
- 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).
82
-
83
- ### Training
84
-
85
- Double-click Train.bat or run `python webui_train.py` to launch the WebUI.
86
-
87
- ### Generating Styles
88
- For those who want to use styles other than the default "Neutral".
89
-
90
- - Double-click `Style.bat` or run `python webui_style_vectors.py` to launch the WebUI.
91
- - 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).
92
- - For more details on the specifications of the style, please refer to [clustering.ipynb](../clustering.ipynb).
93
-
94
- ### Dataset Creation
95
-
96
- - 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.
97
-
98
- 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.
99
-
100
- Please experiment to see what kind of dataset is best.
101
-
102
- ### API Server
103
- Run `python server_fastapi.py` in the constructed environment to launch the API server.
104
- Please check the API specification after launching at `/docs`.
105
-
106
- By default, CORS settings are allowed for all domains.
107
- 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).
108
-
109
- ### Merging
110
- You can create a new model by mixing two models in terms of "voice", "emotional expression", and "tempo".
111
- Double-click `Merge.bat` or run `python webui_merge.py` to launch the WebUI.
112
-
113
- ## Relation to Bert-VITS2 v2.1
114
- 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).
115
-
116
- The differences are as follows:
117
-
118
- - Like [EasyBertVits2](https://github.com/Zuntan03/EasyBertVits2), it is easy to use even for people who do not know Python or Git.
119
- - 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)
120
- - Removed vector quantization from embeddings and replaced it with just a fully connected layer.
121
- - By creating a style vector file `style_vectors.npy`, you can generate voices using that style and continuously specify the strength of the effect.
122
- - Various WebUIs created
123
- - Support for bf16 training
124
- - Support for safetensors format, defaulting to using safetensors
125
- - Other minor bug fixes and refactoring
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 --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
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,32 +0,0 @@
1
- import os
2
- import shutil
3
- import yaml
4
- import argparse
5
-
6
- parser = argparse.ArgumentParser(
7
- description="config.ymlの生成。あらかじめ前準備をしたデータをバッチファイルなどで連続で学習する時にtrain_ms.pyより前に使用する。"
8
- )
9
- # そうしないと最後の前準備したデータで学習してしまう
10
- parser.add_argument("--model_name", type=str, help="Model name", required=True)
11
- parser.add_argument(
12
- "--dataset_path",
13
- type=str,
14
- help="Dataset path(example: Data\\your_model_name)",
15
- required=True,
16
- )
17
- args = parser.parse_args()
18
-
19
-
20
- def gen_yaml(model_name, dataset_path):
21
- if not os.path.exists("config.yml"):
22
- shutil.copy(src="default_config.yml", dst="config.yml")
23
- with open("config.yml", "r", encoding="utf-8") as f:
24
- yml_data = yaml.safe_load(f)
25
- yml_data["model_name"] = model_name
26
- yml_data["dataset_path"] = dataset_path
27
- with open("config.yml", "w", encoding="utf-8") as f:
28
- yaml.dump(yml_data, f, allow_unicode=True)
29
-
30
-
31
- if __name__ == "__main__":
32
- gen_yaml(args.model_name, args.dataset_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
initialize.py CHANGED
@@ -1,27 +1,23 @@
1
  import argparse
2
  import json
 
3
  from pathlib import Path
4
 
5
  import yaml
6
  from huggingface_hub import hf_hub_download
7
 
8
- from common.log import logger
9
 
10
 
11
  def download_bert_models():
12
- with open("bert/bert_models.json", "r") as fp:
13
  models = json.load(fp)
14
  for k, v in models.items():
15
  local_path = Path("bert").joinpath(k)
16
  for file in v["files"]:
17
  if not Path(local_path).joinpath(file).exists():
18
  logger.info(f"Downloading {k} {file}")
19
- hf_hub_download(
20
- v["repo_id"],
21
- file,
22
- local_dir=local_path,
23
- local_dir_use_symlinks=False,
24
- )
25
 
26
 
27
  def download_slm_model():
@@ -29,12 +25,7 @@ def download_slm_model():
29
  file = "pytorch_model.bin"
30
  if not Path(local_path).joinpath(file).exists():
31
  logger.info(f"Downloading wavlm-base-plus {file}")
32
- hf_hub_download(
33
- "microsoft/wavlm-base-plus",
34
- file,
35
- local_dir=local_path,
36
- local_dir_use_symlinks=False,
37
- )
38
 
39
 
40
  def download_pretrained_models():
@@ -44,10 +35,7 @@ def download_pretrained_models():
44
  if not Path(local_path).joinpath(file).exists():
45
  logger.info(f"Downloading pretrained {file}")
46
  hf_hub_download(
47
- "litagin/Style-Bert-VITS2-1.0-base",
48
- file,
49
- local_dir=local_path,
50
- local_dir_use_symlinks=False,
51
  )
52
 
53
 
@@ -58,14 +46,11 @@ def download_jp_extra_pretrained_models():
58
  if not Path(local_path).joinpath(file).exists():
59
  logger.info(f"Downloading JP-Extra pretrained {file}")
60
  hf_hub_download(
61
- "litagin/Style-Bert-VITS2-2.0-base-JP-Extra",
62
- file,
63
- local_dir=local_path,
64
- local_dir_use_symlinks=False,
65
  )
66
 
67
 
68
- def download_jvnv_models():
69
  files = [
70
  "jvnv-F1-jp/config.json",
71
  "jvnv-F1-jp/jvnv-F1-jp_e160_s14000.safetensors",
@@ -87,13 +72,34 @@ def download_jvnv_models():
87
  "litagin/style_bert_vits2_jvnv",
88
  file,
89
  local_dir="model_assets",
90
- local_dir_use_symlinks=False,
91
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
 
94
  def main():
95
  parser = argparse.ArgumentParser()
96
- parser.add_argument("--skip_jvnv", action="store_true")
 
97
  parser.add_argument(
98
  "--dataset_root",
99
  type=str,
@@ -110,21 +116,24 @@ def main():
110
 
111
  download_bert_models()
112
 
113
- download_slm_model()
114
-
115
- download_pretrained_models()
 
 
 
116
 
117
- download_jp_extra_pretrained_models()
118
-
119
- if not args.skip_jvnv:
120
- download_jvnv_models()
 
121
 
122
  if args.dataset_root is None and args.assets_root is None:
123
  return
124
 
125
  # Change default paths if necessary
126
- paths_yml = Path("configs/paths.yml")
127
- with open(paths_yml, "r", encoding="utf-8") as f:
128
  yml_data = yaml.safe_load(f)
129
  if args.assets_root is not None:
130
  yml_data["assets_root"] = args.assets_root
 
1
  import argparse
2
  import json
3
+ import shutil
4
  from pathlib import Path
5
 
6
  import yaml
7
  from huggingface_hub import hf_hub_download
8
 
9
+ from style_bert_vits2.logging import logger
10
 
11
 
12
  def download_bert_models():
13
+ with open("bert/bert_models.json", encoding="utf-8") as fp:
14
  models = json.load(fp)
15
  for k, v in models.items():
16
  local_path = Path("bert").joinpath(k)
17
  for file in v["files"]:
18
  if not Path(local_path).joinpath(file).exists():
19
  logger.info(f"Downloading {k} {file}")
20
+ hf_hub_download(v["repo_id"], file, local_dir=local_path)
 
 
 
 
 
21
 
22
 
23
  def download_slm_model():
 
25
  file = "pytorch_model.bin"
26
  if not Path(local_path).joinpath(file).exists():
27
  logger.info(f"Downloading wavlm-base-plus {file}")
28
+ hf_hub_download("microsoft/wavlm-base-plus", file, local_dir=local_path)
 
 
 
 
 
29
 
30
 
31
  def download_pretrained_models():
 
35
  if not Path(local_path).joinpath(file).exists():
36
  logger.info(f"Downloading pretrained {file}")
37
  hf_hub_download(
38
+ "litagin/Style-Bert-VITS2-1.0-base", file, local_dir=local_path
 
 
 
39
  )
40
 
41
 
 
46
  if not Path(local_path).joinpath(file).exists():
47
  logger.info(f"Downloading JP-Extra pretrained {file}")
48
  hf_hub_download(
49
+ "litagin/Style-Bert-VITS2-2.0-base-JP-Extra", file, local_dir=local_path
 
 
 
50
  )
51
 
52
 
53
+ def download_default_models():
54
  files = [
55
  "jvnv-F1-jp/config.json",
56
  "jvnv-F1-jp/jvnv-F1-jp_e160_s14000.safetensors",
 
72
  "litagin/style_bert_vits2_jvnv",
73
  file,
74
  local_dir="model_assets",
 
75
  )
76
+ additional_files = {
77
+ "litagin/sbv2_koharune_ami": [
78
+ "koharune-ami/config.json",
79
+ "koharune-ami/style_vectors.npy",
80
+ "koharune-ami/koharune-ami.safetensors",
81
+ ],
82
+ "litagin/sbv2_amitaro": [
83
+ "amitaro/config.json",
84
+ "amitaro/style_vectors.npy",
85
+ "amitaro/amitaro.safetensors",
86
+ ],
87
+ }
88
+ for repo_id, files in additional_files.items():
89
+ for file in files:
90
+ if not Path(f"model_assets/{file}").exists():
91
+ logger.info(f"Downloading {file}")
92
+ hf_hub_download(
93
+ repo_id,
94
+ file,
95
+ local_dir="model_assets",
96
+ )
97
 
98
 
99
  def main():
100
  parser = argparse.ArgumentParser()
101
+ parser.add_argument("--skip_default_models", action="store_true")
102
+ parser.add_argument("--only_infer", action="store_true")
103
  parser.add_argument(
104
  "--dataset_root",
105
  type=str,
 
116
 
117
  download_bert_models()
118
 
119
+ if not args.skip_default_models:
120
+ download_default_models()
121
+ if not args.only_infer:
122
+ download_slm_model()
123
+ download_pretrained_models()
124
+ download_jp_extra_pretrained_models()
125
 
126
+ # If configs/paths.yml not exists, create it
127
+ default_paths_yml = Path("configs/default_paths.yml")
128
+ paths_yml = Path("configs/paths.yml")
129
+ if not paths_yml.exists():
130
+ shutil.copy(default_paths_yml, paths_yml)
131
 
132
  if args.dataset_root is None and args.assets_root is None:
133
  return
134
 
135
  # Change default paths if necessary
136
+ with open(paths_yml, encoding="utf-8") as f:
 
137
  yml_data = yaml.safe_load(f)
138
  if args.assets_root is not None:
139
  yml_data["assets_root"] = args.assets_root
inputs/.gitignore DELETED
@@ -1,2 +0,0 @@
1
- *
2
- !.gitignore
 
 
 
losses.py DELETED
@@ -1,155 +0,0 @@
1
- import torch
2
- import torchaudio
3
- from transformers import AutoModel
4
-
5
- from common.log import logger
6
-
7
-
8
- def feature_loss(fmap_r, fmap_g):
9
- loss = 0
10
- for dr, dg in zip(fmap_r, fmap_g):
11
- for rl, gl in zip(dr, dg):
12
- rl = rl.float().detach()
13
- gl = gl.float()
14
- loss += torch.mean(torch.abs(rl - gl))
15
-
16
- return loss * 2
17
-
18
-
19
- def discriminator_loss(disc_real_outputs, disc_generated_outputs):
20
- loss = 0
21
- r_losses = []
22
- g_losses = []
23
- for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
24
- dr = dr.float()
25
- dg = dg.float()
26
- r_loss = torch.mean((1 - dr) ** 2)
27
- g_loss = torch.mean(dg**2)
28
- loss += r_loss + g_loss
29
- r_losses.append(r_loss.item())
30
- g_losses.append(g_loss.item())
31
-
32
- return loss, r_losses, g_losses
33
-
34
-
35
- def generator_loss(disc_outputs):
36
- loss = 0
37
- gen_losses = []
38
- for dg in disc_outputs:
39
- dg = dg.float()
40
- l = torch.mean((1 - dg) ** 2)
41
- gen_losses.append(l)
42
- loss += l
43
-
44
- return loss, gen_losses
45
-
46
-
47
- def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
48
- """
49
- z_p, logs_q: [b, h, t_t]
50
- m_p, logs_p: [b, h, t_t]
51
- """
52
- z_p = z_p.float()
53
- logs_q = logs_q.float()
54
- m_p = m_p.float()
55
- logs_p = logs_p.float()
56
- z_mask = z_mask.float()
57
-
58
- kl = logs_p - logs_q - 0.5
59
- kl += 0.5 * ((z_p - m_p) ** 2) * torch.exp(-2.0 * logs_p)
60
- kl = torch.sum(kl * z_mask)
61
- l = kl / torch.sum(z_mask)
62
- return l
63
-
64
-
65
- class WavLMLoss(torch.nn.Module):
66
- def __init__(self, model, wd, model_sr, slm_sr=16000):
67
- super(WavLMLoss, self).__init__()
68
- self.wavlm = AutoModel.from_pretrained(model)
69
- self.wd = wd
70
- self.resample = torchaudio.transforms.Resample(model_sr, slm_sr)
71
- self.wavlm.eval()
72
- for param in self.wavlm.parameters():
73
- param.requires_grad = False
74
-
75
- def forward(self, wav, y_rec):
76
- with torch.no_grad():
77
- wav_16 = self.resample(wav)
78
- wav_embeddings = self.wavlm(
79
- input_values=wav_16, output_hidden_states=True
80
- ).hidden_states
81
- y_rec_16 = self.resample(y_rec)
82
- y_rec_embeddings = self.wavlm(
83
- input_values=y_rec_16, output_hidden_states=True
84
- ).hidden_states
85
-
86
- floss = 0
87
- for er, eg in zip(wav_embeddings, y_rec_embeddings):
88
- floss += torch.mean(torch.abs(er - eg))
89
-
90
- return floss.mean()
91
-
92
- def generator(self, y_rec):
93
- y_rec_16 = self.resample(y_rec)
94
- y_rec_embeddings = self.wavlm(
95
- input_values=y_rec_16, output_hidden_states=True
96
- ).hidden_states
97
- y_rec_embeddings = (
98
- torch.stack(y_rec_embeddings, dim=1)
99
- .transpose(-1, -2)
100
- .flatten(start_dim=1, end_dim=2)
101
- )
102
- y_df_hat_g = self.wd(y_rec_embeddings)
103
- loss_gen = torch.mean((1 - y_df_hat_g) ** 2)
104
-
105
- return loss_gen
106
-
107
- def discriminator(self, wav, y_rec):
108
- with torch.no_grad():
109
- wav_16 = self.resample(wav)
110
- wav_embeddings = self.wavlm(
111
- input_values=wav_16, output_hidden_states=True
112
- ).hidden_states
113
- y_rec_16 = self.resample(y_rec)
114
- y_rec_embeddings = self.wavlm(
115
- input_values=y_rec_16, output_hidden_states=True
116
- ).hidden_states
117
-
118
- y_embeddings = (
119
- torch.stack(wav_embeddings, dim=1)
120
- .transpose(-1, -2)
121
- .flatten(start_dim=1, end_dim=2)
122
- )
123
- y_rec_embeddings = (
124
- torch.stack(y_rec_embeddings, dim=1)
125
- .transpose(-1, -2)
126
- .flatten(start_dim=1, end_dim=2)
127
- )
128
-
129
- y_d_rs = self.wd(y_embeddings)
130
- y_d_gs = self.wd(y_rec_embeddings)
131
-
132
- y_df_hat_r, y_df_hat_g = y_d_rs, y_d_gs
133
-
134
- r_loss = torch.mean((1 - y_df_hat_r) ** 2)
135
- g_loss = torch.mean((y_df_hat_g) ** 2)
136
-
137
- loss_disc_f = r_loss + g_loss
138
-
139
- return loss_disc_f.mean()
140
-
141
- def discriminator_forward(self, wav):
142
- with torch.no_grad():
143
- wav_16 = self.resample(wav)
144
- wav_embeddings = self.wavlm(
145
- input_values=wav_16, output_hidden_states=True
146
- ).hidden_states
147
- y_embeddings = (
148
- torch.stack(wav_embeddings, dim=1)
149
- .transpose(-1, -2)
150
- .flatten(start_dim=1, end_dim=2)
151
- )
152
-
153
- y_d_rs = self.wd(y_embeddings)
154
-
155
- return y_d_rs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mel_processing.py DELETED
@@ -1,146 +0,0 @@
1
- import torch
2
- import torch.utils.data
3
- from librosa.filters import mel as librosa_mel_fn
4
- import warnings
5
-
6
- # warnings.simplefilter(action='ignore', category=FutureWarning)
7
- warnings.filterwarnings(action="ignore")
8
- MAX_WAV_VALUE = 32768.0
9
-
10
-
11
- def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
12
- """
13
- PARAMS
14
- ------
15
- C: compression factor
16
- """
17
- return torch.log(torch.clamp(x, min=clip_val) * C)
18
-
19
-
20
- def dynamic_range_decompression_torch(x, C=1):
21
- """
22
- PARAMS
23
- ------
24
- C: compression factor used to compress
25
- """
26
- return torch.exp(x) / C
27
-
28
-
29
- def spectral_normalize_torch(magnitudes):
30
- output = dynamic_range_compression_torch(magnitudes)
31
- return output
32
-
33
-
34
- def spectral_de_normalize_torch(magnitudes):
35
- output = dynamic_range_decompression_torch(magnitudes)
36
- return output
37
-
38
-
39
- mel_basis = {}
40
- hann_window = {}
41
-
42
-
43
- def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
44
- if torch.min(y) < -1.0:
45
- print("min value is ", torch.min(y))
46
- if torch.max(y) > 1.0:
47
- print("max value is ", torch.max(y))
48
-
49
- global hann_window
50
- dtype_device = str(y.dtype) + "_" + str(y.device)
51
- wnsize_dtype_device = str(win_size) + "_" + dtype_device
52
- if wnsize_dtype_device not in hann_window:
53
- hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
54
- dtype=y.dtype, device=y.device
55
- )
56
-
57
- y = torch.nn.functional.pad(
58
- y.unsqueeze(1),
59
- (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
60
- mode="reflect",
61
- )
62
- y = y.squeeze(1)
63
-
64
- spec = torch.stft(
65
- y,
66
- n_fft,
67
- hop_length=hop_size,
68
- win_length=win_size,
69
- window=hann_window[wnsize_dtype_device],
70
- center=center,
71
- pad_mode="reflect",
72
- normalized=False,
73
- onesided=True,
74
- return_complex=False,
75
- )
76
-
77
- spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
78
- return spec
79
-
80
-
81
- def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
82
- global mel_basis
83
- dtype_device = str(spec.dtype) + "_" + str(spec.device)
84
- fmax_dtype_device = str(fmax) + "_" + dtype_device
85
- if fmax_dtype_device not in mel_basis:
86
- mel = librosa_mel_fn(
87
- sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax
88
- )
89
- mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
90
- dtype=spec.dtype, device=spec.device
91
- )
92
- spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
93
- spec = spectral_normalize_torch(spec)
94
- return spec
95
-
96
-
97
- def mel_spectrogram_torch(
98
- y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False
99
- ):
100
- if torch.min(y) < -1.0:
101
- print("min value is ", torch.min(y))
102
- if torch.max(y) > 1.0:
103
- print("max value is ", torch.max(y))
104
-
105
- global mel_basis, hann_window
106
- dtype_device = str(y.dtype) + "_" + str(y.device)
107
- fmax_dtype_device = str(fmax) + "_" + dtype_device
108
- wnsize_dtype_device = str(win_size) + "_" + dtype_device
109
- if fmax_dtype_device not in mel_basis:
110
- mel = librosa_mel_fn(
111
- sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax
112
- )
113
- mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
114
- dtype=y.dtype, device=y.device
115
- )
116
- if wnsize_dtype_device not in hann_window:
117
- hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
118
- dtype=y.dtype, device=y.device
119
- )
120
-
121
- y = torch.nn.functional.pad(
122
- y.unsqueeze(1),
123
- (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
124
- mode="reflect",
125
- )
126
- y = y.squeeze(1)
127
-
128
- spec = torch.stft(
129
- y,
130
- n_fft,
131
- hop_length=hop_size,
132
- win_length=win_size,
133
- window=hann_window[wnsize_dtype_device],
134
- center=center,
135
- pad_mode="reflect",
136
- normalized=False,
137
- onesided=True,
138
- return_complex=False,
139
- )
140
-
141
- spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
142
-
143
- spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
144
- spec = spectral_normalize_torch(spec)
145
-
146
- return spec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
model_assets/amitaro/amitaro.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19725d9bfd9d4b4fb17072ed4d40e01f6cf89c22cd83c15e1cccbf3ddf6b81de
3
+ size 251150980
model_assets/amitaro/config.json ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "amitaro",
3
+ "train": {
4
+ "log_interval": 200,
5
+ "eval_interval": 1000,
6
+ "seed": 42,
7
+ "epochs": 100,
8
+ "learning_rate": 0.0001,
9
+ "betas": [0.8, 0.99],
10
+ "eps": 1e-9,
11
+ "batch_size": 4,
12
+ "bf16_run": false,
13
+ "fp16_run": false,
14
+ "lr_decay": 0.99996,
15
+ "segment_size": 16384,
16
+ "init_lr_ratio": 1,
17
+ "warmup_epochs": 0,
18
+ "c_mel": 45,
19
+ "c_kl": 1.0,
20
+ "c_commit": 100,
21
+ "skip_optimizer": false,
22
+ "freeze_ZH_bert": false,
23
+ "freeze_JP_bert": false,
24
+ "freeze_EN_bert": false,
25
+ "freeze_emo": false,
26
+ "freeze_style": false,
27
+ "freeze_decoder": false
28
+ },
29
+ "data": {
30
+ "use_jp_extra": true,
31
+ "training_files": "Data\\amitaro\\train.list",
32
+ "validation_files": "Data\\amitaro\\val.list",
33
+ "max_wav_value": 32768.0,
34
+ "sampling_rate": 44100,
35
+ "filter_length": 2048,
36
+ "hop_length": 512,
37
+ "win_length": 2048,
38
+ "n_mel_channels": 128,
39
+ "mel_fmin": 0.0,
40
+ "mel_fmax": null,
41
+ "add_blank": true,
42
+ "n_speakers": 1,
43
+ "cleaned_text": true,
44
+ "spk2id": {
45
+ "あみたろ": 0
46
+ },
47
+ "num_styles": 5,
48
+ "style2id": {
49
+ "Neutral": 0,
50
+ "01": 1,
51
+ "02": 2,
52
+ "03": 3,
53
+ "04": 4
54
+ }
55
+ },
56
+ "model": {
57
+ "use_spk_conditioned_encoder": true,
58
+ "use_noise_scaled_mas": true,
59
+ "use_mel_posterior_encoder": false,
60
+ "use_duration_discriminator": false,
61
+ "use_wavlm_discriminator": true,
62
+ "inter_channels": 192,
63
+ "hidden_channels": 192,
64
+ "filter_channels": 768,
65
+ "n_heads": 2,
66
+ "n_layers": 6,
67
+ "kernel_size": 3,
68
+ "p_dropout": 0.1,
69
+ "resblock": "1",
70
+ "resblock_kernel_sizes": [3, 7, 11],
71
+ "resblock_dilation_sizes": [
72
+ [1, 3, 5],
73
+ [1, 3, 5],
74
+ [1, 3, 5]
75
+ ],
76
+ "upsample_rates": [8, 8, 2, 2, 2],
77
+ "upsample_initial_channel": 512,
78
+ "upsample_kernel_sizes": [16, 16, 8, 2, 2],
79
+ "n_layers_q": 3,
80
+ "use_spectral_norm": false,
81
+ "gin_channels": 512,
82
+ "slm": {
83
+ "model": "./slm/wavlm-base-plus",
84
+ "sr": 16000,
85
+ "hidden": 768,
86
+ "nlayers": 13,
87
+ "initial_channel": 64
88
+ }
89
+ },
90
+ "version": "2.5.0-JP-Extra"
91
+ }
model_assets/amitaro/style_vectors.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f04b3d679982f11fd29da6ea27f93af86e5876b93aa4fbf910215ce145513cc9
3
+ size 5248
model_assets/koharune-ami/config.json ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "小春音アミ",
3
+ "train": {
4
+ "log_interval": 200,
5
+ "eval_interval": 1000,
6
+ "seed": 42,
7
+ "epochs": 300,
8
+ "learning_rate": 0.0001,
9
+ "betas": [0.8, 0.99],
10
+ "eps": 1e-9,
11
+ "batch_size": 4,
12
+ "bf16_run": false,
13
+ "fp16_run": false,
14
+ "lr_decay": 0.99996,
15
+ "segment_size": 16384,
16
+ "init_lr_ratio": 1,
17
+ "warmup_epochs": 0,
18
+ "c_mel": 45,
19
+ "c_kl": 1.0,
20
+ "c_commit": 100,
21
+ "skip_optimizer": false,
22
+ "freeze_ZH_bert": false,
23
+ "freeze_JP_bert": false,
24
+ "freeze_EN_bert": false,
25
+ "freeze_emo": false,
26
+ "freeze_style": false,
27
+ "freeze_decoder": false
28
+ },
29
+ "data": {
30
+ "use_jp_extra": true,
31
+ "training_files": "Data\\amitaro_combined\\train.list",
32
+ "validation_files": "Data\\amitaro_combined\\val.list",
33
+ "max_wav_value": 32768.0,
34
+ "sampling_rate": 44100,
35
+ "filter_length": 2048,
36
+ "hop_length": 512,
37
+ "win_length": 2048,
38
+ "n_mel_channels": 128,
39
+ "mel_fmin": 0.0,
40
+ "mel_fmax": null,
41
+ "add_blank": true,
42
+ "n_speakers": 1,
43
+ "cleaned_text": true,
44
+ "spk2id": {
45
+ "小春音アミ": 0
46
+ },
47
+ "num_styles": 6,
48
+ "style2id": {
49
+ "Neutral": 0,
50
+ "るんるん": 1,
51
+ "ささやきA(無声)": 2,
52
+ "ささやきB(有声)": 3,
53
+ "ノーマル": 4,
54
+ "よふかし": 5
55
+ }
56
+ },
57
+ "model": {
58
+ "use_spk_conditioned_encoder": true,
59
+ "use_noise_scaled_mas": true,
60
+ "use_mel_posterior_encoder": false,
61
+ "use_duration_discriminator": false,
62
+ "use_wavlm_discriminator": true,
63
+ "inter_channels": 192,
64
+ "hidden_channels": 192,
65
+ "filter_channels": 768,
66
+ "n_heads": 2,
67
+ "n_layers": 6,
68
+ "kernel_size": 3,
69
+ "p_dropout": 0.1,
70
+ "resblock": "1",
71
+ "resblock_kernel_sizes": [3, 7, 11],
72
+ "resblock_dilation_sizes": [
73
+ [1, 3, 5],
74
+ [1, 3, 5],
75
+ [1, 3, 5]
76
+ ],
77
+ "upsample_rates": [8, 8, 2, 2, 2],
78
+ "upsample_initial_channel": 512,
79
+ "upsample_kernel_sizes": [16, 16, 8, 2, 2],
80
+ "n_layers_q": 3,
81
+ "use_spectral_norm": false,
82
+ "gin_channels": 512,
83
+ "slm": {
84
+ "model": "./slm/wavlm-base-plus",
85
+ "sr": 16000,
86
+ "hidden": 768,
87
+ "nlayers": 13,
88
+ "initial_channel": 64
89
+ }
90
+ },
91
+ "version": "2.5.0-JP-Extra"
92
+ }
model_assets/koharune-ami/koharune-ami.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:980119e6660fc241b1c297016933f43240b3fc6203a9f511dd2f2dac74042991
3
+ size 251150980
model_assets/koharune-ami/style_vectors.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:867527952ff45b6621fe18b8b51728c29abe3aeb80b74e06f235df71aa82ae5d
3
+ size 6272
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
preprocess_all.py DELETED
@@ -1,96 +0,0 @@
1
- import argparse
2
- from webui_train import preprocess_all
3
- from multiprocessing import cpu_count
4
-
5
- if __name__ == "__main__":
6
- parser = argparse.ArgumentParser()
7
- parser.add_argument(
8
- "--model_name", "-m", type=str, help="Model name", required=True
9
- )
10
- parser.add_argument("--batch_size", "-b", type=int, help="Batch size", default=2)
11
- parser.add_argument("--epochs", "-e", type=int, help="Epochs", default=100)
12
- parser.add_argument(
13
- "--save_every_steps",
14
- "-s",
15
- type=int,
16
- help="Save every steps",
17
- default=1000,
18
- )
19
- parser.add_argument(
20
- "--num_processes",
21
- type=int,
22
- help="Number of processes",
23
- default=cpu_count() // 2,
24
- )
25
- parser.add_argument(
26
- "--normalize",
27
- action="store_true",
28
- help="Loudness normalize audio",
29
- )
30
- parser.add_argument(
31
- "--trim",
32
- action="store_true",
33
- help="Trim silence",
34
- )
35
- parser.add_argument(
36
- "--freeze_EN_bert",
37
- action="store_true",
38
- help="Freeze English BERT",
39
- )
40
- parser.add_argument(
41
- "--freeze_JP_bert",
42
- action="store_true",
43
- help="Freeze Japanese BERT",
44
- )
45
- parser.add_argument(
46
- "--freeze_ZH_bert",
47
- action="store_true",
48
- help="Freeze Chinese BERT",
49
- )
50
- parser.add_argument(
51
- "--freeze_style",
52
- action="store_true",
53
- help="Freeze style vector",
54
- )
55
- parser.add_argument(
56
- "--freeze_decoder",
57
- action="store_true",
58
- help="Freeze decoder",
59
- )
60
- parser.add_argument(
61
- "--use_jp_extra",
62
- action="store_true",
63
- help="Use JP-Extra model",
64
- )
65
- parser.add_argument(
66
- "--val_per_lang",
67
- type=int,
68
- help="Validation per language",
69
- default=0,
70
- )
71
- parser.add_argument(
72
- "--log_interval",
73
- type=int,
74
- help="Log interval",
75
- default=200,
76
- )
77
-
78
- args = parser.parse_args()
79
-
80
- preprocess_all(
81
- model_name=args.model_name,
82
- batch_size=args.batch_size,
83
- epochs=args.epochs,
84
- save_every_steps=args.save_every_steps,
85
- num_processes=args.num_processes,
86
- normalize=args.normalize,
87
- trim=args.trim,
88
- freeze_EN_bert=args.freeze_EN_bert,
89
- freeze_JP_bert=args.freeze_JP_bert,
90
- freeze_ZH_bert=args.freeze_ZH_bert,
91
- freeze_style=args.freeze_style,
92
- freeze_decoder=args.freeze_decoder,
93
- use_jp_extra=args.use_jp_extra,
94
- val_per_lang=args.val_per_lang,
95
- log_interval=args.log_interval,
96
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
preprocess_text.py DELETED
@@ -1,167 +0,0 @@
1
- import json
2
- import os
3
- from collections import defaultdict
4
- from random import shuffle
5
- from typing import Optional
6
-
7
- import click
8
- from tqdm import tqdm
9
-
10
- from config import config
11
- from text.cleaner import clean_text
12
- from common.stdout_wrapper import SAFE_STDOUT
13
- from common.log import logger
14
-
15
- preprocess_text_config = config.preprocess_text_config
16
-
17
-
18
- # Count lines for tqdm
19
- def count_lines(file_path: str):
20
- with open(file_path, "r", encoding="utf-8") as file:
21
- return sum(1 for _ in file)
22
-
23
-
24
- @click.command()
25
- @click.option(
26
- "--transcription-path",
27
- default=preprocess_text_config.transcription_path,
28
- type=click.Path(exists=True, file_okay=True, dir_okay=False),
29
- )
30
- @click.option("--cleaned-path", default=preprocess_text_config.cleaned_path)
31
- @click.option("--train-path", default=preprocess_text_config.train_path)
32
- @click.option("--val-path", default=preprocess_text_config.val_path)
33
- @click.option(
34
- "--config-path",
35
- default=preprocess_text_config.config_path,
36
- type=click.Path(exists=True, file_okay=True, dir_okay=False),
37
- )
38
- @click.option("--val-per-lang", default=preprocess_text_config.val_per_lang)
39
- @click.option("--max-val-total", default=preprocess_text_config.max_val_total)
40
- @click.option("--clean/--no-clean", default=preprocess_text_config.clean)
41
- @click.option("-y", "--yml_config")
42
- @click.option("--use_jp_extra", is_flag=True)
43
- def preprocess(
44
- transcription_path: str,
45
- cleaned_path: Optional[str],
46
- train_path: str,
47
- val_path: str,
48
- config_path: str,
49
- val_per_lang: int,
50
- max_val_total: int,
51
- clean: bool,
52
- yml_config: str, # 这个不要删
53
- use_jp_extra: bool,
54
- ):
55
- if cleaned_path == "" or cleaned_path is None:
56
- cleaned_path = transcription_path + ".cleaned"
57
-
58
- error_log_path = os.path.join(os.path.dirname(cleaned_path), "text_error.log")
59
- error_count = 0
60
-
61
- if clean:
62
- total_lines = count_lines(transcription_path)
63
- with open(cleaned_path, "w", encoding="utf-8") as out_file:
64
- with open(transcription_path, "r", encoding="utf-8") as trans_file:
65
- for line in tqdm(trans_file, file=SAFE_STDOUT, total=total_lines):
66
- try:
67
- utt, spk, language, text = line.strip().split("|")
68
- norm_text, phones, tones, word2ph = clean_text(
69
- text, language, use_jp_extra
70
- )
71
- out_file.write(
72
- "{}|{}|{}|{}|{}|{}|{}\n".format(
73
- utt,
74
- spk,
75
- language,
76
- norm_text,
77
- " ".join(phones),
78
- " ".join([str(i) for i in tones]),
79
- " ".join([str(i) for i in word2ph]),
80
- )
81
- )
82
- except Exception as e:
83
- logger.error(f"An error occurred at line:\n{line.strip()}\n{e}")
84
- with open(error_log_path, "a", encoding="utf-8") as error_log:
85
- error_log.write(f"{line.strip()}\n{e}\n\n")
86
- error_count += 1
87
-
88
- transcription_path = cleaned_path
89
- spk_utt_map = defaultdict(list)
90
- spk_id_map = {}
91
- current_sid = 0
92
-
93
- with open(transcription_path, "r", encoding="utf-8") as f:
94
- audioPaths = set()
95
- countSame = 0
96
- countNotFound = 0
97
- for line in f.readlines():
98
- utt, spk, language, text, phones, tones, word2ph = line.strip().split("|")
99
- if utt in audioPaths:
100
- # 过滤数据集错误:相同的音频匹配多个文本,导致后续bert出问题
101
- logger.warning(f"Same audio matches multiple texts: {line}")
102
- countSame += 1
103
- continue
104
- if not os.path.isfile(utt):
105
- # 过滤数据集错误:不存在对应音频
106
- logger.warning(f"Audio not found: {utt}")
107
- countNotFound += 1
108
- continue
109
- audioPaths.add(utt)
110
- spk_utt_map[language].append(line)
111
- if spk not in spk_id_map.keys():
112
- spk_id_map[spk] = current_sid
113
- current_sid += 1
114
- if countSame > 0 or countNotFound > 0:
115
- logger.warning(
116
- f"Total repeated audios: {countSame}, Total number of audio not found: {countNotFound}"
117
- )
118
-
119
- train_list = []
120
- val_list = []
121
-
122
- for spk, utts in spk_utt_map.items():
123
- shuffle(utts)
124
- val_list += utts[:val_per_lang]
125
- train_list += utts[val_per_lang:]
126
-
127
- shuffle(val_list)
128
- if len(val_list) > max_val_total:
129
- train_list += val_list[max_val_total:]
130
- val_list = val_list[:max_val_total]
131
-
132
- with open(train_path, "w", encoding="utf-8") as f:
133
- for line in train_list:
134
- f.write(line)
135
-
136
- with open(val_path, "w", encoding="utf-8") as f:
137
- for line in val_list:
138
- f.write(line)
139
-
140
- json_config = json.load(open(config_path, encoding="utf-8"))
141
- json_config["data"]["spk2id"] = spk_id_map
142
- json_config["data"]["n_speakers"] = len(spk_id_map)
143
- # 新增写入:写入训练版本、数据集路径
144
- # json_config["version"] = latest_version
145
- json_config["data"]["training_files"] = os.path.normpath(train_path).replace(
146
- "\\", "/"
147
- )
148
- json_config["data"]["validation_files"] = os.path.normpath(val_path).replace(
149
- "\\", "/"
150
- )
151
- with open(config_path, "w", encoding="utf-8") as f:
152
- json.dump(json_config, f, indent=2, ensure_ascii=False)
153
- if error_count > 0:
154
- logger.error(
155
- f"An error occurred in {error_count} lines. Please check {error_log_path} for details. You can proceed with lines that do not have errors."
156
- )
157
- raise Exception(
158
- f"An error occurred in {error_count} lines. Please check {error_log_path} for details. You can proceed with lines that do not have errors."
159
- )
160
- else:
161
- logger.info(
162
- "Training set and validation set generation from texts is complete!"
163
- )
164
-
165
-
166
- if __name__ == "__main__":
167
- preprocess()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,13 +1,24 @@
1
- gradio
 
 
 
 
 
 
 
 
2
  loguru
3
- matplotlib
4
  num2words
5
- numba
6
- numpy
 
 
 
7
  pyopenjtalk-dict
8
- PyYAML
9
- requests
10
- safetensors
11
- scipy
12
- torch>=2.1,<2.2
13
  transformers
 
 
1
+ # cmudict
2
+ # cn2an
3
+ # faster-whisper==0.10.1
4
+ fastapi
5
+ # g2p_en
6
+ # GPUtil
7
+ # gradio
8
+ # jieba
9
+ # librosa==0.9.2
10
  loguru
 
11
  num2words
12
+ # protobuf==4.25
13
+ # psutil
14
+ # punctuators
15
+ pyannote.audio>=3.1.0
16
+ # pyloudnorm
17
  pyopenjtalk-dict
18
+ # pypinyin
19
+ pyworld-prebuilt
20
+ # stable_ts
21
+ # tensorboard
22
+ torch
23
  transformers
24
+ # umap-learn
resample.py DELETED
@@ -1,131 +0,0 @@
1
- import argparse
2
- import os
3
- from concurrent.futures import ThreadPoolExecutor
4
-
5
- import librosa
6
- import pyloudnorm as pyln
7
- import soundfile
8
- from tqdm import tqdm
9
-
10
- from common.log import logger
11
- from common.stdout_wrapper import SAFE_STDOUT
12
- from config import config
13
-
14
- DEFAULT_BLOCK_SIZE: float = 0.400 # seconds
15
-
16
-
17
- class BlockSizeException(Exception):
18
- pass
19
-
20
-
21
- def normalize_audio(data, sr):
22
- meter = pyln.Meter(sr, block_size=DEFAULT_BLOCK_SIZE) # create BS.1770 meter
23
- try:
24
- loudness = meter.integrated_loudness(data)
25
- except ValueError as e:
26
- raise BlockSizeException(e)
27
- # logger.info(f"loudness: {loudness}")
28
- data = pyln.normalize.loudness(data, loudness, -23.0)
29
- return data
30
-
31
-
32
- def process(item):
33
- spkdir, wav_name, args = item
34
- wav_path = os.path.join(args.in_dir, spkdir, wav_name)
35
- if os.path.exists(wav_path) and wav_path.lower().endswith(".wav"):
36
- wav, sr = librosa.load(wav_path, sr=args.sr)
37
- if args.normalize:
38
- try:
39
- wav = normalize_audio(wav, sr)
40
- except BlockSizeException:
41
- logger.info(
42
- f"Skip normalize due to less than {DEFAULT_BLOCK_SIZE} second audio: {wav_path}"
43
- )
44
- if args.trim:
45
- wav, _ = librosa.effects.trim(wav, top_db=30)
46
- soundfile.write(os.path.join(args.out_dir, spkdir, wav_name), wav, sr)
47
-
48
-
49
- if __name__ == "__main__":
50
- parser = argparse.ArgumentParser()
51
- parser.add_argument(
52
- "--sr",
53
- type=int,
54
- default=config.resample_config.sampling_rate,
55
- help="sampling rate",
56
- )
57
- parser.add_argument(
58
- "--in_dir",
59
- "-i",
60
- type=str,
61
- default=config.resample_config.in_dir,
62
- help="path to source dir",
63
- )
64
- parser.add_argument(
65
- "--out_dir",
66
- "-o",
67
- type=str,
68
- default=config.resample_config.out_dir,
69
- help="path to target dir",
70
- )
71
- parser.add_argument(
72
- "--num_processes",
73
- type=int,
74
- default=4,
75
- help="cpu_processes",
76
- )
77
- parser.add_argument(
78
- "--normalize",
79
- action="store_true",
80
- default=False,
81
- help="loudness normalize audio",
82
- )
83
- parser.add_argument(
84
- "--trim",
85
- action="store_true",
86
- default=False,
87
- help="trim silence (start and end only)",
88
- )
89
- args, _ = parser.parse_known_args()
90
- # autodl 无卡模式会识别出46个cpu
91
- if args.num_processes == 0:
92
- processes = cpu_count() - 2 if cpu_count() > 4 else 1
93
- else:
94
- processes = args.num_processes
95
-
96
- tasks = []
97
-
98
- for dirpath, _, filenames in os.walk(args.in_dir):
99
- # 子级目录
100
- spk_dir = os.path.relpath(dirpath, args.in_dir)
101
- spk_dir_out = os.path.join(args.out_dir, spk_dir)
102
- if not os.path.isdir(spk_dir_out):
103
- os.makedirs(spk_dir_out, exist_ok=True)
104
- for filename in filenames:
105
- if filename.lower().endswith(".wav"):
106
- twople = (spk_dir, filename, args)
107
- tasks.append(twople)
108
-
109
- if len(tasks) == 0:
110
- logger.error(f"No wav files found in {args.in_dir}")
111
- raise ValueError(f"No wav files found in {args.in_dir}")
112
-
113
- # pool = Pool(processes=processes)
114
- # for _ in tqdm(
115
- # pool.imap_unordered(process, tasks), file=SAFE_STDOUT, total=len(tasks)
116
- # ):
117
- # pass
118
-
119
- # pool.close()
120
- # pool.join()
121
-
122
- with ThreadPoolExecutor(max_workers=processes) as executor:
123
- _ = list(
124
- tqdm(
125
- executor.map(process, tasks),
126
- total=len(tasks),
127
- file=SAFE_STDOUT,
128
- )
129
- )
130
-
131
- logger.info("Resampling Done!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/Install-Style-Bert-VITS2-CPU.bat DELETED
@@ -1,69 +0,0 @@
1
- chcp 65001 > NUL
2
- @echo off
3
-
4
- @REM https://github.com/Zuntan03/EasyBertVits2 より引用・改変
5
-
6
- pushd %~dp0
7
- set PS_CMD=PowerShell -Version 5.1 -ExecutionPolicy Bypass
8
-
9
- set CURL_CMD=C:\Windows\System32\curl.exe
10
- if not exist %CURL_CMD% (
11
- echo [ERROR] %CURL_CMD% が見つかりません。
12
- pause & popd & exit /b 1
13
- )
14
-
15
- @REM lib フォルダがなければ作成
16
- if not exist lib\ ( mkdir lib )
17
-
18
- @REM Style-Bert-VITS2.zip をGitHubのmasterの最新のものをダウンロード
19
- %CURL_CMD% -Lo Style-Bert-VITS2.zip^
20
- https://github.com/litagin02/Style-Bert-VITS2/archive/refs/heads/master.zip
21
- if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
22
-
23
- @REM Style-Bert-VITS2.zip を解凍(フォルダ名前がBert-VITS2-masterになる)
24
- %PS_CMD% Expand-Archive -Path Style-Bert-VITS2.zip -DestinationPath . -Force
25
- if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
26
-
27
- @REM 元のzipを削除
28
- del Style-Bert-VITS2.zip
29
- if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
30
-
31
- @REM Bert-VITS2-masterの中身をStyle-Bert-VITS2に上書き移動
32
- xcopy /QSY .\Style-Bert-VITS2-master\ .\Style-Bert-VITS2\
33
- rmdir /s /q Style-Bert-VITS2-master
34
-
35
- echo ----------------------------------------
36
- echo Setup Python and Virtual Environment
37
- echo ----------------------------------------
38
-
39
- @REM Pythonと仮想環境のセットアップを呼び出す(仮想環境が有効化されて戻ってくる)
40
- call Style-Bert-VITS2\scripts\Setup-Python.bat ..\..\lib\python ..\venv
41
- if %errorlevel% neq 0 ( popd & exit /b %errorlevel% )
42
-
43
- @REM 依存関係インストール
44
- pip install -r Style-Bert-VITS2\requirements.txt
45
- if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
46
-
47
- echo ----------------------------------------
48
- echo Environment setup is complete. Start downloading the model.
49
- echo ----------------------------------------
50
-
51
- @REM Style-Bert-VITS2フォルダに移動
52
- pushd Style-Bert-VITS2
53
-
54
- @REM 初期化(必要なモデルのダウンロード)
55
- python initialize.py
56
-
57
- echo ----------------------------------------
58
- echo Model download is complete. Start the WebUI of the voice synthesis.
59
- echo ----------------------------------------
60
-
61
- @REM 音声合成WebUIの起動
62
- python app.py
63
-
64
- pause
65
-
66
- popd
67
-
68
- popd
69
-