kkvc-hf commited on
Commit
05f56db
1 Parent(s): 7cfcd27
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. App.bat +11 -0
  2. Data/.gitignore +2 -0
  3. Dataset.bat +11 -0
  4. LICENSE +661 -0
  5. Merge.bat +13 -0
  6. README.md +213 -1
  7. Style.bat +12 -0
  8. Train.bat +13 -0
  9. __pycache__/attentions.cpython-310.pyc +0 -0
  10. __pycache__/commons.cpython-310.pyc +0 -0
  11. __pycache__/config.cpython-310.pyc +0 -0
  12. __pycache__/infer.cpython-310.pyc +0 -0
  13. __pycache__/models.cpython-310.pyc +0 -0
  14. __pycache__/models_jp_extra.cpython-310.pyc +0 -0
  15. __pycache__/modules.cpython-310.pyc +0 -0
  16. __pycache__/transforms.cpython-310.pyc +0 -0
  17. __pycache__/utils.cpython-310.pyc +0 -0
  18. app.py +475 -0
  19. attentions.py +462 -0
  20. bert/bert_models.json +14 -0
  21. bert/chinese-roberta-wwm-ext-large/.gitattributes +9 -0
  22. bert/chinese-roberta-wwm-ext-large/README.md +57 -0
  23. bert/chinese-roberta-wwm-ext-large/added_tokens.json +1 -0
  24. bert/chinese-roberta-wwm-ext-large/config.json +28 -0
  25. bert/chinese-roberta-wwm-ext-large/pytorch_model.bin +3 -0
  26. bert/chinese-roberta-wwm-ext-large/special_tokens_map.json +1 -0
  27. bert/chinese-roberta-wwm-ext-large/tokenizer.json +0 -0
  28. bert/chinese-roberta-wwm-ext-large/tokenizer_config.json +1 -0
  29. bert/chinese-roberta-wwm-ext-large/vocab.txt +0 -0
  30. bert/deberta-v2-large-japanese-char-wwm/.gitattributes +34 -0
  31. bert/deberta-v2-large-japanese-char-wwm/README.md +89 -0
  32. bert/deberta-v2-large-japanese-char-wwm/config.json +37 -0
  33. bert/deberta-v2-large-japanese-char-wwm/pytorch_model.bin +3 -0
  34. bert/deberta-v2-large-japanese-char-wwm/special_tokens_map.json +7 -0
  35. bert/deberta-v2-large-japanese-char-wwm/tokenizer_config.json +19 -0
  36. bert/deberta-v2-large-japanese-char-wwm/vocab.txt +0 -0
  37. bert/deberta-v3-large/.gitattributes +27 -0
  38. bert/deberta-v3-large/README.md +93 -0
  39. bert/deberta-v3-large/config.json +22 -0
  40. bert/deberta-v3-large/generator_config.json +22 -0
  41. bert/deberta-v3-large/pytorch_model.bin +3 -0
  42. bert/deberta-v3-large/spm.model +3 -0
  43. bert/deberta-v3-large/tokenizer_config.json +4 -0
  44. bert_gen.py +85 -0
  45. clustering.ipynb +0 -0
  46. colab.ipynb +406 -0
  47. common/__pycache__/constants.cpython-310.pyc +0 -0
  48. common/__pycache__/log.cpython-310.pyc +0 -0
  49. common/__pycache__/stdout_wrapper.cpython-310.pyc +0 -0
  50. common/__pycache__/tts_model.cpython-310.pyc +0 -0
App.bat ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *
2
+ !.gitignore
Dataset.bat ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
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
LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
Merge.bat ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
README.md CHANGED
@@ -10,4 +10,216 @@ pinned: false
10
  license: apache-2.0
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  license: apache-2.0
11
  ---
12
 
