Snow-White-995
commited on
Commit
•
b2458f3
1
Parent(s):
0bf0aa4
Upload 13 files
Browse files- LICENSE +661 -0
- app.py +160 -0
- attentions.py +464 -0
- commons.py +166 -0
- infer.py +166 -0
- mel_processing.py +139 -0
- models.py +1002 -0
- modules.py +597 -0
- requirements.txt +35 -0
- server.py +120 -0
- server_fastapi.py +499 -0
- transforms.py +209 -0
- utils.py +357 -0
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/>.
|
app.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import re
|
3 |
+
|
4 |
+
import gradio as gr
|
5 |
+
import numpy
|
6 |
+
import torch
|
7 |
+
|
8 |
+
import utils
|
9 |
+
from infer import infer, get_net_g
|
10 |
+
|
11 |
+
logging.getLogger("numba").setLevel(logging.WARNING)
|
12 |
+
logging.getLogger("markdown_it").setLevel(logging.WARNING)
|
13 |
+
logging.getLogger("urllib3").setLevel(logging.WARNING)
|
14 |
+
logging.getLogger("matplotlib").setLevel(logging.WARNING)
|
15 |
+
|
16 |
+
logging.basicConfig(level=logging.INFO, format="| %(name)s | %(levelname)s | %(message)s")
|
17 |
+
|
18 |
+
logger = logging.getLogger(__name__)
|
19 |
+
|
20 |
+
net_g = None
|
21 |
+
hps = None
|
22 |
+
|
23 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
24 |
+
model_path = "models/G_1000.pth"
|
25 |
+
sampling_rate = 22050
|
26 |
+
|
27 |
+
|
28 |
+
def split_sentence(sentence: str):
|
29 |
+
if len(sentence) == 0:
|
30 |
+
return []
|
31 |
+
|
32 |
+
result = []
|
33 |
+
|
34 |
+
is_english = [i.isascii() for i in sentence]
|
35 |
+
is_chinese = [not re.match(r"[a-zA-Z]", i) for i in sentence]
|
36 |
+
|
37 |
+
assert len(is_english) == len(is_chinese) == len(sentence), "bad length"
|
38 |
+
assert is_english[0] or is_chinese[0], "bad first char: " + sentence[0]
|
39 |
+
|
40 |
+
current_language = ''
|
41 |
+
current_chain = []
|
42 |
+
for idx in range(len(sentence)):
|
43 |
+
if not is_english[idx]:
|
44 |
+
current_language = 'ZH'
|
45 |
+
current_chain = is_chinese
|
46 |
+
break
|
47 |
+
if not is_chinese[idx]:
|
48 |
+
current_language = 'EN'
|
49 |
+
current_chain = is_english
|
50 |
+
break
|
51 |
+
pass
|
52 |
+
|
53 |
+
step = 0
|
54 |
+
while step < len(sentence):
|
55 |
+
try:
|
56 |
+
next_step = current_chain.index(False, step)
|
57 |
+
except ValueError:
|
58 |
+
next_step = len(sentence)
|
59 |
+
result.append((sentence[step:next_step], current_language))
|
60 |
+
step = next_step
|
61 |
+
current_language = 'ZH' if current_language == 'EN' else 'EN'
|
62 |
+
current_chain = is_chinese if current_language == 'ZH' else is_english
|
63 |
+
pass
|
64 |
+
|
65 |
+
return result
|
66 |
+
|
67 |
+
|
68 |
+
def tts_fn(
|
69 |
+
text: str,
|
70 |
+
speaker,
|
71 |
+
sdp_ratio,
|
72 |
+
noise_scale,
|
73 |
+
noise_scale_w,
|
74 |
+
length_scale,
|
75 |
+
language,
|
76 |
+
):
|
77 |
+
language = 'ZH' if language == '普通话' else 'SH'
|
78 |
+
sentences = split_sentence(text)
|
79 |
+
|
80 |
+
silence = numpy.zeros(sampling_rate // 2, dtype=numpy.int16)
|
81 |
+
audio_data = numpy.array([], dtype=numpy.float32)
|
82 |
+
for (sentence, sentence_language) in sentences:
|
83 |
+
sub_audio_data = infer(
|
84 |
+
sentence,
|
85 |
+
sdp_ratio,
|
86 |
+
noise_scale,
|
87 |
+
noise_scale_w,
|
88 |
+
length_scale,
|
89 |
+
sid=speaker,
|
90 |
+
language=language if sentence_language == "ZH" else sentence_language,
|
91 |
+
hps=hps,
|
92 |
+
net_g=net_g,
|
93 |
+
device=device)
|
94 |
+
audio_data = numpy.concatenate((audio_data, sub_audio_data, silence))
|
95 |
+
|
96 |
+
audio_data = audio_data / numpy.abs(audio_data).max()
|
97 |
+
audio_data = audio_data * 32767
|
98 |
+
audio_data = audio_data.astype(numpy.int16)
|
99 |
+
|
100 |
+
return "Success", (sampling_rate, audio_data)
|
101 |
+
|
102 |
+
|
103 |
+
def main():
|
104 |
+
logging.basicConfig(level=logging.DEBUG)
|
105 |
+
|
106 |
+
global hps
|
107 |
+
hps = utils.get_hparams_from_file("configs/config.json")
|
108 |
+
|
109 |
+
global net_g
|
110 |
+
net_g = get_net_g(model_path=model_path, device=device, hps=hps)
|
111 |
+
|
112 |
+
speaker_ids = hps.data.spk2id
|
113 |
+
speakers = list(speaker_ids.keys())
|
114 |
+
languages = ["普通话", "上海话"]
|
115 |
+
with gr.Blocks() as app:
|
116 |
+
with gr.Row():
|
117 |
+
with gr.Column():
|
118 |
+
text = gr.TextArea(
|
119 |
+
label="输入文本内容",
|
120 |
+
value="\n".join([
|
121 |
+
"站一个制高点看上海,",
|
122 |
+
"Looking at Shanghai from a commanding height,",
|
123 |
+
"上海的弄堂是壮观的景象。",
|
124 |
+
"The alleys in Shanghai are a great sight.",
|
125 |
+
"它是这城市背景一样的东西。",
|
126 |
+
"It is something with the same background as this city."
|
127 |
+
]),
|
128 |
+
)
|
129 |
+
sdp_ratio = gr.Slider(minimum=0, maximum=1, value=0.2, step=0.1, label="SDP/DP混合比")
|
130 |
+
noise_scale = gr.Slider(minimum=0.1, maximum=2, value=0.6, step=0.1, label="感情")
|
131 |
+
noise_scale_w = gr.Slider(minimum=0.1, maximum=2, value=0.8, step=0.1, label="音素长度")
|
132 |
+
length_scale = gr.Slider(minimum=0.1, maximum=2, value=1.0, step=0.1, label="语速")
|
133 |
+
with gr.Column():
|
134 |
+
with gr.Row():
|
135 |
+
with gr.Column():
|
136 |
+
speaker = gr.Dropdown(choices=speakers, value=speakers[0], label="选择说话人")
|
137 |
+
with gr.Column():
|
138 |
+
language = gr.Dropdown(choices=languages, value=languages[0], label="选择语言")
|
139 |
+
submit_btn = gr.Button("生成音频", variant="primary")
|
140 |
+
text_output = gr.Textbox(label="状态")
|
141 |
+
audio_output = gr.Audio(label="音频")
|
142 |
+
submit_btn.click(
|
143 |
+
tts_fn,
|
144 |
+
inputs=[
|
145 |
+
text,
|
146 |
+
speaker,
|
147 |
+
sdp_ratio,
|
148 |
+
noise_scale,
|
149 |
+
noise_scale_w,
|
150 |
+
length_scale,
|
151 |
+
language,
|
152 |
+
],
|
153 |
+
outputs=[text_output, audio_output],
|
154 |
+
)
|
155 |
+
|
156 |
+
app.launch(share=False, server_name="0.0.0.0", server_port=7860)
|
157 |
+
|
158 |
+
|
159 |
+
if __name__ == "__main__":
|
160 |
+
main()
|
attentions.py
ADDED
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import torch
|
3 |
+
from torch import nn
|
4 |
+
from torch.nn import functional as F
|
5 |
+
|
6 |
+
import commons
|
7 |
+
import logging
|
8 |
+
|
9 |
+
logger = logging.getLogger(__name__)
|
10 |
+
|
11 |
+
|
12 |
+
class LayerNorm(nn.Module):
|
13 |
+
def __init__(self, channels, eps=1e-5):
|
14 |
+
super().__init__()
|
15 |
+
self.channels = channels
|
16 |
+
self.eps = eps
|
17 |
+
|
18 |
+
self.gamma = nn.Parameter(torch.ones(channels))
|
19 |
+
self.beta = nn.Parameter(torch.zeros(channels))
|
20 |
+
|
21 |
+
def forward(self, x):
|
22 |
+
x = x.transpose(1, -1)
|
23 |
+
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
24 |
+
return x.transpose(1, -1)
|
25 |
+
|
26 |
+
|
27 |
+
@torch.jit.script
|
28 |
+
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
29 |
+
n_channels_int = n_channels[0]
|
30 |
+
in_act = input_a + input_b
|
31 |
+
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
32 |
+
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
33 |
+
acts = t_act * s_act
|
34 |
+
return acts
|
35 |
+
|
36 |
+
|
37 |
+
class Encoder(nn.Module):
|
38 |
+
def __init__(
|
39 |
+
self,
|
40 |
+
hidden_channels,
|
41 |
+
filter_channels,
|
42 |
+
n_heads,
|
43 |
+
n_layers,
|
44 |
+
kernel_size=1,
|
45 |
+
p_dropout=0.0,
|
46 |
+
window_size=4,
|
47 |
+
isflow=True,
|
48 |
+
**kwargs
|
49 |
+
):
|
50 |
+
super().__init__()
|
51 |
+
self.hidden_channels = hidden_channels
|
52 |
+
self.filter_channels = filter_channels
|
53 |
+
self.n_heads = n_heads
|
54 |
+
self.n_layers = n_layers
|
55 |
+
self.kernel_size = kernel_size
|
56 |
+
self.p_dropout = p_dropout
|
57 |
+
self.window_size = window_size
|
58 |
+
# if isflow:
|
59 |
+
# cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
|
60 |
+
# self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
|
61 |
+
# self.cond_layer = weight_norm(cond_layer, name='weight')
|
62 |
+
# self.gin_channels = 256
|
63 |
+
self.cond_layer_idx = self.n_layers
|
64 |
+
if "gin_channels" in kwargs:
|
65 |
+
self.gin_channels = kwargs["gin_channels"]
|
66 |
+
if self.gin_channels != 0:
|
67 |
+
self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
|
68 |
+
# vits2 says 3rd block, so idx is 2 by default
|
69 |
+
self.cond_layer_idx = (
|
70 |
+
kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
|
71 |
+
)
|
72 |
+
logging.debug(self.gin_channels, self.cond_layer_idx)
|
73 |
+
assert (
|
74 |
+
self.cond_layer_idx < self.n_layers
|
75 |
+
), "cond_layer_idx should be less than n_layers"
|
76 |
+
self.drop = nn.Dropout(p_dropout)
|
77 |
+
self.attn_layers = nn.ModuleList()
|
78 |
+
self.norm_layers_1 = nn.ModuleList()
|
79 |
+
self.ffn_layers = nn.ModuleList()
|
80 |
+
self.norm_layers_2 = nn.ModuleList()
|
81 |
+
for i in range(self.n_layers):
|
82 |
+
self.attn_layers.append(
|
83 |
+
MultiHeadAttention(
|
84 |
+
hidden_channels,
|
85 |
+
hidden_channels,
|
86 |
+
n_heads,
|
87 |
+
p_dropout=p_dropout,
|
88 |
+
window_size=window_size,
|
89 |
+
)
|
90 |
+
)
|
91 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
92 |
+
self.ffn_layers.append(
|
93 |
+
FFN(
|
94 |
+
hidden_channels,
|
95 |
+
hidden_channels,
|
96 |
+
filter_channels,
|
97 |
+
kernel_size,
|
98 |
+
p_dropout=p_dropout,
|
99 |
+
)
|
100 |
+
)
|
101 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
102 |
+
|
103 |
+
def forward(self, x, x_mask, g=None):
|
104 |
+
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
105 |
+
x = x * x_mask
|
106 |
+
for i in range(self.n_layers):
|
107 |
+
if i == self.cond_layer_idx and g is not None:
|
108 |
+
g = self.spk_emb_linear(g.transpose(1, 2))
|
109 |
+
g = g.transpose(1, 2)
|
110 |
+
x = x + g
|
111 |
+
x = x * x_mask
|
112 |
+
y = self.attn_layers[i](x, x, attn_mask)
|
113 |
+
y = self.drop(y)
|
114 |
+
x = self.norm_layers_1[i](x + y)
|
115 |
+
|
116 |
+
y = self.ffn_layers[i](x, x_mask)
|
117 |
+
y = self.drop(y)
|
118 |
+
x = self.norm_layers_2[i](x + y)
|
119 |
+
x = x * x_mask
|
120 |
+
return x
|
121 |
+
|
122 |
+
|
123 |
+
class Decoder(nn.Module):
|
124 |
+
def __init__(
|
125 |
+
self,
|
126 |
+
hidden_channels,
|
127 |
+
filter_channels,
|
128 |
+
n_heads,
|
129 |
+
n_layers,
|
130 |
+
kernel_size=1,
|
131 |
+
p_dropout=0.0,
|
132 |
+
proximal_bias=False,
|
133 |
+
proximal_init=True,
|
134 |
+
**kwargs
|
135 |
+
):
|
136 |
+
super().__init__()
|
137 |
+
self.hidden_channels = hidden_channels
|
138 |
+
self.filter_channels = filter_channels
|
139 |
+
self.n_heads = n_heads
|
140 |
+
self.n_layers = n_layers
|
141 |
+
self.kernel_size = kernel_size
|
142 |
+
self.p_dropout = p_dropout
|
143 |
+
self.proximal_bias = proximal_bias
|
144 |
+
self.proximal_init = proximal_init
|
145 |
+
|
146 |
+
self.drop = nn.Dropout(p_dropout)
|
147 |
+
self.self_attn_layers = nn.ModuleList()
|
148 |
+
self.norm_layers_0 = nn.ModuleList()
|
149 |
+
self.encdec_attn_layers = nn.ModuleList()
|
150 |
+
self.norm_layers_1 = nn.ModuleList()
|
151 |
+
self.ffn_layers = nn.ModuleList()
|
152 |
+
self.norm_layers_2 = nn.ModuleList()
|
153 |
+
for i in range(self.n_layers):
|
154 |
+
self.self_attn_layers.append(
|
155 |
+
MultiHeadAttention(
|
156 |
+
hidden_channels,
|
157 |
+
hidden_channels,
|
158 |
+
n_heads,
|
159 |
+
p_dropout=p_dropout,
|
160 |
+
proximal_bias=proximal_bias,
|
161 |
+
proximal_init=proximal_init,
|
162 |
+
)
|
163 |
+
)
|
164 |
+
self.norm_layers_0.append(LayerNorm(hidden_channels))
|
165 |
+
self.encdec_attn_layers.append(
|
166 |
+
MultiHeadAttention(
|
167 |
+
hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
|
168 |
+
)
|
169 |
+
)
|
170 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
171 |
+
self.ffn_layers.append(
|
172 |
+
FFN(
|
173 |
+
hidden_channels,
|
174 |
+
hidden_channels,
|
175 |
+
filter_channels,
|
176 |
+
kernel_size,
|
177 |
+
p_dropout=p_dropout,
|
178 |
+
causal=True,
|
179 |
+
)
|
180 |
+
)
|
181 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
182 |
+
|
183 |
+
def forward(self, x, x_mask, h, h_mask):
|
184 |
+
"""
|
185 |
+
x: decoder input
|
186 |
+
h: encoder output
|
187 |
+
"""
|
188 |
+
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
|
189 |
+
device=x.device, dtype=x.dtype
|
190 |
+
)
|
191 |
+
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
192 |
+
x = x * x_mask
|
193 |
+
for i in range(self.n_layers):
|
194 |
+
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
195 |
+
y = self.drop(y)
|
196 |
+
x = self.norm_layers_0[i](x + y)
|
197 |
+
|
198 |
+
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
|
199 |
+
y = self.drop(y)
|
200 |
+
x = self.norm_layers_1[i](x + y)
|
201 |
+
|
202 |
+
y = self.ffn_layers[i](x, x_mask)
|
203 |
+
y = self.drop(y)
|
204 |
+
x = self.norm_layers_2[i](x + y)
|
205 |
+
x = x * x_mask
|
206 |
+
return x
|
207 |
+
|
208 |
+
|
209 |
+
class MultiHeadAttention(nn.Module):
|
210 |
+
def __init__(
|
211 |
+
self,
|
212 |
+
channels,
|
213 |
+
out_channels,
|
214 |
+
n_heads,
|
215 |
+
p_dropout=0.0,
|
216 |
+
window_size=None,
|
217 |
+
heads_share=True,
|
218 |
+
block_length=None,
|
219 |
+
proximal_bias=False,
|
220 |
+
proximal_init=False,
|
221 |
+
):
|
222 |
+
super().__init__()
|
223 |
+
assert channels % n_heads == 0
|
224 |
+
|
225 |
+
self.channels = channels
|
226 |
+
self.out_channels = out_channels
|
227 |
+
self.n_heads = n_heads
|
228 |
+
self.p_dropout = p_dropout
|
229 |
+
self.window_size = window_size
|
230 |
+
self.heads_share = heads_share
|
231 |
+
self.block_length = block_length
|
232 |
+
self.proximal_bias = proximal_bias
|
233 |
+
self.proximal_init = proximal_init
|
234 |
+
self.attn = None
|
235 |
+
|
236 |
+
self.k_channels = channels // n_heads
|
237 |
+
self.conv_q = nn.Conv1d(channels, channels, 1)
|
238 |
+
self.conv_k = nn.Conv1d(channels, channels, 1)
|
239 |
+
self.conv_v = nn.Conv1d(channels, channels, 1)
|
240 |
+
self.conv_o = nn.Conv1d(channels, out_channels, 1)
|
241 |
+
self.drop = nn.Dropout(p_dropout)
|
242 |
+
|
243 |
+
if window_size is not None:
|
244 |
+
n_heads_rel = 1 if heads_share else n_heads
|
245 |
+
rel_stddev = self.k_channels**-0.5
|
246 |
+
self.emb_rel_k = nn.Parameter(
|
247 |
+
torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
|
248 |
+
* rel_stddev
|
249 |
+
)
|
250 |
+
self.emb_rel_v = nn.Parameter(
|
251 |
+
torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
|
252 |
+
* rel_stddev
|
253 |
+
)
|
254 |
+
|
255 |
+
nn.init.xavier_uniform_(self.conv_q.weight)
|
256 |
+
nn.init.xavier_uniform_(self.conv_k.weight)
|
257 |
+
nn.init.xavier_uniform_(self.conv_v.weight)
|
258 |
+
if proximal_init:
|
259 |
+
with torch.no_grad():
|
260 |
+
self.conv_k.weight.copy_(self.conv_q.weight)
|
261 |
+
self.conv_k.bias.copy_(self.conv_q.bias)
|
262 |
+
|
263 |
+
def forward(self, x, c, attn_mask=None):
|
264 |
+
q = self.conv_q(x)
|
265 |
+
k = self.conv_k(c)
|
266 |
+
v = self.conv_v(c)
|
267 |
+
|
268 |
+
x, self.attn = self.attention(q, k, v, mask=attn_mask)
|
269 |
+
|
270 |
+
x = self.conv_o(x)
|
271 |
+
return x
|
272 |
+
|
273 |
+
def attention(self, query, key, value, mask=None):
|
274 |
+
# reshape [b, d, t] -> [b, n_h, t, d_k]
|
275 |
+
b, d, t_s, t_t = (*key.size(), query.size(2))
|
276 |
+
query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
|
277 |
+
key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
278 |
+
value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
279 |
+
|
280 |
+
scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
|
281 |
+
if self.window_size is not None:
|
282 |
+
assert (
|
283 |
+
t_s == t_t
|
284 |
+
), "Relative attention is only available for self-attention."
|
285 |
+
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
|
286 |
+
rel_logits = self._matmul_with_relative_keys(
|
287 |
+
query / math.sqrt(self.k_channels), key_relative_embeddings
|
288 |
+
)
|
289 |
+
scores_local = self._relative_position_to_absolute_position(rel_logits)
|
290 |
+
scores = scores + scores_local
|
291 |
+
if self.proximal_bias:
|
292 |
+
assert t_s == t_t, "Proximal bias is only available for self-attention."
|
293 |
+
scores = scores + self._attention_bias_proximal(t_s).to(
|
294 |
+
device=scores.device, dtype=scores.dtype
|
295 |
+
)
|
296 |
+
if mask is not None:
|
297 |
+
scores = scores.masked_fill(mask == 0, -1e4)
|
298 |
+
if self.block_length is not None:
|
299 |
+
assert (
|
300 |
+
t_s == t_t
|
301 |
+
), "Local attention is only available for self-attention."
|
302 |
+
block_mask = (
|
303 |
+
torch.ones_like(scores)
|
304 |
+
.triu(-self.block_length)
|
305 |
+
.tril(self.block_length)
|
306 |
+
)
|
307 |
+
scores = scores.masked_fill(block_mask == 0, -1e4)
|
308 |
+
p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
|
309 |
+
p_attn = self.drop(p_attn)
|
310 |
+
output = torch.matmul(p_attn, value)
|
311 |
+
if self.window_size is not None:
|
312 |
+
relative_weights = self._absolute_position_to_relative_position(p_attn)
|
313 |
+
value_relative_embeddings = self._get_relative_embeddings(
|
314 |
+
self.emb_rel_v, t_s
|
315 |
+
)
|
316 |
+
output = output + self._matmul_with_relative_values(
|
317 |
+
relative_weights, value_relative_embeddings
|
318 |
+
)
|
319 |
+
output = (
|
320 |
+
output.transpose(2, 3).contiguous().view(b, d, t_t)
|
321 |
+
) # [b, n_h, t_t, d_k] -> [b, d, t_t]
|
322 |
+
return output, p_attn
|
323 |
+
|
324 |
+
def _matmul_with_relative_values(self, x, y):
|
325 |
+
"""
|
326 |
+
x: [b, h, l, m]
|
327 |
+
y: [h or 1, m, d]
|
328 |
+
ret: [b, h, l, d]
|
329 |
+
"""
|
330 |
+
ret = torch.matmul(x, y.unsqueeze(0))
|
331 |
+
return ret
|
332 |
+
|
333 |
+
def _matmul_with_relative_keys(self, x, y):
|
334 |
+
"""
|
335 |
+
x: [b, h, l, d]
|
336 |
+
y: [h or 1, m, d]
|
337 |
+
ret: [b, h, l, m]
|
338 |
+
"""
|
339 |
+
ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
|
340 |
+
return ret
|
341 |
+
|
342 |
+
def _get_relative_embeddings(self, relative_embeddings, length):
|
343 |
+
2 * self.window_size + 1
|
344 |
+
# Pad first before slice to avoid using cond ops.
|
345 |
+
pad_length = max(length - (self.window_size + 1), 0)
|
346 |
+
slice_start_position = max((self.window_size + 1) - length, 0)
|
347 |
+
slice_end_position = slice_start_position + 2 * length - 1
|
348 |
+
if pad_length > 0:
|
349 |
+
padded_relative_embeddings = F.pad(
|
350 |
+
relative_embeddings,
|
351 |
+
commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
|
352 |
+
)
|
353 |
+
else:
|
354 |
+
padded_relative_embeddings = relative_embeddings
|
355 |
+
used_relative_embeddings = padded_relative_embeddings[
|
356 |
+
:, slice_start_position:slice_end_position
|
357 |
+
]
|
358 |
+
return used_relative_embeddings
|
359 |
+
|
360 |
+
def _relative_position_to_absolute_position(self, x):
|
361 |
+
"""
|
362 |
+
x: [b, h, l, 2*l-1]
|
363 |
+
ret: [b, h, l, l]
|
364 |
+
"""
|
365 |
+
batch, heads, length, _ = x.size()
|
366 |
+
# Concat columns of pad to shift from relative to absolute indexing.
|
367 |
+
x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
|
368 |
+
|
369 |
+
# Concat extra elements so to add up to shape (len+1, 2*len-1).
|
370 |
+
x_flat = x.view([batch, heads, length * 2 * length])
|
371 |
+
x_flat = F.pad(
|
372 |
+
x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
|
373 |
+
)
|
374 |
+
|
375 |
+
# Reshape and slice out the padded elements.
|
376 |
+
x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
|
377 |
+
:, :, :length, length - 1 :
|
378 |
+
]
|
379 |
+
return x_final
|
380 |
+
|
381 |
+
def _absolute_position_to_relative_position(self, x):
|
382 |
+
"""
|
383 |
+
x: [b, h, l, l]
|
384 |
+
ret: [b, h, l, 2*l-1]
|
385 |
+
"""
|
386 |
+
batch, heads, length, _ = x.size()
|
387 |
+
# pad along column
|
388 |
+
x = F.pad(
|
389 |
+
x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
|
390 |
+
)
|
391 |
+
x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
|
392 |
+
# add 0's in the beginning that will skew the elements after reshape
|
393 |
+
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
|
394 |
+
x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
|
395 |
+
return x_final
|
396 |
+
|
397 |
+
def _attention_bias_proximal(self, length):
|
398 |
+
"""Bias for self-attention to encourage attention to close positions.
|
399 |
+
Args:
|
400 |
+
length: an integer scalar.
|
401 |
+
Returns:
|
402 |
+
a Tensor with shape [1, 1, length, length]
|
403 |
+
"""
|
404 |
+
r = torch.arange(length, dtype=torch.float32)
|
405 |
+
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
|
406 |
+
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
|
407 |
+
|
408 |
+
|
409 |
+
class FFN(nn.Module):
|
410 |
+
def __init__(
|
411 |
+
self,
|
412 |
+
in_channels,
|
413 |
+
out_channels,
|
414 |
+
filter_channels,
|
415 |
+
kernel_size,
|
416 |
+
p_dropout=0.0,
|
417 |
+
activation=None,
|
418 |
+
causal=False,
|
419 |
+
):
|
420 |
+
super().__init__()
|
421 |
+
self.in_channels = in_channels
|
422 |
+
self.out_channels = out_channels
|
423 |
+
self.filter_channels = filter_channels
|
424 |
+
self.kernel_size = kernel_size
|
425 |
+
self.p_dropout = p_dropout
|
426 |
+
self.activation = activation
|
427 |
+
self.causal = causal
|
428 |
+
|
429 |
+
if causal:
|
430 |
+
self.padding = self._causal_padding
|
431 |
+
else:
|
432 |
+
self.padding = self._same_padding
|
433 |
+
|
434 |
+
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
|
435 |
+
self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
|
436 |
+
self.drop = nn.Dropout(p_dropout)
|
437 |
+
|
438 |
+
def forward(self, x, x_mask):
|
439 |
+
x = self.conv_1(self.padding(x * x_mask))
|
440 |
+
if self.activation == "gelu":
|
441 |
+
x = x * torch.sigmoid(1.702 * x)
|
442 |
+
else:
|
443 |
+
x = torch.relu(x)
|
444 |
+
x = self.drop(x)
|
445 |
+
x = self.conv_2(self.padding(x * x_mask))
|
446 |
+
return x * x_mask
|
447 |
+
|
448 |
+
def _causal_padding(self, x):
|
449 |
+
if self.kernel_size == 1:
|
450 |
+
return x
|
451 |
+
pad_l = self.kernel_size - 1
|
452 |
+
pad_r = 0
|
453 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
454 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
455 |
+
return x
|
456 |
+
|
457 |
+
def _same_padding(self, x):
|
458 |
+
if self.kernel_size == 1:
|
459 |
+
return x
|
460 |
+
pad_l = (self.kernel_size - 1) // 2
|
461 |
+
pad_r = self.kernel_size // 2
|
462 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
463 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
464 |
+
return x
|
commons.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import torch
|
3 |
+
from torch.nn import functional as F
|
4 |
+
|
5 |
+
|
6 |
+
def init_weights(m, mean=0.0, std=0.01):
|
7 |
+
classname = m.__class__.__name__
|
8 |
+
if classname.find("Conv") != -1:
|
9 |
+
m.weight.data.normal_(mean, std)
|
10 |
+
|
11 |
+
|
12 |
+
def get_padding(kernel_size, dilation=1):
|
13 |
+
return int((kernel_size * dilation - dilation) / 2)
|
14 |
+
|
15 |
+
|
16 |
+
def convert_pad_shape(pad_shape):
|
17 |
+
layer = pad_shape[::-1]
|
18 |
+
pad_shape = [item for sublist in layer for item in sublist]
|
19 |
+
return pad_shape
|
20 |
+
|
21 |
+
|
22 |
+
def intersperse(lst, item):
|
23 |
+
result = [item] * (len(lst) * 2 + 1)
|
24 |
+
result[1::2] = lst
|
25 |
+
return result
|
26 |
+
|
27 |
+
|
28 |
+
def kl_divergence(m_p, logs_p, m_q, logs_q):
|
29 |
+
"""KL(P||Q)"""
|
30 |
+
kl = (logs_q - logs_p) - 0.5
|
31 |
+
kl += (
|
32 |
+
0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
|
33 |
+
)
|
34 |
+
return kl
|
35 |
+
|
36 |
+
|
37 |
+
def rand_gumbel(shape):
|
38 |
+
"""Sample from the Gumbel distribution, protect from overflows."""
|
39 |
+
uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
|
40 |
+
return -torch.log(-torch.log(uniform_samples))
|
41 |
+
|
42 |
+
|
43 |
+
def rand_gumbel_like(x):
|
44 |
+
g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
|
45 |
+
return g
|
46 |
+
|
47 |
+
|
48 |
+
def slice_segments(x, ids_str, segment_size=4):
|
49 |
+
ret = torch.zeros_like(x[:, :, :segment_size])
|
50 |
+
for i in range(x.size(0)):
|
51 |
+
idx_str = ids_str[i]
|
52 |
+
idx_end = idx_str + segment_size
|
53 |
+
if idx_str < 0:
|
54 |
+
i1 = x.size(2) + idx_str
|
55 |
+
r1 = x[i, :, i1:]
|
56 |
+
r2 = x[i, :, :idx_end]
|
57 |
+
ret[i] = torch.cat([r1, r2], dim=1)
|
58 |
+
else:
|
59 |
+
ret[i] = x[i, :, idx_str:idx_end]
|
60 |
+
return ret
|
61 |
+
|
62 |
+
|
63 |
+
def rand_slice_segments(x, x_lengths=None, segment_size=4):
|
64 |
+
b, d, t = x.size()
|
65 |
+
if x_lengths is None:
|
66 |
+
x_lengths = t
|
67 |
+
ids_str_max = x_lengths - segment_size + 1
|
68 |
+
ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
|
69 |
+
ret = slice_segments(x, ids_str, segment_size)
|
70 |
+
return ret, ids_str
|
71 |
+
|
72 |
+
|
73 |
+
def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
|
74 |
+
position = torch.arange(length, dtype=torch.float)
|
75 |
+
num_timescales = channels // 2
|
76 |
+
log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (
|
77 |
+
num_timescales - 1
|
78 |
+
)
|
79 |
+
inv_timescales = min_timescale * torch.exp(
|
80 |
+
torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
|
81 |
+
)
|
82 |
+
scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
|
83 |
+
signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
|
84 |
+
signal = F.pad(signal, [0, 0, 0, channels % 2])
|
85 |
+
signal = signal.view(1, channels, length)
|
86 |
+
return signal
|
87 |
+
|
88 |
+
|
89 |
+
def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
|
90 |
+
b, channels, length = x.size()
|
91 |
+
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
|
92 |
+
return x + signal.to(dtype=x.dtype, device=x.device)
|
93 |
+
|
94 |
+
|
95 |
+
def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
|
96 |
+
b, channels, length = x.size()
|
97 |
+
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
|
98 |
+
return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
|
99 |
+
|
100 |
+
|
101 |
+
def subsequent_mask(length):
|
102 |
+
mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
|
103 |
+
return mask
|
104 |
+
|
105 |
+
|
106 |
+
@torch.jit.script
|
107 |
+
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
108 |
+
n_channels_int = n_channels[0]
|
109 |
+
in_act = input_a + input_b
|
110 |
+
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
111 |
+
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
112 |
+
acts = t_act * s_act
|
113 |
+
return acts
|
114 |
+
|
115 |
+
|
116 |
+
def convert_pad_shape(pad_shape):
|
117 |
+
layer = pad_shape[::-1]
|
118 |
+
pad_shape = [item for sublist in layer for item in sublist]
|
119 |
+
return pad_shape
|
120 |
+
|
121 |
+
|
122 |
+
def shift_1d(x):
|
123 |
+
x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
|
124 |
+
return x
|
125 |
+
|
126 |
+
|
127 |
+
def sequence_mask(length, max_length=None):
|
128 |
+
if max_length is None:
|
129 |
+
max_length = length.max()
|
130 |
+
x = torch.arange(max_length, dtype=length.dtype, device=length.device)
|
131 |
+
return x.unsqueeze(0) < length.unsqueeze(1)
|
132 |
+
|
133 |
+
|
134 |
+
def generate_path(duration, mask):
|
135 |
+
"""
|
136 |
+
duration: [b, 1, t_x]
|
137 |
+
mask: [b, 1, t_y, t_x]
|
138 |
+
"""
|
139 |
+
|
140 |
+
b, _, t_y, t_x = mask.shape
|
141 |
+
cum_duration = torch.cumsum(duration, -1)
|
142 |
+
|
143 |
+
cum_duration_flat = cum_duration.view(b * t_x)
|
144 |
+
path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
|
145 |
+
path = path.view(b, t_x, t_y)
|
146 |
+
path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
|
147 |
+
path = path.unsqueeze(1).transpose(2, 3) * mask
|
148 |
+
return path
|
149 |
+
|
150 |
+
|
151 |
+
def clip_grad_value_(parameters, clip_value, norm_type=2):
|
152 |
+
if isinstance(parameters, torch.Tensor):
|
153 |
+
parameters = [parameters]
|
154 |
+
parameters = list(filter(lambda p: p.grad is not None, parameters))
|
155 |
+
norm_type = float(norm_type)
|
156 |
+
if clip_value is not None:
|
157 |
+
clip_value = float(clip_value)
|
158 |
+
|
159 |
+
total_norm = 0
|
160 |
+
for p in parameters:
|
161 |
+
param_norm = p.grad.data.norm(norm_type)
|
162 |
+
total_norm += param_norm.item() ** norm_type
|
163 |
+
if clip_value is not None:
|
164 |
+
p.grad.data.clamp_(min=-clip_value, max=clip_value)
|
165 |
+
total_norm = total_norm ** (1.0 / norm_type)
|
166 |
+
return total_norm
|
infer.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
|
3 |
+
import numpy
|
4 |
+
import numpy as np
|
5 |
+
import pydub
|
6 |
+
import torch
|
7 |
+
|
8 |
+
import commons
|
9 |
+
import utils
|
10 |
+
from models import SynthesizerTrn
|
11 |
+
from text import cleaned_text_to_sequence, get_bert
|
12 |
+
from text.cleaner import clean_text
|
13 |
+
from text.symbols import symbols
|
14 |
+
|
15 |
+
# 当前版本信息
|
16 |
+
latest_version = "2.0"
|
17 |
+
|
18 |
+
|
19 |
+
def get_net_g(model_path: str, device: str, hps):
|
20 |
+
net_g = SynthesizerTrn(
|
21 |
+
len(symbols),
|
22 |
+
hps.data.filter_length // 2 + 1,
|
23 |
+
hps.train.segment_size // hps.data.hop_length,
|
24 |
+
n_speakers=hps.data.n_speakers,
|
25 |
+
**hps.model,
|
26 |
+
).to(device)
|
27 |
+
_ = net_g.eval()
|
28 |
+
_ = utils.load_checkpoint(model_path, net_g, None, skip_optimizer=True)
|
29 |
+
return net_g
|
30 |
+
|
31 |
+
|
32 |
+
def get_text(text, language_str, hps, device):
|
33 |
+
# 在此处实现当前版本的get_text
|
34 |
+
norm_text, phone, tone, word2ph = clean_text(text, language_str)
|
35 |
+
phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
|
36 |
+
|
37 |
+
if hps.data.add_blank:
|
38 |
+
phone = commons.intersperse(phone, 0)
|
39 |
+
tone = commons.intersperse(tone, 0)
|
40 |
+
language = commons.intersperse(language, 0)
|
41 |
+
for i in range(len(word2ph)):
|
42 |
+
word2ph[i] = word2ph[i] * 2
|
43 |
+
word2ph[0] += 1
|
44 |
+
bert = get_bert(norm_text, word2ph, language_str, device)
|
45 |
+
del word2ph
|
46 |
+
assert bert.shape[-1] == len(phone), phone
|
47 |
+
|
48 |
+
if language_str == "ZH":
|
49 |
+
bert = bert
|
50 |
+
sh_bert = torch.zeros(1024, len(phone))
|
51 |
+
en_bert = torch.zeros(1024, len(phone))
|
52 |
+
elif language_str == "SH":
|
53 |
+
bert = torch.zeros(1024, len(phone))
|
54 |
+
sh_bert = bert
|
55 |
+
en_bert = torch.zeros(1024, len(phone))
|
56 |
+
elif language_str == "EN":
|
57 |
+
bert = torch.zeros(1024, len(phone))
|
58 |
+
sh_bert = torch.zeros(1024, len(phone))
|
59 |
+
en_bert = bert
|
60 |
+
else:
|
61 |
+
raise ValueError("language_str should be ZH, SH or EN")
|
62 |
+
|
63 |
+
assert bert.shape[-1] == len(phone), f"Bert seq len {bert.shape[-1]} != {len(phone)}"
|
64 |
+
|
65 |
+
phone = torch.LongTensor(phone)
|
66 |
+
tone = torch.LongTensor(tone)
|
67 |
+
language = torch.LongTensor(language)
|
68 |
+
return bert, sh_bert, en_bert, phone, tone, language
|
69 |
+
|
70 |
+
|
71 |
+
def infer(
|
72 |
+
text,
|
73 |
+
sdp_ratio,
|
74 |
+
noise_scale,
|
75 |
+
noise_scale_w,
|
76 |
+
length_scale,
|
77 |
+
sid,
|
78 |
+
language,
|
79 |
+
hps,
|
80 |
+
net_g,
|
81 |
+
device,
|
82 |
+
):
|
83 |
+
bert, sh_bert, en_bert, phones, tones, lang_ids = get_text(text, language, hps, device)
|
84 |
+
with torch.no_grad():
|
85 |
+
x_tst = phones.to(device).unsqueeze(0)
|
86 |
+
tones = tones.to(device).unsqueeze(0)
|
87 |
+
lang_ids = lang_ids.to(device).unsqueeze(0)
|
88 |
+
bert = bert.to(device).unsqueeze(0)
|
89 |
+
sh_bert = sh_bert.to(device).unsqueeze(0)
|
90 |
+
en_bert = en_bert.to(device).unsqueeze(0)
|
91 |
+
x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device)
|
92 |
+
del phones
|
93 |
+
speakers = torch.LongTensor([hps.data.spk2id[sid]]).to(device)
|
94 |
+
audio = (
|
95 |
+
net_g.infer(
|
96 |
+
x_tst,
|
97 |
+
x_tst_lengths,
|
98 |
+
speakers,
|
99 |
+
tones,
|
100 |
+
lang_ids,
|
101 |
+
bert,
|
102 |
+
sh_bert,
|
103 |
+
en_bert,
|
104 |
+
sdp_ratio=sdp_ratio,
|
105 |
+
noise_scale=noise_scale,
|
106 |
+
noise_scale_w=noise_scale_w,
|
107 |
+
length_scale=length_scale,
|
108 |
+
)[0][0, 0]
|
109 |
+
.data.cpu()
|
110 |
+
.float()
|
111 |
+
.numpy()
|
112 |
+
)
|
113 |
+
del x_tst, tones, lang_ids, bert, x_tst_lengths, speakers
|
114 |
+
torch.cuda.empty_cache()
|
115 |
+
return audio
|
116 |
+
|
117 |
+
|
118 |
+
def main():
|
119 |
+
parser = argparse.ArgumentParser()
|
120 |
+
parser.add_argument('--config', type=str, default='configs/config.json')
|
121 |
+
parser.add_argument('--device', type=str, default='cpu')
|
122 |
+
parser.add_argument('--model_path', type=str, default='models/G_1000.pth')
|
123 |
+
parser.add_argument('--output', type=str, default='sample')
|
124 |
+
args = parser.parse_args()
|
125 |
+
|
126 |
+
hps = utils.get_hparams_from_file(args.config)
|
127 |
+
net_g = get_net_g(args.model_path, device=args.device, hps=hps)
|
128 |
+
|
129 |
+
# noise_scale = 0.667
|
130 |
+
# noise_scale_w = 0.8
|
131 |
+
# length_scale = 0.9
|
132 |
+
|
133 |
+
sdp_ratio = 0
|
134 |
+
noise_scale = 0.667
|
135 |
+
noise_scale_w = 0.8
|
136 |
+
length_scale = 0.9
|
137 |
+
|
138 |
+
def do_sample(texts, sid, export_tag):
|
139 |
+
audio_data = numpy.array([], dtype=numpy.float32)
|
140 |
+
|
141 |
+
for (sub_text, language) in texts:
|
142 |
+
sub_audio_data = infer(sub_text, sdp_ratio, noise_scale, noise_scale_w, length_scale, sid, language, hps, net_g, args.device)
|
143 |
+
audio_data = np.concatenate((audio_data, sub_audio_data))
|
144 |
+
|
145 |
+
audio_data = audio_data / numpy.abs(audio_data).max()
|
146 |
+
audio_data = audio_data * 32767
|
147 |
+
audio_data = audio_data.astype(numpy.int16)
|
148 |
+
sound = pydub.AudioSegment(audio_data, frame_rate=hps.data.sampling_rate, sample_width=audio_data.dtype.itemsize, channels=1)
|
149 |
+
export_filename = args.output + export_tag + sid + '.mp3'
|
150 |
+
sound.export(export_filename, format='mp3')
|
151 |
+
print(export_filename)
|
152 |
+
|
153 |
+
text = [('我觉得有点贵。', 'ZH'), ('so expensive, can they?', 'EN'), ('哈巨,吃不消它。', 'SH')]
|
154 |
+
|
155 |
+
do_sample(text, '小庄', '_1_')
|
156 |
+
do_sample(text, '小嘟', '_1_')
|
157 |
+
do_sample(text, 'Jane', '_1_')
|
158 |
+
do_sample(text, '小贝', '_1_')
|
159 |
+
do_sample(text, '老克勒', '_1_')
|
160 |
+
do_sample(text, '美琳', '_1_')
|
161 |
+
|
162 |
+
pass
|
163 |
+
|
164 |
+
|
165 |
+
if __name__ == "__main__":
|
166 |
+
main()
|
mel_processing.py
ADDED
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.utils.data
|
3 |
+
from librosa.filters import mel as librosa_mel_fn
|
4 |
+
|
5 |
+
MAX_WAV_VALUE = 32768.0
|
6 |
+
|
7 |
+
|
8 |
+
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
|
9 |
+
"""
|
10 |
+
PARAMS
|
11 |
+
------
|
12 |
+
C: compression factor
|
13 |
+
"""
|
14 |
+
return torch.log(torch.clamp(x, min=clip_val) * C)
|
15 |
+
|
16 |
+
|
17 |
+
def dynamic_range_decompression_torch(x, C=1):
|
18 |
+
"""
|
19 |
+
PARAMS
|
20 |
+
------
|
21 |
+
C: compression factor used to compress
|
22 |
+
"""
|
23 |
+
return torch.exp(x) / C
|
24 |
+
|
25 |
+
|
26 |
+
def spectral_normalize_torch(magnitudes):
|
27 |
+
output = dynamic_range_compression_torch(magnitudes)
|
28 |
+
return output
|
29 |
+
|
30 |
+
|
31 |
+
def spectral_de_normalize_torch(magnitudes):
|
32 |
+
output = dynamic_range_decompression_torch(magnitudes)
|
33 |
+
return output
|
34 |
+
|
35 |
+
|
36 |
+
mel_basis = {}
|
37 |
+
hann_window = {}
|
38 |
+
|
39 |
+
|
40 |
+
def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
|
41 |
+
if torch.min(y) < -1.0:
|
42 |
+
print("min value is ", torch.min(y))
|
43 |
+
if torch.max(y) > 1.0:
|
44 |
+
print("max value is ", torch.max(y))
|
45 |
+
|
46 |
+
global hann_window
|
47 |
+
dtype_device = str(y.dtype) + "_" + str(y.device)
|
48 |
+
wnsize_dtype_device = str(win_size) + "_" + dtype_device
|
49 |
+
if wnsize_dtype_device not in hann_window:
|
50 |
+
hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
|
51 |
+
dtype=y.dtype, device=y.device
|
52 |
+
)
|
53 |
+
|
54 |
+
y = torch.nn.functional.pad(
|
55 |
+
y.unsqueeze(1),
|
56 |
+
(int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
|
57 |
+
mode="reflect",
|
58 |
+
)
|
59 |
+
y = y.squeeze(1)
|
60 |
+
|
61 |
+
spec = torch.stft(
|
62 |
+
y,
|
63 |
+
n_fft,
|
64 |
+
hop_length=hop_size,
|
65 |
+
win_length=win_size,
|
66 |
+
window=hann_window[wnsize_dtype_device],
|
67 |
+
center=center,
|
68 |
+
pad_mode="reflect",
|
69 |
+
normalized=False,
|
70 |
+
onesided=True,
|
71 |
+
return_complex=False,
|
72 |
+
)
|
73 |
+
|
74 |
+
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
|
75 |
+
return spec
|
76 |
+
|
77 |
+
|
78 |
+
def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
|
79 |
+
global mel_basis
|
80 |
+
dtype_device = str(spec.dtype) + "_" + str(spec.device)
|
81 |
+
fmax_dtype_device = str(fmax) + "_" + dtype_device
|
82 |
+
if fmax_dtype_device not in mel_basis:
|
83 |
+
mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
|
84 |
+
mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
|
85 |
+
dtype=spec.dtype, device=spec.device
|
86 |
+
)
|
87 |
+
spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
|
88 |
+
spec = spectral_normalize_torch(spec)
|
89 |
+
return spec
|
90 |
+
|
91 |
+
|
92 |
+
def mel_spectrogram_torch(
|
93 |
+
y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False
|
94 |
+
):
|
95 |
+
if torch.min(y) < -1.0:
|
96 |
+
print("min value is ", torch.min(y))
|
97 |
+
if torch.max(y) > 1.0:
|
98 |
+
print("max value is ", torch.max(y))
|
99 |
+
|
100 |
+
global mel_basis, hann_window
|
101 |
+
dtype_device = str(y.dtype) + "_" + str(y.device)
|
102 |
+
fmax_dtype_device = str(fmax) + "_" + dtype_device
|
103 |
+
wnsize_dtype_device = str(win_size) + "_" + dtype_device
|
104 |
+
if fmax_dtype_device not in mel_basis:
|
105 |
+
mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
|
106 |
+
mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
|
107 |
+
dtype=y.dtype, device=y.device
|
108 |
+
)
|
109 |
+
if wnsize_dtype_device not in hann_window:
|
110 |
+
hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
|
111 |
+
dtype=y.dtype, device=y.device
|
112 |
+
)
|
113 |
+
|
114 |
+
y = torch.nn.functional.pad(
|
115 |
+
y.unsqueeze(1),
|
116 |
+
(int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
|
117 |
+
mode="reflect",
|
118 |
+
)
|
119 |
+
y = y.squeeze(1)
|
120 |
+
|
121 |
+
spec = torch.stft(
|
122 |
+
y,
|
123 |
+
n_fft,
|
124 |
+
hop_length=hop_size,
|
125 |
+
win_length=win_size,
|
126 |
+
window=hann_window[wnsize_dtype_device],
|
127 |
+
center=center,
|
128 |
+
pad_mode="reflect",
|
129 |
+
normalized=False,
|
130 |
+
onesided=True,
|
131 |
+
return_complex=False,
|
132 |
+
)
|
133 |
+
|
134 |
+
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
|
135 |
+
|
136 |
+
spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
|
137 |
+
spec = spectral_normalize_torch(spec)
|
138 |
+
|
139 |
+
return spec
|
models.py
ADDED
@@ -0,0 +1,1002 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import torch
|
3 |
+
from torch import nn
|
4 |
+
from torch.nn import functional as F
|
5 |
+
|
6 |
+
import commons
|
7 |
+
import modules
|
8 |
+
import attentions
|
9 |
+
import monotonic_align
|
10 |
+
|
11 |
+
from torch.nn import Conv1d, ConvTranspose1d, Conv2d
|
12 |
+
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
|
13 |
+
|
14 |
+
from commons import init_weights, get_padding
|
15 |
+
from text import symbols, num_tones, num_languages
|
16 |
+
|
17 |
+
|
18 |
+
class DurationDiscriminator(nn.Module): # vits2
|
19 |
+
def __init__(
|
20 |
+
self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0
|
21 |
+
):
|
22 |
+
super().__init__()
|
23 |
+
|
24 |
+
self.in_channels = in_channels
|
25 |
+
self.filter_channels = filter_channels
|
26 |
+
self.kernel_size = kernel_size
|
27 |
+
self.p_dropout = p_dropout
|
28 |
+
self.gin_channels = gin_channels
|
29 |
+
|
30 |
+
self.drop = nn.Dropout(p_dropout)
|
31 |
+
self.conv_1 = nn.Conv1d(
|
32 |
+
in_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
33 |
+
)
|
34 |
+
self.norm_1 = modules.LayerNorm(filter_channels)
|
35 |
+
self.conv_2 = nn.Conv1d(
|
36 |
+
filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
37 |
+
)
|
38 |
+
self.norm_2 = modules.LayerNorm(filter_channels)
|
39 |
+
self.dur_proj = nn.Conv1d(1, filter_channels, 1)
|
40 |
+
|
41 |
+
self.pre_out_conv_1 = nn.Conv1d(
|
42 |
+
2 * filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
43 |
+
)
|
44 |
+
self.pre_out_norm_1 = modules.LayerNorm(filter_channels)
|
45 |
+
self.pre_out_conv_2 = nn.Conv1d(
|
46 |
+
filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
47 |
+
)
|
48 |
+
self.pre_out_norm_2 = modules.LayerNorm(filter_channels)
|
49 |
+
|
50 |
+
if gin_channels != 0:
|
51 |
+
self.cond = nn.Conv1d(gin_channels, in_channels, 1)
|
52 |
+
|
53 |
+
self.output_layer = nn.Sequential(nn.Linear(filter_channels, 1), nn.Sigmoid())
|
54 |
+
|
55 |
+
def forward_probability(self, x, x_mask, dur, g=None):
|
56 |
+
dur = self.dur_proj(dur)
|
57 |
+
x = torch.cat([x, dur], dim=1)
|
58 |
+
x = self.pre_out_conv_1(x * x_mask)
|
59 |
+
x = torch.relu(x)
|
60 |
+
x = self.pre_out_norm_1(x)
|
61 |
+
x = self.drop(x)
|
62 |
+
x = self.pre_out_conv_2(x * x_mask)
|
63 |
+
x = torch.relu(x)
|
64 |
+
x = self.pre_out_norm_2(x)
|
65 |
+
x = self.drop(x)
|
66 |
+
x = x * x_mask
|
67 |
+
x = x.transpose(1, 2)
|
68 |
+
output_prob = self.output_layer(x)
|
69 |
+
return output_prob
|
70 |
+
|
71 |
+
def forward(self, x, x_mask, dur_r, dur_hat, g=None):
|
72 |
+
x = torch.detach(x)
|
73 |
+
if g is not None:
|
74 |
+
g = torch.detach(g)
|
75 |
+
x = x + self.cond(g)
|
76 |
+
x = self.conv_1(x * x_mask)
|
77 |
+
x = torch.relu(x)
|
78 |
+
x = self.norm_1(x)
|
79 |
+
x = self.drop(x)
|
80 |
+
x = self.conv_2(x * x_mask)
|
81 |
+
x = torch.relu(x)
|
82 |
+
x = self.norm_2(x)
|
83 |
+
x = self.drop(x)
|
84 |
+
|
85 |
+
output_probs = []
|
86 |
+
for dur in [dur_r, dur_hat]:
|
87 |
+
output_prob = self.forward_probability(x, x_mask, dur, g)
|
88 |
+
output_probs.append(output_prob)
|
89 |
+
|
90 |
+
return output_probs
|
91 |
+
|
92 |
+
|
93 |
+
class TransformerCouplingBlock(nn.Module):
|
94 |
+
def __init__(
|
95 |
+
self,
|
96 |
+
channels,
|
97 |
+
hidden_channels,
|
98 |
+
filter_channels,
|
99 |
+
n_heads,
|
100 |
+
n_layers,
|
101 |
+
kernel_size,
|
102 |
+
p_dropout,
|
103 |
+
n_flows=4,
|
104 |
+
gin_channels=0,
|
105 |
+
share_parameter=False,
|
106 |
+
):
|
107 |
+
super().__init__()
|
108 |
+
self.channels = channels
|
109 |
+
self.hidden_channels = hidden_channels
|
110 |
+
self.kernel_size = kernel_size
|
111 |
+
self.n_layers = n_layers
|
112 |
+
self.n_flows = n_flows
|
113 |
+
self.gin_channels = gin_channels
|
114 |
+
|
115 |
+
self.flows = nn.ModuleList()
|
116 |
+
|
117 |
+
self.wn = (
|
118 |
+
attentions.FFT(
|
119 |
+
hidden_channels,
|
120 |
+
filter_channels,
|
121 |
+
n_heads,
|
122 |
+
n_layers,
|
123 |
+
kernel_size,
|
124 |
+
p_dropout,
|
125 |
+
isflow=True,
|
126 |
+
gin_channels=self.gin_channels,
|
127 |
+
)
|
128 |
+
if share_parameter
|
129 |
+
else None
|
130 |
+
)
|
131 |
+
|
132 |
+
for i in range(n_flows):
|
133 |
+
self.flows.append(
|
134 |
+
modules.TransformerCouplingLayer(
|
135 |
+
channels,
|
136 |
+
hidden_channels,
|
137 |
+
kernel_size,
|
138 |
+
n_layers,
|
139 |
+
n_heads,
|
140 |
+
p_dropout,
|
141 |
+
filter_channels,
|
142 |
+
mean_only=True,
|
143 |
+
wn_sharing_parameter=self.wn,
|
144 |
+
gin_channels=self.gin_channels,
|
145 |
+
)
|
146 |
+
)
|
147 |
+
self.flows.append(modules.Flip())
|
148 |
+
|
149 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
150 |
+
if not reverse:
|
151 |
+
for flow in self.flows:
|
152 |
+
x, _ = flow(x, x_mask, g=g, reverse=reverse)
|
153 |
+
else:
|
154 |
+
for flow in reversed(self.flows):
|
155 |
+
x = flow(x, x_mask, g=g, reverse=reverse)
|
156 |
+
return x
|
157 |
+
|
158 |
+
|
159 |
+
class StochasticDurationPredictor(nn.Module):
|
160 |
+
def __init__(
|
161 |
+
self,
|
162 |
+
in_channels,
|
163 |
+
filter_channels,
|
164 |
+
kernel_size,
|
165 |
+
p_dropout,
|
166 |
+
n_flows=4,
|
167 |
+
gin_channels=0,
|
168 |
+
):
|
169 |
+
super().__init__()
|
170 |
+
filter_channels = in_channels # it needs to be removed from future version.
|
171 |
+
self.in_channels = in_channels
|
172 |
+
self.filter_channels = filter_channels
|
173 |
+
self.kernel_size = kernel_size
|
174 |
+
self.p_dropout = p_dropout
|
175 |
+
self.n_flows = n_flows
|
176 |
+
self.gin_channels = gin_channels
|
177 |
+
|
178 |
+
self.log_flow = modules.Log()
|
179 |
+
self.flows = nn.ModuleList()
|
180 |
+
self.flows.append(modules.ElementwiseAffine(2))
|
181 |
+
for i in range(n_flows):
|
182 |
+
self.flows.append(
|
183 |
+
modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
|
184 |
+
)
|
185 |
+
self.flows.append(modules.Flip())
|
186 |
+
|
187 |
+
self.post_pre = nn.Conv1d(1, filter_channels, 1)
|
188 |
+
self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
189 |
+
self.post_convs = modules.DDSConv(
|
190 |
+
filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
|
191 |
+
)
|
192 |
+
self.post_flows = nn.ModuleList()
|
193 |
+
self.post_flows.append(modules.ElementwiseAffine(2))
|
194 |
+
for i in range(4):
|
195 |
+
self.post_flows.append(
|
196 |
+
modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
|
197 |
+
)
|
198 |
+
self.post_flows.append(modules.Flip())
|
199 |
+
|
200 |
+
self.pre = nn.Conv1d(in_channels, filter_channels, 1)
|
201 |
+
self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
202 |
+
self.convs = modules.DDSConv(
|
203 |
+
filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
|
204 |
+
)
|
205 |
+
if gin_channels != 0:
|
206 |
+
self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
|
207 |
+
|
208 |
+
def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
|
209 |
+
x = torch.detach(x)
|
210 |
+
x = self.pre(x)
|
211 |
+
if g is not None:
|
212 |
+
g = torch.detach(g)
|
213 |
+
x = x + self.cond(g)
|
214 |
+
x = self.convs(x, x_mask)
|
215 |
+
x = self.proj(x) * x_mask
|
216 |
+
|
217 |
+
if not reverse:
|
218 |
+
flows = self.flows
|
219 |
+
assert w is not None
|
220 |
+
|
221 |
+
logdet_tot_q = 0
|
222 |
+
h_w = self.post_pre(w)
|
223 |
+
h_w = self.post_convs(h_w, x_mask)
|
224 |
+
h_w = self.post_proj(h_w) * x_mask
|
225 |
+
e_q = (
|
226 |
+
torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype)
|
227 |
+
* x_mask
|
228 |
+
)
|
229 |
+
z_q = e_q
|
230 |
+
for flow in self.post_flows:
|
231 |
+
z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
|
232 |
+
logdet_tot_q += logdet_q
|
233 |
+
z_u, z1 = torch.split(z_q, [1, 1], 1)
|
234 |
+
u = torch.sigmoid(z_u) * x_mask
|
235 |
+
z0 = (w - u) * x_mask
|
236 |
+
logdet_tot_q += torch.sum(
|
237 |
+
(F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2]
|
238 |
+
)
|
239 |
+
logq = (
|
240 |
+
torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q**2)) * x_mask, [1, 2])
|
241 |
+
- logdet_tot_q
|
242 |
+
)
|
243 |
+
|
244 |
+
logdet_tot = 0
|
245 |
+
z0, logdet = self.log_flow(z0, x_mask)
|
246 |
+
logdet_tot += logdet
|
247 |
+
z = torch.cat([z0, z1], 1)
|
248 |
+
for flow in flows:
|
249 |
+
z, logdet = flow(z, x_mask, g=x, reverse=reverse)
|
250 |
+
logdet_tot = logdet_tot + logdet
|
251 |
+
nll = (
|
252 |
+
torch.sum(0.5 * (math.log(2 * math.pi) + (z**2)) * x_mask, [1, 2])
|
253 |
+
- logdet_tot
|
254 |
+
)
|
255 |
+
return nll + logq # [b]
|
256 |
+
else:
|
257 |
+
flows = list(reversed(self.flows))
|
258 |
+
flows = flows[:-2] + [flows[-1]] # remove a useless vflow
|
259 |
+
z = (
|
260 |
+
torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype)
|
261 |
+
* noise_scale
|
262 |
+
)
|
263 |
+
for flow in flows:
|
264 |
+
z = flow(z, x_mask, g=x, reverse=reverse)
|
265 |
+
z0, z1 = torch.split(z, [1, 1], 1)
|
266 |
+
logw = z0
|
267 |
+
return logw
|
268 |
+
|
269 |
+
|
270 |
+
class DurationPredictor(nn.Module):
|
271 |
+
def __init__(
|
272 |
+
self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0
|
273 |
+
):
|
274 |
+
super().__init__()
|
275 |
+
|
276 |
+
self.in_channels = in_channels
|
277 |
+
self.filter_channels = filter_channels
|
278 |
+
self.kernel_size = kernel_size
|
279 |
+
self.p_dropout = p_dropout
|
280 |
+
self.gin_channels = gin_channels
|
281 |
+
|
282 |
+
self.drop = nn.Dropout(p_dropout)
|
283 |
+
self.conv_1 = nn.Conv1d(
|
284 |
+
in_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
285 |
+
)
|
286 |
+
self.norm_1 = modules.LayerNorm(filter_channels)
|
287 |
+
self.conv_2 = nn.Conv1d(
|
288 |
+
filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
289 |
+
)
|
290 |
+
self.norm_2 = modules.LayerNorm(filter_channels)
|
291 |
+
self.proj = nn.Conv1d(filter_channels, 1, 1)
|
292 |
+
|
293 |
+
if gin_channels != 0:
|
294 |
+
self.cond = nn.Conv1d(gin_channels, in_channels, 1)
|
295 |
+
|
296 |
+
def forward(self, x, x_mask, g=None):
|
297 |
+
x = torch.detach(x)
|
298 |
+
if g is not None:
|
299 |
+
g = torch.detach(g)
|
300 |
+
x = x + self.cond(g)
|
301 |
+
x = self.conv_1(x * x_mask)
|
302 |
+
x = torch.relu(x)
|
303 |
+
x = self.norm_1(x)
|
304 |
+
x = self.drop(x)
|
305 |
+
x = self.conv_2(x * x_mask)
|
306 |
+
x = torch.relu(x)
|
307 |
+
x = self.norm_2(x)
|
308 |
+
x = self.drop(x)
|
309 |
+
x = self.proj(x * x_mask)
|
310 |
+
return x * x_mask
|
311 |
+
|
312 |
+
|
313 |
+
class TextEncoder(nn.Module):
|
314 |
+
def __init__(
|
315 |
+
self,
|
316 |
+
n_vocab,
|
317 |
+
out_channels,
|
318 |
+
hidden_channels,
|
319 |
+
filter_channels,
|
320 |
+
n_heads,
|
321 |
+
n_layers,
|
322 |
+
kernel_size,
|
323 |
+
p_dropout,
|
324 |
+
gin_channels=0,
|
325 |
+
):
|
326 |
+
super().__init__()
|
327 |
+
self.n_vocab = n_vocab
|
328 |
+
self.out_channels = out_channels
|
329 |
+
self.hidden_channels = hidden_channels
|
330 |
+
self.filter_channels = filter_channels
|
331 |
+
self.n_heads = n_heads
|
332 |
+
self.n_layers = n_layers
|
333 |
+
self.kernel_size = kernel_size
|
334 |
+
self.p_dropout = p_dropout
|
335 |
+
self.gin_channels = gin_channels
|
336 |
+
self.emb = nn.Embedding(len(symbols), hidden_channels)
|
337 |
+
nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
|
338 |
+
self.tone_emb = nn.Embedding(num_tones, hidden_channels)
|
339 |
+
nn.init.normal_(self.tone_emb.weight, 0.0, hidden_channels**-0.5)
|
340 |
+
self.language_emb = nn.Embedding(num_languages, hidden_channels)
|
341 |
+
nn.init.normal_(self.language_emb.weight, 0.0, hidden_channels**-0.5)
|
342 |
+
self.bert_proj = nn.Conv1d(1024, hidden_channels, 1)
|
343 |
+
self.ja_bert_proj = nn.Conv1d(1024, hidden_channels, 1)
|
344 |
+
self.en_bert_proj = nn.Conv1d(1024, hidden_channels, 1)
|
345 |
+
|
346 |
+
self.encoder = attentions.Encoder(
|
347 |
+
hidden_channels,
|
348 |
+
filter_channels,
|
349 |
+
n_heads,
|
350 |
+
n_layers,
|
351 |
+
kernel_size,
|
352 |
+
p_dropout,
|
353 |
+
gin_channels=self.gin_channels,
|
354 |
+
)
|
355 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
356 |
+
|
357 |
+
def forward(self, x, x_lengths, tone, language, bert, ja_bert, en_bert, g=None):
|
358 |
+
bert_emb = self.bert_proj(bert).transpose(1, 2)
|
359 |
+
ja_bert_emb = self.ja_bert_proj(ja_bert).transpose(1, 2)
|
360 |
+
en_bert_emb = self.en_bert_proj(en_bert).transpose(1, 2)
|
361 |
+
x = (
|
362 |
+
self.emb(x)
|
363 |
+
+ self.tone_emb(tone)
|
364 |
+
+ self.language_emb(language)
|
365 |
+
+ bert_emb
|
366 |
+
+ ja_bert_emb
|
367 |
+
+ en_bert_emb
|
368 |
+
) * math.sqrt(
|
369 |
+
self.hidden_channels
|
370 |
+
) # [b, t, h]
|
371 |
+
x = torch.transpose(x, 1, -1) # [b, h, t]
|
372 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
|
373 |
+
x.dtype
|
374 |
+
)
|
375 |
+
|
376 |
+
x = self.encoder(x * x_mask, x_mask, g=g)
|
377 |
+
stats = self.proj(x) * x_mask
|
378 |
+
|
379 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
380 |
+
return x, m, logs, x_mask
|
381 |
+
|
382 |
+
|
383 |
+
class ResidualCouplingBlock(nn.Module):
|
384 |
+
def __init__(
|
385 |
+
self,
|
386 |
+
channels,
|
387 |
+
hidden_channels,
|
388 |
+
kernel_size,
|
389 |
+
dilation_rate,
|
390 |
+
n_layers,
|
391 |
+
n_flows=4,
|
392 |
+
gin_channels=0,
|
393 |
+
):
|
394 |
+
super().__init__()
|
395 |
+
self.channels = channels
|
396 |
+
self.hidden_channels = hidden_channels
|
397 |
+
self.kernel_size = kernel_size
|
398 |
+
self.dilation_rate = dilation_rate
|
399 |
+
self.n_layers = n_layers
|
400 |
+
self.n_flows = n_flows
|
401 |
+
self.gin_channels = gin_channels
|
402 |
+
|
403 |
+
self.flows = nn.ModuleList()
|
404 |
+
for i in range(n_flows):
|
405 |
+
self.flows.append(
|
406 |
+
modules.ResidualCouplingLayer(
|
407 |
+
channels,
|
408 |
+
hidden_channels,
|
409 |
+
kernel_size,
|
410 |
+
dilation_rate,
|
411 |
+
n_layers,
|
412 |
+
gin_channels=gin_channels,
|
413 |
+
mean_only=True,
|
414 |
+
)
|
415 |
+
)
|
416 |
+
self.flows.append(modules.Flip())
|
417 |
+
|
418 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
419 |
+
if not reverse:
|
420 |
+
for flow in self.flows:
|
421 |
+
x, _ = flow(x, x_mask, g=g, reverse=reverse)
|
422 |
+
else:
|
423 |
+
for flow in reversed(self.flows):
|
424 |
+
x = flow(x, x_mask, g=g, reverse=reverse)
|
425 |
+
return x
|
426 |
+
|
427 |
+
|
428 |
+
class PosteriorEncoder(nn.Module):
|
429 |
+
def __init__(
|
430 |
+
self,
|
431 |
+
in_channels,
|
432 |
+
out_channels,
|
433 |
+
hidden_channels,
|
434 |
+
kernel_size,
|
435 |
+
dilation_rate,
|
436 |
+
n_layers,
|
437 |
+
gin_channels=0,
|
438 |
+
):
|
439 |
+
super().__init__()
|
440 |
+
self.in_channels = in_channels
|
441 |
+
self.out_channels = out_channels
|
442 |
+
self.hidden_channels = hidden_channels
|
443 |
+
self.kernel_size = kernel_size
|
444 |
+
self.dilation_rate = dilation_rate
|
445 |
+
self.n_layers = n_layers
|
446 |
+
self.gin_channels = gin_channels
|
447 |
+
|
448 |
+
self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
|
449 |
+
self.enc = modules.WN(
|
450 |
+
hidden_channels,
|
451 |
+
kernel_size,
|
452 |
+
dilation_rate,
|
453 |
+
n_layers,
|
454 |
+
gin_channels=gin_channels,
|
455 |
+
)
|
456 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
457 |
+
|
458 |
+
def forward(self, x, x_lengths, g=None):
|
459 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
|
460 |
+
x.dtype
|
461 |
+
)
|
462 |
+
x = self.pre(x) * x_mask
|
463 |
+
x = self.enc(x, x_mask, g=g)
|
464 |
+
stats = self.proj(x) * x_mask
|
465 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
466 |
+
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
|
467 |
+
return z, m, logs, x_mask
|
468 |
+
|
469 |
+
|
470 |
+
class Generator(torch.nn.Module):
|
471 |
+
def __init__(
|
472 |
+
self,
|
473 |
+
initial_channel,
|
474 |
+
resblock,
|
475 |
+
resblock_kernel_sizes,
|
476 |
+
resblock_dilation_sizes,
|
477 |
+
upsample_rates,
|
478 |
+
upsample_initial_channel,
|
479 |
+
upsample_kernel_sizes,
|
480 |
+
gin_channels=0,
|
481 |
+
):
|
482 |
+
super(Generator, self).__init__()
|
483 |
+
self.num_kernels = len(resblock_kernel_sizes)
|
484 |
+
self.num_upsamples = len(upsample_rates)
|
485 |
+
self.conv_pre = Conv1d(
|
486 |
+
initial_channel, upsample_initial_channel, 7, 1, padding=3
|
487 |
+
)
|
488 |
+
resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
|
489 |
+
|
490 |
+
self.ups = nn.ModuleList()
|
491 |
+
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
492 |
+
self.ups.append(
|
493 |
+
weight_norm(
|
494 |
+
ConvTranspose1d(
|
495 |
+
upsample_initial_channel // (2**i),
|
496 |
+
upsample_initial_channel // (2 ** (i + 1)),
|
497 |
+
k,
|
498 |
+
u,
|
499 |
+
padding=(k - u) // 2,
|
500 |
+
)
|
501 |
+
)
|
502 |
+
)
|
503 |
+
|
504 |
+
self.resblocks = nn.ModuleList()
|
505 |
+
for i in range(len(self.ups)):
|
506 |
+
ch = upsample_initial_channel // (2 ** (i + 1))
|
507 |
+
for j, (k, d) in enumerate(
|
508 |
+
zip(resblock_kernel_sizes, resblock_dilation_sizes)
|
509 |
+
):
|
510 |
+
self.resblocks.append(resblock(ch, k, d))
|
511 |
+
|
512 |
+
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
|
513 |
+
self.ups.apply(init_weights)
|
514 |
+
|
515 |
+
if gin_channels != 0:
|
516 |
+
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
|
517 |
+
|
518 |
+
def forward(self, x, g=None):
|
519 |
+
x = self.conv_pre(x)
|
520 |
+
if g is not None:
|
521 |
+
x = x + self.cond(g)
|
522 |
+
|
523 |
+
for i in range(self.num_upsamples):
|
524 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
525 |
+
x = self.ups[i](x)
|
526 |
+
xs = None
|
527 |
+
for j in range(self.num_kernels):
|
528 |
+
if xs is None:
|
529 |
+
xs = self.resblocks[i * self.num_kernels + j](x)
|
530 |
+
else:
|
531 |
+
xs += self.resblocks[i * self.num_kernels + j](x)
|
532 |
+
x = xs / self.num_kernels
|
533 |
+
x = F.leaky_relu(x)
|
534 |
+
x = self.conv_post(x)
|
535 |
+
x = torch.tanh(x)
|
536 |
+
|
537 |
+
return x
|
538 |
+
|
539 |
+
def remove_weight_norm(self):
|
540 |
+
print("Removing weight norm...")
|
541 |
+
for layer in self.ups:
|
542 |
+
remove_weight_norm(layer)
|
543 |
+
for layer in self.resblocks:
|
544 |
+
layer.remove_weight_norm()
|
545 |
+
|
546 |
+
|
547 |
+
class DiscriminatorP(torch.nn.Module):
|
548 |
+
def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
|
549 |
+
super(DiscriminatorP, self).__init__()
|
550 |
+
self.period = period
|
551 |
+
self.use_spectral_norm = use_spectral_norm
|
552 |
+
norm_f = weight_norm if use_spectral_norm is False else spectral_norm
|
553 |
+
self.convs = nn.ModuleList(
|
554 |
+
[
|
555 |
+
norm_f(
|
556 |
+
Conv2d(
|
557 |
+
1,
|
558 |
+
32,
|
559 |
+
(kernel_size, 1),
|
560 |
+
(stride, 1),
|
561 |
+
padding=(get_padding(kernel_size, 1), 0),
|
562 |
+
)
|
563 |
+
),
|
564 |
+
norm_f(
|
565 |
+
Conv2d(
|
566 |
+
32,
|
567 |
+
128,
|
568 |
+
(kernel_size, 1),
|
569 |
+
(stride, 1),
|
570 |
+
padding=(get_padding(kernel_size, 1), 0),
|
571 |
+
)
|
572 |
+
),
|
573 |
+
norm_f(
|
574 |
+
Conv2d(
|
575 |
+
128,
|
576 |
+
512,
|
577 |
+
(kernel_size, 1),
|
578 |
+
(stride, 1),
|
579 |
+
padding=(get_padding(kernel_size, 1), 0),
|
580 |
+
)
|
581 |
+
),
|
582 |
+
norm_f(
|
583 |
+
Conv2d(
|
584 |
+
512,
|
585 |
+
1024,
|
586 |
+
(kernel_size, 1),
|
587 |
+
(stride, 1),
|
588 |
+
padding=(get_padding(kernel_size, 1), 0),
|
589 |
+
)
|
590 |
+
),
|
591 |
+
norm_f(
|
592 |
+
Conv2d(
|
593 |
+
1024,
|
594 |
+
1024,
|
595 |
+
(kernel_size, 1),
|
596 |
+
1,
|
597 |
+
padding=(get_padding(kernel_size, 1), 0),
|
598 |
+
)
|
599 |
+
),
|
600 |
+
]
|
601 |
+
)
|
602 |
+
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
|
603 |
+
|
604 |
+
def forward(self, x):
|
605 |
+
fmap = []
|
606 |
+
|
607 |
+
# 1d to 2d
|
608 |
+
b, c, t = x.shape
|
609 |
+
if t % self.period != 0: # pad first
|
610 |
+
n_pad = self.period - (t % self.period)
|
611 |
+
x = F.pad(x, (0, n_pad), "reflect")
|
612 |
+
t = t + n_pad
|
613 |
+
x = x.view(b, c, t // self.period, self.period)
|
614 |
+
|
615 |
+
for layer in self.convs:
|
616 |
+
x = layer(x)
|
617 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
618 |
+
fmap.append(x)
|
619 |
+
x = self.conv_post(x)
|
620 |
+
fmap.append(x)
|
621 |
+
x = torch.flatten(x, 1, -1)
|
622 |
+
|
623 |
+
return x, fmap
|
624 |
+
|
625 |
+
|
626 |
+
class DiscriminatorS(torch.nn.Module):
|
627 |
+
def __init__(self, use_spectral_norm=False):
|
628 |
+
super(DiscriminatorS, self).__init__()
|
629 |
+
norm_f = weight_norm if use_spectral_norm is False else spectral_norm
|
630 |
+
self.convs = nn.ModuleList(
|
631 |
+
[
|
632 |
+
norm_f(Conv1d(1, 16, 15, 1, padding=7)),
|
633 |
+
norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
|
634 |
+
norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
|
635 |
+
norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
|
636 |
+
norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
|
637 |
+
norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
|
638 |
+
]
|
639 |
+
)
|
640 |
+
self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
|
641 |
+
|
642 |
+
def forward(self, x):
|
643 |
+
fmap = []
|
644 |
+
|
645 |
+
for layer in self.convs:
|
646 |
+
x = layer(x)
|
647 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
648 |
+
fmap.append(x)
|
649 |
+
x = self.conv_post(x)
|
650 |
+
fmap.append(x)
|
651 |
+
x = torch.flatten(x, 1, -1)
|
652 |
+
|
653 |
+
return x, fmap
|
654 |
+
|
655 |
+
|
656 |
+
class MultiPeriodDiscriminator(torch.nn.Module):
|
657 |
+
def __init__(self, use_spectral_norm=False):
|
658 |
+
super(MultiPeriodDiscriminator, self).__init__()
|
659 |
+
periods = [2, 3, 5, 7, 11]
|
660 |
+
|
661 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
662 |
+
discs = discs + [
|
663 |
+
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
|
664 |
+
]
|
665 |
+
self.discriminators = nn.ModuleList(discs)
|
666 |
+
|
667 |
+
def forward(self, y, y_hat):
|
668 |
+
y_d_rs = []
|
669 |
+
y_d_gs = []
|
670 |
+
fmap_rs = []
|
671 |
+
fmap_gs = []
|
672 |
+
for i, d in enumerate(self.discriminators):
|
673 |
+
y_d_r, fmap_r = d(y)
|
674 |
+
y_d_g, fmap_g = d(y_hat)
|
675 |
+
y_d_rs.append(y_d_r)
|
676 |
+
y_d_gs.append(y_d_g)
|
677 |
+
fmap_rs.append(fmap_r)
|
678 |
+
fmap_gs.append(fmap_g)
|
679 |
+
|
680 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
681 |
+
|
682 |
+
|
683 |
+
class ReferenceEncoder(nn.Module):
|
684 |
+
"""
|
685 |
+
inputs --- [N, Ty/r, n_mels*r] mels
|
686 |
+
outputs --- [N, ref_enc_gru_size]
|
687 |
+
"""
|
688 |
+
|
689 |
+
def __init__(self, spec_channels, gin_channels=0):
|
690 |
+
super().__init__()
|
691 |
+
self.spec_channels = spec_channels
|
692 |
+
ref_enc_filters = [32, 32, 64, 64, 128, 128]
|
693 |
+
K = len(ref_enc_filters)
|
694 |
+
filters = [1] + ref_enc_filters
|
695 |
+
convs = [
|
696 |
+
weight_norm(
|
697 |
+
nn.Conv2d(
|
698 |
+
in_channels=filters[i],
|
699 |
+
out_channels=filters[i + 1],
|
700 |
+
kernel_size=(3, 3),
|
701 |
+
stride=(2, 2),
|
702 |
+
padding=(1, 1),
|
703 |
+
)
|
704 |
+
)
|
705 |
+
for i in range(K)
|
706 |
+
]
|
707 |
+
self.convs = nn.ModuleList(convs)
|
708 |
+
# self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)]) # noqa: E501
|
709 |
+
|
710 |
+
out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K)
|
711 |
+
self.gru = nn.GRU(
|
712 |
+
input_size=ref_enc_filters[-1] * out_channels,
|
713 |
+
hidden_size=256 // 2,
|
714 |
+
batch_first=True,
|
715 |
+
)
|
716 |
+
self.proj = nn.Linear(128, gin_channels)
|
717 |
+
|
718 |
+
def forward(self, inputs, mask=None):
|
719 |
+
N = inputs.size(0)
|
720 |
+
out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs]
|
721 |
+
for conv in self.convs:
|
722 |
+
out = conv(out)
|
723 |
+
# out = wn(out)
|
724 |
+
out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K]
|
725 |
+
|
726 |
+
out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
|
727 |
+
T = out.size(1)
|
728 |
+
N = out.size(0)
|
729 |
+
out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
|
730 |
+
|
731 |
+
self.gru.flatten_parameters()
|
732 |
+
memory, out = self.gru(out) # out --- [1, N, 128]
|
733 |
+
|
734 |
+
return self.proj(out.squeeze(0))
|
735 |
+
|
736 |
+
def calculate_channels(self, L, kernel_size, stride, pad, n_convs):
|
737 |
+
for i in range(n_convs):
|
738 |
+
L = (L - kernel_size + 2 * pad) // stride + 1
|
739 |
+
return L
|
740 |
+
|
741 |
+
|
742 |
+
class SynthesizerTrn(nn.Module):
|
743 |
+
"""
|
744 |
+
Synthesizer for Training
|
745 |
+
"""
|
746 |
+
|
747 |
+
def __init__(
|
748 |
+
self,
|
749 |
+
n_vocab,
|
750 |
+
spec_channels,
|
751 |
+
segment_size,
|
752 |
+
inter_channels,
|
753 |
+
hidden_channels,
|
754 |
+
filter_channels,
|
755 |
+
n_heads,
|
756 |
+
n_layers,
|
757 |
+
kernel_size,
|
758 |
+
p_dropout,
|
759 |
+
resblock,
|
760 |
+
resblock_kernel_sizes,
|
761 |
+
resblock_dilation_sizes,
|
762 |
+
upsample_rates,
|
763 |
+
upsample_initial_channel,
|
764 |
+
upsample_kernel_sizes,
|
765 |
+
n_speakers=256,
|
766 |
+
gin_channels=256,
|
767 |
+
use_sdp=True,
|
768 |
+
n_flow_layer=4,
|
769 |
+
n_layers_trans_flow=4,
|
770 |
+
flow_share_parameter=False,
|
771 |
+
use_transformer_flow=True,
|
772 |
+
**kwargs
|
773 |
+
):
|
774 |
+
super().__init__()
|
775 |
+
self.n_vocab = n_vocab
|
776 |
+
self.spec_channels = spec_channels
|
777 |
+
self.inter_channels = inter_channels
|
778 |
+
self.hidden_channels = hidden_channels
|
779 |
+
self.filter_channels = filter_channels
|
780 |
+
self.n_heads = n_heads
|
781 |
+
self.n_layers = n_layers
|
782 |
+
self.kernel_size = kernel_size
|
783 |
+
self.p_dropout = p_dropout
|
784 |
+
self.resblock = resblock
|
785 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
786 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
787 |
+
self.upsample_rates = upsample_rates
|
788 |
+
self.upsample_initial_channel = upsample_initial_channel
|
789 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
790 |
+
self.segment_size = segment_size
|
791 |
+
self.n_speakers = n_speakers
|
792 |
+
self.gin_channels = gin_channels
|
793 |
+
self.n_layers_trans_flow = n_layers_trans_flow
|
794 |
+
self.use_spk_conditioned_encoder = kwargs.get(
|
795 |
+
"use_spk_conditioned_encoder", True
|
796 |
+
)
|
797 |
+
self.use_sdp = use_sdp
|
798 |
+
self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False)
|
799 |
+
self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01)
|
800 |
+
self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6)
|
801 |
+
self.current_mas_noise_scale = self.mas_noise_scale_initial
|
802 |
+
if self.use_spk_conditioned_encoder and gin_channels > 0:
|
803 |
+
self.enc_gin_channels = gin_channels
|
804 |
+
self.enc_p = TextEncoder(
|
805 |
+
n_vocab,
|
806 |
+
inter_channels,
|
807 |
+
hidden_channels,
|
808 |
+
filter_channels,
|
809 |
+
n_heads,
|
810 |
+
n_layers,
|
811 |
+
kernel_size,
|
812 |
+
p_dropout,
|
813 |
+
gin_channels=self.enc_gin_channels,
|
814 |
+
)
|
815 |
+
self.dec = Generator(
|
816 |
+
inter_channels,
|
817 |
+
resblock,
|
818 |
+
resblock_kernel_sizes,
|
819 |
+
resblock_dilation_sizes,
|
820 |
+
upsample_rates,
|
821 |
+
upsample_initial_channel,
|
822 |
+
upsample_kernel_sizes,
|
823 |
+
gin_channels=gin_channels,
|
824 |
+
)
|
825 |
+
self.enc_q = PosteriorEncoder(
|
826 |
+
spec_channels,
|
827 |
+
inter_channels,
|
828 |
+
hidden_channels,
|
829 |
+
5,
|
830 |
+
1,
|
831 |
+
16,
|
832 |
+
gin_channels=gin_channels,
|
833 |
+
)
|
834 |
+
if use_transformer_flow:
|
835 |
+
self.flow = TransformerCouplingBlock(
|
836 |
+
inter_channels,
|
837 |
+
hidden_channels,
|
838 |
+
filter_channels,
|
839 |
+
n_heads,
|
840 |
+
n_layers_trans_flow,
|
841 |
+
5,
|
842 |
+
p_dropout,
|
843 |
+
n_flow_layer,
|
844 |
+
gin_channels=gin_channels,
|
845 |
+
share_parameter=flow_share_parameter,
|
846 |
+
)
|
847 |
+
else:
|
848 |
+
self.flow = ResidualCouplingBlock(
|
849 |
+
inter_channels,
|
850 |
+
hidden_channels,
|
851 |
+
5,
|
852 |
+
1,
|
853 |
+
n_flow_layer,
|
854 |
+
gin_channels=gin_channels,
|
855 |
+
)
|
856 |
+
self.sdp = StochasticDurationPredictor(
|
857 |
+
hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels
|
858 |
+
)
|
859 |
+
self.dp = DurationPredictor(
|
860 |
+
hidden_channels, 256, 3, 0.5, gin_channels=gin_channels
|
861 |
+
)
|
862 |
+
|
863 |
+
if n_speakers > 1:
|
864 |
+
self.emb_g = nn.Embedding(n_speakers, gin_channels)
|
865 |
+
else:
|
866 |
+
self.ref_enc = ReferenceEncoder(spec_channels, gin_channels)
|
867 |
+
|
868 |
+
def forward(
|
869 |
+
self,
|
870 |
+
x,
|
871 |
+
x_lengths,
|
872 |
+
y,
|
873 |
+
y_lengths,
|
874 |
+
sid,
|
875 |
+
tone,
|
876 |
+
language,
|
877 |
+
bert,
|
878 |
+
ja_bert,
|
879 |
+
en_bert,
|
880 |
+
):
|
881 |
+
if self.n_speakers > 0:
|
882 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
883 |
+
else:
|
884 |
+
g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
|
885 |
+
x, m_p, logs_p, x_mask = self.enc_p(
|
886 |
+
x, x_lengths, tone, language, bert, ja_bert, en_bert, g=g
|
887 |
+
)
|
888 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
889 |
+
z_p = self.flow(z, y_mask, g=g)
|
890 |
+
|
891 |
+
with torch.no_grad():
|
892 |
+
# negative cross-entropy
|
893 |
+
s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
|
894 |
+
neg_cent1 = torch.sum(
|
895 |
+
-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True
|
896 |
+
) # [b, 1, t_s]
|
897 |
+
neg_cent2 = torch.matmul(
|
898 |
+
-0.5 * (z_p**2).transpose(1, 2), s_p_sq_r
|
899 |
+
) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
|
900 |
+
neg_cent3 = torch.matmul(
|
901 |
+
z_p.transpose(1, 2), (m_p * s_p_sq_r)
|
902 |
+
) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
|
903 |
+
neg_cent4 = torch.sum(
|
904 |
+
-0.5 * (m_p**2) * s_p_sq_r, [1], keepdim=True
|
905 |
+
) # [b, 1, t_s]
|
906 |
+
neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
|
907 |
+
if self.use_noise_scaled_mas:
|
908 |
+
epsilon = (
|
909 |
+
torch.std(neg_cent)
|
910 |
+
* torch.randn_like(neg_cent)
|
911 |
+
* self.current_mas_noise_scale
|
912 |
+
)
|
913 |
+
neg_cent = neg_cent + epsilon
|
914 |
+
|
915 |
+
attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
|
916 |
+
attn = (
|
917 |
+
monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1))
|
918 |
+
.unsqueeze(1)
|
919 |
+
.detach()
|
920 |
+
)
|
921 |
+
|
922 |
+
w = attn.sum(2)
|
923 |
+
|
924 |
+
l_length_sdp = self.sdp(x, x_mask, w, g=g)
|
925 |
+
l_length_sdp = l_length_sdp / torch.sum(x_mask)
|
926 |
+
|
927 |
+
logw_ = torch.log(w + 1e-6) * x_mask
|
928 |
+
logw = self.dp(x, x_mask, g=g)
|
929 |
+
l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(
|
930 |
+
x_mask
|
931 |
+
) # for averaging
|
932 |
+
|
933 |
+
l_length = l_length_dp + l_length_sdp
|
934 |
+
|
935 |
+
# expand prior
|
936 |
+
m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
|
937 |
+
logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
|
938 |
+
|
939 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
940 |
+
z, y_lengths, self.segment_size
|
941 |
+
)
|
942 |
+
o = self.dec(z_slice, g=g)
|
943 |
+
return (
|
944 |
+
o,
|
945 |
+
l_length,
|
946 |
+
attn,
|
947 |
+
ids_slice,
|
948 |
+
x_mask,
|
949 |
+
y_mask,
|
950 |
+
(z, z_p, m_p, logs_p, m_q, logs_q),
|
951 |
+
(x, logw, logw_),
|
952 |
+
)
|
953 |
+
|
954 |
+
def infer(
|
955 |
+
self,
|
956 |
+
x,
|
957 |
+
x_lengths,
|
958 |
+
sid,
|
959 |
+
tone,
|
960 |
+
language,
|
961 |
+
bert,
|
962 |
+
ja_bert,
|
963 |
+
en_bert,
|
964 |
+
noise_scale=0.667,
|
965 |
+
length_scale=1,
|
966 |
+
noise_scale_w=0.8,
|
967 |
+
max_len=None,
|
968 |
+
sdp_ratio=0,
|
969 |
+
y=None,
|
970 |
+
):
|
971 |
+
# x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert)
|
972 |
+
# g = self.gst(y)
|
973 |
+
if self.n_speakers > 0:
|
974 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
975 |
+
else:
|
976 |
+
g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
|
977 |
+
x, m_p, logs_p, x_mask = self.enc_p(
|
978 |
+
x, x_lengths, tone, language, bert, ja_bert, en_bert, g=g
|
979 |
+
)
|
980 |
+
logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (
|
981 |
+
sdp_ratio
|
982 |
+
) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio)
|
983 |
+
w = torch.exp(logw) * x_mask * length_scale
|
984 |
+
w_ceil = torch.ceil(w)
|
985 |
+
y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
|
986 |
+
y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(
|
987 |
+
x_mask.dtype
|
988 |
+
)
|
989 |
+
attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
|
990 |
+
attn = commons.generate_path(w_ceil, attn_mask)
|
991 |
+
|
992 |
+
m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(
|
993 |
+
1, 2
|
994 |
+
) # [b, t', t], [b, t, d] -> [b, d, t']
|
995 |
+
logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(
|
996 |
+
1, 2
|
997 |
+
) # [b, t', t], [b, t, d] -> [b, d, t']
|
998 |
+
|
999 |
+
z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
|
1000 |
+
z = self.flow(z_p, y_mask, g=g, reverse=True)
|
1001 |
+
o = self.dec((z * y_mask)[:, :, :max_len], g=g)
|
1002 |
+
return o, attn, y_mask, (z, z_p, m_p, logs_p)
|
modules.py
ADDED
@@ -0,0 +1,597 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import torch
|
3 |
+
from torch import nn
|
4 |
+
from torch.nn import functional as F
|
5 |
+
|
6 |
+
from torch.nn import Conv1d
|
7 |
+
from torch.nn.utils import weight_norm, remove_weight_norm
|
8 |
+
|
9 |
+
import commons
|
10 |
+
from commons import init_weights, get_padding
|
11 |
+
from transforms import piecewise_rational_quadratic_transform
|
12 |
+
from attentions import Encoder
|
13 |
+
|
14 |
+
LRELU_SLOPE = 0.1
|
15 |
+
|
16 |
+
|
17 |
+
class LayerNorm(nn.Module):
|
18 |
+
def __init__(self, channels, eps=1e-5):
|
19 |
+
super().__init__()
|
20 |
+
self.channels = channels
|
21 |
+
self.eps = eps
|
22 |
+
|
23 |
+
self.gamma = nn.Parameter(torch.ones(channels))
|
24 |
+
self.beta = nn.Parameter(torch.zeros(channels))
|
25 |
+
|
26 |
+
def forward(self, x):
|
27 |
+
x = x.transpose(1, -1)
|
28 |
+
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
29 |
+
return x.transpose(1, -1)
|
30 |
+
|
31 |
+
|
32 |
+
class ConvReluNorm(nn.Module):
|
33 |
+
def __init__(
|
34 |
+
self,
|
35 |
+
in_channels,
|
36 |
+
hidden_channels,
|
37 |
+
out_channels,
|
38 |
+
kernel_size,
|
39 |
+
n_layers,
|
40 |
+
p_dropout,
|
41 |
+
):
|
42 |
+
super().__init__()
|
43 |
+
self.in_channels = in_channels
|
44 |
+
self.hidden_channels = hidden_channels
|
45 |
+
self.out_channels = out_channels
|
46 |
+
self.kernel_size = kernel_size
|
47 |
+
self.n_layers = n_layers
|
48 |
+
self.p_dropout = p_dropout
|
49 |
+
assert n_layers > 1, "Number of layers should be larger than 0."
|
50 |
+
|
51 |
+
self.conv_layers = nn.ModuleList()
|
52 |
+
self.norm_layers = nn.ModuleList()
|
53 |
+
self.conv_layers.append(
|
54 |
+
nn.Conv1d(
|
55 |
+
in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
|
56 |
+
)
|
57 |
+
)
|
58 |
+
self.norm_layers.append(LayerNorm(hidden_channels))
|
59 |
+
self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
|
60 |
+
for _ in range(n_layers - 1):
|
61 |
+
self.conv_layers.append(
|
62 |
+
nn.Conv1d(
|
63 |
+
hidden_channels,
|
64 |
+
hidden_channels,
|
65 |
+
kernel_size,
|
66 |
+
padding=kernel_size // 2,
|
67 |
+
)
|
68 |
+
)
|
69 |
+
self.norm_layers.append(LayerNorm(hidden_channels))
|
70 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
|
71 |
+
self.proj.weight.data.zero_()
|
72 |
+
self.proj.bias.data.zero_()
|
73 |
+
|
74 |
+
def forward(self, x, x_mask):
|
75 |
+
x_org = x
|
76 |
+
for i in range(self.n_layers):
|
77 |
+
x = self.conv_layers[i](x * x_mask)
|
78 |
+
x = self.norm_layers[i](x)
|
79 |
+
x = self.relu_drop(x)
|
80 |
+
x = x_org + self.proj(x)
|
81 |
+
return x * x_mask
|
82 |
+
|
83 |
+
|
84 |
+
class DDSConv(nn.Module):
|
85 |
+
"""
|
86 |
+
Dialted and Depth-Separable Convolution
|
87 |
+
"""
|
88 |
+
|
89 |
+
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
|
90 |
+
super().__init__()
|
91 |
+
self.channels = channels
|
92 |
+
self.kernel_size = kernel_size
|
93 |
+
self.n_layers = n_layers
|
94 |
+
self.p_dropout = p_dropout
|
95 |
+
|
96 |
+
self.drop = nn.Dropout(p_dropout)
|
97 |
+
self.convs_sep = nn.ModuleList()
|
98 |
+
self.convs_1x1 = nn.ModuleList()
|
99 |
+
self.norms_1 = nn.ModuleList()
|
100 |
+
self.norms_2 = nn.ModuleList()
|
101 |
+
for i in range(n_layers):
|
102 |
+
dilation = kernel_size**i
|
103 |
+
padding = (kernel_size * dilation - dilation) // 2
|
104 |
+
self.convs_sep.append(
|
105 |
+
nn.Conv1d(
|
106 |
+
channels,
|
107 |
+
channels,
|
108 |
+
kernel_size,
|
109 |
+
groups=channels,
|
110 |
+
dilation=dilation,
|
111 |
+
padding=padding,
|
112 |
+
)
|
113 |
+
)
|
114 |
+
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
|
115 |
+
self.norms_1.append(LayerNorm(channels))
|
116 |
+
self.norms_2.append(LayerNorm(channels))
|
117 |
+
|
118 |
+
def forward(self, x, x_mask, g=None):
|
119 |
+
if g is not None:
|
120 |
+
x = x + g
|
121 |
+
for i in range(self.n_layers):
|
122 |
+
y = self.convs_sep[i](x * x_mask)
|
123 |
+
y = self.norms_1[i](y)
|
124 |
+
y = F.gelu(y)
|
125 |
+
y = self.convs_1x1[i](y)
|
126 |
+
y = self.norms_2[i](y)
|
127 |
+
y = F.gelu(y)
|
128 |
+
y = self.drop(y)
|
129 |
+
x = x + y
|
130 |
+
return x * x_mask
|
131 |
+
|
132 |
+
|
133 |
+
class WN(torch.nn.Module):
|
134 |
+
def __init__(
|
135 |
+
self,
|
136 |
+
hidden_channels,
|
137 |
+
kernel_size,
|
138 |
+
dilation_rate,
|
139 |
+
n_layers,
|
140 |
+
gin_channels=0,
|
141 |
+
p_dropout=0,
|
142 |
+
):
|
143 |
+
super(WN, self).__init__()
|
144 |
+
assert kernel_size % 2 == 1
|
145 |
+
self.hidden_channels = hidden_channels
|
146 |
+
self.kernel_size = (kernel_size,)
|
147 |
+
self.dilation_rate = dilation_rate
|
148 |
+
self.n_layers = n_layers
|
149 |
+
self.gin_channels = gin_channels
|
150 |
+
self.p_dropout = p_dropout
|
151 |
+
|
152 |
+
self.in_layers = torch.nn.ModuleList()
|
153 |
+
self.res_skip_layers = torch.nn.ModuleList()
|
154 |
+
self.drop = nn.Dropout(p_dropout)
|
155 |
+
|
156 |
+
if gin_channels != 0:
|
157 |
+
cond_layer = torch.nn.Conv1d(
|
158 |
+
gin_channels, 2 * hidden_channels * n_layers, 1
|
159 |
+
)
|
160 |
+
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
|
161 |
+
|
162 |
+
for i in range(n_layers):
|
163 |
+
dilation = dilation_rate**i
|
164 |
+
padding = int((kernel_size * dilation - dilation) / 2)
|
165 |
+
in_layer = torch.nn.Conv1d(
|
166 |
+
hidden_channels,
|
167 |
+
2 * hidden_channels,
|
168 |
+
kernel_size,
|
169 |
+
dilation=dilation,
|
170 |
+
padding=padding,
|
171 |
+
)
|
172 |
+
in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
|
173 |
+
self.in_layers.append(in_layer)
|
174 |
+
|
175 |
+
# last one is not necessary
|
176 |
+
if i < n_layers - 1:
|
177 |
+
res_skip_channels = 2 * hidden_channels
|
178 |
+
else:
|
179 |
+
res_skip_channels = hidden_channels
|
180 |
+
|
181 |
+
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
|
182 |
+
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
|
183 |
+
self.res_skip_layers.append(res_skip_layer)
|
184 |
+
|
185 |
+
def forward(self, x, x_mask, g=None, **kwargs):
|
186 |
+
output = torch.zeros_like(x)
|
187 |
+
n_channels_tensor = torch.IntTensor([self.hidden_channels])
|
188 |
+
|
189 |
+
if g is not None:
|
190 |
+
g = self.cond_layer(g)
|
191 |
+
|
192 |
+
for i in range(self.n_layers):
|
193 |
+
x_in = self.in_layers[i](x)
|
194 |
+
if g is not None:
|
195 |
+
cond_offset = i * 2 * self.hidden_channels
|
196 |
+
g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
|
197 |
+
else:
|
198 |
+
g_l = torch.zeros_like(x_in)
|
199 |
+
|
200 |
+
acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
|
201 |
+
acts = self.drop(acts)
|
202 |
+
|
203 |
+
res_skip_acts = self.res_skip_layers[i](acts)
|
204 |
+
if i < self.n_layers - 1:
|
205 |
+
res_acts = res_skip_acts[:, : self.hidden_channels, :]
|
206 |
+
x = (x + res_acts) * x_mask
|
207 |
+
output = output + res_skip_acts[:, self.hidden_channels :, :]
|
208 |
+
else:
|
209 |
+
output = output + res_skip_acts
|
210 |
+
return output * x_mask
|
211 |
+
|
212 |
+
def remove_weight_norm(self):
|
213 |
+
if self.gin_channels != 0:
|
214 |
+
torch.nn.utils.remove_weight_norm(self.cond_layer)
|
215 |
+
for l in self.in_layers:
|
216 |
+
torch.nn.utils.remove_weight_norm(l)
|
217 |
+
for l in self.res_skip_layers:
|
218 |
+
torch.nn.utils.remove_weight_norm(l)
|
219 |
+
|
220 |
+
|
221 |
+
class ResBlock1(torch.nn.Module):
|
222 |
+
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
|
223 |
+
super(ResBlock1, self).__init__()
|
224 |
+
self.convs1 = nn.ModuleList(
|
225 |
+
[
|
226 |
+
weight_norm(
|
227 |
+
Conv1d(
|
228 |
+
channels,
|
229 |
+
channels,
|
230 |
+
kernel_size,
|
231 |
+
1,
|
232 |
+
dilation=dilation[0],
|
233 |
+
padding=get_padding(kernel_size, dilation[0]),
|
234 |
+
)
|
235 |
+
),
|
236 |
+
weight_norm(
|
237 |
+
Conv1d(
|
238 |
+
channels,
|
239 |
+
channels,
|
240 |
+
kernel_size,
|
241 |
+
1,
|
242 |
+
dilation=dilation[1],
|
243 |
+
padding=get_padding(kernel_size, dilation[1]),
|
244 |
+
)
|
245 |
+
),
|
246 |
+
weight_norm(
|
247 |
+
Conv1d(
|
248 |
+
channels,
|
249 |
+
channels,
|
250 |
+
kernel_size,
|
251 |
+
1,
|
252 |
+
dilation=dilation[2],
|
253 |
+
padding=get_padding(kernel_size, dilation[2]),
|
254 |
+
)
|
255 |
+
),
|
256 |
+
]
|
257 |
+
)
|
258 |
+
self.convs1.apply(init_weights)
|
259 |
+
|
260 |
+
self.convs2 = nn.ModuleList(
|
261 |
+
[
|
262 |
+
weight_norm(
|
263 |
+
Conv1d(
|
264 |
+
channels,
|
265 |
+
channels,
|
266 |
+
kernel_size,
|
267 |
+
1,
|
268 |
+
dilation=1,
|
269 |
+
padding=get_padding(kernel_size, 1),
|
270 |
+
)
|
271 |
+
),
|
272 |
+
weight_norm(
|
273 |
+
Conv1d(
|
274 |
+
channels,
|
275 |
+
channels,
|
276 |
+
kernel_size,
|
277 |
+
1,
|
278 |
+
dilation=1,
|
279 |
+
padding=get_padding(kernel_size, 1),
|
280 |
+
)
|
281 |
+
),
|
282 |
+
weight_norm(
|
283 |
+
Conv1d(
|
284 |
+
channels,
|
285 |
+
channels,
|
286 |
+
kernel_size,
|
287 |
+
1,
|
288 |
+
dilation=1,
|
289 |
+
padding=get_padding(kernel_size, 1),
|
290 |
+
)
|
291 |
+
),
|
292 |
+
]
|
293 |
+
)
|
294 |
+
self.convs2.apply(init_weights)
|
295 |
+
|
296 |
+
def forward(self, x, x_mask=None):
|
297 |
+
for c1, c2 in zip(self.convs1, self.convs2):
|
298 |
+
xt = F.leaky_relu(x, LRELU_SLOPE)
|
299 |
+
if x_mask is not None:
|
300 |
+
xt = xt * x_mask
|
301 |
+
xt = c1(xt)
|
302 |
+
xt = F.leaky_relu(xt, LRELU_SLOPE)
|
303 |
+
if x_mask is not None:
|
304 |
+
xt = xt * x_mask
|
305 |
+
xt = c2(xt)
|
306 |
+
x = xt + x
|
307 |
+
if x_mask is not None:
|
308 |
+
x = x * x_mask
|
309 |
+
return x
|
310 |
+
|
311 |
+
def remove_weight_norm(self):
|
312 |
+
for l in self.convs1:
|
313 |
+
remove_weight_norm(l)
|
314 |
+
for l in self.convs2:
|
315 |
+
remove_weight_norm(l)
|
316 |
+
|
317 |
+
|
318 |
+
class ResBlock2(torch.nn.Module):
|
319 |
+
def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
|
320 |
+
super(ResBlock2, self).__init__()
|
321 |
+
self.convs = nn.ModuleList(
|
322 |
+
[
|
323 |
+
weight_norm(
|
324 |
+
Conv1d(
|
325 |
+
channels,
|
326 |
+
channels,
|
327 |
+
kernel_size,
|
328 |
+
1,
|
329 |
+
dilation=dilation[0],
|
330 |
+
padding=get_padding(kernel_size, dilation[0]),
|
331 |
+
)
|
332 |
+
),
|
333 |
+
weight_norm(
|
334 |
+
Conv1d(
|
335 |
+
channels,
|
336 |
+
channels,
|
337 |
+
kernel_size,
|
338 |
+
1,
|
339 |
+
dilation=dilation[1],
|
340 |
+
padding=get_padding(kernel_size, dilation[1]),
|
341 |
+
)
|
342 |
+
),
|
343 |
+
]
|
344 |
+
)
|
345 |
+
self.convs.apply(init_weights)
|
346 |
+
|
347 |
+
def forward(self, x, x_mask=None):
|
348 |
+
for c in self.convs:
|
349 |
+
xt = F.leaky_relu(x, LRELU_SLOPE)
|
350 |
+
if x_mask is not None:
|
351 |
+
xt = xt * x_mask
|
352 |
+
xt = c(xt)
|
353 |
+
x = xt + x
|
354 |
+
if x_mask is not None:
|
355 |
+
x = x * x_mask
|
356 |
+
return x
|
357 |
+
|
358 |
+
def remove_weight_norm(self):
|
359 |
+
for l in self.convs:
|
360 |
+
remove_weight_norm(l)
|
361 |
+
|
362 |
+
|
363 |
+
class Log(nn.Module):
|
364 |
+
def forward(self, x, x_mask, reverse=False, **kwargs):
|
365 |
+
if not reverse:
|
366 |
+
y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
|
367 |
+
logdet = torch.sum(-y, [1, 2])
|
368 |
+
return y, logdet
|
369 |
+
else:
|
370 |
+
x = torch.exp(x) * x_mask
|
371 |
+
return x
|
372 |
+
|
373 |
+
|
374 |
+
class Flip(nn.Module):
|
375 |
+
def forward(self, x, *args, reverse=False, **kwargs):
|
376 |
+
x = torch.flip(x, [1])
|
377 |
+
if not reverse:
|
378 |
+
logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
|
379 |
+
return x, logdet
|
380 |
+
else:
|
381 |
+
return x
|
382 |
+
|
383 |
+
|
384 |
+
class ElementwiseAffine(nn.Module):
|
385 |
+
def __init__(self, channels):
|
386 |
+
super().__init__()
|
387 |
+
self.channels = channels
|
388 |
+
self.m = nn.Parameter(torch.zeros(channels, 1))
|
389 |
+
self.logs = nn.Parameter(torch.zeros(channels, 1))
|
390 |
+
|
391 |
+
def forward(self, x, x_mask, reverse=False, **kwargs):
|
392 |
+
if not reverse:
|
393 |
+
y = self.m + torch.exp(self.logs) * x
|
394 |
+
y = y * x_mask
|
395 |
+
logdet = torch.sum(self.logs * x_mask, [1, 2])
|
396 |
+
return y, logdet
|
397 |
+
else:
|
398 |
+
x = (x - self.m) * torch.exp(-self.logs) * x_mask
|
399 |
+
return x
|
400 |
+
|
401 |
+
|
402 |
+
class ResidualCouplingLayer(nn.Module):
|
403 |
+
def __init__(
|
404 |
+
self,
|
405 |
+
channels,
|
406 |
+
hidden_channels,
|
407 |
+
kernel_size,
|
408 |
+
dilation_rate,
|
409 |
+
n_layers,
|
410 |
+
p_dropout=0,
|
411 |
+
gin_channels=0,
|
412 |
+
mean_only=False,
|
413 |
+
):
|
414 |
+
assert channels % 2 == 0, "channels should be divisible by 2"
|
415 |
+
super().__init__()
|
416 |
+
self.channels = channels
|
417 |
+
self.hidden_channels = hidden_channels
|
418 |
+
self.kernel_size = kernel_size
|
419 |
+
self.dilation_rate = dilation_rate
|
420 |
+
self.n_layers = n_layers
|
421 |
+
self.half_channels = channels // 2
|
422 |
+
self.mean_only = mean_only
|
423 |
+
|
424 |
+
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
425 |
+
self.enc = WN(
|
426 |
+
hidden_channels,
|
427 |
+
kernel_size,
|
428 |
+
dilation_rate,
|
429 |
+
n_layers,
|
430 |
+
p_dropout=p_dropout,
|
431 |
+
gin_channels=gin_channels,
|
432 |
+
)
|
433 |
+
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
434 |
+
self.post.weight.data.zero_()
|
435 |
+
self.post.bias.data.zero_()
|
436 |
+
|
437 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
438 |
+
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
|
439 |
+
h = self.pre(x0) * x_mask
|
440 |
+
h = self.enc(h, x_mask, g=g)
|
441 |
+
stats = self.post(h) * x_mask
|
442 |
+
if not self.mean_only:
|
443 |
+
m, logs = torch.split(stats, [self.half_channels] * 2, 1)
|
444 |
+
else:
|
445 |
+
m = stats
|
446 |
+
logs = torch.zeros_like(m)
|
447 |
+
|
448 |
+
if not reverse:
|
449 |
+
x1 = m + x1 * torch.exp(logs) * x_mask
|
450 |
+
x = torch.cat([x0, x1], 1)
|
451 |
+
logdet = torch.sum(logs, [1, 2])
|
452 |
+
return x, logdet
|
453 |
+
else:
|
454 |
+
x1 = (x1 - m) * torch.exp(-logs) * x_mask
|
455 |
+
x = torch.cat([x0, x1], 1)
|
456 |
+
return x
|
457 |
+
|
458 |
+
|
459 |
+
class ConvFlow(nn.Module):
|
460 |
+
def __init__(
|
461 |
+
self,
|
462 |
+
in_channels,
|
463 |
+
filter_channels,
|
464 |
+
kernel_size,
|
465 |
+
n_layers,
|
466 |
+
num_bins=10,
|
467 |
+
tail_bound=5.0,
|
468 |
+
):
|
469 |
+
super().__init__()
|
470 |
+
self.in_channels = in_channels
|
471 |
+
self.filter_channels = filter_channels
|
472 |
+
self.kernel_size = kernel_size
|
473 |
+
self.n_layers = n_layers
|
474 |
+
self.num_bins = num_bins
|
475 |
+
self.tail_bound = tail_bound
|
476 |
+
self.half_channels = in_channels // 2
|
477 |
+
|
478 |
+
self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
|
479 |
+
self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
|
480 |
+
self.proj = nn.Conv1d(
|
481 |
+
filter_channels, self.half_channels * (num_bins * 3 - 1), 1
|
482 |
+
)
|
483 |
+
self.proj.weight.data.zero_()
|
484 |
+
self.proj.bias.data.zero_()
|
485 |
+
|
486 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
487 |
+
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
|
488 |
+
h = self.pre(x0)
|
489 |
+
h = self.convs(h, x_mask, g=g)
|
490 |
+
h = self.proj(h) * x_mask
|
491 |
+
|
492 |
+
b, c, t = x0.shape
|
493 |
+
h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
|
494 |
+
|
495 |
+
unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
|
496 |
+
unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
|
497 |
+
self.filter_channels
|
498 |
+
)
|
499 |
+
unnormalized_derivatives = h[..., 2 * self.num_bins :]
|
500 |
+
|
501 |
+
x1, logabsdet = piecewise_rational_quadratic_transform(
|
502 |
+
x1,
|
503 |
+
unnormalized_widths,
|
504 |
+
unnormalized_heights,
|
505 |
+
unnormalized_derivatives,
|
506 |
+
inverse=reverse,
|
507 |
+
tails="linear",
|
508 |
+
tail_bound=self.tail_bound,
|
509 |
+
)
|
510 |
+
|
511 |
+
x = torch.cat([x0, x1], 1) * x_mask
|
512 |
+
logdet = torch.sum(logabsdet * x_mask, [1, 2])
|
513 |
+
if not reverse:
|
514 |
+
return x, logdet
|
515 |
+
else:
|
516 |
+
return x
|
517 |
+
|
518 |
+
|
519 |
+
class TransformerCouplingLayer(nn.Module):
|
520 |
+
def __init__(
|
521 |
+
self,
|
522 |
+
channels,
|
523 |
+
hidden_channels,
|
524 |
+
kernel_size,
|
525 |
+
n_layers,
|
526 |
+
n_heads,
|
527 |
+
p_dropout=0,
|
528 |
+
filter_channels=0,
|
529 |
+
mean_only=False,
|
530 |
+
wn_sharing_parameter=None,
|
531 |
+
gin_channels=0,
|
532 |
+
):
|
533 |
+
assert channels % 2 == 0, "channels should be divisible by 2"
|
534 |
+
super().__init__()
|
535 |
+
self.channels = channels
|
536 |
+
self.hidden_channels = hidden_channels
|
537 |
+
self.kernel_size = kernel_size
|
538 |
+
self.n_layers = n_layers
|
539 |
+
self.half_channels = channels // 2
|
540 |
+
self.mean_only = mean_only
|
541 |
+
|
542 |
+
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
543 |
+
self.enc = (
|
544 |
+
Encoder(
|
545 |
+
hidden_channels,
|
546 |
+
filter_channels,
|
547 |
+
n_heads,
|
548 |
+
n_layers,
|
549 |
+
kernel_size,
|
550 |
+
p_dropout,
|
551 |
+
isflow=True,
|
552 |
+
gin_channels=gin_channels,
|
553 |
+
)
|
554 |
+
if wn_sharing_parameter is None
|
555 |
+
else wn_sharing_parameter
|
556 |
+
)
|
557 |
+
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
558 |
+
self.post.weight.data.zero_()
|
559 |
+
self.post.bias.data.zero_()
|
560 |
+
|
561 |
+
def forward(self, x, x_mask, g=None, reverse=False):
|
562 |
+
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
|
563 |
+
h = self.pre(x0) * x_mask
|
564 |
+
h = self.enc(h, x_mask, g=g)
|
565 |
+
stats = self.post(h) * x_mask
|
566 |
+
if not self.mean_only:
|
567 |
+
m, logs = torch.split(stats, [self.half_channels] * 2, 1)
|
568 |
+
else:
|
569 |
+
m = stats
|
570 |
+
logs = torch.zeros_like(m)
|
571 |
+
|
572 |
+
if not reverse:
|
573 |
+
x1 = m + x1 * torch.exp(logs) * x_mask
|
574 |
+
x = torch.cat([x0, x1], 1)
|
575 |
+
logdet = torch.sum(logs, [1, 2])
|
576 |
+
return x, logdet
|
577 |
+
else:
|
578 |
+
x1 = (x1 - m) * torch.exp(-logs) * x_mask
|
579 |
+
x = torch.cat([x0, x1], 1)
|
580 |
+
return x
|
581 |
+
|
582 |
+
x1, logabsdet = piecewise_rational_quadratic_transform(
|
583 |
+
x1,
|
584 |
+
unnormalized_widths,
|
585 |
+
unnormalized_heights,
|
586 |
+
unnormalized_derivatives,
|
587 |
+
inverse=reverse,
|
588 |
+
tails="linear",
|
589 |
+
tail_bound=self.tail_bound,
|
590 |
+
)
|
591 |
+
|
592 |
+
x = torch.cat([x0, x1], 1) * x_mask
|
593 |
+
logdet = torch.sum(logabsdet * x_mask, [1, 2])
|
594 |
+
if not reverse:
|
595 |
+
return x, logdet
|
596 |
+
else:
|
597 |
+
return x
|
requirements.txt
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
amfm_decompy
|
2 |
+
av
|
3 |
+
cmudict
|
4 |
+
cn2an
|
5 |
+
fugashi
|
6 |
+
g2p_en
|
7 |
+
GPUtil
|
8 |
+
gradio
|
9 |
+
jaconv
|
10 |
+
jieba
|
11 |
+
librosa==0.9.1
|
12 |
+
loguru
|
13 |
+
matplotlib
|
14 |
+
mecab-python3
|
15 |
+
numpy
|
16 |
+
numba
|
17 |
+
num2words
|
18 |
+
opencc==1.1.6
|
19 |
+
phonemizer
|
20 |
+
psutil
|
21 |
+
pydub
|
22 |
+
pypinyin
|
23 |
+
PyYAML
|
24 |
+
pyopenjtalk; sys_platform == 'linux'
|
25 |
+
openjtalk; sys_platform != 'linux'
|
26 |
+
requests
|
27 |
+
sentencepiece
|
28 |
+
scipy
|
29 |
+
tensorboard
|
30 |
+
torch
|
31 |
+
torchvision
|
32 |
+
transformers
|
33 |
+
Unidecode
|
34 |
+
unidic-lite
|
35 |
+
vector_quantize_pytorch
|
server.py
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from io import BytesIO
|
2 |
+
from typing import Dict, List
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from av import open as avopen
|
6 |
+
from flask import Flask, request, Response
|
7 |
+
from scipy.io import wavfile
|
8 |
+
|
9 |
+
import utils
|
10 |
+
from config import config
|
11 |
+
from infer import infer, get_net_g, latest_version
|
12 |
+
|
13 |
+
# Flask Init
|
14 |
+
app = Flask(__name__)
|
15 |
+
app.config["JSON_AS_ASCII"] = False
|
16 |
+
|
17 |
+
|
18 |
+
def replace_punctuation(text, i=2):
|
19 |
+
punctuation = ",。?!"
|
20 |
+
for char in punctuation:
|
21 |
+
text = text.replace(char, char * i)
|
22 |
+
return text
|
23 |
+
|
24 |
+
|
25 |
+
def wav2(i, o, format):
|
26 |
+
inp = avopen(i, "rb")
|
27 |
+
out = avopen(o, "wb", format=format)
|
28 |
+
if format == "ogg":
|
29 |
+
format = "libvorbis"
|
30 |
+
|
31 |
+
ostream = out.add_stream(format)
|
32 |
+
|
33 |
+
for frame in inp.decode(audio=0):
|
34 |
+
for p in ostream.encode(frame):
|
35 |
+
out.mux(p)
|
36 |
+
|
37 |
+
for p in ostream.encode(None):
|
38 |
+
out.mux(p)
|
39 |
+
|
40 |
+
out.close()
|
41 |
+
inp.close()
|
42 |
+
|
43 |
+
|
44 |
+
net_g_List = []
|
45 |
+
hps_List = []
|
46 |
+
# 模型角色字典
|
47 |
+
# 使用方法 chr_name = chrsMap[model_id][chr_id]
|
48 |
+
chrsMap: List[Dict[int, str]] = list()
|
49 |
+
|
50 |
+
# 加载模型
|
51 |
+
models = config.server_config.models
|
52 |
+
for model in models:
|
53 |
+
hps_List.append(utils.get_hparams_from_file(model["config"]))
|
54 |
+
# 添加角色字典
|
55 |
+
chrsMap.append(dict())
|
56 |
+
for name, cid in hps_List[-1].data.spk2id.items():
|
57 |
+
chrsMap[-1][cid] = name
|
58 |
+
version = (hps_List[-1].version if hasattr(hps_List[-1], "version") else latest_version)
|
59 |
+
net_g_List.append(get_net_g(model_path=model["model"], device=model["device"], hps=hps_List[-1], ))
|
60 |
+
|
61 |
+
|
62 |
+
@app.route("/")
|
63 |
+
def main():
|
64 |
+
try:
|
65 |
+
model = int(request.args.get("model"))
|
66 |
+
speaker = request.args.get("speaker", "") # 指定人物名
|
67 |
+
speaker_id = request.args.get("speaker_id", None) # 直接指定id
|
68 |
+
text = request.args.get("text").replace("/n", "")
|
69 |
+
sdp_ratio = float(request.args.get("sdp_ratio", 0.2))
|
70 |
+
noise = float(request.args.get("noise", 0.5))
|
71 |
+
noisew = float(request.args.get("noisew", 0.6))
|
72 |
+
length = float(request.args.get("length", 1.2))
|
73 |
+
language = request.args.get("language")
|
74 |
+
if length >= 2:
|
75 |
+
return "Too big length"
|
76 |
+
if len(text) >= 250:
|
77 |
+
return "Too long text"
|
78 |
+
fmt = request.args.get("format", "wav")
|
79 |
+
if None in (speaker, text):
|
80 |
+
return "Missing Parameter"
|
81 |
+
if fmt not in ("mp3", "wav", "ogg"):
|
82 |
+
return "Invalid Format"
|
83 |
+
if language not in ("SH", "ZH"):
|
84 |
+
return "Invalid language"
|
85 |
+
except:
|
86 |
+
return "Invalid Parameter"
|
87 |
+
|
88 |
+
if speaker_id is not None:
|
89 |
+
if speaker_id.isdigit():
|
90 |
+
speaker = chrsMap[model][int(speaker_id)]
|
91 |
+
|
92 |
+
with torch.no_grad():
|
93 |
+
audio = infer(
|
94 |
+
text=text,
|
95 |
+
sdp_ratio=sdp_ratio,
|
96 |
+
noise_scale=noise,
|
97 |
+
noise_scale_w=noisew,
|
98 |
+
length_scale=length,
|
99 |
+
sid=speaker,
|
100 |
+
language=models[model]["language"],
|
101 |
+
hps=hps_List[model],
|
102 |
+
net_g=net_g_List[model],
|
103 |
+
device=models[model]["device"],
|
104 |
+
)
|
105 |
+
|
106 |
+
with BytesIO() as wav:
|
107 |
+
wavfile.write(wav, hps_List[model].data.sampling_rate, audio)
|
108 |
+
torch.cuda.empty_cache()
|
109 |
+
if fmt == "wav":
|
110 |
+
return Response(wav.getvalue(), mimetype="audio/wav")
|
111 |
+
wav.seek(0, 0)
|
112 |
+
with BytesIO() as ofp:
|
113 |
+
wav2(wav, ofp, fmt)
|
114 |
+
return Response(
|
115 |
+
ofp.getvalue(), mimetype="audio/mpeg" if fmt == "mp3" else "audio/ogg"
|
116 |
+
)
|
117 |
+
|
118 |
+
|
119 |
+
if __name__ == "__main__":
|
120 |
+
app.run(port=config.server_config.port)
|
server_fastapi.py
ADDED
@@ -0,0 +1,499 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
api服务 多版本多模型 fastapi实现
|
3 |
+
"""
|
4 |
+
import gc
|
5 |
+
import logging
|
6 |
+
import os
|
7 |
+
import random
|
8 |
+
import webbrowser
|
9 |
+
from io import BytesIO
|
10 |
+
from typing import Dict, Optional, List
|
11 |
+
|
12 |
+
import GPUtil
|
13 |
+
import psutil
|
14 |
+
import torch
|
15 |
+
import uvicorn
|
16 |
+
from fastapi import FastAPI, Query
|
17 |
+
from fastapi.responses import Response, FileResponse
|
18 |
+
from fastapi.staticfiles import StaticFiles
|
19 |
+
from loguru import logger
|
20 |
+
from scipy.io import wavfile
|
21 |
+
|
22 |
+
import tools.translate as trans
|
23 |
+
import utils
|
24 |
+
from config import config
|
25 |
+
from infer import infer, get_net_g, latest_version
|
26 |
+
|
27 |
+
|
28 |
+
class Model:
|
29 |
+
"""模型封装类"""
|
30 |
+
|
31 |
+
def __init__(self, config_path: str, model_path: str, device: str, language: str):
|
32 |
+
self.config_path: str = os.path.normpath(config_path)
|
33 |
+
self.model_path: str = os.path.normpath(model_path)
|
34 |
+
self.device: str = device
|
35 |
+
self.language: str = language
|
36 |
+
self.hps = utils.get_hparams_from_file(config_path)
|
37 |
+
self.spk2id: Dict[str, int] = self.hps.data.spk2id # spk - id 映射字典
|
38 |
+
self.id2spk: Dict[int, str] = dict() # id - spk 映射字典
|
39 |
+
for speaker, speaker_id in self.hps.data.spk2id.items():
|
40 |
+
self.id2spk[speaker_id] = speaker
|
41 |
+
self.version: str = (
|
42 |
+
self.hps.version if hasattr(self.hps, "version") else latest_version
|
43 |
+
)
|
44 |
+
self.net_g = get_net_g(model_path=model_path, device=device, hps=self.hps)
|
45 |
+
|
46 |
+
def to_dict(self) -> Dict[str, any]:
|
47 |
+
return {
|
48 |
+
"config_path": self.config_path,
|
49 |
+
"model_path": self.model_path,
|
50 |
+
"device": self.device,
|
51 |
+
"language": self.language,
|
52 |
+
"spk2id": self.spk2id,
|
53 |
+
"id2spk": self.id2spk,
|
54 |
+
"version": self.version,
|
55 |
+
}
|
56 |
+
|
57 |
+
|
58 |
+
class Models:
|
59 |
+
def __init__(self):
|
60 |
+
self.models: Dict[int, Model] = dict()
|
61 |
+
self.num = 0
|
62 |
+
# spkInfo[角色名][模型id] = 角色id
|
63 |
+
self.spk_info: Dict[str, Dict[int, int]] = dict()
|
64 |
+
self.paths: Dict[str, int] = dict() # 路径, 引用数
|
65 |
+
|
66 |
+
def add_model(self, model: Model):
|
67 |
+
"""添加一个模型"""
|
68 |
+
self.models[self.num] = model
|
69 |
+
# 添加角色信息
|
70 |
+
for speaker, speaker_id in model.spk2id.items():
|
71 |
+
if speaker not in self.spk_info.keys():
|
72 |
+
self.spk_info[speaker] = {self.num: speaker_id}
|
73 |
+
else:
|
74 |
+
self.spk_info[speaker][self.num] = speaker_id
|
75 |
+
# 添加路径信息
|
76 |
+
model_path = os.path.realpath(model.model_path)
|
77 |
+
if model_path not in self.paths.keys():
|
78 |
+
self.paths[model_path] = 1
|
79 |
+
else:
|
80 |
+
self.paths[model_path] += 1
|
81 |
+
# 修改计数
|
82 |
+
self.num += 1
|
83 |
+
|
84 |
+
def init_model(
|
85 |
+
self, config_path: str, model_path: str, device: str, language: str
|
86 |
+
) -> int:
|
87 |
+
"""
|
88 |
+
初始化并添加一个模型
|
89 |
+
|
90 |
+
:param config_path: 模型config.json路径
|
91 |
+
:param model_path: 模型路径
|
92 |
+
:param device: 模型推理使用设备
|
93 |
+
:param language: 模型推理默认语言
|
94 |
+
"""
|
95 |
+
self.models[self.num] = Model(
|
96 |
+
config_path=config_path,
|
97 |
+
model_path=model_path,
|
98 |
+
device=device,
|
99 |
+
language=language,
|
100 |
+
)
|
101 |
+
# 添加角色信息
|
102 |
+
for speaker, speaker_id in self.models[self.num].spk2id.items():
|
103 |
+
if speaker not in self.spk_info.keys():
|
104 |
+
self.spk_info[speaker] = {self.num: speaker_id}
|
105 |
+
else:
|
106 |
+
self.spk_info[speaker][self.num] = speaker_id
|
107 |
+
# 添加路径信息
|
108 |
+
model_path = os.path.realpath(self.models[self.num].model_path)
|
109 |
+
if model_path not in self.paths.keys():
|
110 |
+
self.paths[model_path] = 1
|
111 |
+
else:
|
112 |
+
self.paths[model_path] += 1
|
113 |
+
# 修改计数
|
114 |
+
logger.success(f"添加模型{model_path},使用配置文件{os.path.realpath(config_path)}")
|
115 |
+
self.num += 1
|
116 |
+
return self.num - 1
|
117 |
+
|
118 |
+
def del_model(self, index: int) -> Optional[int]:
|
119 |
+
"""删除对应序号的模型,若不存在则返回None"""
|
120 |
+
if index not in self.models.keys():
|
121 |
+
return None
|
122 |
+
# 删除角色信息
|
123 |
+
for speaker, speaker_id in self.models[index].spk2id.items():
|
124 |
+
self.spk_info[speaker].pop(index)
|
125 |
+
if len(self.spk_info[speaker]) == 0:
|
126 |
+
# 若对应角色的所有模型都被删除,则清除该角色信息
|
127 |
+
self.spk_info.pop(speaker)
|
128 |
+
# 删除路径信息
|
129 |
+
model_path = os.path.realpath(self.models[index].model_path)
|
130 |
+
self.paths[model_path] -= 1
|
131 |
+
assert self.paths[model_path] >= 0
|
132 |
+
if self.paths[model_path] == 0:
|
133 |
+
# 引用数为零时予以清空
|
134 |
+
self.paths.pop(model_path)
|
135 |
+
# 删除模型
|
136 |
+
logger.success(f"卸载模型{model_path}, id = {index}")
|
137 |
+
self.models.pop(index)
|
138 |
+
gc.collect()
|
139 |
+
if torch.cuda.is_available():
|
140 |
+
torch.cuda.empty_cache()
|
141 |
+
return index
|
142 |
+
|
143 |
+
def get_models(self):
|
144 |
+
"""获取所有模型"""
|
145 |
+
return self.models
|
146 |
+
|
147 |
+
|
148 |
+
if __name__ == "__main__":
|
149 |
+
app = FastAPI()
|
150 |
+
app.logger = logger
|
151 |
+
# 挂载静态文件
|
152 |
+
StaticDir: str = "./Web"
|
153 |
+
dirs = [fir.name for fir in os.scandir(StaticDir) if fir.is_dir()]
|
154 |
+
files = [fir.name for fir in os.scandir(StaticDir) if fir.is_dir()]
|
155 |
+
for dirName in dirs:
|
156 |
+
app.mount(
|
157 |
+
f"/{dirName}",
|
158 |
+
StaticFiles(directory=f"./{StaticDir}/{dirName}"),
|
159 |
+
name=dirName,
|
160 |
+
)
|
161 |
+
loaded_models = Models()
|
162 |
+
# 加载模型
|
163 |
+
models_info = config.server_config.models
|
164 |
+
for model_info in models_info:
|
165 |
+
loaded_models.init_model(
|
166 |
+
config_path=model_info["config"],
|
167 |
+
model_path=model_info["model"],
|
168 |
+
device=model_info["device"],
|
169 |
+
language=model_info["language"],
|
170 |
+
)
|
171 |
+
|
172 |
+
|
173 |
+
@app.get("/")
|
174 |
+
async def index():
|
175 |
+
return FileResponse("./Web/index.html")
|
176 |
+
|
177 |
+
|
178 |
+
@app.get("/voice")
|
179 |
+
def voice(
|
180 |
+
text: str = Query(..., description="输入文字"),
|
181 |
+
model_id: int = Query(..., description="模型ID"), # 模型序号
|
182 |
+
speaker_name: str = Query(
|
183 |
+
None, description="说话人名"
|
184 |
+
), # speaker_name与 speaker_id二者选其一
|
185 |
+
speaker_id: int = Query(None, description="说话人id,与speaker_name二选一"),
|
186 |
+
sdp_ratio: float = Query(0.2, description="SDP/DP混合比"),
|
187 |
+
noise: float = Query(0.2, description="感情"),
|
188 |
+
noisew: float = Query(0.9, description="音素长度"),
|
189 |
+
length: float = Query(1, description="语速"),
|
190 |
+
language: str = Query(None, description="语言"), # 若不指定使用语言则使用默认值
|
191 |
+
auto_translate: bool = Query(False, description="自动翻译"),
|
192 |
+
):
|
193 |
+
"""语音接口"""
|
194 |
+
|
195 |
+
# 检查模型是否存在
|
196 |
+
if model_id not in loaded_models.models.keys():
|
197 |
+
return {"status": 10, "detail": f"模型model_id={model_id}未加载"}
|
198 |
+
# 检查是否提供speaker
|
199 |
+
if speaker_name is None and speaker_id is None:
|
200 |
+
return {"status": 11, "detail": "请提供speaker_name或speaker_id"}
|
201 |
+
elif speaker_name is None:
|
202 |
+
# 检查speaker_id是否存在
|
203 |
+
if speaker_id not in loaded_models.models[model_id].id2spk.keys():
|
204 |
+
return {"status": 12, "detail": f"角色speaker_id={speaker_id}不存在"}
|
205 |
+
speaker_name = loaded_models.models[model_id].id2spk[speaker_id]
|
206 |
+
# 检查speaker_name是否存在
|
207 |
+
if speaker_name not in loaded_models.models[model_id].spk2id.keys():
|
208 |
+
return {"status": 13, "detail": f"角色speaker_name={speaker_name}不存在"}
|
209 |
+
if language is None:
|
210 |
+
language = loaded_models.models[model_id].language
|
211 |
+
if auto_translate:
|
212 |
+
text = trans.translate(Sentence=text, to_Language=language.lower())
|
213 |
+
with torch.no_grad():
|
214 |
+
audio = infer(
|
215 |
+
text=text,
|
216 |
+
sdp_ratio=sdp_ratio,
|
217 |
+
noise_scale=noise,
|
218 |
+
noise_scale_w=noisew,
|
219 |
+
length_scale=length,
|
220 |
+
sid=speaker_name,
|
221 |
+
language=language,
|
222 |
+
hps=loaded_models.models[model_id].hps,
|
223 |
+
net_g=loaded_models.models[model_id].net_g,
|
224 |
+
device=loaded_models.models[model_id].device,
|
225 |
+
)
|
226 |
+
wavContent = BytesIO()
|
227 |
+
wavfile.write(
|
228 |
+
wavContent, loaded_models.models[model_id].hps.data.sampling_rate, audio
|
229 |
+
)
|
230 |
+
response = Response(content=wavContent.getvalue(), media_type="audio/wav")
|
231 |
+
return response
|
232 |
+
|
233 |
+
|
234 |
+
@app.get("/models/info")
|
235 |
+
def get_loaded_models_info():
|
236 |
+
"""获取已加载模型信息"""
|
237 |
+
|
238 |
+
result: Dict[str, Dict] = dict()
|
239 |
+
for key, model in loaded_models.models.items():
|
240 |
+
result[str(key)] = model.to_dict()
|
241 |
+
return result
|
242 |
+
|
243 |
+
|
244 |
+
@app.get("/models/delete")
|
245 |
+
def delete_model(model_id: int = Query(..., description="删除模型id")):
|
246 |
+
"""删除指定模型"""
|
247 |
+
|
248 |
+
result = loaded_models.del_model(model_id)
|
249 |
+
if result is None:
|
250 |
+
return {"status": 14, "detail": f"模型{model_id}不存在,删除失败"}
|
251 |
+
return {"status": 0, "detail": "删除成功"}
|
252 |
+
|
253 |
+
|
254 |
+
@app.get("/models/add")
|
255 |
+
def add_model(
|
256 |
+
model_path: str = Query(..., description="添加模型路径"),
|
257 |
+
config_path: str = Query(
|
258 |
+
None, description="添加模型配置文件路径,不填则使用./config.json或../config.json"
|
259 |
+
),
|
260 |
+
device: str = Query("cuda", description="推理使用设备"),
|
261 |
+
language: str = Query("ZH", description="模型默认语言"),
|
262 |
+
):
|
263 |
+
"""添加指定模型:允许重复添加相同路径模型,注意,当前实现中模型会重复加载,加载两次占用两份内存"""
|
264 |
+
if config_path is None:
|
265 |
+
model_dir = os.path.dirname(model_path)
|
266 |
+
if os.path.isfile(os.path.join(model_dir, "config.json")):
|
267 |
+
config_path = os.path.join(model_dir, "config.json")
|
268 |
+
elif os.path.isfile(os.path.join(model_dir, "../config.json")):
|
269 |
+
config_path = os.path.join(model_dir, "../config.json")
|
270 |
+
else:
|
271 |
+
return {
|
272 |
+
"status": 15,
|
273 |
+
"detail": "查询未传入配置文件路径,同时默认路径./与../中不存在配置文件config.json。",
|
274 |
+
}
|
275 |
+
try:
|
276 |
+
model_id = loaded_models.init_model(
|
277 |
+
config_path=config_path,
|
278 |
+
model_path=model_path,
|
279 |
+
device=device,
|
280 |
+
language=language,
|
281 |
+
)
|
282 |
+
except Exception:
|
283 |
+
logging.exception("模型加载出错")
|
284 |
+
return {
|
285 |
+
"status": 16,
|
286 |
+
"detail": "模型加载出错,详细查看日志",
|
287 |
+
}
|
288 |
+
return {
|
289 |
+
"status": 0,
|
290 |
+
"detail": "模型添加成功",
|
291 |
+
"Data": {
|
292 |
+
"model_id": model_id,
|
293 |
+
"model_info": loaded_models.models[model_id].to_dict(),
|
294 |
+
},
|
295 |
+
}
|
296 |
+
|
297 |
+
|
298 |
+
def _get_all_models(root_dir: str = "Data", only_unloaded: bool = False):
|
299 |
+
result: Dict[str, List[str]] = dict()
|
300 |
+
files = os.listdir(root_dir) + ["."]
|
301 |
+
for file in files:
|
302 |
+
if os.path.isdir(os.path.join(root_dir, file)):
|
303 |
+
sub_dir = os.path.join(root_dir, file)
|
304 |
+
# 搜索 "sub_dir" 、 "sub_dir/models" 两个路径
|
305 |
+
result[file] = list()
|
306 |
+
sub_files = os.listdir(sub_dir)
|
307 |
+
model_files = []
|
308 |
+
for sub_file in sub_files:
|
309 |
+
relpath = os.path.realpath(os.path.join(sub_dir, sub_file))
|
310 |
+
if only_unloaded and relpath in loaded_models.paths.keys():
|
311 |
+
continue
|
312 |
+
if sub_file.endswith(".pth") and sub_file.startswith("G_"):
|
313 |
+
if os.path.isfile(relpath):
|
314 |
+
model_files.append(sub_file)
|
315 |
+
model_files = sorted(
|
316 |
+
model_files,
|
317 |
+
key=lambda pth: int(pth.lstrip("G_").rstrip(".pth"))
|
318 |
+
if pth.lstrip("G_").rstrip(".pth").isdigit()
|
319 |
+
else 10 ** 10,
|
320 |
+
)
|
321 |
+
result[file] = model_files
|
322 |
+
models_dir = os.path.join(sub_dir, "models")
|
323 |
+
model_files = []
|
324 |
+
if os.path.isdir(models_dir):
|
325 |
+
sub_files = os.listdir(models_dir)
|
326 |
+
for sub_file in sub_files:
|
327 |
+
relpath = os.path.realpath(os.path.join(models_dir, sub_file))
|
328 |
+
if only_unloaded and relpath in loaded_models.paths.keys():
|
329 |
+
continue
|
330 |
+
if sub_file.endswith(".pth") and sub_file.startswith("G_"):
|
331 |
+
if os.path.isfile(os.path.join(models_dir, sub_file)):
|
332 |
+
model_files.append(f"models/{sub_file}")
|
333 |
+
model_files = sorted(
|
334 |
+
model_files,
|
335 |
+
key=lambda pth: int(pth.lstrip("models/G_").rstrip(".pth"))
|
336 |
+
if pth.lstrip("models/G_").rstrip(".pth").isdigit()
|
337 |
+
else 10 ** 10,
|
338 |
+
)
|
339 |
+
result[file] += model_files
|
340 |
+
if len(result[file]) == 0:
|
341 |
+
result.pop(file)
|
342 |
+
|
343 |
+
return result
|
344 |
+
|
345 |
+
|
346 |
+
@app.get("/models/get_unloaded")
|
347 |
+
def get_unloaded_models_info(root_dir: str = Query("Data", description="搜索根目录")):
|
348 |
+
"""获取未加载模型"""
|
349 |
+
return _get_all_models(root_dir, only_unloaded=True)
|
350 |
+
|
351 |
+
|
352 |
+
@app.get("/models/get_local")
|
353 |
+
def get_local_models_info(root_dir: str = Query("Data", description="搜索根目录")):
|
354 |
+
"""获取全部本地模型"""
|
355 |
+
return _get_all_models(root_dir, only_unloaded=False)
|
356 |
+
|
357 |
+
|
358 |
+
@app.get("/status")
|
359 |
+
def get_status():
|
360 |
+
"""获取电脑运行状态"""
|
361 |
+
cpu_percent = psutil.cpu_percent(interval=1)
|
362 |
+
memory_info = psutil.virtual_memory()
|
363 |
+
memory_total = memory_info.total
|
364 |
+
memory_available = memory_info.available
|
365 |
+
memory_used = memory_info.used
|
366 |
+
memory_percent = memory_info.percent
|
367 |
+
gpuInfo = []
|
368 |
+
devices = ["cpu"]
|
369 |
+
for i in range(torch.cuda.device_count()):
|
370 |
+
devices.append(f"cuda:{i}")
|
371 |
+
gpus = GPUtil.getGPUs()
|
372 |
+
for gpu in gpus:
|
373 |
+
gpuInfo.append(
|
374 |
+
{
|
375 |
+
"gpu_id": gpu.id,
|
376 |
+
"gpu_load": gpu.load,
|
377 |
+
"gpu_memory": {
|
378 |
+
"total": gpu.memoryTotal,
|
379 |
+
"used": gpu.memoryUsed,
|
380 |
+
"free": gpu.memoryFree,
|
381 |
+
},
|
382 |
+
}
|
383 |
+
)
|
384 |
+
return {
|
385 |
+
"devices": devices,
|
386 |
+
"cpu_percent": cpu_percent,
|
387 |
+
"memory_total": memory_total,
|
388 |
+
"memory_available": memory_available,
|
389 |
+
"memory_used": memory_used,
|
390 |
+
"memory_percent": memory_percent,
|
391 |
+
"gpu": gpuInfo,
|
392 |
+
}
|
393 |
+
|
394 |
+
|
395 |
+
@app.get("/tools/translate")
|
396 |
+
def translate(
|
397 |
+
texts: str = Query(..., description="待翻译文本"),
|
398 |
+
to_language: str = Query(..., description="翻译目标语言"),
|
399 |
+
):
|
400 |
+
"""翻译"""
|
401 |
+
return {"texts": trans.translate(Sentence=texts, to_Language=to_language)}
|
402 |
+
|
403 |
+
|
404 |
+
all_examples: Dict[str, Dict[str, List]] = dict() # 存放示例
|
405 |
+
|
406 |
+
|
407 |
+
@app.get("/tools/random_example")
|
408 |
+
def random_example(
|
409 |
+
language: str = Query(None, description="指定语言,未指定则随机返回"),
|
410 |
+
root_dir: str = Query("Data", description="搜索根目录"),
|
411 |
+
):
|
412 |
+
"""
|
413 |
+
获取一个随机音频+文本,用于对比,音频会从本地目录随机选择。
|
414 |
+
"""
|
415 |
+
global all_examples
|
416 |
+
# 数据初始化
|
417 |
+
if root_dir not in all_examples.keys():
|
418 |
+
all_examples[root_dir] = {"ZH": [], "SH": [], "EN": []}
|
419 |
+
|
420 |
+
examples = all_examples[root_dir]
|
421 |
+
|
422 |
+
# 从项目Data目录中搜索train/val.list
|
423 |
+
for root, directories, _files in os.walk("Data"):
|
424 |
+
for file in _files:
|
425 |
+
if file in ["train.list", "val.list"]:
|
426 |
+
print(file)
|
427 |
+
with open(
|
428 |
+
os.path.join(root, file), mode="r", encoding="utf-8"
|
429 |
+
) as f:
|
430 |
+
lines = f.readlines()
|
431 |
+
for line in lines:
|
432 |
+
data = line.split("|")
|
433 |
+
if len(data) != 7:
|
434 |
+
continue
|
435 |
+
# 音频存在 且语言为ZH/EN/JP
|
436 |
+
if os.path.isfile(data[0]) and data[2] in [
|
437 |
+
"ZH",
|
438 |
+
"SH",
|
439 |
+
"EN",
|
440 |
+
]:
|
441 |
+
examples[data[2]].append(
|
442 |
+
{
|
443 |
+
"text": data[3],
|
444 |
+
"audio": data[0],
|
445 |
+
"speaker": data[1],
|
446 |
+
}
|
447 |
+
)
|
448 |
+
|
449 |
+
examples = all_examples[root_dir]
|
450 |
+
if language is None:
|
451 |
+
if len(examples["ZH"]) + len(examples["SH"]) + len(examples["EN"]) == 0:
|
452 |
+
return {"status": 17, "detail": "没有加载任何示例数据"}
|
453 |
+
else:
|
454 |
+
# 随机选一个
|
455 |
+
rand_num = random.randint(
|
456 |
+
0,
|
457 |
+
len(examples["ZH"]) + len(examples["SH"]) + len(examples["EN"]) - 1,
|
458 |
+
)
|
459 |
+
# ZH
|
460 |
+
if rand_num < len(examples["ZH"]):
|
461 |
+
return {"status": 0, "Data": examples["ZH"][rand_num]}
|
462 |
+
# JP
|
463 |
+
if rand_num < len(examples["ZH"]) + len(examples["SH"]):
|
464 |
+
return {
|
465 |
+
"status": 0,
|
466 |
+
"Data": examples["SH"][rand_num - len(examples["ZH"])],
|
467 |
+
}
|
468 |
+
# EN
|
469 |
+
return {
|
470 |
+
"status": 0,
|
471 |
+
"Data": examples["EN"][
|
472 |
+
rand_num - len(examples["ZH"]) - len(examples["SH"])
|
473 |
+
],
|
474 |
+
}
|
475 |
+
|
476 |
+
else:
|
477 |
+
if len(examples[language]) == 0:
|
478 |
+
return {"status": 17, "detail": f"没有加载任何{language}数据"}
|
479 |
+
return {
|
480 |
+
"status": 0,
|
481 |
+
"Data": examples[language][
|
482 |
+
random.randint(0, len(examples[language]) - 1)
|
483 |
+
],
|
484 |
+
}
|
485 |
+
|
486 |
+
|
487 |
+
@app.get("/tools/get_audio")
|
488 |
+
def get_audio(path: str = Query(..., description="本地音频路径")):
|
489 |
+
if not os.path.isfile(path):
|
490 |
+
return {"status": 18, "detail": "指定音频不存在"}
|
491 |
+
if not path.endswith(".wav"):
|
492 |
+
return {"status": 19, "detail": "非wav格式文件"}
|
493 |
+
return FileResponse(path=path)
|
494 |
+
|
495 |
+
|
496 |
+
logger.warning("本地服务,请勿将服务端口暴露于外网")
|
497 |
+
print(f"api文档地址 http://127.0.0.1:{config.server_config.port}/docs")
|
498 |
+
webbrowser.open(f"http://127.0.0.1:{config.server_config.port}")
|
499 |
+
uvicorn.run(app, port=config.server_config.port, host="0.0.0.0")
|
transforms.py
ADDED
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch.nn import functional as F
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
|
7 |
+
DEFAULT_MIN_BIN_WIDTH = 1e-3
|
8 |
+
DEFAULT_MIN_BIN_HEIGHT = 1e-3
|
9 |
+
DEFAULT_MIN_DERIVATIVE = 1e-3
|
10 |
+
|
11 |
+
|
12 |
+
def piecewise_rational_quadratic_transform(
|
13 |
+
inputs,
|
14 |
+
unnormalized_widths,
|
15 |
+
unnormalized_heights,
|
16 |
+
unnormalized_derivatives,
|
17 |
+
inverse=False,
|
18 |
+
tails=None,
|
19 |
+
tail_bound=1.0,
|
20 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
21 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
22 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE,
|
23 |
+
):
|
24 |
+
if tails is None:
|
25 |
+
spline_fn = rational_quadratic_spline
|
26 |
+
spline_kwargs = {}
|
27 |
+
else:
|
28 |
+
spline_fn = unconstrained_rational_quadratic_spline
|
29 |
+
spline_kwargs = {"tails": tails, "tail_bound": tail_bound}
|
30 |
+
|
31 |
+
outputs, logabsdet = spline_fn(
|
32 |
+
inputs=inputs,
|
33 |
+
unnormalized_widths=unnormalized_widths,
|
34 |
+
unnormalized_heights=unnormalized_heights,
|
35 |
+
unnormalized_derivatives=unnormalized_derivatives,
|
36 |
+
inverse=inverse,
|
37 |
+
min_bin_width=min_bin_width,
|
38 |
+
min_bin_height=min_bin_height,
|
39 |
+
min_derivative=min_derivative,
|
40 |
+
**spline_kwargs
|
41 |
+
)
|
42 |
+
return outputs, logabsdet
|
43 |
+
|
44 |
+
|
45 |
+
def searchsorted(bin_locations, inputs, eps=1e-6):
|
46 |
+
bin_locations[..., -1] += eps
|
47 |
+
return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1
|
48 |
+
|
49 |
+
|
50 |
+
def unconstrained_rational_quadratic_spline(
|
51 |
+
inputs,
|
52 |
+
unnormalized_widths,
|
53 |
+
unnormalized_heights,
|
54 |
+
unnormalized_derivatives,
|
55 |
+
inverse=False,
|
56 |
+
tails="linear",
|
57 |
+
tail_bound=1.0,
|
58 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
59 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
60 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE,
|
61 |
+
):
|
62 |
+
inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
|
63 |
+
outside_interval_mask = ~inside_interval_mask
|
64 |
+
|
65 |
+
outputs = torch.zeros_like(inputs)
|
66 |
+
logabsdet = torch.zeros_like(inputs)
|
67 |
+
|
68 |
+
if tails == "linear":
|
69 |
+
unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
|
70 |
+
constant = np.log(np.exp(1 - min_derivative) - 1)
|
71 |
+
unnormalized_derivatives[..., 0] = constant
|
72 |
+
unnormalized_derivatives[..., -1] = constant
|
73 |
+
|
74 |
+
outputs[outside_interval_mask] = inputs[outside_interval_mask]
|
75 |
+
logabsdet[outside_interval_mask] = 0
|
76 |
+
else:
|
77 |
+
raise RuntimeError("{} tails are not implemented.".format(tails))
|
78 |
+
|
79 |
+
(
|
80 |
+
outputs[inside_interval_mask],
|
81 |
+
logabsdet[inside_interval_mask],
|
82 |
+
) = rational_quadratic_spline(
|
83 |
+
inputs=inputs[inside_interval_mask],
|
84 |
+
unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
|
85 |
+
unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
|
86 |
+
unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
|
87 |
+
inverse=inverse,
|
88 |
+
left=-tail_bound,
|
89 |
+
right=tail_bound,
|
90 |
+
bottom=-tail_bound,
|
91 |
+
top=tail_bound,
|
92 |
+
min_bin_width=min_bin_width,
|
93 |
+
min_bin_height=min_bin_height,
|
94 |
+
min_derivative=min_derivative,
|
95 |
+
)
|
96 |
+
|
97 |
+
return outputs, logabsdet
|
98 |
+
|
99 |
+
|
100 |
+
def rational_quadratic_spline(
|
101 |
+
inputs,
|
102 |
+
unnormalized_widths,
|
103 |
+
unnormalized_heights,
|
104 |
+
unnormalized_derivatives,
|
105 |
+
inverse=False,
|
106 |
+
left=0.0,
|
107 |
+
right=1.0,
|
108 |
+
bottom=0.0,
|
109 |
+
top=1.0,
|
110 |
+
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
|
111 |
+
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
|
112 |
+
min_derivative=DEFAULT_MIN_DERIVATIVE,
|
113 |
+
):
|
114 |
+
if torch.min(inputs) < left or torch.max(inputs) > right:
|
115 |
+
raise ValueError("Input to a transform is not within its domain")
|
116 |
+
|
117 |
+
num_bins = unnormalized_widths.shape[-1]
|
118 |
+
|
119 |
+
if min_bin_width * num_bins > 1.0:
|
120 |
+
raise ValueError("Minimal bin width too large for the number of bins")
|
121 |
+
if min_bin_height * num_bins > 1.0:
|
122 |
+
raise ValueError("Minimal bin height too large for the number of bins")
|
123 |
+
|
124 |
+
widths = F.softmax(unnormalized_widths, dim=-1)
|
125 |
+
widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
|
126 |
+
cumwidths = torch.cumsum(widths, dim=-1)
|
127 |
+
cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0)
|
128 |
+
cumwidths = (right - left) * cumwidths + left
|
129 |
+
cumwidths[..., 0] = left
|
130 |
+
cumwidths[..., -1] = right
|
131 |
+
widths = cumwidths[..., 1:] - cumwidths[..., :-1]
|
132 |
+
|
133 |
+
derivatives = min_derivative + F.softplus(unnormalized_derivatives)
|
134 |
+
|
135 |
+
heights = F.softmax(unnormalized_heights, dim=-1)
|
136 |
+
heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
|
137 |
+
cumheights = torch.cumsum(heights, dim=-1)
|
138 |
+
cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0)
|
139 |
+
cumheights = (top - bottom) * cumheights + bottom
|
140 |
+
cumheights[..., 0] = bottom
|
141 |
+
cumheights[..., -1] = top
|
142 |
+
heights = cumheights[..., 1:] - cumheights[..., :-1]
|
143 |
+
|
144 |
+
if inverse:
|
145 |
+
bin_idx = searchsorted(cumheights, inputs)[..., None]
|
146 |
+
else:
|
147 |
+
bin_idx = searchsorted(cumwidths, inputs)[..., None]
|
148 |
+
|
149 |
+
input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
|
150 |
+
input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
|
151 |
+
|
152 |
+
input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
|
153 |
+
delta = heights / widths
|
154 |
+
input_delta = delta.gather(-1, bin_idx)[..., 0]
|
155 |
+
|
156 |
+
input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
|
157 |
+
input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
|
158 |
+
|
159 |
+
input_heights = heights.gather(-1, bin_idx)[..., 0]
|
160 |
+
|
161 |
+
if inverse:
|
162 |
+
a = (inputs - input_cumheights) * (
|
163 |
+
input_derivatives + input_derivatives_plus_one - 2 * input_delta
|
164 |
+
) + input_heights * (input_delta - input_derivatives)
|
165 |
+
b = input_heights * input_derivatives - (inputs - input_cumheights) * (
|
166 |
+
input_derivatives + input_derivatives_plus_one - 2 * input_delta
|
167 |
+
)
|
168 |
+
c = -input_delta * (inputs - input_cumheights)
|
169 |
+
|
170 |
+
discriminant = b.pow(2) - 4 * a * c
|
171 |
+
assert (discriminant >= 0).all()
|
172 |
+
|
173 |
+
root = (2 * c) / (-b - torch.sqrt(discriminant))
|
174 |
+
outputs = root * input_bin_widths + input_cumwidths
|
175 |
+
|
176 |
+
theta_one_minus_theta = root * (1 - root)
|
177 |
+
denominator = input_delta + (
|
178 |
+
(input_derivatives + input_derivatives_plus_one - 2 * input_delta)
|
179 |
+
* theta_one_minus_theta
|
180 |
+
)
|
181 |
+
derivative_numerator = input_delta.pow(2) * (
|
182 |
+
input_derivatives_plus_one * root.pow(2)
|
183 |
+
+ 2 * input_delta * theta_one_minus_theta
|
184 |
+
+ input_derivatives * (1 - root).pow(2)
|
185 |
+
)
|
186 |
+
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
187 |
+
|
188 |
+
return outputs, -logabsdet
|
189 |
+
else:
|
190 |
+
theta = (inputs - input_cumwidths) / input_bin_widths
|
191 |
+
theta_one_minus_theta = theta * (1 - theta)
|
192 |
+
|
193 |
+
numerator = input_heights * (
|
194 |
+
input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta
|
195 |
+
)
|
196 |
+
denominator = input_delta + (
|
197 |
+
(input_derivatives + input_derivatives_plus_one - 2 * input_delta)
|
198 |
+
* theta_one_minus_theta
|
199 |
+
)
|
200 |
+
outputs = input_cumheights + numerator / denominator
|
201 |
+
|
202 |
+
derivative_numerator = input_delta.pow(2) * (
|
203 |
+
input_derivatives_plus_one * theta.pow(2)
|
204 |
+
+ 2 * input_delta * theta_one_minus_theta
|
205 |
+
+ input_derivatives * (1 - theta).pow(2)
|
206 |
+
)
|
207 |
+
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
208 |
+
|
209 |
+
return outputs, logabsdet
|
utils.py
ADDED
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import glob
|
3 |
+
import argparse
|
4 |
+
import logging
|
5 |
+
import json
|
6 |
+
import subprocess
|
7 |
+
import numpy as np
|
8 |
+
from scipy.io.wavfile import read
|
9 |
+
import torch
|
10 |
+
|
11 |
+
MATPLOTLIB_FLAG = False
|
12 |
+
|
13 |
+
logger = logging.getLogger(__name__)
|
14 |
+
|
15 |
+
|
16 |
+
def load_checkpoint(checkpoint_path, model, optimizer=None, skip_optimizer=False):
|
17 |
+
assert os.path.isfile(checkpoint_path)
|
18 |
+
checkpoint_dict = torch.load(checkpoint_path, map_location="cpu")
|
19 |
+
iteration = checkpoint_dict["iteration"]
|
20 |
+
learning_rate = checkpoint_dict["learning_rate"]
|
21 |
+
if (
|
22 |
+
optimizer is not None
|
23 |
+
and not skip_optimizer
|
24 |
+
and checkpoint_dict["optimizer"] is not None
|
25 |
+
):
|
26 |
+
optimizer.load_state_dict(checkpoint_dict["optimizer"])
|
27 |
+
elif optimizer is None and not skip_optimizer:
|
28 |
+
# else: Disable this line if Infer and resume checkpoint,then enable the line upper
|
29 |
+
new_opt_dict = optimizer.state_dict()
|
30 |
+
new_opt_dict_params = new_opt_dict["param_groups"][0]["params"]
|
31 |
+
new_opt_dict["param_groups"] = checkpoint_dict["optimizer"]["param_groups"]
|
32 |
+
new_opt_dict["param_groups"][0]["params"] = new_opt_dict_params
|
33 |
+
optimizer.load_state_dict(new_opt_dict)
|
34 |
+
|
35 |
+
saved_state_dict = checkpoint_dict["model"]
|
36 |
+
if hasattr(model, "module"):
|
37 |
+
state_dict = model.module.state_dict()
|
38 |
+
else:
|
39 |
+
state_dict = model.state_dict()
|
40 |
+
|
41 |
+
new_state_dict = {}
|
42 |
+
for k, v in state_dict.items():
|
43 |
+
try:
|
44 |
+
# assert "emb_g" not in k
|
45 |
+
new_state_dict[k] = saved_state_dict[k]
|
46 |
+
assert saved_state_dict[k].shape == v.shape, (
|
47 |
+
saved_state_dict[k].shape,
|
48 |
+
v.shape,
|
49 |
+
)
|
50 |
+
except:
|
51 |
+
# For upgrading from the old version
|
52 |
+
if "ja_bert_proj" in k:
|
53 |
+
v = torch.zeros_like(v)
|
54 |
+
logger.warn(
|
55 |
+
f"Seems you are using the old version of the model, the {k} is automatically set to zero for backward compatibility"
|
56 |
+
)
|
57 |
+
else:
|
58 |
+
logger.error(f"{k} is not in the checkpoint")
|
59 |
+
|
60 |
+
new_state_dict[k] = v
|
61 |
+
|
62 |
+
if hasattr(model, "module"):
|
63 |
+
model.module.load_state_dict(new_state_dict, strict=False)
|
64 |
+
else:
|
65 |
+
model.load_state_dict(new_state_dict, strict=False)
|
66 |
+
|
67 |
+
logger.info(
|
68 |
+
"Loaded checkpoint '{}' (iteration {})".format(checkpoint_path, iteration)
|
69 |
+
)
|
70 |
+
|
71 |
+
return model, optimizer, learning_rate, iteration
|
72 |
+
|
73 |
+
|
74 |
+
def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
|
75 |
+
logger.info(
|
76 |
+
"Saving model and optimizer state at iteration {} to {}".format(
|
77 |
+
iteration, checkpoint_path
|
78 |
+
)
|
79 |
+
)
|
80 |
+
if hasattr(model, "module"):
|
81 |
+
state_dict = model.module.state_dict()
|
82 |
+
else:
|
83 |
+
state_dict = model.state_dict()
|
84 |
+
torch.save(
|
85 |
+
{
|
86 |
+
"model": state_dict,
|
87 |
+
"iteration": iteration,
|
88 |
+
"optimizer": optimizer.state_dict(),
|
89 |
+
"learning_rate": learning_rate,
|
90 |
+
},
|
91 |
+
checkpoint_path,
|
92 |
+
)
|
93 |
+
|
94 |
+
|
95 |
+
def summarize(
|
96 |
+
writer,
|
97 |
+
global_step,
|
98 |
+
scalars={},
|
99 |
+
histograms={},
|
100 |
+
images={},
|
101 |
+
audios={},
|
102 |
+
audio_sampling_rate=22050,
|
103 |
+
):
|
104 |
+
for k, v in scalars.items():
|
105 |
+
writer.add_scalar(k, v, global_step)
|
106 |
+
for k, v in histograms.items():
|
107 |
+
writer.add_histogram(k, v, global_step)
|
108 |
+
for k, v in images.items():
|
109 |
+
writer.add_image(k, v, global_step, dataformats="HWC")
|
110 |
+
for k, v in audios.items():
|
111 |
+
writer.add_audio(k, v, global_step, audio_sampling_rate)
|
112 |
+
|
113 |
+
|
114 |
+
def latest_checkpoint_path(dir_path, regex="G_*.pth"):
|
115 |
+
f_list = glob.glob(os.path.join(dir_path, regex))
|
116 |
+
f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
|
117 |
+
x = f_list[-1]
|
118 |
+
return x
|
119 |
+
|
120 |
+
|
121 |
+
def plot_spectrogram_to_numpy(spectrogram):
|
122 |
+
global MATPLOTLIB_FLAG
|
123 |
+
if not MATPLOTLIB_FLAG:
|
124 |
+
import matplotlib
|
125 |
+
|
126 |
+
matplotlib.use("Agg")
|
127 |
+
MATPLOTLIB_FLAG = True
|
128 |
+
mpl_logger = logging.getLogger("matplotlib")
|
129 |
+
mpl_logger.setLevel(logging.WARNING)
|
130 |
+
import matplotlib.pylab as plt
|
131 |
+
import numpy as np
|
132 |
+
|
133 |
+
fig, ax = plt.subplots(figsize=(10, 2))
|
134 |
+
im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none")
|
135 |
+
plt.colorbar(im, ax=ax)
|
136 |
+
plt.xlabel("Frames")
|
137 |
+
plt.ylabel("Channels")
|
138 |
+
plt.tight_layout()
|
139 |
+
|
140 |
+
fig.canvas.draw()
|
141 |
+
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
|
142 |
+
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
143 |
+
plt.close()
|
144 |
+
return data
|
145 |
+
|
146 |
+
|
147 |
+
def plot_alignment_to_numpy(alignment, info=None):
|
148 |
+
global MATPLOTLIB_FLAG
|
149 |
+
if not MATPLOTLIB_FLAG:
|
150 |
+
import matplotlib
|
151 |
+
|
152 |
+
matplotlib.use("Agg")
|
153 |
+
MATPLOTLIB_FLAG = True
|
154 |
+
mpl_logger = logging.getLogger("matplotlib")
|
155 |
+
mpl_logger.setLevel(logging.WARNING)
|
156 |
+
import matplotlib.pylab as plt
|
157 |
+
import numpy as np
|
158 |
+
|
159 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
160 |
+
im = ax.imshow(
|
161 |
+
alignment.transpose(), aspect="auto", origin="lower", interpolation="none"
|
162 |
+
)
|
163 |
+
fig.colorbar(im, ax=ax)
|
164 |
+
xlabel = "Decoder timestep"
|
165 |
+
if info is not None:
|
166 |
+
xlabel += "\n\n" + info
|
167 |
+
plt.xlabel(xlabel)
|
168 |
+
plt.ylabel("Encoder timestep")
|
169 |
+
plt.tight_layout()
|
170 |
+
|
171 |
+
fig.canvas.draw()
|
172 |
+
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
|
173 |
+
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
174 |
+
plt.close()
|
175 |
+
return data
|
176 |
+
|
177 |
+
|
178 |
+
def load_wav_to_torch(full_path):
|
179 |
+
sampling_rate, data = read(full_path)
|
180 |
+
return torch.FloatTensor(data.astype(np.float32)), sampling_rate
|
181 |
+
|
182 |
+
|
183 |
+
def load_filepaths_and_text(filename, split="|"):
|
184 |
+
with open(filename, encoding="utf-8") as f:
|
185 |
+
filepaths_and_text = [line.strip().split(split) for line in f]
|
186 |
+
return filepaths_and_text
|
187 |
+
|
188 |
+
|
189 |
+
def get_hparams(init=True):
|
190 |
+
parser = argparse.ArgumentParser()
|
191 |
+
parser.add_argument(
|
192 |
+
"-c",
|
193 |
+
"--config",
|
194 |
+
type=str,
|
195 |
+
default="./configs/base.json",
|
196 |
+
help="JSON file for configuration",
|
197 |
+
)
|
198 |
+
parser.add_argument("-m", "--model", type=str, required=True, help="Model name")
|
199 |
+
|
200 |
+
args = parser.parse_args()
|
201 |
+
model_dir = os.path.join("./logs", args.model)
|
202 |
+
|
203 |
+
if not os.path.exists(model_dir):
|
204 |
+
os.makedirs(model_dir)
|
205 |
+
|
206 |
+
config_path = args.config
|
207 |
+
config_save_path = os.path.join(model_dir, "config.json")
|
208 |
+
if init:
|
209 |
+
with open(config_path, "r", encoding="utf-8") as f:
|
210 |
+
data = f.read()
|
211 |
+
with open(config_save_path, "w", encoding="utf-8") as f:
|
212 |
+
f.write(data)
|
213 |
+
else:
|
214 |
+
with open(config_save_path, "r", vencoding="utf-8") as f:
|
215 |
+
data = f.read()
|
216 |
+
config = json.loads(data)
|
217 |
+
hparams = HParams(**config)
|
218 |
+
hparams.model_dir = model_dir
|
219 |
+
return hparams
|
220 |
+
|
221 |
+
|
222 |
+
def clean_checkpoints(path_to_models="logs/44k/", n_ckpts_to_keep=2, sort_by_time=True):
|
223 |
+
"""Freeing up space by deleting saved ckpts
|
224 |
+
|
225 |
+
Arguments:
|
226 |
+
path_to_models -- Path to the model directory
|
227 |
+
n_ckpts_to_keep -- Number of ckpts to keep, excluding G_0.pth and D_0.pth
|
228 |
+
sort_by_time -- True -> chronologically delete ckpts
|
229 |
+
False -> lexicographically delete ckpts
|
230 |
+
"""
|
231 |
+
import re
|
232 |
+
|
233 |
+
ckpts_files = [
|
234 |
+
f
|
235 |
+
for f in os.listdir(path_to_models)
|
236 |
+
if os.path.isfile(os.path.join(path_to_models, f))
|
237 |
+
]
|
238 |
+
|
239 |
+
def name_key(_f):
|
240 |
+
return int(re.compile("._(\\d+)\\.pth").match(_f).group(1))
|
241 |
+
|
242 |
+
def time_key(_f):
|
243 |
+
return os.path.getmtime(os.path.join(path_to_models, _f))
|
244 |
+
|
245 |
+
sort_key = time_key if sort_by_time else name_key
|
246 |
+
|
247 |
+
def x_sorted(_x):
|
248 |
+
return sorted(
|
249 |
+
[f for f in ckpts_files if f.startswith(_x) and not f.endswith("_0.pth")],
|
250 |
+
key=sort_key,
|
251 |
+
)
|
252 |
+
|
253 |
+
to_del = [
|
254 |
+
os.path.join(path_to_models, fn)
|
255 |
+
for fn in (x_sorted("G")[:-n_ckpts_to_keep] + x_sorted("D")[:-n_ckpts_to_keep])
|
256 |
+
]
|
257 |
+
|
258 |
+
def del_info(fn):
|
259 |
+
return logger.info(f".. Free up space by deleting ckpt {fn}")
|
260 |
+
|
261 |
+
def del_routine(x):
|
262 |
+
return [os.remove(x), del_info(x)]
|
263 |
+
|
264 |
+
[del_routine(fn) for fn in to_del]
|
265 |
+
|
266 |
+
|
267 |
+
def get_hparams_from_dir(model_dir):
|
268 |
+
config_save_path = os.path.join(model_dir, "config.json")
|
269 |
+
with open(config_save_path, "r", encoding="utf-8") as f:
|
270 |
+
data = f.read()
|
271 |
+
config = json.loads(data)
|
272 |
+
|
273 |
+
hparams = HParams(**config)
|
274 |
+
hparams.model_dir = model_dir
|
275 |
+
return hparams
|
276 |
+
|
277 |
+
|
278 |
+
def get_hparams_from_file(config_path):
|
279 |
+
# print("config_path: ", config_path)
|
280 |
+
with open(config_path, "r", encoding="utf-8") as f:
|
281 |
+
data = f.read()
|
282 |
+
config = json.loads(data)
|
283 |
+
|
284 |
+
hparams = HParams(**config)
|
285 |
+
return hparams
|
286 |
+
|
287 |
+
|
288 |
+
def check_git_hash(model_dir):
|
289 |
+
source_dir = os.path.dirname(os.path.realpath(__file__))
|
290 |
+
if not os.path.exists(os.path.join(source_dir, ".git")):
|
291 |
+
logger.warn(
|
292 |
+
"{} is not a git repository, therefore hash value comparison will be ignored.".format(
|
293 |
+
source_dir
|
294 |
+
)
|
295 |
+
)
|
296 |
+
return
|
297 |
+
|
298 |
+
cur_hash = subprocess.getoutput("git rev-parse HEAD")
|
299 |
+
|
300 |
+
path = os.path.join(model_dir, "githash")
|
301 |
+
if os.path.exists(path):
|
302 |
+
saved_hash = open(path).read()
|
303 |
+
if saved_hash != cur_hash:
|
304 |
+
logger.warn(
|
305 |
+
"git hash values are different. {}(saved) != {}(current)".format(
|
306 |
+
saved_hash[:8], cur_hash[:8]
|
307 |
+
)
|
308 |
+
)
|
309 |
+
else:
|
310 |
+
open(path, "w").write(cur_hash)
|
311 |
+
|
312 |
+
|
313 |
+
def get_logger(model_dir, filename="train.log"):
|
314 |
+
global logger
|
315 |
+
logger = logging.getLogger(os.path.basename(model_dir))
|
316 |
+
logger.setLevel(logging.DEBUG)
|
317 |
+
|
318 |
+
formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
|
319 |
+
if not os.path.exists(model_dir):
|
320 |
+
os.makedirs(model_dir)
|
321 |
+
h = logging.FileHandler(os.path.join(model_dir, filename))
|
322 |
+
h.setLevel(logging.DEBUG)
|
323 |
+
h.setFormatter(formatter)
|
324 |
+
logger.addHandler(h)
|
325 |
+
return logger
|
326 |
+
|
327 |
+
|
328 |
+
class HParams:
|
329 |
+
def __init__(self, **kwargs):
|
330 |
+
for k, v in kwargs.items():
|
331 |
+
if type(v) == dict:
|
332 |
+
v = HParams(**v)
|
333 |
+
self[k] = v
|
334 |
+
|
335 |
+
def keys(self):
|
336 |
+
return self.__dict__.keys()
|
337 |
+
|
338 |
+
def items(self):
|
339 |
+
return self.__dict__.items()
|
340 |
+
|
341 |
+
def values(self):
|
342 |
+
return self.__dict__.values()
|
343 |
+
|
344 |
+
def __len__(self):
|
345 |
+
return len(self.__dict__)
|
346 |
+
|
347 |
+
def __getitem__(self, key):
|
348 |
+
return getattr(self, key)
|
349 |
+
|
350 |
+
def __setitem__(self, key, value):
|
351 |
+
return setattr(self, key, value)
|
352 |
+
|
353 |
+
def __contains__(self, key):
|
354 |
+
return key in self.__dict__
|
355 |
+
|
356 |
+
def __repr__(self):
|
357 |
+
return self.__dict__.__repr__()
|