13
+ # Style-Bert-VITS2
14
+
15
+ Bert-VITS2 with more controllable voice styles.
16
+
17
+ https://github.com/litagin02/Style-Bert-VITS2/assets/139731664/e853f9a2-db4a-4202-a1dd-56ded3c562a0
18
+
19
+ - [English README](docs/README_en.md)
20
+ - [![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
+ - [🤗 オンラインデモはこちらから](https://huggingface.co/spaces/litagin/Style-Bert-VITS2-JVNV)
22
+ - [Zennの解説記事](https://zenn.dev/litagin/articles/034819a5256ff4)
23
+
24
+ - [**リリースページ**](https://github.com/litagin02/Style-Bert-VITS2/releases/)、[更新履歴](docs/CHANGELOG.md)
25
+
26
+ - 2024-02-09: ver 2.2
27
+ - 2024-02-07: ver 2.1
28
+ - 2024-02-03: ver 2.0
29
+ - 2024-01-09: ver 1.3
30
+ - 2023-12-31: ver 1.2
31
+ - 2023-12-29: ver 1.1
32
+ - 2023-12-27: ver 1.0
33
+
34
+ This repository is based on [Bert-VITS2](https://github.com/fishaudio/Bert-VITS2) v2.1 and Japanese-Extra, so many thanks to the original author!
35
+
36
+ **概要**
37
+
38
+ - 入力されたテキストの内容をもとに感情豊かな音声を生成する[Bert-VITS2](https://github.com/fishaudio/Bert-VITS2)のv2.1とJapanese-Extraを元に、感情や発話スタイルを強弱込みで自由に制御できるようにしたものです。
39
+ - GitやPythonがない人でも(Windowsユーザーなら)簡単にインストールでき、学習もできます (多くを[EasyBertVits2](https://github.com/Zuntan03/EasyBertVits2/)からお借りしました)。またGoogle Colabでの学習もサポートしています: [![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)
40
+ - 音声合成のみに使う場合は、グラボがなくてもCPUで動作します。
41
+ - 他との連携に使えるAPIサーバーも同梱しています ([@darai0512](https://github.com/darai0512) 様によるPRです、ありがとうございます)。
42
+ - 元々「楽しそうな文章は楽しそうに、悲しそうな文章は悲しそうに」読むのがBert-VITS2の強みですので、スタイル指定がデフォルトでも感情豊かな音声を生成することができます。
43
+
44
+
45
+ ## 使い方
46
+
47
+ <!-- 詳しくは[こちら](docs/tutorial.md)を参照してください。 -->
48
+
49
+ ### 動作環境
50
+
51
+ 各UIとAPI Serverにおいて、Windows コマンドプロンプト・WSL2・Linux(Ubuntu Desktop)での動作を確認しています(WSLでのパス指定は相対パスなど工夫ください)。NVidiaのGPUが無い場合は学習はできませんが音声合成とマージは可能です。
52
+
53
+ ### インストール
54
+
55
+ #### GitやPythonに馴染みが無い方
56
+
57
+ Windowsを前提としています。
58
+
59
+ 1. [このzipファイル](https://github.com/litagin02/Style-Bert-VITS2/releases/download/2.2/Style-Bert-VITS2.zip)を**パスに日本語や空白が含まれない場所に**ダウンロードして展開します。
60
+ - グラボがある方は、`Install-Style-Bert-VITS2.bat`をダブルクリックします。
61
+ - グラボがない方は、`Install-Style-Bert-VITS2-CPU.bat`をダブルクリックします。CPU版では学習はできませんが、音声合成とマージは可能です。
62
+ 2. 待つと自動で必要な環境がインストールされます。
63
+ 3. その後、自動的に音声合成するためのWebUIが起動したらインストール成功です。デフォルトのモデルがダウンロードされるているので、そのまま遊ぶことができます。
64
+
65
+ またアップデートをしたい場合は、`Update-Style-Bert-VITS2.bat`をダブルクリックしてください。ただし**1.x**から**2.x**へアップデートする場合は、[このbatファイル](https://github.com/litagin02/Style-Bert-VITS2/releases/download/2.2/Update-to-JP-Extra.bat)を`Style-Bert-VITS2`フォルダがあるフォルダ(`Update-Style-Bert-VITS2.bat`等があるフォルダ)へ保存してからダブルクリックしてください。
66
+
67
+ #### GitやPython使える人
68
+
69
+ ```bash
70
+ git clone https://github.com/litagin02/Style-Bert-VITS2.git
71
+ cd Style-Bert-VITS2
72
+ python -m venv venv
73
+ venv\Scripts\activate
74
+ # PyTorch 2.2.x系は今のところは学習エラーが出るので前のバージョンを使う
75
+ pip install torch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 --index-url https://download.pytorch.org/whl/cu118
76
+ pip install -r requirements.txt
77
+ python initialize.py # 必要なモデルとデフォルトTTSモデルをダウンロード
78
+ ```
79
+ 最後を忘れずに。
80
+
81
+ ### 音声合成
82
+
83
+ `App.bat`をダブルクリックか、`python app.py`するとWebUIが起動します(`python app.py --cpu`でCPUモードで起動、学習中チェックに便利です)。インストール時にデフォルトのモデルがダウンロードされているので、学��していなくてもそれを使うことができます。
84
+
85
+ 音声合成に必要なモデルファイルたちの構造は以下の通りです(手動で配置する必要はありません)。
86
+ ```
87
+ model_assets
88
+ ├── your_model
89
+ │ ├── config.json
90
+ │ ├── your_model_file1.safetensors
91
+ │ ├── your_model_file2.safetensors
92
+ │ ├── ...
93
+ │ └── style_vectors.npy
94
+ └── another_model
95
+ ├── ...
96
+ ```
97
+ このように、推論には`config.json`と`*.safetensors`と`style_vectors.npy`が必要です。モデルを共有する場合は、この3つのファイルを共有してください。
98
+
99
+ このうち`style_vectors.npy`はスタイルを制御するために必要なファイルで、学習の時にデフォルトで平均スタイル「Neutral」が生成されます。
100
+ 複数スタイルを使ってより詳しくスタイルを制御したい方は、下の「スタイルの生成」を参照してください(平均スタイルのみでも、学習データが感情豊かならば十分感情豊かな音声が生成されます)。
101
+
102
+ ### 学習
103
+
104
+ 学習には2-14秒程度の音声ファイルが複数と、それらの書き起こしデータが必要です。
105
+
106
+ - 既存コーパスなどですでに分割された音声ファイルと書き起こしデータがある場合はそのまま(必要に応じて書き起こしファイルを修正して)使えます。下の「学習WebUI」を参照してください。
107
+ - そうでない場合、(長さは問わない)音声ファイルのみがあれば、そこから学習にすぐに使えるようにデータセットを作るためのツールを同梱しています。
108
+
109
+ #### データセット作り
110
+
111
+ - `Dataset.bat`をダブルクリックか`python webui_dataset.py`すると、音声ファイルからデータセットを作るためのWebUIが起動します(音声ファイルを適切な長さにスライスし、その後に文字の書き起こしを自動で行います)。
112
+ - 指示に従った後、閉じて下の「学習WebUI」でそのまま学習を行うことができます。
113
+
114
+ 注意: データセットの手動修正やノイズ除去等、細かい修正を行いたい場合は[Aivis](https://github.com/tsukumijima/Aivis)や、そのデータセット部分のWindows対応版 [Aivis Dataset](https://github.com/litagin02/Aivis-Dataset) を使うといいかもしれません。ですがファイル数が多い場合などは、このツールで簡易的に切り出してデータセットを作るだけでも十分という気もしています。
115
+
116
+ データセットがどのようなものがいいかは各自試行錯誤中してください。
117
+
118
+ #### 学習WebUI
119
+
120
+ - `Train.bat`をダブルクリックか`python webui_train.py`するとWebUIが起動するので指示に従ってください。
121
+
122
+ ### スタイルの生成
123
+
124
+ - デフォルトスタイル「Neutral」以外のスタイルを使いたい人向けです。
125
+ - `Style.bat`をダブルクリックか`python webui_style_vectors.py`するとWebUIが起動します。
126
+ - 学習とは独立しているので、学習中でもできるし、学習が終わっても何度もやりなおせます(前処理は終わらせている必要があります)。
127
+ - スタイルについての仕様の詳細は[clustering.ipynb](clustering.ipynb)を参照してください。
128
+
129
+ ### API Server
130
+
131
+ 構築した環境下で`python server_fastapi.py`するとAPIサーバーが起動します。
132
+ API仕様は起動後に`/docs`にて確認ください。
133
+
134
+ - 入力文字数はデフォルトで100文字が上限となっています。これは`config.yml`の`server.limit`で変更できます。
135
+ - デフォルトではCORS設定を全てのドメインで許可しています。できる限り、`config.yml`の`server.origins`の値を変更し、信頼できるドメインに制限ください(キーを消せばCORS設定を無効にできます)。
136
+
137
+ ### マージ
138
+
139
+ 2つのモデルを、「声質」「声の高さ」「感情表現」「テンポ」の4点で混ぜ合わせて、新しいモデルを作ることが出来ます。
140
+ `Merge.bat`をダブルクリックか`python webui_merge.py`するとWebUIが起動します。
141
+
142
+ ### 自然性評価
143
+
144
+ 学習結果のうちどのステップ数がいいかの「一つの」指標として、[SpeechMOS](https://github.com/tarepan/SpeechMOS) を使うスクリプトを用意しています:
145
+ ```bash
146
+ python speech_mos.py -m <model_name>
147
+ ```
148
+ ステップごとの自然性評価が表示され、`mos_results`フォルダの`mos_{model_name}.csv`と`mos_{model_name}.png`に結果が保存される。読み上げさせたい文章を変えたかったら中のファイルを弄って各自調整してください。またあくまでアクセントや感情表現や抑揚を全く考えない基準での評価で、目安のひとつなので、実際に読み上げさせて選別するのが一番だと思います。
149
+
150
+ ## Bert-VITS2との関係
151
+
152
+ 基本的にはBert-VITS2のモデル構造を少し改造しただけです。[旧事前学習モデル](https://huggingface.co/litagin/Style-Bert-VITS2-1.0-base)も[JP-Extraの事前学習モデル](https://huggingface.co/litagin/Style-Bert-VITS2-2.0-base-JP-Extra)も、実質Bert-VITS2 v2.1 or JP-Extraと同じものを使用しています(不要な重みを削ってsafetensorsに変換したもの)。
153
+
154
+ 具体的には以下の点が異なります。
155
+
156
+ - [EasyBertVits2](https://github.com/Zuntan03/EasyBertVits2)のように、PythonやGitを知らない人でも簡単に使える。
157
+ - 感情埋め込みのモデルを変更(256次元の[wespeaker-voxceleb-resnet34-LM](https://huggingface.co/pyannote/wespeaker-voxceleb-resnet34-LM)へ、感情埋め込みというよりは話者識別のための埋め込み)
158
+ - 感情埋め込みもベクトル量子化を取り払い、単なる全結合層に。
159
+ - スタイルベクトルファイル`style_vectors.npy`を作ることで、そのスタイルを使って効果の強さも連続的に指定しつつ音声を生成することができる。
160
+ - 各種WebUIを作成
161
+ - bf16での学習のサポート
162
+ - safetensors形式のサポート、デフォルトでsafetensorsを使用するように
163
+ - その他軽微なbugfixやリファクタリング
164
+
165
+ ## TODO
166
+ - [x] デフォルトのJVNVモデルにJP-Extra版のものを追加
167
+ - [x] LinuxやWSL等、Windowsの通常環境以外でのサポート ← おそらく問題ないとの報告あり
168
+ - [x] 複数話者学習での音声合成対応(学習は現在でも可能)
169
+ - [x] `server_fastapi.py`の対応、とくにAPIで使えるようになると嬉しい人が増えるのかもしれない
170
+ - [x] モデルのマージで声音と感情表現を混ぜる機能の実装
171
+ - [ ] 英語等多言語対応?
172
+
173
+ ## References
174
+ In addition to the original reference (written below), I used the following repositories:
175
+ - [Bert-VITS2](https://github.com/fishaudio/Bert-VITS2)
176
+ - [EasyBertVits2](https://github.com/Zuntan03/EasyBertVits2)
177
+
178
+ [The pretrained model](https://huggingface.co/litagin/Style-Bert-VITS2-1.0-base) and [JP-Extra version](https://huggingface.co/litagin/Style-Bert-VITS2-2.0-base-JP-Extra) is essentially taken from [the original base model of Bert-VITS2 v2.1](https://huggingface.co/Garydesu/bert-vits2_base_model-2.1) and [JP-Extra pretrained model of Bert-VITS2](https://huggingface.co/Stardust-minus/Bert-VITS2-Japanese-Extra), so all the credits go to the original author ([Fish Audio](https://github.com/fishaudio)):
179
+
180
+
181
+ Below is the original README.md.
182
+ ---
183
+
184
+ <div align="center">
185
+
186
+ <img alt="LOGO" src="https://cdn.jsdelivr.net/gh/fishaudio/fish-diffusion@main/images/logo_512x512.png" width="256" height="256" />
187
+
188
+ # Bert-VITS2
189
+
190
+ VITS2 Backbone with multilingual bert
191
+
192
+ For quick guide, please refer to `webui_preprocess.py`.
193
+
194
+ 简易教程请参见 `webui_preprocess.py`。
195
+
196
+ ## 请注意,本项目核心思路来源于[anyvoiceai/MassTTS](https://github.com/anyvoiceai/MassTTS) 一个非常好的tts项目
197
+ ## MassTTS的演示demo为[ai版峰哥锐评峰哥本人,并找回了在金三角失落的腰子](https://www.bilibili.com/video/BV1w24y1c7z9)
198
+
199
+ [//]: # (## 本项目与[PlayVoice/vits_chinese]&#40;https://github.com/PlayVoice/vits_chinese&#41; 没有任何关系)
200
+
201
+ [//]: # ()
202
+ [//]: # (本仓库来源于之前朋友分享了ai峰哥的视频,本人被其中的效果惊艳,在自己尝试MassTTS以后发现fs在音质方面与vits有一定差距,并且training的pipeline比vits更复杂,因此按照其思路将bert)
203
+
204
+ ## 成熟的旅行者/开拓者/舰长/博士/sensei/猎魔人/喵喵露/V应当参阅代码自己学习如何训练。
205
+
206
+ ### 严禁将此项目用于一切违反《中华人民共和国宪法》,《中华人民共和国刑法》,《中华人民共和国治安管理处罚法》和《中华人民共和国民法典》之用途。
207
+ ### 严禁用于任何政治相关用途。
208
+ #### Video:https://www.bilibili.com/video/BV1hp4y1K78E
209
+ #### Demo:https://www.bilibili.com/video/BV1TF411k78w
210
+ #### QQ Group:815818430
211
+ ## References
212
+ + [anyvoiceai/MassTTS](https://github.com/anyvoiceai/MassTTS)
213
+ + [jaywalnut310/vits](https://github.com/jaywalnut310/vits)
214
+ + [p0p4k/vits2_pytorch](https://github.com/p0p4k/vits2_pytorch)
215
+ + [svc-develop-team/so-vits-svc](https://github.com/svc-develop-team/so-vits-svc)
216
+ + [PaddlePaddle/PaddleSpeech](https://github.com/PaddlePaddle/PaddleSpeech)
217
+ + [emotional-vits](https://github.com/innnky/emotional-vits)
218
+ + [fish-speech](https://github.com/fishaudio/fish-speech)
219
+ + [Bert-VITS2-UI](https://github.com/jiangyuxiaoxiao/Bert-VITS2-UI)
220
+ ## 感谢所有贡献者作出的努力
221
+ <a href="https://github.com/fishaudio/Bert-VITS2/graphs/contributors" target="_blank">
222
+ <img src="https://contrib.rocks/image?repo=fishaudio/Bert-VITS2"/>
223
+ </a>
224
+
225
+ [//]: # (# 本项目所有代码引用均已写明,bert部分代码思路来源于[AI峰哥]&#40;https://www.bilibili.com/video/BV1w24y1c7z9&#41;,与[vits_chinese]&#40;https://github.com/PlayVoice/vits_chinese&#41;无任何关系。欢迎各位查阅代码。同时,我们也对该开发者的[碰瓷,乃至开盒开发者的行为]&#40;https://www.bilibili.com/read/cv27101514/&#41;表示强烈谴责。)
Style.bat ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
__pycache__/attentions.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
__pycache__/commons.cpython-310.pyc ADDED
Binary file (5.54 kB). View file
 
__pycache__/config.cpython-310.pyc ADDED
Binary file (7.95 kB). View file
 
__pycache__/infer.cpython-310.pyc ADDED
Binary file (5.39 kB). View file
 
__pycache__/models.cpython-310.pyc ADDED
Binary file (20.9 kB). View file
 
__pycache__/models_jp_extra.cpython-310.pyc ADDED
Binary file (22.9 kB). View file
 
__pycache__/modules.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
__pycache__/transforms.cpython-310.pyc ADDED
Binary file (3.91 kB). View file
 
__pycache__/utils.cpython-310.pyc ADDED
Binary file (14.8 kB). View file
 
app.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import datetime
3
+ import json
4
+ import os
5
+ import sys
6
+ from typing import Optional
7
+
8
+ import gradio as gr
9
+ import torch
10
+ import yaml
11
+
12
+ from common.constants import (
13
+ DEFAULT_ASSIST_TEXT_WEIGHT,
14
+ DEFAULT_LENGTH,
15
+ DEFAULT_LINE_SPLIT,
16
+ DEFAULT_NOISE,
17
+ DEFAULT_NOISEW,
18
+ DEFAULT_SDP_RATIO,
19
+ DEFAULT_SPLIT_INTERVAL,
20
+ DEFAULT_STYLE,
21
+ DEFAULT_STYLE_WEIGHT,
22
+ GRADIO_THEME,
23
+ LATEST_VERSION,
24
+ Languages,
25
+ )
26
+ from common.log import logger
27
+ from common.tts_model import ModelHolder
28
+ from infer import InvalidToneError
29
+ from text.japanese import g2kata_tone, kata_tone2phone_tone, text_normalize
30
+
31
+ # Get path settings
32
+ with open(os.path.join("configs", "paths.yml"), "r", encoding="utf-8") as f:
33
+ path_config: dict[str, str] = yaml.safe_load(f.read())
34
+ # dataset_root = path_config["dataset_root"]
35
+ assets_root = path_config["assets_root"]
36
+
37
+ languages = [l.value for l in Languages]
38
+
39
+
40
+ def tts_fn(
41
+ model_name,
42
+ model_path,
43
+ text,
44
+ language,
45
+ reference_audio_path,
46
+ sdp_ratio,
47
+ noise_scale,
48
+ noise_scale_w,
49
+ length_scale,
50
+ line_split,
51
+ split_interval,
52
+ assist_text,
53
+ assist_text_weight,
54
+ use_assist_text,
55
+ style,
56
+ style_weight,
57
+ kata_tone_json_str,
58
+ use_tone,
59
+ speaker,
60
+ ):
61
+ model_holder.load_model_gr(model_name, model_path)
62
+
63
+ wrong_tone_message = ""
64
+ kata_tone: Optional[list[tuple[str, int]]] = None
65
+ if use_tone and kata_tone_json_str != "":
66
+ if language != "JP":
67
+ logger.warning("Only Japanese is supported for tone generation.")
68
+ wrong_tone_message = "アクセント指定は現在日本語のみ対応しています。"
69
+ if line_split:
70
+ logger.warning("Tone generation is not supported for line split.")
71
+ wrong_tone_message = (
72
+ "アクセント指定は改行で分けて生成を使わない場合のみ対応しています。"
73
+ )
74
+ try:
75
+ kata_tone = []
76
+ json_data = json.loads(kata_tone_json_str)
77
+ # tupleを使うように変換
78
+ for kana, tone in json_data:
79
+ assert isinstance(kana, str) and tone in (0, 1), f"{kana}, {tone}"
80
+ kata_tone.append((kana, tone))
81
+ except Exception as e:
82
+ logger.warning(f"Error occurred when parsing kana_tone_json: {e}")
83
+ wrong_tone_message = f"アクセント指定が不正です: {e}"
84
+ kata_tone = None
85
+
86
+ # toneは実際に音声合成に代入される際のみnot Noneになる
87
+ tone: Optional[list[int]] = None
88
+ if kata_tone is not None:
89
+ phone_tone = kata_tone2phone_tone(kata_tone)
90
+ tone = [t for _, t in phone_tone]
91
+
92
+ speaker_id = model_holder.current_model.spk2id[speaker]
93
+
94
+ start_time = datetime.datetime.now()
95
+
96
+ try:
97
+ sr, audio = model_holder.current_model.infer(
98
+ text=text,
99
+ language=language,
100
+ reference_audio_path=reference_audio_path,
101
+ sdp_ratio=sdp_ratio,
102
+ noise=noise_scale,
103
+ noisew=noise_scale_w,
104
+ length=length_scale,
105
+ line_split=line_split,
106
+ split_interval=split_interval,
107
+ assist_text=assist_text,
108
+ assist_text_weight=assist_text_weight,
109
+ use_assist_text=use_assist_text,
110
+ style=style,
111
+ style_weight=style_weight,
112
+ given_tone=tone,
113
+ sid=speaker_id,
114
+ )
115
+ except InvalidToneError as e:
116
+ logger.error(f"Tone error: {e}")
117
+ return f"Error: アクセント指定が不正です:\n{e}", None, kata_tone_json_str
118
+ except ValueError as e:
119
+ logger.error(f"Value error: {e}")
120
+ return f"Error: {e}", None, kata_tone_json_str
121
+
122
+ end_time = datetime.datetime.now()
123
+ duration = (end_time - start_time).total_seconds()
124
+
125
+ if tone is None and language == "JP":
126
+ # アクセント指定に使えるようにアクセント情報を返す
127
+ norm_text = text_normalize(text)
128
+ kata_tone = g2kata_tone(norm_text)
129
+ kata_tone_json_str = json.dumps(kata_tone, ensure_ascii=False)
130
+ elif tone is None:
131
+ kata_tone_json_str = ""
132
+ message = f"Success, time: {duration} seconds."
133
+ if wrong_tone_message != "":
134
+ message = wrong_tone_message + "\n" + message
135
+ return message, (sr, audio), kata_tone_json_str
136
+
137
+
138
+ initial_text = "こんにちは、初めまして。あなたの名前はなんていうの?"
139
+
140
+ examples = [
141
+ [initial_text, "JP"],
142
+ [
143
+ """あなたがそんなこと言うなんて、私はとっても嬉しい。
144
+ あなたがそんなこと言うなんて、私はとっても怒ってる。
145
+ あなたがそんなこと言うなんて、私はとっても驚いてる。
146
+ あなたがそんなこと言うなんて、私はとっても辛い。""",
147
+ "JP",
148
+ ],
149
+ [ # ChatGPTに考えてもらった告白セリフ
150
+ """私、ずっと前からあなたのこ��を見てきました。あなたの笑顔、優しさ、強さに、心惹かれていたんです。
151
+ 友達として過ごす中で、あなたのことがだんだんと特別な存在になっていくのがわかりました。
152
+ えっと、私、あなたのことが好きです!もしよければ、私と付き合ってくれませんか?""",
153
+ "JP",
154
+ ],
155
+ [ # 夏目漱石『吾輩は猫である』
156
+ """吾輩は猫である。名前はまだ無い。
157
+ どこで生れたかとんと見当がつかぬ。なんでも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。
158
+ 吾輩はここで初めて人間というものを見た。しかもあとで聞くと、それは書生という、人間中で一番獰悪な種族であったそうだ。
159
+ この書生というのは時々我々を捕まえて煮て食うという話である。""",
160
+ "JP",
161
+ ],
162
+ [ # 梶井基次郎『桜の樹の下には』
163
+ """桜の樹の下には屍体が埋まっている!これは信じていいことなんだよ。
164
+ 何故って、桜の花があんなにも見事に咲くなんて信じられないことじゃないか。俺はあの美しさが信じられないので、このにさんにち不安だった。
165
+ しかしいま、やっとわかるときが来た。桜の樹の下には屍体が埋まっている。これは信じていいことだ。""",
166
+ "JP",
167
+ ],
168
+ [ # ChatGPTと考えた、感情を表すセリフ
169
+ """やったー!テストで満点取れた!私とっても嬉しいな!
170
+ どうして私の意見を無視するの?許せない!ムカつく!あんたなんか死ねばいいのに。
171
+ あはははっ!この漫画めっちゃ笑える、見てよこれ、ふふふ、あはは。
172
+ あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しい。""",
173
+ "JP",
174
+ ],
175
+ [ # 上の丁寧語バージョン
176
+ """やりました!テストで満点取れましたよ!私とっても嬉しいです!
177
+ どうして私の意見を無視するんですか?許せません!ムカつきます!あんたなんか死んでください。
178
+ あはははっ!この漫画めっちゃ笑えます、見てくださいこれ、ふふふ、あはは。
179
+ あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しいです。""",
180
+ "JP",
181
+ ],
182
+ [ # ChatGPTに考えてもらった音声合成の説明文章
183
+ """音声合成は、機械学習を活用して、テキストから人の声を再現する技術です。この技術は、言語の構造を解析し、それに基づいて音声を生成します。
184
+ この分野の最新の研究成果を使うと、より自然で表現豊かな音声の生成が可能である。深層学習の応用により、感情やアクセントを含む声質の微妙な変化も再現することが出来る。""",
185
+ "JP",
186
+ ],
187
+ [
188
+ "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.",
189
+ "EN",
190
+ ],
191
+ [
192
+ "语音合成是人工制造人类语音。用于此目的的计算机系统称为语音合成器,可以通过软件或硬件产品实现。",
193
+ "ZH",
194
+ ],
195
+ ]
196
+
197
+ initial_md = f"""
198
+ # Style-Bert-VITS2 ver {LATEST_VERSION} 音声合成
199
+
200
+ 注意: 初期からある[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)です。
201
+ """
202
+
203
+ how_to_md = """
204
+ 下のように`model_assets`ディレクトリの中にモデルファイルたちを置いてください。
205
+ ```
206
+ model_assets
207
+ ├── your_model
208
+ │ ├── config.json
209
+ │ ├── your_model_file1.safetensors
210
+ │ ├── your_model_file2.safetensors
211
+ │ ├── ...
212
+ │ └── style_vectors.npy
213
+ └── another_model
214
+ ├── ...
215
+ ```
216
+ 各モデルにはファイルたちが必要です:
217
+ - `config.json`:学習時の設定ファイル
218
+ - `*.safetensors`:学習済みモデルファイル(1つ以上が必要、複数可)
219
+ - `style_vectors.npy`:スタイルベクトルファイル
220
+
221
+ 上2つは`Train.bat`による学習で自動的に正しい位置に保存されます。`style_vectors.npy`は`Style.bat`を実行して指示に従って生成してください。
222
+ """
223
+
224
+ style_md = f"""
225
+ - プリセットまたは音声ファイルから読み上げの声音・感情・スタイルのようなものを制御できます。
226
+ - デフォルトの{DEFAULT_STYLE}でも、十分に読み上げる文に応じた感情で感情豊かに読み上���られます。このスタイル制御は、それを重み付きで上書きするような感じです。
227
+ - 強さを大きくしすぎると発音が変になったり声にならなかったりと崩壊することがあります。
228
+ - どのくらいに強さがいいかはモデルやスタイルによって異なるようです。
229
+ - 音声ファイルを入力する場合は、学習データと似た声音の話者(特に同じ性別)でないとよい効果が出ないかもしれません。
230
+ """
231
+
232
+
233
+ def make_interactive():
234
+ return gr.update(interactive=True, value="音声合成")
235
+
236
+
237
+ def make_non_interactive():
238
+ return gr.update(interactive=False, value="音声合成(モデルをロードしてください)")
239
+
240
+
241
+ def gr_util(item):
242
+ if item == "プリセットから選ぶ":
243
+ return (gr.update(visible=True), gr.Audio(visible=False, value=None))
244
+ else:
245
+ return (gr.update(visible=False), gr.update(visible=True))
246
+
247
+
248
+ if __name__ == "__main__":
249
+ parser = argparse.ArgumentParser()
250
+ parser.add_argument("--cpu", action="store_true", help="Use CPU instead of GPU")
251
+ parser.add_argument(
252
+ "--dir", "-d", type=str, help="Model directory", default=assets_root
253
+ )
254
+ parser.add_argument(
255
+ "--share", action="store_true", help="Share this app publicly", default=False
256
+ )
257
+ parser.add_argument(
258
+ "--server-name",
259
+ type=str,
260
+ default=None,
261
+ help="Server name for Gradio app",
262
+ )
263
+ parser.add_argument(
264
+ "--no-autolaunch",
265
+ action="store_true",
266
+ default=False,
267
+ help="Do not launch app automatically",
268
+ )
269
+ args = parser.parse_args()
270
+ model_dir = args.dir
271
+
272
+ if args.cpu:
273
+ device = "cpu"
274
+ else:
275
+ device = "cuda" if torch.cuda.is_available() else "cpu"
276
+
277
+ model_holder = ModelHolder(model_dir, device)
278
+
279
+ model_names = model_holder.model_names
280
+ if len(model_names) == 0:
281
+ logger.error(
282
+ f"モデルが見つかりませんでした。{model_dir}にモデルを置いてください。"
283
+ )
284
+ sys.exit(1)
285
+ initial_id = 0
286
+ initial_pth_files = model_holder.model_files_dict[model_names[initial_id]]
287
+
288
+ with gr.Blocks(theme=GRADIO_THEME) as app:
289
+ gr.Markdown(initial_md)
290
+ with gr.Accordion(label="使い方", open=False):
291
+ gr.Markdown(how_to_md)
292
+ with gr.Row():
293
+ with gr.Column():
294
+ with gr.Row():
295
+ with gr.Column(scale=3):
296
+ model_name = gr.Dropdown(
297
+ label="モデル一覧",
298
+ choices=model_names,
299
+ value=model_names[initial_id],
300
+ )
301
+ model_path = gr.Dropdown(
302
+ label="モデルファイル",
303
+ choices=initial_pth_files,
304
+ value=initial_pth_files[0],
305
+ )
306
+ refresh_button = gr.Button("更新", scale=1, visible=True)
307
+ load_button = gr.Button("ロード", scale=1, variant="primary")
308
+ text_input = gr.TextArea(label="テキスト", value=initial_text)
309
+
310
+ line_split = gr.Checkbox(
311
+ label="改行で分けて生成(分けたほうが感情が乗ります)",
312
+ value=DEFAULT_LINE_SPLIT,
313
+ )
314
+ split_interval = gr.Slider(
315
+ minimum=0.0,
316
+ maximum=2,
317
+ value=DEFAULT_SPLIT_INTERVAL,
318
+ step=0.1,
319
+ label="改行ごとに挟む無音の長さ(秒)",
320
+ )
321
+ line_split.change(
322
+ lambda x: (gr.Slider(visible=x)),
323
+ inputs=[line_split],
324
+ outputs=[split_interval],
325
+ )
326
+ tone = gr.Textbox(
327
+ label="アクセント調整(数値は 0=低 か1=高 のみ)",
328
+ info="改行で分けない場合のみ使えます。万能ではありません。",
329
+ )
330
+ use_tone = gr.Checkbox(label="アクセント調整を使う", value=False)
331
+ use_tone.change(
332
+ lambda x: (gr.Checkbox(value=False) if x else gr.Checkbox()),
333
+ inputs=[use_tone],
334
+ outputs=[line_split],
335
+ )
336
+ language = gr.Dropdown(choices=languages, value="JP", label="Language")
337
+ speaker = gr.Dropdown(label="話者")
338
+ with gr.Accordion(label="詳細設定", open=False):
339
+ sdp_ratio = gr.Slider(
340
+ minimum=0,
341
+ maximum=1,
342
+ value=DEFAULT_SDP_RATIO,
343
+ step=0.1,
344
+ label="SDP Ratio",
345
+ )
346
+ noise_scale = gr.Slider(
347
+ minimum=0.1,
348
+ maximum=2,
349
+ value=DEFAULT_NOISE,
350
+ step=0.1,
351
+ label="Noise",
352
+ )
353
+ noise_scale_w = gr.Slider(
354
+ minimum=0.1,
355
+ maximum=2,
356
+ value=DEFAULT_NOISEW,
357
+ step=0.1,
358
+ label="Noise_W",
359
+ )
360
+ length_scale = gr.Slider(
361
+ minimum=0.1,
362
+ maximum=2,
363
+ value=DEFAULT_LENGTH,
364
+ step=0.1,
365
+ label="Length",
366
+ )
367
+ use_assist_text = gr.Checkbox(
368
+ label="Assist textを使う", value=False
369
+ )
370
+ assist_text = gr.Textbox(
371
+ label="Assist text",
372
+ placeholder="どうして私の意見を無視するの?許せない、ムカつく!死ねばいいのに。",
373
+ info="このテキストの読み上げと似た声音・感情になりやすくなります。ただ抑揚やテンポ等が犠牲になる傾向があります。",
374
+ visible=False,
375
+ )
376
+ assist_text_weight = gr.Slider(
377
+ minimum=0,
378
+ maximum=1,
379
+ value=DEFAULT_ASSIST_TEXT_WEIGHT,
380
+ step=0.1,
381
+ label="Assist textの強さ",
382
+ visible=False,
383
+ )
384
+ use_assist_text.change(
385
+ lambda x: (gr.Textbox(visible=x), gr.Slider(visible=x)),
386
+ inputs=[use_assist_text],
387
+ outputs=[assist_text, assist_text_weight],
388
+ )
389
+ with gr.Column():
390
+ with gr.Accordion("スタイルについて詳細", open=False):
391
+ gr.Markdown(style_md)
392
+ style_mode = gr.Radio(
393
+ ["プリセットから選ぶ", "音声ファイルを入力"],
394
+ label="スタイルの指定方法",
395
+ value="プリセットから選ぶ",
396
+ )
397
+ style = gr.Dropdown(
398
+ label=f"スタイル({DEFAULT_STYLE}が平均スタイル)",
399
+ choices=["モデルをロードしてください"],
400
+ value="モデルをロードしてください",
401
+ )
402
+ style_weight = gr.Slider(
403
+ minimum=0,
404
+ maximum=50,
405
+ value=DEFAULT_STYLE_WEIGHT,
406
+ step=0.1,
407
+ label="スタイルの強さ",
408
+ )
409
+ ref_audio_path = gr.Audio(
410
+ label="参照音声", type="filepath", visible=False
411
+ )
412
+ tts_button = gr.Button(
413
+ "音声合成(モデルをロードしてください)",
414
+ variant="primary",
415
+ interactive=False,
416
+ )
417
+ text_output = gr.Textbox(label="情報")
418
+ audio_output = gr.Audio(label="結果")
419
+ with gr.Accordion("テキスト例", open=False):
420
+ gr.Examples(examples, inputs=[text_input, language])
421
+
422
+ tts_button.click(
423
+ tts_fn,
424
+ inputs=[
425
+ model_name,
426
+ model_path,
427
+ text_input,
428
+ language,
429
+ ref_audio_path,
430
+ sdp_ratio,
431
+ noise_scale,
432
+ noise_scale_w,
433
+ length_scale,
434
+ line_split,
435
+ split_interval,
436
+ assist_text,
437
+ assist_text_weight,
438
+ use_assist_text,
439
+ style,
440
+ style_weight,
441
+ tone,
442
+ use_tone,
443
+ speaker,
444
+ ],
445
+ outputs=[text_output, audio_output, tone],
446
+ )
447
+
448
+ model_name.change(
449
+ model_holder.update_model_files_gr,
450
+ inputs=[model_name],
451
+ outputs=[model_path],
452
+ )
453
+
454
+ model_path.change(make_non_interactive, outputs=[tts_button])
455
+
456
+ refresh_button.click(
457
+ model_holder.update_model_names_gr,
458
+ outputs=[model_name, model_path, tts_button],
459
+ )
460
+
461
+ load_button.click(
462
+ model_holder.load_model_gr,
463
+ inputs=[model_name, model_path],
464
+ outputs=[style, tts_button, speaker],
465
+ )
466
+
467
+ style_mode.change(
468
+ gr_util,
469
+ inputs=[style_mode],
470
+ outputs=[style, ref_audio_path],
471
+ )
472
+
473
+ app.launch(
474
+ inbrowser=not args.no_autolaunch, share=args.share, server_name=args.server_name
475
+ )
attentions.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ import commons
7
+ from common.log import logger as logging
8
+
9
+
10
+ class LayerNorm(nn.Module):
11
+ def __init__(self, channels, eps=1e-5):
12
+ super().__init__()
13
+ self.channels = channels
14
+ self.eps = eps
15
+
16
+ self.gamma = nn.Parameter(torch.ones(channels))
17
+ self.beta = nn.Parameter(torch.zeros(channels))
18
+
19
+ def forward(self, x):
20
+ x = x.transpose(1, -1)
21
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
22
+ return x.transpose(1, -1)
23
+
24
+
25
+ @torch.jit.script
26
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
27
+ n_channels_int = n_channels[0]
28
+ in_act = input_a + input_b
29
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
30
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
31
+ acts = t_act * s_act
32
+ return acts
33
+
34
+
35
+ class Encoder(nn.Module):
36
+ def __init__(
37
+ self,
38
+ hidden_channels,
39
+ filter_channels,
40
+ n_heads,
41
+ n_layers,
42
+ kernel_size=1,
43
+ p_dropout=0.0,
44
+ window_size=4,
45
+ isflow=True,
46
+ **kwargs
47
+ ):
48
+ super().__init__()
49
+ self.hidden_channels = hidden_channels
50
+ self.filter_channels = filter_channels
51
+ self.n_heads = n_heads
52
+ self.n_layers = n_layers
53
+ self.kernel_size = kernel_size
54
+ self.p_dropout = p_dropout
55
+ self.window_size = window_size
56
+ # if isflow:
57
+ # cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
58
+ # self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
59
+ # self.cond_layer = weight_norm(cond_layer, name='weight')
60
+ # self.gin_channels = 256
61
+ self.cond_layer_idx = self.n_layers
62
+ if "gin_channels" in kwargs:
63
+ self.gin_channels = kwargs["gin_channels"]
64
+ if self.gin_channels != 0:
65
+ self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
66
+ # vits2 says 3rd block, so idx is 2 by default
67
+ self.cond_layer_idx = (
68
+ kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
69
+ )
70
+ # logging.debug(self.gin_channels, self.cond_layer_idx)
71
+ assert (
72
+ self.cond_layer_idx < self.n_layers
73
+ ), "cond_layer_idx should be less than n_layers"
74
+ self.drop = nn.Dropout(p_dropout)
75
+ self.attn_layers = nn.ModuleList()
76
+ self.norm_layers_1 = nn.ModuleList()
77
+ self.ffn_layers = nn.ModuleList()
78
+ self.norm_layers_2 = nn.ModuleList()
79
+ for i in range(self.n_layers):
80
+ self.attn_layers.append(
81
+ MultiHeadAttention(
82
+ hidden_channels,
83
+ hidden_channels,
84
+ n_heads,
85
+ p_dropout=p_dropout,
86
+ window_size=window_size,
87
+ )
88
+ )
89
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
90
+ self.ffn_layers.append(
91
+ FFN(
92
+ hidden_channels,
93
+ hidden_channels,
94
+ filter_channels,
95
+ kernel_size,
96
+ p_dropout=p_dropout,
97
+ )
98
+ )
99
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
100
+
101
+ def forward(self, x, x_mask, g=None):
102
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
103
+ x = x * x_mask
104
+ for i in range(self.n_layers):
105
+ if i == self.cond_layer_idx and g is not None:
106
+ g = self.spk_emb_linear(g.transpose(1, 2))
107
+ g = g.transpose(1, 2)
108
+ x = x + g
109
+ x = x * x_mask
110
+ y = self.attn_layers[i](x, x, attn_mask)
111
+ y = self.drop(y)
112
+ x = self.norm_layers_1[i](x + y)
113
+
114
+ y = self.ffn_layers[i](x, x_mask)
115
+ y = self.drop(y)
116
+ x = self.norm_layers_2[i](x + y)
117
+ x = x * x_mask
118
+ return x
119
+
120
+
121
+ class Decoder(nn.Module):
122
+ def __init__(
123
+ self,
124
+ hidden_channels,
125
+ filter_channels,
126
+ n_heads,
127
+ n_layers,
128
+ kernel_size=1,
129
+ p_dropout=0.0,
130
+ proximal_bias=False,
131
+ proximal_init=True,
132
+ **kwargs
133
+ ):
134
+ super().__init__()
135
+ self.hidden_channels = hidden_channels
136
+ self.filter_channels = filter_channels
137
+ self.n_heads = n_heads
138
+ self.n_layers = n_layers
139
+ self.kernel_size = kernel_size
140
+ self.p_dropout = p_dropout
141
+ self.proximal_bias = proximal_bias
142
+ self.proximal_init = proximal_init
143
+
144
+ self.drop = nn.Dropout(p_dropout)
145
+ self.self_attn_layers = nn.ModuleList()
146
+ self.norm_layers_0 = nn.ModuleList()
147
+ self.encdec_attn_layers = nn.ModuleList()
148
+ self.norm_layers_1 = nn.ModuleList()
149
+ self.ffn_layers = nn.ModuleList()
150
+ self.norm_layers_2 = nn.ModuleList()
151
+ for i in range(self.n_layers):
152
+ self.self_attn_layers.append(
153
+ MultiHeadAttention(
154
+ hidden_channels,
155
+ hidden_channels,
156
+ n_heads,
157
+ p_dropout=p_dropout,
158
+ proximal_bias=proximal_bias,
159
+ proximal_init=proximal_init,
160
+ )
161
+ )
162
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
163
+ self.encdec_attn_layers.append(
164
+ MultiHeadAttention(
165
+ hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
166
+ )
167
+ )
168
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
169
+ self.ffn_layers.append(
170
+ FFN(
171
+ hidden_channels,
172
+ hidden_channels,
173
+ filter_channels,
174
+ kernel_size,
175
+ p_dropout=p_dropout,
176
+ causal=True,
177
+ )
178
+ )
179
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
180
+
181
+ def forward(self, x, x_mask, h, h_mask):
182
+ """
183
+ x: decoder input
184
+ h: encoder output
185
+ """
186
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
187
+ device=x.device, dtype=x.dtype
188
+ )
189
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
190
+ x = x * x_mask
191
+ for i in range(self.n_layers):
192
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
193
+ y = self.drop(y)
194
+ x = self.norm_layers_0[i](x + y)
195
+
196
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
197
+ y = self.drop(y)
198
+ x = self.norm_layers_1[i](x + y)
199
+
200
+ y = self.ffn_layers[i](x, x_mask)
201
+ y = self.drop(y)
202
+ x = self.norm_layers_2[i](x + y)
203
+ x = x * x_mask
204
+ return x
205
+
206
+
207
+ class MultiHeadAttention(nn.Module):
208
+ def __init__(
209
+ self,
210
+ channels,
211
+ out_channels,
212
+ n_heads,
213
+ p_dropout=0.0,
214
+ window_size=None,
215
+ heads_share=True,
216
+ block_length=None,
217
+ proximal_bias=False,
218
+ proximal_init=False,
219
+ ):
220
+ super().__init__()
221
+ assert channels % n_heads == 0
222
+
223
+ self.channels = channels
224
+ self.out_channels = out_channels
225
+ self.n_heads = n_heads
226
+ self.p_dropout = p_dropout
227
+ self.window_size = window_size
228
+ self.heads_share = heads_share
229
+ self.block_length = block_length
230
+ self.proximal_bias = proximal_bias
231
+ self.proximal_init = proximal_init
232
+ self.attn = None
233
+
234
+ self.k_channels = channels // n_heads
235
+ self.conv_q = nn.Conv1d(channels, channels, 1)
236
+ self.conv_k = nn.Conv1d(channels, channels, 1)
237
+ self.conv_v = nn.Conv1d(channels, channels, 1)
238
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
239
+ self.drop = nn.Dropout(p_dropout)
240
+
241
+ if window_size is not None:
242
+ n_heads_rel = 1 if heads_share else n_heads
243
+ rel_stddev = self.k_channels**-0.5
244
+ self.emb_rel_k = nn.Parameter(
245
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
246
+ * rel_stddev
247
+ )
248
+ self.emb_rel_v = nn.Parameter(
249
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
250
+ * rel_stddev
251
+ )
252
+
253
+ nn.init.xavier_uniform_(self.conv_q.weight)
254
+ nn.init.xavier_uniform_(self.conv_k.weight)
255
+ nn.init.xavier_uniform_(self.conv_v.weight)
256
+ if proximal_init:
257
+ with torch.no_grad():
258
+ self.conv_k.weight.copy_(self.conv_q.weight)
259
+ self.conv_k.bias.copy_(self.conv_q.bias)
260
+
261
+ def forward(self, x, c, attn_mask=None):
262
+ q = self.conv_q(x)
263
+ k = self.conv_k(c)
264
+ v = self.conv_v(c)
265
+
266
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
267
+
268
+ x = self.conv_o(x)
269
+ return x
270
+
271
+ def attention(self, query, key, value, mask=None):
272
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
273
+ b, d, t_s, t_t = (*key.size(), query.size(2))
274
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
275
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
276
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
277
+
278
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
279
+ if self.window_size is not None:
280
+ assert (
281
+ t_s == t_t
282
+ ), "Relative attention is only available for self-attention."
283
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
284
+ rel_logits = self._matmul_with_relative_keys(
285
+ query / math.sqrt(self.k_channels), key_relative_embeddings
286
+ )
287
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
288
+ scores = scores + scores_local
289
+ if self.proximal_bias:
290
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
291
+ scores = scores + self._attention_bias_proximal(t_s).to(
292
+ device=scores.device, dtype=scores.dtype
293
+ )
294
+ if mask is not None:
295
+ scores = scores.masked_fill(mask == 0, -1e4)
296
+ if self.block_length is not None:
297
+ assert (
298
+ t_s == t_t
299
+ ), "Local attention is only available for self-attention."
300
+ block_mask = (
301
+ torch.ones_like(scores)
302
+ .triu(-self.block_length)
303
+ .tril(self.block_length)
304
+ )
305
+ scores = scores.masked_fill(block_mask == 0, -1e4)
306
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
307
+ p_attn = self.drop(p_attn)
308
+ output = torch.matmul(p_attn, value)
309
+ if self.window_size is not None:
310
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
311
+ value_relative_embeddings = self._get_relative_embeddings(
312
+ self.emb_rel_v, t_s
313
+ )
314
+ output = output + self._matmul_with_relative_values(
315
+ relative_weights, value_relative_embeddings
316
+ )
317
+ output = (
318
+ output.transpose(2, 3).contiguous().view(b, d, t_t)
319
+ ) # [b, n_h, t_t, d_k] -> [b, d, t_t]
320
+ return output, p_attn
321
+
322
+ def _matmul_with_relative_values(self, x, y):
323
+ """
324
+ x: [b, h, l, m]
325
+ y: [h or 1, m, d]
326
+ ret: [b, h, l, d]
327
+ """
328
+ ret = torch.matmul(x, y.unsqueeze(0))
329
+ return ret
330
+
331
+ def _matmul_with_relative_keys(self, x, y):
332
+ """
333
+ x: [b, h, l, d]
334
+ y: [h or 1, m, d]
335
+ ret: [b, h, l, m]
336
+ """
337
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
338
+ return ret
339
+
340
+ def _get_relative_embeddings(self, relative_embeddings, length):
341
+ 2 * self.window_size + 1
342
+ # Pad first before slice to avoid using cond ops.
343
+ pad_length = max(length - (self.window_size + 1), 0)
344
+ slice_start_position = max((self.window_size + 1) - length, 0)
345
+ slice_end_position = slice_start_position + 2 * length - 1
346
+ if pad_length > 0:
347
+ padded_relative_embeddings = F.pad(
348
+ relative_embeddings,
349
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
350
+ )
351
+ else:
352
+ padded_relative_embeddings = relative_embeddings
353
+ used_relative_embeddings = padded_relative_embeddings[
354
+ :, slice_start_position:slice_end_position
355
+ ]
356
+ return used_relative_embeddings
357
+
358
+ def _relative_position_to_absolute_position(self, x):
359
+ """
360
+ x: [b, h, l, 2*l-1]
361
+ ret: [b, h, l, l]
362
+ """
363
+ batch, heads, length, _ = x.size()
364
+ # Concat columns of pad to shift from relative to absolute indexing.
365
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
366
+
367
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
368
+ x_flat = x.view([batch, heads, length * 2 * length])
369
+ x_flat = F.pad(
370
+ x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
371
+ )
372
+
373
+ # Reshape and slice out the padded elements.
374
+ x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
375
+ :, :, :length, length - 1 :
376
+ ]
377
+ return x_final
378
+
379
+ def _absolute_position_to_relative_position(self, x):
380
+ """
381
+ x: [b, h, l, l]
382
+ ret: [b, h, l, 2*l-1]
383
+ """
384
+ batch, heads, length, _ = x.size()
385
+ # pad along column
386
+ x = F.pad(
387
+ x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
388
+ )
389
+ x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
390
+ # add 0's in the beginning that will skew the elements after reshape
391
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
392
+ x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
393
+ return x_final
394
+
395
+ def _attention_bias_proximal(self, length):
396
+ """Bias for self-attention to encourage attention to close positions.
397
+ Args:
398
+ length: an integer scalar.
399
+ Returns:
400
+ a Tensor with shape [1, 1, length, length]
401
+ """
402
+ r = torch.arange(length, dtype=torch.float32)
403
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
404
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
405
+
406
+
407
+ class FFN(nn.Module):
408
+ def __init__(
409
+ self,
410
+ in_channels,
411
+ out_channels,
412
+ filter_channels,
413
+ kernel_size,
414
+ p_dropout=0.0,
415
+ activation=None,
416
+ causal=False,
417
+ ):
418
+ super().__init__()
419
+ self.in_channels = in_channels
420
+ self.out_channels = out_channels
421
+ self.filter_channels = filter_channels
422
+ self.kernel_size = kernel_size
423
+ self.p_dropout = p_dropout
424
+ self.activation = activation
425
+ self.causal = causal
426
+
427
+ if causal:
428
+ self.padding = self._causal_padding
429
+ else:
430
+ self.padding = self._same_padding
431
+
432
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
433
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
434
+ self.drop = nn.Dropout(p_dropout)
435
+
436
+ def forward(self, x, x_mask):
437
+ x = self.conv_1(self.padding(x * x_mask))
438
+ if self.activation == "gelu":
439
+ x = x * torch.sigmoid(1.702 * x)
440
+ else:
441
+ x = torch.relu(x)
442
+ x = self.drop(x)
443
+ x = self.conv_2(self.padding(x * x_mask))
444
+ return x * x_mask
445
+
446
+ def _causal_padding(self, x):
447
+ if self.kernel_size == 1:
448
+ return x
449
+ pad_l = self.kernel_size - 1
450
+ pad_r = 0
451
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
452
+ x = F.pad(x, commons.convert_pad_shape(padding))
453
+ return x
454
+
455
+ def _same_padding(self, x):
456
+ if self.kernel_size == 1:
457
+ return x
458
+ pad_l = (self.kernel_size - 1) // 2
459
+ pad_r = self.kernel_size // 2
460
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
461
+ x = F.pad(x, commons.convert_pad_shape(padding))
462
+ return x
bert/bert_models.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/chinese-roberta-wwm-ext-large/.gitattributes ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
2
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.h5 filter=lfs diff=lfs merge=lfs -text
5
+ *.tflite filter=lfs diff=lfs merge=lfs -text
6
+ *.tar.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.ot filter=lfs diff=lfs merge=lfs -text
8
+ *.onnx filter=lfs diff=lfs merge=lfs -text
9
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
bert/chinese-roberta-wwm-ext-large/README.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ tags:
5
+ - bert
6
+ license: "apache-2.0"
7
+ ---
8
+
9
+ # Please use 'Bert' related functions to load this model!
10
+
11
+ ## Chinese BERT with Whole Word Masking
12
+ For further accelerating Chinese natural language processing, we provide **Chinese pre-trained BERT with Whole Word Masking**.
13
+
14
+ **[Pre-Training with Whole Word Masking for Chinese BERT](https://arxiv.org/abs/1906.08101)**
15
+ Yiming Cui, Wanxiang Che, Ting Liu, Bing Qin, Ziqing Yang, Shijin Wang, Guoping Hu
16
+
17
+ This repository is developed based on:https://github.com/google-research/bert
18
+
19
+ You may also interested in,
20
+ - Chinese BERT series: https://github.com/ymcui/Chinese-BERT-wwm
21
+ - Chinese MacBERT: https://github.com/ymcui/MacBERT
22
+ - Chinese ELECTRA: https://github.com/ymcui/Chinese-ELECTRA
23
+ - Chinese XLNet: https://github.com/ymcui/Chinese-XLNet
24
+ - Knowledge Distillation Toolkit - TextBrewer: https://github.com/airaria/TextBrewer
25
+
26
+ More resources by HFL: https://github.com/ymcui/HFL-Anthology
27
+
28
+ ## Citation
29
+ If you find the technical report or resource is useful, please cite the following technical report in your paper.
30
+ - Primary: https://arxiv.org/abs/2004.13922
31
+ ```
32
+ @inproceedings{cui-etal-2020-revisiting,
33
+ title = "Revisiting Pre-Trained Models for {C}hinese Natural Language Processing",
34
+ author = "Cui, Yiming and
35
+ Che, Wanxiang and
36
+ Liu, Ting and
37
+ Qin, Bing and
38
+ Wang, Shijin and
39
+ Hu, Guoping",
40
+ booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: Findings",
41
+ month = nov,
42
+ year = "2020",
43
+ address = "Online",
44
+ publisher = "Association for Computational Linguistics",
45
+ url = "https://www.aclweb.org/anthology/2020.findings-emnlp.58",
46
+ pages = "657--668",
47
+ }
48
+ ```
49
+ - Secondary: https://arxiv.org/abs/1906.08101
50
+ ```
51
+ @article{chinese-bert-wwm,
52
+ title={Pre-Training with Whole Word Masking for Chinese BERT},
53
+ author={Cui, Yiming and Che, Wanxiang and Liu, Ting and Qin, Bing and Yang, Ziqing and Wang, Shijin and Hu, Guoping},
54
+ journal={arXiv preprint arXiv:1906.08101},
55
+ year={2019}
56
+ }
57
+ ```
bert/chinese-roberta-wwm-ext-large/added_tokens.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
bert/chinese-roberta-wwm-ext-large/config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertForMaskedLM"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "bos_token_id": 0,
7
+ "directionality": "bidi",
8
+ "eos_token_id": 2,
9
+ "hidden_act": "gelu",
10
+ "hidden_dropout_prob": 0.1,
11
+ "hidden_size": 1024,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 4096,
14
+ "layer_norm_eps": 1e-12,
15
+ "max_position_embeddings": 512,
16
+ "model_type": "bert",
17
+ "num_attention_heads": 16,
18
+ "num_hidden_layers": 24,
19
+ "output_past": true,
20
+ "pad_token_id": 0,
21
+ "pooler_fc_size": 768,
22
+ "pooler_num_attention_heads": 12,
23
+ "pooler_num_fc_layers": 3,
24
+ "pooler_size_per_head": 128,
25
+ "pooler_type": "first_token_transform",
26
+ "type_vocab_size": 2,
27
+ "vocab_size": 21128
28
+ }
bert/chinese-roberta-wwm-ext-large/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ac62d49144d770c5ca9a5d1d3039c4995665a080febe63198189857c6bd11cd
3
+ size 1306484351
bert/chinese-roberta-wwm-ext-large/special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]"}
bert/chinese-roberta-wwm-ext-large/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
bert/chinese-roberta-wwm-ext-large/tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"init_inputs": []}
bert/chinese-roberta-wwm-ext-large/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
bert/deberta-v2-large-japanese-char-wwm/.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
bert/deberta-v2-large-japanese-char-wwm/README.md ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: ja
3
+ license: cc-by-sa-4.0
4
+ library_name: transformers
5
+ tags:
6
+ - deberta
7
+ - deberta-v2
8
+ - fill-mask
9
+ - character
10
+ - wwm
11
+ datasets:
12
+ - wikipedia
13
+ - cc100
14
+ - oscar
15
+ metrics:
16
+ - accuracy
17
+ mask_token: "[MASK]"
18
+ widget:
19
+ - text: "京都大学で自然言語処理を[MASK][MASK]する。"
20
+ ---
21
+
22
+ # Model Card for Japanese character-level DeBERTa V2 large
23
+
24
+ ## Model description
25
+
26
+ This is a Japanese DeBERTa V2 large model pre-trained on Japanese Wikipedia, the Japanese portion of CC-100, and the Japanese portion of OSCAR.
27
+ This model is trained with character-level tokenization and whole word masking.
28
+
29
+ ## How to use
30
+
31
+ You can use this model for masked language modeling as follows:
32
+
33
+ ```python
34
+ from transformers import AutoTokenizer, AutoModelForMaskedLM
35
+ tokenizer = AutoTokenizer.from_pretrained('ku-nlp/deberta-v2-large-japanese-char-wwm')
36
+ model = AutoModelForMaskedLM.from_pretrained('ku-nlp/deberta-v2-large-japanese-char-wwm')
37
+
38
+ sentence = '京都大学で自然言語処理を[MASK][MASK]する。'
39
+ encoding = tokenizer(sentence, return_tensors='pt')
40
+ ...
41
+ ```
42
+
43
+ You can also fine-tune this model on downstream tasks.
44
+
45
+ ## Tokenization
46
+
47
+ There is no need to tokenize texts in advance, and you can give raw texts to the tokenizer.
48
+ The texts are tokenized into character-level tokens by [sentencepiece](https://github.com/google/sentencepiece).
49
+
50
+ ## Training data
51
+
52
+ We used the following corpora for pre-training:
53
+
54
+ - Japanese Wikipedia (as of 20221020, 3.2GB, 27M sentences, 1.3M documents)
55
+ - Japanese portion of CC-100 (85GB, 619M sentences, 66M documents)
56
+ - Japanese portion of OSCAR (54GB, 326M sentences, 25M documents)
57
+
58
+ Note that we filtered out documents annotated with "header", "footer", or "noisy" tags in OSCAR.
59
+ Also note that Japanese Wikipedia was duplicated 10 times to make the total size of the corpus comparable to that of CC-100 and OSCAR. As a result, the total size of the training data is 171GB.
60
+
61
+ ## Training procedure
62
+
63
+ We first segmented texts in the corpora into words using [Juman++ 2.0.0-rc3](https://github.com/ku-nlp/jumanpp/releases/tag/v2.0.0-rc3) for whole word masking.
64
+ Then, we built a sentencepiece model with 22,012 tokens including all characters that appear in the training corpus.
65
+
66
+ We tokenized raw corpora into character-level subwords using the sentencepiece model and trained the Japanese DeBERTa model using [transformers](https://github.com/huggingface/transformers) library.
67
+ The training took 26 days using 16 NVIDIA A100-SXM4-40GB GPUs.
68
+
69
+ The following hyperparameters were used during pre-training:
70
+
71
+ - learning_rate: 1e-4
72
+ - per_device_train_batch_size: 26
73
+ - distributed_type: multi-GPU
74
+ - num_devices: 16
75
+ - gradient_accumulation_steps: 8
76
+ - total_train_batch_size: 3,328
77
+ - max_seq_length: 512
78
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-06
79
+ - lr_scheduler_type: linear schedule with warmup (lr = 0 at 300k steps)
80
+ - training_steps: 260,000
81
+ - warmup_steps: 10,000
82
+
83
+ The accuracy of the trained model on the masked language modeling task was 0.795.
84
+ The evaluation set consists of 5,000 randomly sampled documents from each of the training corpora.
85
+
86
+ ## Acknowledgments
87
+
88
+ This work was supported by Joint Usage/Research Center for Interdisciplinary Large-scale Information Infrastructures (JHPCN) through General Collaboration Project no. jh221004, "Developing a Platform for Constructing and Sharing of Large-Scale Japanese Language Models".
89
+ For training models, we used the mdx: a platform for the data-driven future.
bert/deberta-v2-large-japanese-char-wwm/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DebertaV2ForMaskedLM"
4
+ ],
5
+ "attention_head_size": 64,
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "conv_act": "gelu",
8
+ "conv_kernel_size": 3,
9
+ "hidden_act": "gelu",
10
+ "hidden_dropout_prob": 0.1,
11
+ "hidden_size": 1024,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 4096,
14
+ "layer_norm_eps": 1e-07,
15
+ "max_position_embeddings": 512,
16
+ "max_relative_positions": -1,
17
+ "model_type": "deberta-v2",
18
+ "norm_rel_ebd": "layer_norm",
19
+ "num_attention_heads": 16,
20
+ "num_hidden_layers": 24,
21
+ "pad_token_id": 0,
22
+ "pooler_dropout": 0,
23
+ "pooler_hidden_act": "gelu",
24
+ "pooler_hidden_size": 1024,
25
+ "pos_att_type": [
26
+ "p2c",
27
+ "c2p"
28
+ ],
29
+ "position_biased_input": false,
30
+ "position_buckets": 256,
31
+ "relative_attention": true,
32
+ "share_att_key": true,
33
+ "torch_dtype": "float16",
34
+ "transformers_version": "4.25.1",
35
+ "type_vocab_size": 0,
36
+ "vocab_size": 22012
37
+ }
bert/deberta-v2-large-japanese-char-wwm/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf0dab8ad87bd7c22e85ec71e04f2240804fda6d33196157d6b5923af6ea1201
3
+ size 1318456639
bert/deberta-v2-large-japanese-char-wwm/special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
bert/deberta-v2-large-japanese-char-wwm/tokenizer_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "do_lower_case": false,
4
+ "do_subword_tokenize": true,
5
+ "do_word_tokenize": true,
6
+ "jumanpp_kwargs": null,
7
+ "mask_token": "[MASK]",
8
+ "mecab_kwargs": null,
9
+ "model_max_length": 1000000000000000019884624838656,
10
+ "never_split": null,
11
+ "pad_token": "[PAD]",
12
+ "sep_token": "[SEP]",
13
+ "special_tokens_map_file": null,
14
+ "subword_tokenizer_type": "character",
15
+ "sudachi_kwargs": null,
16
+ "tokenizer_class": "BertJapaneseTokenizer",
17
+ "unk_token": "[UNK]",
18
+ "word_tokenizer_type": "basic"
19
+ }
bert/deberta-v2-large-japanese-char-wwm/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
bert/deberta-v3-large/.gitattributes ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.model filter=lfs diff=lfs merge=lfs -text
12
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
13
+ *.onnx filter=lfs diff=lfs merge=lfs -text
14
+ *.ot filter=lfs diff=lfs merge=lfs -text
15
+ *.parquet filter=lfs diff=lfs merge=lfs -text
16
+ *.pb filter=lfs diff=lfs merge=lfs -text
17
+ *.pt filter=lfs diff=lfs merge=lfs -text
18
+ *.pth filter=lfs diff=lfs merge=lfs -text
19
+ *.rar filter=lfs diff=lfs merge=lfs -text
20
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
21
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
22
+ *.tflite filter=lfs diff=lfs merge=lfs -text
23
+ *.tgz filter=lfs diff=lfs merge=lfs -text
24
+ *.xz filter=lfs diff=lfs merge=lfs -text
25
+ *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
bert/deberta-v3-large/README.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: en
3
+ tags:
4
+ - deberta
5
+ - deberta-v3
6
+ - fill-mask
7
+ thumbnail: https://huggingface.co/front/thumbnails/microsoft.png
8
+ license: mit
9
+ ---
10
+
11
+ ## DeBERTaV3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing
12
+
13
+ [DeBERTa](https://arxiv.org/abs/2006.03654) improves the BERT and RoBERTa models using disentangled attention and enhanced mask decoder. With those two improvements, DeBERTa out perform RoBERTa on a majority of NLU tasks with 80GB training data.
14
+
15
+ In [DeBERTa V3](https://arxiv.org/abs/2111.09543), we further improved the efficiency of DeBERTa using ELECTRA-Style pre-training with Gradient Disentangled Embedding Sharing. Compared to DeBERTa, our V3 version significantly improves the model performance on downstream tasks. You can find more technique details about the new model from our [paper](https://arxiv.org/abs/2111.09543).
16
+
17
+ Please check the [official repository](https://github.com/microsoft/DeBERTa) for more implementation details and updates.
18
+
19
+ The DeBERTa V3 large model comes with 24 layers and a hidden size of 1024. It has 304M backbone parameters with a vocabulary containing 128K tokens which introduces 131M parameters in the Embedding layer. This model was trained using the 160GB data as DeBERTa V2.
20
+
21
+
22
+ #### Fine-tuning on NLU tasks
23
+
24
+ We present the dev results on SQuAD 2.0 and MNLI tasks.
25
+
26
+ | Model |Vocabulary(K)|Backbone #Params(M)| SQuAD 2.0(F1/EM) | MNLI-m/mm(ACC)|
27
+ |-------------------|----------|-------------------|-----------|----------|
28
+ | RoBERTa-large |50 |304 | 89.4/86.5 | 90.2 |
29
+ | XLNet-large |32 |- | 90.6/87.9 | 90.8 |
30
+ | DeBERTa-large |50 |- | 90.7/88.0 | 91.3 |
31
+ | **DeBERTa-v3-large**|128|304 | **91.5/89.0**| **91.8/91.9**|
32
+
33
+
34
+ #### Fine-tuning with HF transformers
35
+
36
+ ```bash
37
+ #!/bin/bash
38
+
39
+ cd transformers/examples/pytorch/text-classification/
40
+
41
+ pip install datasets
42
+ export TASK_NAME=mnli
43
+
44
+ output_dir="ds_results"
45
+
46
+ num_gpus=8
47
+
48
+ batch_size=8
49
+
50
+ python -m torch.distributed.launch --nproc_per_node=${num_gpus} \
51
+ run_glue.py \
52
+ --model_name_or_path microsoft/deberta-v3-large \
53
+ --task_name $TASK_NAME \
54
+ --do_train \
55
+ --do_eval \
56
+ --evaluation_strategy steps \
57
+ --max_seq_length 256 \
58
+ --warmup_steps 50 \
59
+ --per_device_train_batch_size ${batch_size} \
60
+ --learning_rate 6e-6 \
61
+ --num_train_epochs 2 \
62
+ --output_dir $output_dir \
63
+ --overwrite_output_dir \
64
+ --logging_steps 1000 \
65
+ --logging_dir $output_dir
66
+
67
+ ```
68
+
69
+ ### Citation
70
+
71
+ If you find DeBERTa useful for your work, please cite the following papers:
72
+
73
+ ``` latex
74
+ @misc{he2021debertav3,
75
+ title={DeBERTaV3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing},
76
+ author={Pengcheng He and Jianfeng Gao and Weizhu Chen},
77
+ year={2021},
78
+ eprint={2111.09543},
79
+ archivePrefix={arXiv},
80
+ primaryClass={cs.CL}
81
+ }
82
+ ```
83
+
84
+ ``` latex
85
+ @inproceedings{
86
+ he2021deberta,
87
+ title={DEBERTA: DECODING-ENHANCED BERT WITH DISENTANGLED ATTENTION},
88
+ author={Pengcheng He and Xiaodong Liu and Jianfeng Gao and Weizhu Chen},
89
+ booktitle={International Conference on Learning Representations},
90
+ year={2021},
91
+ url={https://openreview.net/forum?id=XPZIaotutsD}
92
+ }
93
+ ```
bert/deberta-v3-large/config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "deberta-v2",
3
+ "attention_probs_dropout_prob": 0.1,
4
+ "hidden_act": "gelu",
5
+ "hidden_dropout_prob": 0.1,
6
+ "hidden_size": 1024,
7
+ "initializer_range": 0.02,
8
+ "intermediate_size": 4096,
9
+ "max_position_embeddings": 512,
10
+ "relative_attention": true,
11
+ "position_buckets": 256,
12
+ "norm_rel_ebd": "layer_norm",
13
+ "share_att_key": true,
14
+ "pos_att_type": "p2c|c2p",
15
+ "layer_norm_eps": 1e-7,
16
+ "max_relative_positions": -1,
17
+ "position_biased_input": false,
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 24,
20
+ "type_vocab_size": 0,
21
+ "vocab_size": 128100
22
+ }
bert/deberta-v3-large/generator_config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "deberta-v2",
3
+ "attention_probs_dropout_prob": 0.1,
4
+ "hidden_act": "gelu",
5
+ "hidden_dropout_prob": 0.1,
6
+ "hidden_size": 1024,
7
+ "initializer_range": 0.02,
8
+ "intermediate_size": 4096,
9
+ "max_position_embeddings": 512,
10
+ "relative_attention": true,
11
+ "position_buckets": 256,
12
+ "norm_rel_ebd": "layer_norm",
13
+ "share_att_key": true,
14
+ "pos_att_type": "p2c|c2p",
15
+ "layer_norm_eps": 1e-7,
16
+ "max_relative_positions": -1,
17
+ "position_biased_input": false,
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 12,
20
+ "type_vocab_size": 0,
21
+ "vocab_size": 128100
22
+ }
bert/deberta-v3-large/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dd5b5d93e2db101aaf281df0ea1216c07ad73620ff59c5b42dccac4bf2eef5b5
3
+ size 873673253
bert/deberta-v3-large/spm.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c679fbf93643d19aab7ee10c0b99e460bdbc02fedf34b92b05af343b4af586fd
3
+ size 2464616
bert/deberta-v3-large/tokenizer_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "do_lower_case": false,
3
+ "vocab_type": "spm"
4
+ }
bert_gen.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
The diff for this file is too large to render. See raw diff
 
colab.ipynb ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Style-Bert-VITS2 (ver 2.2) の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
+ "!python slice.py -i {input_dir} -o {dataset_root}/{model_name}/raw\n",
119
+ "!python transcribe.py -i {dataset_root}/{model_name}/raw -o {dataset_root}/{model_name}/esd.list --speaker_name {model_name} --compute_type float16"
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "markdown",
124
+ "metadata": {},
125
+ "source": [
126
+ "成功したらそのまま3へ進んでください"
127
+ ]
128
+ },
129
+ {
130
+ "cell_type": "markdown",
131
+ "metadata": {},
132
+ "source": [
133
+ "### 2.2 音声ファイルと書き起こしデータがすでにある場合\n",
134
+ "\n",
135
+ "指示に従って適切にデータセットを配置してください。\n",
136
+ "\n",
137
+ "次のセルを実行して、学習データをいれるフォルダ(1で設定した`dataset_root`)を作成します。"
138
+ ]
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "execution_count": 5,
143
+ "metadata": {
144
+ "id": "esCNJl704h52"
145
+ },
146
+ "outputs": [],
147
+ "source": [
148
+ "import os\n",
149
+ "\n",
150
+ "os.makedirs(dataset_root, exist_ok=True)"
151
+ ]
152
+ },
153
+ {
154
+ "cell_type": "markdown",
155
+ "metadata": {},
156
+ "source": [
157
+ "次に、学習に必要なデータを、Google driveに作成された`Style-Bert-VITS2/Data`フォルダに配置します。\n",
158
+ "\n",
159
+ "まず音声データ(wavファイルで1ファイルが2-12秒程度の、長すぎず短すぎない発話のものをいくつか)と、書き起こしテキストを用意してください。wavファイル名やモデルの名前は空白を含まない半角で、wavファイルの拡張子は小文字`.wav`である必要があります。\n",
160
+ "\n",
161
+ "書き起こしテキストは、次の形式で記述してください。\n",
162
+ "```\n",
163
+ "****.wav|{話者名}|{言語ID、ZHかJPかEN}|{書き起こしテキスト}\n",
164
+ "```\n",
165
+ "\n",
166
+ "例:\n",
167
+ "```\n",
168
+ "wav_number1.wav|hanako|JP|こんにちは、聞こえて、いますか?\n",
169
+ "wav_next.wav|taro|JP|はい、聞こえています……。\n",
170
+ "english_teacher.wav|Mary|EN|How are you? I'm fine, thank you, and you?\n",
171
+ "...\n",
172
+ "```\n",
173
+ "日本語話者の単一話者データセットで構いません。\n",
174
+ "\n",
175
+ "### データセットの配置\n",
176
+ "\n",
177
+ "次にモデルの名前を適当に決めてください(空白を含まない半角英数字がよいです)。\n",
178
+ "そして、書き起こしファイルを`esd.list`という名前で保存し、またwavファイルも`raw`というフォルダを作成し、あなたのGoogle Driveの中の(上で自動的に作られるはずの)`Data`フォルダのなかに、次のように配置します。\n",
179
+ "```\n",
180
+ "├── Data\n",
181
+ "│ ├── {モデルの名前}\n",
182
+ "│ │ ├── esd.list\n",
183
+ "│ │ ├── raw\n",
184
+ "│ │ │ ├── ****.wav\n",
185
+ "│ │ │ ├── ****.wav\n",
186
+ "│ │ │ ├── ...\n",
187
+ "```"
188
+ ]
189
+ },
190
+ {
191
+ "cell_type": "markdown",
192
+ "metadata": {
193
+ "id": "5r85-W20ECcr"
194
+ },
195
+ "source": [
196
+ "## 3. 学習の前処理\n",
197
+ "\n",
198
+ "次に学習の前処理を行います。必要なパラメータをここで指定します。次のセルに設定等を入力して実行してください。「~~かどうか」は`True`もしくは`False`を指定してください。"
199
+ ]
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "execution_count": 6,
204
+ "metadata": {
205
+ "id": "CXR7kjuF5GlE"
206
+ },
207
+ "outputs": [],
208
+ "source": [
209
+ "# 上でつけたフォルダの名前`Data/{model_name}/`\n",
210
+ "model_name = \"your_model_name\"\n",
211
+ "\n",
212
+ "# JP-Extra (日本語特化版)を使うかどうか。日本語の能力が向上する代わりに英語と中国語は使えなくなります。\n",
213
+ "use_jp_extra = True\n",
214
+ "\n",
215
+ "# 学習のバッチサイズ。VRAMのはみ出具合に応じて調整してください。\n",
216
+ "batch_size = 4\n",
217
+ "\n",
218
+ "# 学習のエポック数(データセットを合計何周するか)。\n",
219
+ "# 100ぐらいで十分かもしれませんが、もっと多くやると質が上がるのかもしれません。\n",
220
+ "epochs = 100\n",
221
+ "\n",
222
+ "# 保存頻度。何ステップごとにモデルを保存するか。分からなければデフォルトのままで。\n",
223
+ "save_every_steps = 1000\n",
224
+ "\n",
225
+ "# 音声ファイルの音量を正規化するかどうか\n",
226
+ "normalize = False\n",
227
+ "\n",
228
+ "# 音声ファイルの開始・終了にある無音区間を削除するかどうか\n",
229
+ "trim = False"
230
+ ]
231
+ },
232
+ {
233
+ "cell_type": "markdown",
234
+ "metadata": {},
235
+ "source": [
236
+ "上のセルが実行されたら、次のセルを実行して学習の前処理を行います。"
237
+ ]
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "execution_count": null,
242
+ "metadata": {
243
+ "colab": {
244
+ "base_uri": "https://localhost:8080/"
245
+ },
246
+ "id": "xMVaOIPLabV5",
247
+ "outputId": "15fac868-9132-45d9-9f5f-365b6aeb67b0"
248
+ },
249
+ "outputs": [],
250
+ "source": [
251
+ "from webui_train import preprocess_all\n",
252
+ "\n",
253
+ "preprocess_all(\n",
254
+ " model_name=model_name,\n",
255
+ " batch_size=batch_size,\n",
256
+ " epochs=epochs,\n",
257
+ " save_every_steps=save_every_steps,\n",
258
+ " num_processes=2,\n",
259
+ " normalize=normalize,\n",
260
+ " trim=trim,\n",
261
+ " freeze_EN_bert=False,\n",
262
+ " freeze_JP_bert=False,\n",
263
+ " freeze_ZH_bert=False,\n",
264
+ " freeze_style=False,\n",
265
+ " use_jp_extra=use_jp_extra,\n",
266
+ " val_per_lang=0,\n",
267
+ " log_interval=200,\n",
268
+ ")"
269
+ ]
270
+ },
271
+ {
272
+ "cell_type": "markdown",
273
+ "metadata": {},
274
+ "source": [
275
+ "## 4. 学習\n",
276
+ "\n",
277
+ "前処理が正常に終わったら、学習を行います。次のセルを実行すると学習が始まります。\n",
278
+ "\n",
279
+ "学習の結果は、上で指定した`save_every_steps`の間隔で、Google Driveの中の`Style-Bert-VITS2/Data/{モデルの名前}/model_assets/`フォルダに保存されます。\n",
280
+ "\n",
281
+ "このフォルダをダウンロードし、ローカルのStyle-Bert-VITS2の`model_assets`フォルダに上書きすれば、学習結果を使うことができます。"
282
+ ]
283
+ },
284
+ {
285
+ "cell_type": "code",
286
+ "execution_count": null,
287
+ "metadata": {
288
+ "colab": {
289
+ "base_uri": "https://localhost:8080/"
290
+ },
291
+ "id": "laieKrbEb6Ij",
292
+ "outputId": "72238c88-f294-4ed9-84f6-84c1c17999ca"
293
+ },
294
+ "outputs": [],
295
+ "source": [
296
+ "# 上でつけたモデル名を入力。学習を途中からする場合はきちんとモデルが保存されているフォルダ名を入力。\n",
297
+ "model_name = \"your_model_name\"\n",
298
+ "\n",
299
+ "\n",
300
+ "import yaml\n",
301
+ "from webui_train import get_path\n",
302
+ "\n",
303
+ "dataset_path, _, _, _, config_path = get_path(model_name)\n",
304
+ "\n",
305
+ "with open(\"default_config.yml\", \"r\", encoding=\"utf-8\") as f:\n",
306
+ " yml_data = yaml.safe_load(f)\n",
307
+ "yml_data[\"model_name\"] = model_name\n",
308
+ "with open(\"config.yml\", \"w\", encoding=\"utf-8\") as f:\n",
309
+ " yaml.dump(yml_data, f, allow_unicode=True)"
310
+ ]
311
+ },
312
+ {
313
+ "cell_type": "code",
314
+ "execution_count": null,
315
+ "metadata": {},
316
+ "outputs": [],
317
+ "source": [
318
+ "# 日本語特化版を「使う」場合\n",
319
+ "!python train_ms_jp_extra.py --config {config_path} --model {dataset_path} --assets_root {assets_root}"
320
+ ]
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "execution_count": null,
325
+ "metadata": {},
326
+ "outputs": [],
327
+ "source": [
328
+ "# 日本語特化版を「使わない」場合\n",
329
+ "!python train_ms.py --config {config_path} --model {dataset_path} --assets_root {assets_root}"
330
+ ]
331
+ },
332
+ {
333
+ "cell_type": "code",
334
+ "execution_count": null,
335
+ "metadata": {
336
+ "colab": {
337
+ "base_uri": "https://localhost:8080/"
338
+ },
339
+ "id": "c7g0hrdeP1Tl",
340
+ "outputId": "94f9a6f6-027f-4554-ce0c-60ac56251c22"
341
+ },
342
+ "outputs": [],
343
+ "source": [
344
+ "#@title 学習結果を試すならここから\n",
345
+ "!python app.py --share --dir {assets_root}"
346
+ ]
347
+ },
348
+ {
349
+ "cell_type": "markdown",
350
+ "metadata": {},
351
+ "source": [
352
+ "## 5. スタイル分け"
353
+ ]
354
+ },
355
+ {
356
+ "cell_type": "code",
357
+ "execution_count": null,
358
+ "metadata": {},
359
+ "outputs": [],
360
+ "source": [
361
+ "!python webui_style_vectors.py --share"
362
+ ]
363
+ },
364
+ {
365
+ "cell_type": "markdown",
366
+ "metadata": {},
367
+ "source": [
368
+ "## 6. マージ"
369
+ ]
370
+ },
371
+ {
372
+ "cell_type": "code",
373
+ "execution_count": null,
374
+ "metadata": {},
375
+ "outputs": [],
376
+ "source": [
377
+ "!python webui_merge.py --share"
378
+ ]
379
+ }
380
+ ],
381
+ "metadata": {
382
+ "accelerator": "GPU",
383
+ "colab": {
384
+ "gpuType": "T4",
385
+ "provenance": []
386
+ },
387
+ "kernelspec": {
388
+ "display_name": "Python 3",
389
+ "name": "python3"
390
+ },
391
+ "language_info": {
392
+ "codemirror_mode": {
393
+ "name": "ipython",
394
+ "version": 3
395
+ },
396
+ "file_extension": ".py",
397
+ "mimetype": "text/x-python",
398
+ "name": "python",
399
+ "nbconvert_exporter": "python",
400
+ "pygments_lexer": "ipython3",
401
+ "version": "3.10.11"
402
+ }
403
+ },
404
+ "nbformat": 4,
405
+ "nbformat_minor": 0
406
+ }
common/__pycache__/constants.cpython-310.pyc ADDED
Binary file (935 Bytes). View file
 
common/__pycache__/log.cpython-310.pyc ADDED
Binary file (444 Bytes). View file
 
common/__pycache__/stdout_wrapper.cpython-310.pyc ADDED
Binary file (1.54 kB). View file
 
common/__pycache__/tts_model.cpython-310.pyc ADDED
Binary file (7.63 kB). View file