├── LICENSE
├── README.md
├── dataloader
├── dataloader.py
└── test_dataloader.py
├── model
├── GRU.py
└── Tree.py
├── preparation
├── 1_sb_vad.py
├── 2_clip_segments.py
├── 3_generate_list.py
├── libri_sim_code
│ ├── 4_gen_simulated_room.py
│ ├── 5_generate_json.py
│ ├── 6_json_2_list.py
│ └── gen_room_para.py
└── libri_spkid2gender.py
├── test.sh
├── test
└── test.py
├── tools
└── misc.py
├── train.sh
├── train
└── train.py
└── utils
└── utils.py
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
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 General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License.
2 |
3 | # Locate and Beamform: Two-dimensional Locating All-neural Beamformer for Multi-channel Speech Separation (LaBNet)
4 |
5 | Official PyTorch implementation and dataset generation scripts of the Interspeech 2023 paper ["Locate and Beamform: Two-dimensional Locating All-neural Beamformer for Multi-channel Speech Separation"](https://arxiv.org/abs/2305.10821) by Fu Yanjie et al.
6 |
7 | ## How to cite
8 | 1. Fu, Yanjie, et al. "Locate and Beamform: Two-dimensional Locating All-neural Beamformer for Multi-channel Speech Separation." arXiv preprint arXiv:2305.10821 (2023).
9 | ```bibtex
10 | @misc{fu2023locate,
11 | title={Locate and Beamform: Two-dimensional Locating All-neural Beamformer for Multi-channel Speech Separation},
12 | author={Yanjie Fu and Meng Ge and Honglong Wang and Nan Li and Haoran Yin and Longbiao Wang and Gaoyan Zhang and Jianwu Dang and Chengyun Deng and Fei Wang},
13 | year={2023},
14 | eprint={2305.10821},
15 | archivePrefix={arXiv},
16 | primaryClass={eess.AS}
17 | }
18 | ```
19 |
20 | ## Model
21 | We implement LaBNet based on Generalized spatio-temporal RNN Beamformer (GRNN-BF), which directly learns the beamforming weights from the estimated speech and noise spatial covariance matrices. For more details, please refer to the original paper: ["Generalized Spatio-Temporal RNN Beamformer for Target Speech Separation"](https://www.isca-speech.org/archive/pdfs/interspeech_2021/xu21i_interspeech.pdf).
22 |
23 | The figure below shows the architecture of our proposed LaBNet.
24 | 
25 |
26 | ## Dataset (Libri-SIM)
27 | The simulated dataset `Libri-SIM` is based on the [Librispeech](http://www.openslr.org/12) corpus.
28 |
29 | ### Raw data download
30 | 1) Download the *train-clean-100*, *dev-clean* and *test-clean* data from Librispeech's website and unzip them into any directory. The absolute path for the directory is denoted as *libri_path*, which should contain 3 subfolders *train-clean-100*, *dev-clean* and *test-clean*.
31 | 2) Download or clone this repository.
32 |
33 | ### Preprocess
34 | Run the command below for *train-clean-100*, *dev-clean* and *test-clean* respectively.
35 | ```python3
36 | python ./preparation/1_sb_vad.py
37 | python ./preparation/2_clip_segments.py
38 | python ./preparation/3_generate_list.py
39 | ```
40 | The preprocessing here is to clip 4 seconds long speech segments with few silence for further simulation.
41 |
42 |
43 | ### Simulation
44 | - We simulate 6-channel audio data from original single-channel audio through pyroomacoustics, the spacings of 6 microphones are 0.04 m, 0.04 m, 0.12 m, 0.04 m, 0.04 m. The parameters of simulated rooms are shown in Tabel 1, the length of room is randomly selected between 4 m and 12 m, the width of room is a random number between 3 m and 9 m, and the height of room is a random number between 2.5 m and 5 m. There are small, middle, large 3 types of room according to the length of the room, the RT60 is a random number between 0.3 s and 0.6 s, 0.4 s and 0.7 s, 0.5 s and 0.8 s respectively.
45 |
46 |
47 |

48 |
49 |
50 | - As shown in Figure 1, the microphone array is located in the middle of the wall, at a distance of 0.5 m from the wall and 2 m from the ground. In order to make sound sources cover the area in rooms better, we first set the direction-of-arrival of sound source, then we leave 0.5 m between the sound source and the microphone array and between the sound source and the wall, and divide the rest range into near, medium and far range, the distance between microphone array and sound source is a random number in 3 types of range, so we simulate one original single channel speech data at near, medium, far distance simultaneously.
51 | - We simulate 50 training rooms, 10 validation rooms and 10 testing rooms, respectively. The angular spacing between simulated sources is 1°.
52 | - Then we generate 3 sets of training, validation set, and testing set from the simulated rooms. We randomly select 2 sources by random angles and source-to-array distances.
53 | - The training set contains 40,000 utterances (44.44 hours), the validation set and the testing set contains 5,000 and 3,000 utterances, respectively.
54 |
55 | Run commands below to simulate and generate the `.lst` which contains dataset paths.
56 | ```python3
57 | python ./preparation/libri_sim_code/4_gen_simulated_room.py
58 | python ./preparation/libri_sim_code/5_generate_json.py
59 | python ./preparation/libri_sim_code/6_json_2_list.py
60 | ```
61 |
--------------------------------------------------------------------------------
/dataloader/dataloader.py:
--------------------------------------------------------------------------------
1 | import os
2 | import copy
3 | import json
4 | import librosa
5 | import numpy as np
6 | import multiprocessing as mp
7 | import soundfile as sf
8 | import torch
9 |
10 | import torch.utils.data as tud
11 | from torch.utils.data import Dataset
12 |
13 | def audioread(path, duration, fs = 16000):
14 | wave_data, sr = sf.read(path)
15 | if sr != fs:
16 | wave_data = librosa.resample(wave_data,sr,fs)
17 | return wave_data[:fs*duration]
18 |
19 |
20 | def activelev(data):
21 | eps = np.finfo(np.float32).eps
22 | max_val = (1. + eps) / (np.std(data)+eps)
23 | data = data * max_val
24 | return data
25 |
26 | def gaussian_func(gt_idx, output_dimention, sigma):
27 | indices = np.arange(output_dimention)
28 | out = np.array(np.exp(-1 * np.square(indices - gt_idx) / sigma ** 2))
29 | return out
30 |
31 | def encode_AS(input_list):
32 | # Azimuth Spectrum
33 | AS = []
34 | for input_idx in input_list:
35 | AS.append(gaussian_func(input_idx, 210, 8))
36 | AS = np.asarray(AS) # [1, 210]
37 | return AS
38 |
39 | def encode_DS(input_list):
40 | # Distance Spectrum
41 | DS = []
42 | for input_idx in input_list:
43 | DS.append(gaussian_func(input_idx, 200, 20))
44 | DS = np.asarray(DS)
45 | return DS
46 |
47 | def gaussian_func_2d(x_len=10, y_len=10, granularity=0.5, x_mu=5, y_mu=5, x_sigma_pow2=0.1, y_sigma_pow2=0.1):
48 | '''
49 | Input: x_mu, y_mu
50 | Output: 2D array (each element indicates the probability of active sound source at each coordinate)
51 | '''
52 | X, Y = np.meshgrid(np.arange(0, x_len, granularity), np.arange(0, y_len, granularity))
53 | print(f'X.shape {X.shape}')
54 | # TODO
55 | Z = np.array(np.exp(-0.5 * np.square(X - x_mu) / x_sigma_pow2 - 0.5 * np.square(Y - y_mu) / y_sigma_pow2))
56 | print(f'Z.shape {X.shape}')
57 |
58 | return Z.flatten() # [400]
59 |
60 | def encode_LS(x, y):
61 | # location heatmap
62 | DS = []
63 | DS.append(gaussian_func_2d(x_mu=x, y_mu=y))
64 | DS = np.asarray(DS) # [1, 400]
65 | return DS
66 |
67 | def parse_scp(scp, path_list):
68 | with open(scp, encoding='utf-8') as fid:
69 | for line in fid:
70 | path_list.append(line.strip())
71 |
72 | class TFDataset(Dataset):
73 | def __init__(self, wav_scp, data_mix_info, n_mics = 6, duration = 4, sample_rate= 16000,
74 | perturb_prob = 0.0, negatives=0.2, hold_coff=0.003, n_avb_mics = 2):
75 | mgr = mp.Manager()
76 | self.file_list = mgr.list()
77 | self.noise_list = mgr.list()
78 | self.index = mgr.list()
79 |
80 | self.data_mix_info = data_mix_info
81 | self.duration = duration
82 |
83 | self.sr = sample_rate
84 | self.n_mics = n_mics
85 | self.n_avb_mics = n_avb_mics
86 | self.perturb_prob = perturb_prob
87 | self.negatives = negatives
88 | self.hlod_coff = hold_coff
89 |
90 | self.angle_dimension = 210
91 | self.time_bins = 249
92 | self.speaker_num = 2
93 |
94 | pc_list = []
95 | p = mp.Process(target = parse_scp, args=(wav_scp,self.file_list))
96 | p.start()
97 | pc_list.append(p)
98 |
99 | for p in pc_list:
100 | p.join()
101 |
102 | self.index = [idx for idx in range(len(self.file_list))]
103 |
104 | def __len__(self):
105 | return len(self.index)
106 |
107 | def __getitem__(self, idx):
108 | item = self.index[idx]
109 | file_index = item
110 | file_path = self.file_list[file_index]
111 |
112 | with open(file_path) as json_file:
113 | metadata = json.load(json_file)
114 |
115 | all_sources, doa_as_array, target_1, target_2, wave_paths, doa_idx_array, xy_coordinates = self.get_mixture_and_gt(metadata)
116 |
117 | all_sources = torch.stack(all_sources,dim=0)
118 | mixed_data = torch.sum(all_sources,dim=0)
119 | channel_num, _ = mixed_data.size()
120 | target_1 = torch.stack(target_1,dim=0)
121 | target_1 = torch.sum(target_1,dim=0)
122 | target_2 = torch.stack(target_2,dim=0)
123 | target_2 = torch.sum(target_2,dim=0)
124 |
125 | scale = 0.5
126 | for channel_idx in range(channel_num):
127 | mix_single_channel_wav = mixed_data[channel_idx,:]
128 | max_amp = torch.max(torch.abs(mix_single_channel_wav))
129 | if max_amp == 0:
130 | max_amp =1
131 | mix_scale = 1/max_amp*scale
132 | mixed_data[channel_idx,:] = mixed_data[channel_idx,:] * mix_scale
133 | target_1[channel_idx, :] = target_1[channel_idx, :] * mix_scale
134 | target_2[channel_idx, :] = target_2[channel_idx, :] * mix_scale
135 |
136 | # without noise data
137 | target_1 = target_1[0, :]
138 | target_2 = target_2[0, :]
139 |
140 | return {
141 | "mixed_data": mixed_data,
142 | "target_1": target_1,
143 | "target_2": target_2,
144 | "doa_as_array": doa_as_array, # [B, T, S, n_mics, 210]
145 | "doa_idx_array": doa_idx_array, # [B, T, S, n_mics]
146 | "wave_paths": wave_paths,
147 | "xy": xy_coordinates # [B, T, S, 2]
148 | }
149 |
150 | # # with noise data (need test)
151 | # target_1 = target_1[0, :]
152 | # target_2 = target_1[0, :]
153 |
154 | # mixed_data = np.array(mixed_data)
155 | # target_1 = np.array(target_1)
156 | # target_2 = np.array(target_2)
157 | # interference = np.zeros(len(target_1))
158 |
159 | # stationary_noise_wav_path_part = metadata["stationary_noise"]['wave_path']
160 |
161 | # SNR = metadata["stationary_noise"]['SNR']
162 |
163 | # for channel_idx in range(channel_num):
164 | # stationary_noise_wav_path = stationary_noise_wav_path_part + '_' + str(channel_idx) + '.wav'
165 |
166 | # noise_change_weight = np.max(mixed_data)*(10 ** (-SNR / 20))
167 | # noise_wav = activelev(audioread(stationary_noise_wav_path, self.duration)) * noise_change_weight
168 | # mixed_data[channel_idx, :] = mixed_data[channel_idx, :] + noise_wav
169 |
170 | # if channel_idx == 0:
171 | # interference = interference + noise_wav
172 |
173 | # mixed_data = torch.from_numpy(mixed_data)
174 | # target_1 = torch.from_numpy(target_1)
175 | # target_2 = torch.from_numpy(target_2)
176 | # interference = torch.from_numpy(interference)
177 |
178 | # return mixed_data, doa_as_array, doa_ont_hot_array, target_1, target_2, interference
179 |
180 | def get_mixture_and_gt(self, metadata):
181 | # dataset_prefix = "/local02/fuyanjie"
182 | # dataset_prefix = "/sata/fuyanjie"
183 | all_sources = []
184 | source_index = 0
185 | target_data_1 = []
186 | target_data_2 = []
187 | wave_paths= {}
188 |
189 | as_dict = dict([])
190 | doa_idx_array = np.zeros([self.time_bins, self.speaker_num, self.n_avb_mics], dtype=np.int16)
191 | doa_as_array = np.zeros([self.time_bins, self.speaker_num, self.n_avb_mics, self.angle_dimension])
192 | angle_list = np.zeros([self.speaker_num], dtype=np.int16)
193 | xy_coordinates = np.zeros([self.time_bins, self.speaker_num, 2])
194 |
195 | for key in metadata.keys():
196 | if "source" in key:
197 | channel_index_list = np.arange(self.n_mics)
198 | flag = metadata[key]['wave_path']
199 | # flag.replace(dataset_prefix, "/CDShare3")
200 | gt_audio_files = [flag + '_'+ str(channel_index) + '.wav' for channel_index in channel_index_list]
201 | gt_waveforms = []
202 | for index, gt_audio_file in enumerate(gt_audio_files):
203 | gt_waveform = audioread(gt_audio_file, self.duration)
204 | single_channel_wav = activelev(gt_waveform)
205 | gt_waveforms.append(torch.from_numpy(single_channel_wav))
206 |
207 | shifted_gt = np.stack(gt_waveforms)
208 | perturbed_source = shifted_gt
209 |
210 | perturbed_source = torch.from_numpy(perturbed_source)
211 | perturbed_source = perturbed_source.to(torch.float32)
212 |
213 | if source_index !=0:
214 | # ignore the SIR between diffrent speakers
215 | # SIR = metadata[key]['SIR']
216 | SIR = 0
217 | change_weight = 10 ** (SIR/20)
218 | perturbed_source = perturbed_source * change_weight
219 |
220 | all_sources.append(perturbed_source)
221 |
222 | source_azimuth = int(metadata[key]['azimuth'])
223 | source2mic_dist = int(metadata[key]['s2m_dist'])
224 |
225 | source_azimuth1 = int(round(metadata[key]['azimuth1']))
226 | source_azimuth3 = int(round(metadata[key]['azimuth3']))
227 | source_azimuth4 = int(round(metadata[key]['azimuth4']))
228 | source_azimuth6 = int(round(metadata[key]['azimuth6']))
229 |
230 | if source_index == 0:
231 | target_data_1.append(perturbed_source)
232 | wave_paths["spk1"] = flag
233 | angle_list[source_index] = source_azimuth
234 | elif source_index == 1:
235 | target_data_2.append(perturbed_source)
236 | wave_paths["spk2"] = flag
237 | angle_list[source_index] = source_azimuth
238 |
239 | ASs = np.zeros([self.n_avb_mics, self.angle_dimension]) # [4, 210]
240 | if self.n_avb_mics == 2:
241 | ASs[0, :] = encode_AS([source_azimuth1 + 15])
242 | ASs[1, :] = encode_AS([source_azimuth6 + 15])
243 | elif self.n_avb_mics == 4:
244 | ASs[0, :] = encode_AS([source_azimuth1 + 15])
245 | ASs[1, :] = encode_AS([source_azimuth3 + 15])
246 | ASs[2, :] = encode_AS([source_azimuth4 + 15])
247 | ASs[3, :] = encode_AS([source_azimuth6 + 15])
248 | elif self.n_avb_mics == 1:
249 | ASs[0, :] = encode_AS([source_azimuth + 15])
250 |
251 | as_dict[source_index] = ASs
252 | vad_label = metadata[key]['vad_label']
253 | for vad_index in range(len(vad_label)-1):
254 | if vad_label[vad_index] == 1:
255 | source_azimuth_rad = source_azimuth / 180.0 * np.pi
256 | xy_coordinates[vad_index, source_index, 0] = source2mic_dist * np.cos(source_azimuth_rad)
257 | xy_coordinates[vad_index, source_index, 1] = source2mic_dist * np.sin(source_azimuth_rad)
258 | if self.n_avb_mics == 2:
259 | doa_idx_array[vad_index, source_index, 0] = source_azimuth1 + 15
260 | doa_idx_array[vad_index, source_index, 1] = source_azimuth6 + 15
261 | elif self.n_avb_mics == 4:
262 | doa_idx_array[vad_index, source_index, 0] = source_azimuth1 + 15
263 | doa_idx_array[vad_index, source_index, 1] = source_azimuth3 + 15
264 | doa_idx_array[vad_index, source_index, 2] = source_azimuth4 + 15
265 | doa_idx_array[vad_index, source_index, 3] = source_azimuth6 + 15
266 | elif self.n_avb_mics == 1:
267 | doa_idx_array[vad_index, source_index, 0] = source_azimuth + 15
268 | else:
269 | doa_idx_array[vad_index, source_index, :] = -1
270 | source_index = source_index + 1
271 |
272 |
273 | # Sort by Azimuth
274 | for i in range(0, self.speaker_num):
275 | for j in range(i+1, self.speaker_num):
276 | if angle_list[i] > angle_list[j]:
277 | temp_doa_arr_1 = copy.deepcopy(doa_idx_array[:, i, :])
278 | temp_doa_arr_2 = copy.deepcopy(doa_idx_array[:, j, :])
279 | doa_idx_array[:, i, :], doa_idx_array[:, j, :] = temp_doa_arr_2, temp_doa_arr_1
280 | temp_target_1 = copy.deepcopy(target_data_1)
281 | temp_target_2 = copy.deepcopy(target_data_2)
282 | target_data_1, target_data_2 = temp_target_2, temp_target_1
283 | temp1 = copy.deepcopy(angle_list[i])
284 | temp2 = copy.deepcopy(angle_list[j])
285 | angle_list[i], angle_list[j] = temp2, temp1
286 | temp_as_1 = copy.deepcopy(as_dict[i])
287 | temp_as_2 = copy.deepcopy(as_dict[j])
288 | as_dict[0], as_dict[1] = temp_as_2, temp_as_1
289 | temp_xy_1 = copy.deepcopy(xy_coordinates[:, i, :])
290 | temp_xy_2 = copy.deepcopy(xy_coordinates[:, j, :])
291 | xy_coordinates[:, i, :], xy_coordinates[:, j, :] = temp_xy_2, temp_xy_1
292 |
293 | # Assign after sorting
294 | for source_idx in range(0, source_index):
295 | for time_idx in range(0, self.time_bins):
296 | if (doa_idx_array[time_idx, source_idx, :] == -1).any():
297 | doa_as_array[time_idx, source_idx, :, :] = np.zeros([self.n_avb_mics, self.angle_dimension])
298 | else:
299 | azi_s = as_dict[source_idx]
300 | doa_as_array[time_idx, source_idx, :, :] = azi_s
301 |
302 | return all_sources, doa_as_array, target_data_1, target_data_2, wave_paths, doa_idx_array, xy_coordinates
303 |
304 | class Sampler(tud.sampler.Sampler):
305 | def __init__(self, data_source, batch_size):
306 | it_end = len(data_source) - batch_size + 1
307 | self.batches = [range(i,i+batch_size) for i in range(0, it_end, batch_size)]
308 | self.data_source = data_source
309 |
310 | def __iter__(self):
311 | return (i for b in self.batches for i in b)
312 |
313 | def __len__(self):
314 | return len(self.data_source)
315 |
316 | def static_loader(clean_scp, batch_size = 4, shuffle = True, num_workers = 8, duration = 4, sample_rate = 16000, data_mix_info = None, n_avb_mics = 2):
317 | dataset = TFDataset(
318 | wav_scp= clean_scp,
319 | data_mix_info = data_mix_info,
320 | duration = duration,
321 | sample_rate = sample_rate,
322 | n_avb_mics = n_avb_mics
323 | )
324 |
325 | loader = tud.DataLoader(
326 | dataset,
327 | batch_size = batch_size,
328 | shuffle = shuffle,
329 | num_workers = num_workers,
330 | drop_last = False
331 | )
332 | return loader
333 |
334 |
335 | if __name__ == "__main__":
336 | lst_path = '/Work21/2021/fuyanjie/pycode/LaBNet/data/exp_list/test-clean_0101.lst'
337 | data_loader = static_loader(lst_path, shuffle=True, batch_size=4)
338 | print(f'len(data_loader) {len(data_loader)}') # len(data_loader) is samples / batch_size
339 | one_batch_data = next(iter(data_loader))
340 | print('AAA ', one_batch_data["wave_paths"])
341 | print('B ', one_batch_data["doa_as_array"].dtype)
342 | print('C ', one_batch_data["doa_idx_array"].dtype)
343 | # AAA torch.Size([224, 12, 7, 257]) torch.Size([224])
344 | # one_batch_data = next(iter(data_loader))
345 | # print('BBB ', one_batch_data["clean_ris"].shape, one_batch_data["target_doa"].shape)
346 | os.makedirs('../debug_plot', exist_ok=True)
347 | import matplotlib.pyplot as plt
348 | for idx, data in enumerate(data_loader):
349 | fig, ax = plt.subplots() # 创建图实例
350 | ax.plot(np.linspace(0, 210, 210), data['doa_as_array'][3, 50, 0, 0], color='r')
351 | # ax.plot(np.linspace(0, 210, 210), data['doa_idx_array'][2, 50, 0, 0], color='b')
352 | print(f' AAA DOA {data["doa_as_array"].shape}')
353 | print(f' A doa_as_array {data["doa_as_array"][3, 50, 0, 0].shape}')
354 | print(f' B DOA {data["doa_idx_array"][3, 50, 0]}')
355 | plt.savefig(f'../debug_plot/test_as_spk1_{idx}.png')
356 | plt.cla()
357 | ax.plot(np.linspace(0, 210, 210), data['doa_as_array'][3, 50, 1, 0], color='r')
358 | # ax.plot(np.linspace(0, 210, 210), data['doa_one_hot_array'][2, 50, 1, 0], color='b')
359 | print(f' C doa_as_array {data["doa_as_array"][3, 50, 1, 0].shape}')
360 | print(f' D doa_idx_array {data["doa_idx_array"][3, 50, 1]}')
361 | plt.savefig(f'../debug_plot/test_as_spk2_{idx}.png')
362 | # plt.cla()
363 | # ax.plot(np.linspace(0, 400, 400), data['dist_ds_array'][2, 50, 1], color='r')
364 | # ax.plot(np.linspace(0, 400, 400), data['dist_one_hot_array'][2, 50, 1], color='b')
365 | # print(f' C Dist {data["dist_idx_array"][2, 50, 1]}')
366 | # print(f' D Dist {np.where(data["dist_one_hot_array"][2, 50, 1] == 1)[0]}')
367 | # plt.savefig(f'./test_ds_spk2_{idx}.png')
368 | # print(data['wave_paths'])
369 | # print(data['mixed_data'].shape)
370 | # print(data['target_1'].shape)
371 | # print(data['target_2'].shape)
372 | # print(data['doa_as_array'].shape)
373 | # print(data['doa_one_hot_array'].shape)
374 |
375 | print('------------')
376 | if idx >= 3:
377 | break
--------------------------------------------------------------------------------
/dataloader/test_dataloader.py:
--------------------------------------------------------------------------------
1 | import os
2 | import copy
3 | import json
4 | import librosa
5 | import numpy as np
6 | import multiprocessing as mp
7 | import soundfile as sf
8 | import torch
9 |
10 | import torch.utils.data as tud
11 | from torch.utils.data import Dataset
12 |
13 | def audioread(path, duration, fs = 16000):
14 | wave_data, sr = sf.read(path)
15 | if sr != fs:
16 | wave_data = librosa.resample(wave_data,sr,fs)
17 | return wave_data[:fs*duration]
18 |
19 |
20 | def activelev(data):
21 | eps = np.finfo(np.float32).eps
22 | max_val = (1. + eps) / (np.std(data)+eps)
23 | data = data * max_val
24 | return data
25 |
26 | def gaussian_func(gt_idx, output_dimention, sigma):
27 | indices = np.arange(output_dimention)
28 | out = np.array(np.exp(-1 * np.square(indices - gt_idx) / sigma ** 2))
29 | return out
30 |
31 | def encode_AS(input_list):
32 | # Azimuth Spectrum
33 | AS = []
34 | for input_idx in input_list:
35 | AS.append(gaussian_func(input_idx, 210, 8))
36 | AS = np.asarray(AS) # [1, 210]
37 | return AS
38 |
39 | def encode_DS(input_list):
40 | # Distance Spectrum
41 | DS = []
42 | for input_idx in input_list:
43 | DS.append(gaussian_func(input_idx, 200, 20))
44 | DS = np.asarray(DS)
45 | return DS
46 |
47 | def gaussian_func_2d(x_len=10, y_len=10, granularity=0.5, x_mu=5, y_mu=5, x_sigma_pow2=0.1, y_sigma_pow2=0.1):
48 | '''
49 | Input: x_mu, y_mu
50 | Output: 2D array (each element indicates the probability of active sound source at each coordinate)
51 | '''
52 | X, Y = np.meshgrid(np.arange(0, x_len, granularity), np.arange(0, y_len, granularity))
53 | print(f'X.shape {X.shape}')
54 | # TODO
55 | Z = np.array(np.exp(-0.5 * np.square(X - x_mu) / x_sigma_pow2 - 0.5 * np.square(Y - y_mu) / y_sigma_pow2))
56 | print(f'Z.shape {X.shape}')
57 |
58 | return Z.flatten() # [400]
59 |
60 | def encode_LS(x, y):
61 | # location heatmap
62 | DS = []
63 | DS.append(gaussian_func_2d(x_mu=x, y_mu=y))
64 | DS = np.asarray(DS) # [1, 400]
65 | return DS
66 |
67 | def parse_scp(scp, path_list):
68 | with open(scp, encoding='utf-8') as fid:
69 | # with open(scp, encoding='utf-8-sig') as fid:
70 | for line in fid:
71 | path_list.append(line.strip())
72 |
73 | class TFDataset(Dataset):
74 | def __init__(self, wav_scp, data_mix_info, n_mics = 6, duration = 4, sample_rate= 16000,
75 | perturb_prob = 0.0, negatives=0.2, hold_coff=0.003, n_avb_mics = 2):
76 |
77 | mgr = mp.Manager()
78 | self.file_list = mgr.list()
79 | self.noise_list = mgr.list()
80 | self.index = mgr.list()
81 |
82 | self.data_mix_info = data_mix_info
83 | self.duration = duration
84 |
85 | self.sr = sample_rate
86 | self.n_mics = n_mics
87 | self.n_avb_mics = n_avb_mics
88 | self.perturb_prob = perturb_prob
89 | self.negatives = negatives
90 | self.hlod_coff = hold_coff
91 |
92 | self.angle_dimension = 210
93 | self.time_bins = 249
94 | self.speaker_num = 2
95 |
96 | pc_list = []
97 | p = mp.Process(target = parse_scp, args=(wav_scp,self.file_list))
98 | p.start()
99 | pc_list.append(p)
100 |
101 | for p in pc_list:
102 | p.join()
103 |
104 | self.index = [idx for idx in range(len(self.file_list))]
105 |
106 | def __len__(self):
107 | return len(self.index)
108 |
109 | def __getitem__(self, idx):
110 | item = self.index[idx]
111 | file_index = item
112 | file_path = self.file_list[file_index]
113 |
114 | with open(file_path) as json_file:
115 | metadata = json.load(json_file)
116 |
117 | all_sources, doa_as_array, target_1, target_2, angle_list, wave_paths, doa_idx_array, xy_coordinates = self.get_mixture_and_gt(metadata)
118 |
119 | all_sources = torch.stack(all_sources,dim=0)
120 | mixed_data = torch.sum(all_sources,dim=0)
121 | channel_num, _ = mixed_data.size()
122 | target_1 = torch.stack(target_1,dim=0)
123 | target_1 = torch.sum(target_1,dim=0)
124 | target_2 = torch.stack(target_2,dim=0)
125 | target_2 = torch.sum(target_2,dim=0)
126 |
127 | scale = 0.5
128 | for channel_idx in range(channel_num):
129 | mix_single_channel_wav = mixed_data[channel_idx,:]
130 | max_amp = torch.max(torch.abs(mix_single_channel_wav))
131 | if max_amp == 0:
132 | max_amp =1
133 | mix_scale = 1/max_amp*scale
134 | mixed_data[channel_idx,:] = mixed_data[channel_idx,:] * mix_scale
135 | target_1[channel_idx, :] = target_1[channel_idx, :] * mix_scale
136 | target_2[channel_idx, :] = target_2[channel_idx, :] * mix_scale
137 |
138 | # without noise data
139 | target_1 = target_1[0, :]
140 | target_2 = target_2[0, :]
141 |
142 | angular_distance = abs(angle_list[0]-angle_list[1])
143 | social_distance = float(metadata["social_dist"])
144 |
145 | return {
146 | "mixed_data": mixed_data,
147 | "target_1": target_1,
148 | "target_2": target_2,
149 | "doa_as_array": doa_as_array, # [B, T, S, n_mics, 210]
150 | "doa_idx_array": doa_idx_array, # [B, T, S, n_mics]
151 | "angular_distance": angular_distance,
152 | "social_distance": social_distance,
153 | "wave_paths": wave_paths,
154 | "xy": xy_coordinates # [B, T, S, 2]
155 | }
156 |
157 | # # with noise data (need test)
158 | # target_1 = target_1[0, :]
159 | # target_2 = target_1[0, :]
160 |
161 | # mixed_data = np.array(mixed_data)
162 | # target_1 = np.array(target_1)
163 | # target_2 = np.array(target_2)
164 | # interference = np.zeros(len(target_1))
165 |
166 | # stationary_noise_wav_path_part = metadata["stationary_noise"]['wave_path']
167 |
168 | # SNR = metadata["stationary_noise"]['SNR']
169 |
170 | # for channel_idx in range(channel_num):
171 | # stationary_noise_wav_path = stationary_noise_wav_path_part + '_' + str(channel_idx) + '.wav'
172 |
173 | # noise_change_weight = np.max(mixed_data)*(10 ** (-SNR / 20))
174 | # noise_wav = activelev(audioread(stationary_noise_wav_path, self.duration)) * noise_change_weight
175 | # mixed_data[channel_idx, :] = mixed_data[channel_idx, :] + noise_wav
176 |
177 | # if channel_idx == 0:
178 | # interference = interference + noise_wav
179 |
180 | # mixed_data = torch.from_numpy(mixed_data)
181 | # target_1 = torch.from_numpy(target_1)
182 | # target_2 = torch.from_numpy(target_2)
183 | # interference = torch.from_numpy(interference)
184 |
185 | # return mixed_data, doa_as_array, doa_ont_hot_array, target_1, target_2, interference
186 |
187 | def get_mixture_and_gt(self, metadata):
188 | dataset_prefix = "/local01/fuyanjie"
189 | # dataset_prefix = "/sata/fuyanjie"
190 | all_sources = []
191 | source_index = 0
192 | target_data_1 = []
193 | target_data_2 = []
194 | wave_paths= {}
195 |
196 | as_dict = dict([])
197 | doa_idx_array = np.zeros([self.time_bins, self.speaker_num, self.n_avb_mics], dtype=np.int16)
198 | doa_as_array = np.zeros([self.time_bins, self.speaker_num, self.n_avb_mics, self.angle_dimension])
199 | angle_list = np.zeros([self.speaker_num], dtype=np.int16)
200 | xy_coordinates = np.zeros([self.time_bins, self.speaker_num, 2])
201 | for key in metadata.keys():
202 | if "source" in key:
203 | channel_index_list = np.arange(self.n_mics)
204 | flag = metadata[key]['wave_path']
205 | gt_audio_files = [flag + '_'+ str(channel_index) + '.wav' for channel_index in channel_index_list]
206 | gt_waveforms = []
207 | for index, gt_audio_file in enumerate(gt_audio_files):
208 | gt_waveform = audioread(gt_audio_file, self.duration)
209 | single_channel_wav = activelev(gt_waveform)
210 | gt_waveforms.append(torch.from_numpy(single_channel_wav))
211 |
212 | shifted_gt = np.stack(gt_waveforms)
213 | perturbed_source = shifted_gt
214 |
215 | perturbed_source = torch.from_numpy(perturbed_source)
216 | perturbed_source = perturbed_source.to(torch.float32)
217 |
218 | if source_index !=0:
219 | # ignore the SIR between diffrent speakers
220 | # SIR = metadata[key]['SIR']
221 | SIR = 0
222 | change_weight = 10 ** (SIR/20)
223 | perturbed_source = perturbed_source * change_weight
224 |
225 | all_sources.append(perturbed_source)
226 |
227 | source_azimuth = int(metadata[key]['azimuth'])
228 | source2mic_dist = int(metadata[key]['s2m_dist'])
229 |
230 | source_azimuth1 = int(round(metadata[key]['azimuth1']))
231 | source_azimuth3 = int(round(metadata[key]['azimuth3']))
232 | source_azimuth4 = int(round(metadata[key]['azimuth4']))
233 | source_azimuth6 = int(round(metadata[key]['azimuth6']))
234 |
235 | if source_index == 0:
236 | target_data_1.append(perturbed_source)
237 | wave_paths["spk1"] = flag
238 | angle_list[source_index] = source_azimuth
239 | elif source_index == 1:
240 | target_data_2.append(perturbed_source)
241 | wave_paths["spk2"] = flag
242 | angle_list[source_index] = source_azimuth
243 |
244 | ASs = np.zeros([self.n_avb_mics, self.angle_dimension]) # [4, 210]
245 | if self.n_avb_mics == 2:
246 | ASs[0, :] = encode_AS([source_azimuth1 + 15])
247 | ASs[1, :] = encode_AS([source_azimuth6 + 15])
248 | elif self.n_avb_mics == 4:
249 | ASs[0, :] = encode_AS([source_azimuth1 + 15])
250 | ASs[1, :] = encode_AS([source_azimuth3 + 15])
251 | ASs[2, :] = encode_AS([source_azimuth4 + 15])
252 | ASs[3, :] = encode_AS([source_azimuth6 + 15])
253 | elif self.n_avb_mics == 1:
254 | ASs[0, :] = encode_AS([source_azimuth + 15])
255 | as_dict[source_index] = ASs
256 |
257 | vad_label = metadata[key]['vad_label']
258 | for vad_index in range(len(vad_label)-1):
259 | if vad_label[vad_index] == 1:
260 | source_azimuth_rad = source_azimuth / 180.0 * np.pi
261 | xy_coordinates[vad_index, source_index, 0] = source2mic_dist * np.cos(source_azimuth_rad)
262 | xy_coordinates[vad_index, source_index, 1] = source2mic_dist * np.sin(source_azimuth_rad)
263 | if self.n_avb_mics == 2:
264 | doa_idx_array[vad_index, source_index, 0] = source_azimuth1 + 15
265 | doa_idx_array[vad_index, source_index, 1] = source_azimuth6 + 15
266 | elif self.n_avb_mics == 4:
267 | doa_idx_array[vad_index, source_index, 0] = source_azimuth1 + 15
268 | doa_idx_array[vad_index, source_index, 1] = source_azimuth3 + 15
269 | doa_idx_array[vad_index, source_index, 2] = source_azimuth4 + 15
270 | doa_idx_array[vad_index, source_index, 3] = source_azimuth6 + 15
271 | elif self.n_avb_mics == 1:
272 | doa_idx_array[vad_index, source_index, 0] = source_azimuth + 15
273 | else:
274 | doa_idx_array[vad_index, source_index, :] = -1
275 | source_index = source_index + 1
276 |
277 |
278 | # # Sort by Azimuth
279 | # for i in range(0, self.speaker_num):
280 | # for j in range(i+1, self.speaker_num):
281 | # if angle_list[i] > angle_list[j]:
282 | # temp_doa_arr_1 = copy.deepcopy(doa_idx_array[:, i, :])
283 | # temp_doa_arr_2 = copy.deepcopy(doa_idx_array[:, j, :])
284 | # doa_idx_array[:, i, :], doa_idx_array[:, j, :] = temp_doa_arr_2, temp_doa_arr_1
285 | # temp_target_1 = copy.deepcopy(target_data_1)
286 | # temp_target_2 = copy.deepcopy(target_data_2)
287 | # target_data_1, target_data_2 = temp_target_2, temp_target_1
288 | # temp1 = copy.deepcopy(angle_list[i])
289 | # temp2 = copy.deepcopy(angle_list[j])
290 | # angle_list[i], angle_list[j] = temp2, temp1
291 | # temp_as_1 = copy.deepcopy(as_dict[0])
292 | # temp_as_2 = copy.deepcopy(as_dict[1])
293 | # as_dict[0], as_dict[1] = temp_as_2, temp_as_1
294 |
295 | # Assign after sorting
296 | for source_idx in range(0, source_index):
297 | for time_idx in range(0, self.time_bins):
298 | if (doa_idx_array[time_idx, source_idx, :] == -1).any():
299 | doa_as_array[time_idx, source_idx, :, :] = np.zeros([self.n_avb_mics, self.angle_dimension])
300 | else:
301 | azi_s = as_dict[source_idx]
302 | doa_as_array[time_idx, source_idx, :, :] = azi_s
303 |
304 | return all_sources, doa_as_array, target_data_1, target_data_2, angle_list, wave_paths, doa_idx_array, xy_coordinates
305 |
306 | class Sampler(tud.sampler.Sampler):
307 | def __init__(self, data_source, batch_size):
308 | it_end = len(data_source) - batch_size + 1
309 | self.batches = [range(i,i+batch_size) for i in range(0, it_end, batch_size)]
310 | self.data_source = data_source
311 |
312 | def __iter__(self):
313 | return (i for b in self.batches for i in b)
314 |
315 | def __len__(self):
316 | return len(self.data_source)
317 |
318 | def static_loader(clean_scp, batch_size = 4, shuffle = True, num_workers = 8, duration = 4, sample_rate = 16000, data_mix_info = None, n_avb_mics = 2):
319 | dataset = TFDataset(
320 | wav_scp= clean_scp,
321 | data_mix_info = data_mix_info,
322 | duration = duration,
323 | sample_rate = sample_rate,
324 | n_avb_mics = n_avb_mics
325 | )
326 |
327 | loader = tud.DataLoader(
328 | dataset,
329 | batch_size = batch_size,
330 | shuffle = shuffle,
331 | num_workers = num_workers,
332 | drop_last = False
333 | )
334 | return loader
335 |
336 |
337 | if __name__ == "__main__":
338 | lst_path = '/Work21/2021/fuyanjie/pycode/LaBNet/data/exp_list/test-clean_0101.lst'
339 | data_loader = static_loader(lst_path, shuffle=False)
340 | print(f'len(data_loader) {len(data_loader)}') # len(data_loader) is samples / batch_size
341 | one_batch_data = next(iter(data_loader))
342 | print('AAA ', one_batch_data["wave_paths"])
343 | print('B ', one_batch_data["doa_as_array"].dtype)
344 | print('C ', one_batch_data["doa_idx_array"].dtype)
345 | # AAA torch.Size([224, 12, 7, 257]) torch.Size([224])
346 | # one_batch_data = next(iter(data_loader))
347 | # print('BBB ', one_batch_data["clean_ris"].shape, one_batch_data["target_doa"].shape)
348 | import matplotlib.pyplot as plt
349 | for idx, data in enumerate(data_loader):
350 | print(f' AAA DOA {data["doa_as_array"].shape}')
351 | print(f' A doa_as_array {data["doa_as_array"][3, 50, 0, 0].shape}')
352 | print(f' B DOA {data["doa_idx_array"][3, 50, 0]}')
353 |
354 | print(f' C doa_as_array {data["doa_as_array"][3, 50, 1, 0].shape}')
355 | print(f' D doa_idx_array {data["doa_idx_array"][3, 50, 1]}')
356 | # print(data['wave_paths'])
357 | # print(data['mixed_data'].shape)
358 | # print(data['target_1'].shape)
359 | # print(data['target_2'].shape)
360 | # print(data['doa_as_array'].shape)
361 | # print(data['doa_one_hot_array'].shape)
362 |
363 | print('------------')
364 | if idx >= 3:
365 | break
--------------------------------------------------------------------------------
/model/GRU.py:
--------------------------------------------------------------------------------
1 | import torch as th
2 | from torch.nn.utils.rnn import pad_packed_sequence, PackedSequence
3 |
4 | class RNN_MASK(th.nn.Module):
5 | def __init__(self,
6 | num_bins = 256, # num of feature channels
7 | freq_bins = 257,
8 | rnn = "gru",
9 | num_mask = 4,
10 | num_layer = 2,
11 | hidden_size = 500,
12 | dropout = 0.0,
13 | non_linear = "relu",
14 | bidirectional = False
15 | ):
16 | super(RNN_MASK,self).__init__()
17 | if non_linear not in ["relu","sigmoid","tanh"]:
18 | raise ValueError(
19 | "Unsupported non-linear type:{}".format(non_linear)
20 | )
21 | self.num_mask = num_mask
22 | rnn = rnn.upper()
23 | if rnn not in ["RNN", "LSTM", "GRU"]:
24 | raise ValueError(
25 | "Unsupported rnn type:{}".format(rnn)
26 | )
27 | self.rnn = getattr(th.nn, rnn)(
28 | num_bins,
29 | hidden_size,
30 | num_layer,
31 | batch_first = True,
32 | dropout = dropout,
33 | bidirectional = bidirectional
34 | )
35 | self.filter_size = 3
36 | self.drops = th.nn.Dropout(p=dropout)
37 | self.linear = th.nn.ModuleList([
38 | th.nn.Linear(hidden_size * 2 if bidirectional else hidden_size, 2 * freq_bins * self.filter_size * self.filter_size)
39 | for _ in range(self.num_mask)
40 | ])
41 |
42 | # self.conv1d = th.nn.Conv1d(hidden_size * 2 if bidirectional else hidden_size, self.num_mask * 2 * freq_bins * self.filter_size * self.filter_size, kernel_size=1)
43 |
44 | self.non_linear = {
45 | "relu": th.nn.functional.relu,
46 | "sigmoid": th.nn.functional.sigmoid,
47 | "tanh": th.nn.functional.tanh
48 | }[non_linear]
49 | self.num_bins = num_bins
50 |
51 | def forward(self,x):
52 | is_packed = isinstance(x, PackedSequence)
53 | if not is_packed and x.dim()!=3:
54 | x = th.unsqueeze(x,0)
55 | x, _ = self.rnn(x) # [B, C, T]
56 |
57 | if is_packed:
58 | x, _ = pad_packed_sequence(x,batch_first = True)
59 | x = self.drops(x)
60 | m = []
61 | for linear in self.linear:
62 | y = linear(x)
63 | y = self.non_linear(y)
64 | m.append(y)
65 | return m
--------------------------------------------------------------------------------
/model/Tree.py:
--------------------------------------------------------------------------------
1 | import sys
2 | sys.path.append("/Work21/2021/fuyanjie/pycode/LaBNetPro")
3 |
4 | from dataloader.dataloader import static_loader
5 | from model.GRU import RNN_MASK
6 | from torch_complex import ComplexTensor
7 | from torch_complex import functional as FC
8 | import torch.nn.functional as F
9 | import torch.nn as nn
10 | import torch
11 | import numpy as np
12 | from scipy.signal import get_window
13 |
14 | EPS = 1e-8
15 |
16 |
17 | def get_ipd(spec, dim):
18 | '''
19 | : param spec: (batch, channels, freq_bins:257 × 2, time_bins)
20 | : param dim:
21 | : return:
22 | '''
23 |
24 | real = spec[:, :, :dim, :]
25 | imag = spec[:, :, dim:, :]
26 | phase = torch.atan2(imag,real) # (batch,channels, freq_bins:257, time_bins)
27 | # 8, 12, 16, 16, 20 cm
28 | # diff1 = torch.cos((phase[:, 2, :, :] - phase[:, 0, :, :])).unsqueeze(1)
29 | # diff2 = torch.cos((phase[:, 3, :, :] - phase[:, 2, :, :])).unsqueeze(1)
30 | # diff3 = torch.cos((phase[:, 4, :, :] - phase[:, 2, :, :])).unsqueeze(1)
31 | # diff4 = torch.cos((phase[:, 3, :, :] - phase[:, 1, :, :])).unsqueeze(1)
32 | # diff5 = torch.cos((phase[:, 3, :, :] - phase[:, 0, :, :])).unsqueeze(1)
33 |
34 | # 8, 8, 12, 16, 16 cm
35 | # diff1 = torch.cos((phase[:, 2, :, :] - phase[:, 0, :, :])).unsqueeze(1)
36 | # diff2 = torch.cos((phase[:, 3, :, :] - phase[:, 1, :, :])).unsqueeze(1)
37 | # diff3 = torch.cos((phase[:, 3, :, :] - phase[:, 2, :, :])).unsqueeze(1)
38 | # diff4 = torch.cos((phase[:, 4, :, :] - phase[:, 2, :, :])).unsqueeze(1)
39 | # diff5 = torch.cos((phase[:, 5, :, :] - phase[:, 3, :, :])).unsqueeze(1)
40 |
41 | diff1 = torch.cos((phase[:, 1, :, :] - phase[:, 0, :, :])).unsqueeze(1)
42 | diff2 = torch.cos((phase[:, 2, :, :] - phase[:, 0, :, :])).unsqueeze(1)
43 | diff3 = torch.cos((phase[:, 3, :, :] - phase[:, 0, :, :])).unsqueeze(1)
44 | diff4 = torch.cos((phase[:, 4, :, :] - phase[:, 0, :, :])).unsqueeze(1)
45 | diff5 = torch.cos((phase[:, 5, :, :] - phase[:, 0, :, :])).unsqueeze(1)
46 |
47 | sin_diff1 = torch.sin((phase[:, 1, :, :] - phase[:, 0, :, :])).unsqueeze(1)
48 | sin_diff2 = torch.sin((phase[:, 2, :, :] - phase[:, 0, :, :])).unsqueeze(1)
49 | sin_diff3 = torch.sin((phase[:, 3, :, :] - phase[:, 0, :, :])).unsqueeze(1)
50 | sin_diff4 = torch.sin((phase[:, 4, :, :] - phase[:, 0, :, :])).unsqueeze(1)
51 | sin_diff5 = torch.sin((phase[:, 5, :, :] - phase[:, 0, :, :])).unsqueeze(1)
52 |
53 | result = torch.cat((diff1, diff2, diff3, diff4, diff5), dim=1)
54 | # result = torch.cat((diff1,diff2,diff3,diff4,diff5,sin_diff1,sin_diff2,sin_diff3,sin_diff4,sin_diff5), dim=1)
55 | #(batch, (m-1) pair microphones, freq bins:257, time_bins)
56 | return result
57 |
58 | def get_lps(spec, dim):
59 | '''
60 | : param spec: (batch,channels, freq _bins:257 × 2, time_bins)
61 | : param dim:
62 | : return:
63 | '''
64 | real = spec[:, :, :dim, :]
65 | imag = spec[:, :, dim:, :]
66 | mags = torch.sqrt(real ** 2 + imag ** 2)
67 | mags_refch = mags[:, 0, :, : ].unsqueeze(1)
68 | result = torch.log(mags_refch ** 2 + EPS) - np.log(EPS) # (batch, 1,freq_bins :257, time_bins)
69 | return result
70 |
71 | def get_spec_mag(spec, dim):
72 | '''
73 | :param spec: (batch, channels, freq bins:257 × 2, time_bins)
74 | :param dim:
75 | :return:
76 | '''
77 | real = spec[:, :, :dim, :]
78 | imag = spec[:, :, dim:, :]
79 | mags = torch.sqrt(real ** 2 + imag ** 2)
80 | mags_refch = mags[:, 0, :, :].unsqueeze(1)
81 | return mags_refch
82 |
83 |
84 | def get_covariance_v2(spec, crf, filter_size):
85 | batch, channels, two_freq_bins, time_bins = spec.size()
86 | freq_bins = two_freq_bins // 2
87 | spec = spec.reshape(batch, channels, 2, freq_bins, time_bins)
88 | spec = spec.permute(0, 1, 2, 4, 3)
89 | pad = nn.ZeroPad2d(1)
90 | spec_horizental = pad(spec)
91 | result_horizental = spec_horizental[:,:,:,:time_bins,:freq_bins+1]
92 | for i in range(1, filter_size):
93 | result_horizental = torch.cat((result_horizental, spec_horizental[:,:,:,i:i+time_bins,:freq_bins+1]),dim=3)
94 |
95 | spec_vertical = pad(result_horizental)
96 | result_vertical = spec_vertical[:,:,:,1:filter_size*time_bins+1,1:1+freq_bins]
97 | for j in range(1,filter_size):
98 | result_vertical = torch.cat((result_vertical,spec_vertical[:,:,:,1:3*time_bins+1,1+j:1+j+freq_bins]),dim=4)
99 |
100 | spec_final = result_vertical.reshape(batch, channels, 2, filter_size, time_bins, filter_size * freq_bins)
101 | spec_final = spec_final.reshape(batch, channels, 2, filter_size, time_bins, filter_size, freq_bins)
102 | spec_final = spec_final.permute(0, 1, 2, 4, 6, 3, 5)
103 |
104 | spec_real = spec_final[:,:,0,...]
105 | spec_imag = spec_final[:,:,1,...]
106 | spec_com = ComplexTensor(spec_real, spec_imag)
107 | spec_com = spec_com.permute(0, 3, 1, 2, 4, 5)
108 | crf_com = ComplexTensor(crf[:,0,...],crf[:,1,...])
109 | crf_com = crf_com.permute(0, 2, 1, 3, 4)
110 | psd_Y = FC.einsum("...ctkl,...etkl->...tcekl",[spec_com,spec_com.conj()])
111 | psd = psd_Y * crf_com[...,None,None,:,:]
112 | psd = psd.sum(dim=-1)
113 | psd = psd.sum(dim=-1)
114 |
115 | convariance_final_real = psd.real
116 | convariance_final_real = convariance_final_real.permute(0, 2, 1, 3, 4)
117 | convariance_final_imag = psd.imag
118 | convariance_final_imag = convariance_final_imag.permute(0, 2, 1, 3, 4)
119 |
120 | convariance_final = torch.stack((convariance_final_real,convariance_final_imag),dim=1)
121 |
122 | return convariance_final
123 |
124 | def remove_dc(signal):
125 | """Normalized to zero mean"""
126 | mean = torch.mean(signal, dim=-1, keepdim=True)
127 | signal = signal - mean
128 | return signal
129 |
130 | def dotproduct(y, y_hat) :
131 | #batch x channel x nsamples
132 | return torch.bmm(y.reshape(y.shape[0], 1, y.shape[ -1]), y_hat.reshape(y_hat.shape[0], y_hat.shape[-1], 1)).reshape(-1)
133 |
134 | def si_sdr_loss(e1, c1, c2):
135 | # [B, T]
136 | def sisdr(estimated, original, eps=1e-8):
137 | # estimated = remove_dc(estimated)
138 | # original = remove_dc(original)
139 | target = pow_norm(estimated, original) * original / (pow_p_norm(original) + eps)
140 | noise = estimated - target
141 | return -10 * torch.log10(eps + pow_p_norm(target) / pow_p_norm(noise) + eps)
142 |
143 | sisdr_loss = sisdr(e1, c1)
144 | avg_loss = torch.mean(sisdr_loss)
145 |
146 | return avg_loss
147 |
148 | def wsdr_loss(output, target_signal, inference_signal):
149 | """
150 | : param output: B, 1, T
151 | : param target_signal: (batch, time samples)
152 | : param inference_signal: (batch, time_samples)
153 | : return:
154 | """
155 |
156 | output = torch.squeeze(output, 1)
157 |
158 | y = target_signal
159 | z = inference_signal
160 |
161 | # target size: torch.Size([32, 15988B]) noise torch.Size([32, 159888]) output: torch.Size([32, 159800])# print ( "target size:", target_sig.size(),"noise ", noise.size(), 'output : ' , output .size(
162 | y_hat = output
163 | z_hat = y + z - y_hat # expected noise signal
164 |
165 | y_norm = torch.norm(y, dim=-1)
166 | z_norm = torch.norm(z, dim=-1)
167 | y_hat_norm = torch.norm(y_hat, dim=-1)
168 | z_hat_norm = torch.norm(z_hat, dim=-1)
169 |
170 | def loss_sdr(a, a_hat, a_norm, a_hat_norm):
171 | return dotproduct(a, a_hat) / (a_norm * a_hat_norm + EPS)
172 |
173 | alpha = y_norm.pow(2) / (y_norm.pow(2) + z_norm.pow(2) + EPS)
174 | loss_wSDR = -alpha * loss_sdr(y, y_hat, y_norm, y_hat_norm) - (1 - alpha) * loss_sdr(z, z_hat, z_norm, z_hat_norm)
175 |
176 | return loss_wSDR.mean()
177 |
178 | def pow_p_norm_np(signal):
179 | """Compute 2 Norm"""
180 | return np.square(np.linalg.norm(signal, ord=2, axis=-1))
181 |
182 | def pow_norm_np(s1, s2):
183 | return np.sum(s1 * s2, axis=-1)
184 |
185 | def pow_p_norm(signal):
186 | """Compute 2 Norm"""
187 | return torch.pow(torch.norm(signal, p=2, dim=-1, keepdim=True), 2)
188 |
189 | def pow_norm(s1, s2):
190 | return torch.sum(s1 * s2, dim=-1, keepdim=True)
191 |
192 | def pit_sisdr_loss(e1, e2, c1, c2):
193 | # [1, T]
194 | def sisdr(estimated, original):
195 | # estimated = remove_dc(estimated)
196 | # original = remove_dc(original)
197 | target = pow_norm(estimated, original) * original / pow_p_norm(original)
198 | noise = estimated - target
199 | return 10 * torch.log10(pow_p_norm(target) / pow_p_norm(noise))
200 |
201 | e1b = e1.squeeze() # [T]
202 | e2b = e2.squeeze() # [T]
203 | c1b = c1.squeeze() # [T]
204 | c2b = c2.squeeze() # [T]
205 |
206 | sdr1 = (sisdr(e1b, c1b) + sisdr(e2b, c2b)) * 0.5
207 | sdr2 = (sisdr(e2b, c1b) + sisdr(e1b, c2b)) * 0.5
208 |
209 | loss, idx = torch.max(torch.stack((sdr1, sdr2), dim=-1), dim=-1)
210 | avg_loss = torch.mean(loss)
211 |
212 | return avg_loss, idx
213 |
214 | def pit_sisdr_numpy(e1, e2, c1, c2):
215 | # [1, T]
216 | def sisdr(estimated, original):
217 | # estimated = remove_dc(estimated)
218 | # original = remove_dc(original)
219 | target = pow_norm_np(estimated, original) * original / pow_p_norm_np(original)
220 | noise = estimated - target
221 | return 10 * np.log10(pow_p_norm_np(target) / pow_p_norm_np(noise))
222 |
223 | e1b = np.squeeze(e1) # [T]
224 | e2b = np.squeeze(e2) # [T]
225 | c1b = np.squeeze(c1) # [T]
226 | c2b = np.squeeze(c2) # [T]
227 |
228 | sdr1 = (sisdr(e1b, c1b) + sisdr(e2b, c2b)) * 0.5
229 | sdr2 = (sisdr(e2b, c1b) + sisdr(e1b, c2b)) * 0.5
230 | print(f'sdr for permutation 1 {sdr1} sdr for permutation 2 {sdr2}', flush=True)
231 | loss = np.max(np.stack((sdr1, sdr2), axis=-1), axis=-1)
232 | idx = np.argmax(np.stack((sdr1, sdr2), axis=-1), axis=-1)
233 | avg_loss = np.mean(loss)
234 |
235 | return avg_loss, idx
236 |
237 | def init_kernels(win_len, win_inc, fft_len, win_type=None, invers=False):
238 | if win_type == 'None' or win_type is None:
239 | window = np.ones(win_len)
240 | else:
241 | window = get_window(win_type, win_len, fftbins=True) # **0.5
242 |
243 | N = fft_len
244 | fourier_basis = np.fft.rfft(np.eye(N))[:win_len]
245 | real_kernel = np.real(fourier_basis)
246 | imag_kernel = np.imag(fourier_basis)
247 | kernel = np.concatenate([real_kernel, imag_kernel], 1).T
248 |
249 | if invers:
250 | kernel = np.linalg.pinv(kernel).T
251 |
252 | kernel = kernel * window
253 | kernel = kernel[:, None, :]
254 | return torch.from_numpy(kernel.astype(np.float32)), torch.from_numpy(window[None, :, None].astype(np.float32))
255 |
256 |
257 | class ConvSTFT(nn.Module):
258 | def __init__(self, win_len, win_inc, fft_len=None, win_type='hamming', feature_type='real', fix=True):
259 | super(ConvSTFT, self).__init__()
260 |
261 | if fft_len == None:
262 | self.fft_len = np.int(2 ** np.ceil(np.log2(win_len)))
263 | else:
264 | self.fft_len = fft_len
265 |
266 | kernel, _ = init_kernels(win_len, win_inc, self.fft_len, win_type)
267 | # self.weight = nn.Parameter(kernel, requires_grad=(not fix))
268 | self.register_buffer('weight', kernel)
269 | self.feature_type = feature_type
270 | self.stride = win_inc
271 | self.win_len = win_len
272 | self.dim = self.fft_len
273 |
274 | def forward(self, inputs):
275 | if inputs.dim() == 2:
276 | inputs = torch.unsqueeze(inputs, 1)
277 | inputs = F.pad(inputs, [self.win_len - self.stride, self.win_len - self.stride])
278 | outputs = F.conv1d(inputs, self.weight, stride=self.stride)
279 |
280 | if self.feature_type == 'complex':
281 | return outputs
282 | else:
283 | dim = self.dim // 2 + 1
284 | real = outputs[:, :dim, :]
285 | imag = outputs[:, dim:, :]
286 | mags = torch.sqrt(real ** 2 + imag ** 2)
287 | phase = torch.atan2(imag, real)
288 | return mags, phase
289 |
290 |
291 | class ConviSTFT(nn.Module):
292 | def __init__(self, win_len, win_inc, fft_len=None, win_type='hamming', feature_type='real', fix=True):
293 | super(ConviSTFT, self).__init__()
294 | if fft_len == None:
295 | self.fft_len = np.int(2 ** np.ceil(np.log2(win_len)))
296 | else:
297 | self.fft_len = fft_len
298 | kernel, window = init_kernels(win_len, win_inc, self.fft_len, win_type, invers=True)
299 | # self.weight = nn.Parameter(kernel, requires_grad=(not fix))
300 | self.register_buffer('weight', kernel)
301 | self.feature_type = feature_type
302 | self.win_type = win_type
303 | self.win_len = win_len
304 | self.stride = win_inc
305 | self.stride = win_inc
306 | self.dim = self.fft_len
307 | self.register_buffer('window', window)
308 | self.register_buffer('enframe', torch.eye(win_len)[:, None, :])
309 |
310 | def forward(self, inputs, phase=None):
311 | """
312 | inputs : [B, N+2, T] (complex spec) or [B, N//2+1, T] (mags)
313 | phase: [B, N//2+1, T] (if not none)
314 | """
315 |
316 | if phase is not None:
317 | real = inputs * torch.cos(phase)
318 | imag = inputs * torch.sin(phase)
319 | inputs = torch.cat([real, imag], 1)
320 | outputs = F.conv_transpose1d(inputs, self.weight, stride=self.stride)
321 |
322 | # this is from torch-stft: https://github.com/pseeth/torch-stft
323 | t = self.window.repeat(1, 1, inputs.size(-1)) ** 2
324 | coff = F.conv_transpose1d(t, self.enframe, stride=self.stride)
325 | outputs = outputs / (coff + 1e-8)
326 | # outputs = torch.where(coff == 0, outputs, outputs/coff)
327 | outputs = outputs[..., self.win_len - self.stride:-(self.win_len - self.stride)]
328 |
329 | return outputs
330 |
331 | class Triangulation(nn.Module):
332 | def __init__(self):
333 | super(Triangulation, self).__init__()
334 |
335 | def forward(self, doas, mic_itval=28):
336 | """
337 | doas : [B*F, T, n_avb_mics]
338 | xy: [B*F, T, 2]
339 | """
340 | if doas.shape[-1] == 4:
341 | doas = torch.index_select(doas, -1, torch.tensor([0, 3], device=doas.device)) # [B*F, T, 2]
342 |
343 | # doas = torch.max(azi_s, dim=-1)[1] # [B, T, n_avb_mics] if input [B, T, n_avb_mics, 210]
344 | # if azi_s.shape[-1] == 4:
345 | # doas = torch.index_select(azi_s, -1, torch.tensor([0, 3])) # [B, T, 2]
346 |
347 | doa1 = doas[:, :, 0]
348 | doa2 = doas[:, :, 1]
349 | if (doa1 == doa2).any():
350 | doa1 = doa1 + 1
351 | doa1 = doa1 / 180.0 * np.pi
352 | doa2 = doa2 / 180.0 * np.pi
353 |
354 | side = torch.clamp(torch.sin(doa2) * mic_itval / (torch.sin(doa1-doa2) + 1e-8), min=50, max=800)
355 |
356 | x = -side * torch.cos(doa1)
357 | y = side * torch.sin(doa1)
358 | xy = torch.stack((x, y), dim=2)
359 | # print(f'side {side} doa1 {doa1} doa2 {doa2} xy {xy}', flush=True)
360 | return xy
361 |
362 |
363 | class Tree(nn.Module):
364 | def __init__(self, fft_len=512,speaker_num=2,n_avb_mics=2):
365 | super(Tree, self).__init__()
366 | self.channels = 6
367 | self.dim = fft_len // 2 + 1
368 | self.win_len = fft_len
369 | self.win_inc = fft_len // 2
370 | self.fft_len = fft_len
371 | self.win_type = 'hamming'
372 | self.filter_size = 3
373 | self.stftConv = ConvSTFT(self.win_len, self.win_inc, self.fft_len, self.win_type, feature_type='complex')
374 | self.istftConv = ConviSTFT(self.win_len, self.win_inc, self.fft_len, self.win_type, feature_type='complex')
375 | self.P = 3
376 | self.R = 4
377 | self.X = 8
378 | self.causal = True
379 | self.norm_type = 'cLN'
380 | self.n_mics = 6 # len(mic_location)
381 | self.n_avb_mics = n_avb_mics
382 | self.speaker_num = speaker_num
383 | self.reduction_linear = nn.Linear(in_features = (10+1)*257,out_features=256)
384 |
385 | self.repeats = RNN_MASK()
386 |
387 | self.width_window_length = 2
388 |
389 | self.RELU = nn.ReLU()
390 | self.PRELU = nn.PReLU()
391 | self.Sigmoid = nn.Sigmoid()
392 | self.covariance_ln_ss = nn.LayerNorm([self.n_mics, self.n_mics])
393 | self.covariance_ln_nn = nn.LayerNorm([self.n_mics, self.n_mics])
394 |
395 | self.conv1_doa = nn.Sequential(
396 | nn.Conv2d(144, 210*self.n_avb_mics, kernel_size=(1, 1), stride=(1, 1), padding=(0, 0)),
397 | nn.BatchNorm2d(210*self.n_avb_mics), nn.ReLU(inplace=True)
398 | )
399 | self.conv_emb_doa = nn.Sequential(
400 | nn.Conv2d(210, 1, kernel_size=(1, 1), stride=(1, 1), padding=(0, 0)),
401 | nn.BatchNorm2d(1), nn.ReLU(inplace=True)
402 | )
403 | self.conv2_doa = nn.Sequential(
404 | nn.Conv2d(257, 1, kernel_size=(3, 5), stride=(1, 1), padding=(1, 2)),
405 | nn.BatchNorm2d(1), nn.ReLU(inplace=True)
406 | )
407 |
408 | self.gru_doa = nn.GRU(210, hidden_size=210, num_layers=2, batch_first=True)
409 |
410 | ###
411 | # self.triangulation = nn.Linear(self.n_avb_mics * 210, 400)
412 | self.triangulation = Triangulation()
413 | # self.conv1_loc = nn.Sequential(
414 | # nn.Conv2d(210*self.n_avb_mics, 400, kernel_size=(3, 5), stride=(1, 1), padding=(1, 2)),
415 | # nn.BatchNorm2d(400), nn.ReLU(inplace=True)
416 | # )
417 | # self.conv2_loc = nn.Sequential(
418 | # nn.Conv2d(257, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
419 | # nn.BatchNorm2d(1), nn.ReLU(inplace=True)
420 | # )
421 | ###
422 |
423 | # Branch 1 (gru_bss)
424 | self.linear_bss_1 = nn.Linear(self.n_mics * self.n_mics * 2 * 2 + self.n_avb_mics * 210 + 2, 300)
425 | # self.linear_bss_1 = nn.Linear(self.n_mics * self.n_mics * 2 * 2 + self.n_avb_mics * 210, 300)
426 | self.gru_bss_1 = nn.GRU(300, hidden_size=300, num_layers=2, batch_first=True)
427 | self.linear_w1 = nn.Linear(300, self.channels * 2)
428 |
429 | # Branch 2 (gru_bss)
430 | self.linear_bss_2 = nn.Linear(self.n_mics * self.n_mics * 2 * 2 + self.n_avb_mics * 210 + 2, 300)
431 | # self.linear_bss_2 = nn.Linear(self.n_mics * self.n_mics * 2 * 2 + self.n_avb_mics * 210, 300)
432 | self.gru_bss_2 = nn.GRU(300, hidden_size=300, num_layers=2, batch_first=True)
433 | self.linear_w2 = nn.Linear(300, self.channels * 2)
434 |
435 | def get_params(self, weight_decay=0.0):
436 | #add L2 penalty
437 | weights, biases = [], []
438 | for name, param in self.named_parameters():
439 | if 'bias' in name:
440 | biases += [param]
441 | else:
442 | weights += [param]
443 | params = [{
444 | 'params': weights,
445 | 'weight_decay': weight_decay,
446 | }, {
447 | 'params': biases,
448 | 'weight_decay': 0.0,
449 | }]
450 | return params
451 |
452 | def forward(self, inputs):
453 | """
454 | Returns
455 | -------
456 | azis_1 / azis_2: [B, T, n_mics=self.n_avb_mics, 210]
457 | es_sig: [B, 1, T]
458 | """
459 | self.gru_doa.flatten_parameters()
460 | self.gru_bss_1.flatten_parameters()
461 | self.gru_bss_2.flatten_parameters()
462 | inputs = torch.unsqueeze(inputs, 2) # bs * channels * 1 * time_samples
463 | batch, channels, _, time_samples = inputs.size()
464 | inputs = inputs.view(batch * channels, 1, time_samples) # bs * channels, l, time_samples
465 |
466 | #STFT
467 | #que stftConv返回的维度是2 * 257吗
468 | spectrograms = self.stftConv(inputs)
469 | _, double_freq_bins, time_bins = spectrograms.size() # batch * channels, 2 * 257,time bins
470 | freq_bins = double_freq_bins // 2
471 | spectrograms = spectrograms.reshape(batch, channels, double_freq_bins, time_bins)
472 |
473 | '''compute ipd , lps and width feature,concat'''
474 | ipd = get_ipd(spectrograms, self.dim) # batch, M microphone pair num, freq_bins, time_bin$
475 | lps = get_spec_mag(spectrograms, self.dim) # batch, 1, freq_bins, time_bins
476 |
477 | audio_blocks = torch.cat((ipd, lps), dim=1) #(batch, n_mics, freq_bins:257, time_bins
478 | audio_blocks = audio_blocks.view(batch, (10+1) * 257, time_bins)
479 | audio_blocks = audio_blocks.permute(0,2,1) # [B, time_bins, 6*freq_bins]
480 |
481 | '''pass through front-GRU '''
482 | audio_reduction = self.reduction_linear(audio_blocks) # batch, time_bins, 256 channels
483 | masks = self.repeats(audio_reduction) # batch, time_bins, 256 channels
484 |
485 | convariance_set_doa_list = []
486 | convariance_set_bss_list = []
487 |
488 | """audio embeddings经过blstm得到 crf,crf与spectrograms得到目标信号的协方差矩阵"""
489 |
490 | for mask_idx in range(self.speaker_num):
491 | comlex_filter_ss = masks[mask_idx * 2].permute(0,2,1)
492 | comlex_filter_nn = masks[mask_idx * 2 + 1].permute(0,2,1)
493 |
494 | comlex_filter_ss = comlex_filter_ss.view(batch, freq_bins, 2 * self.filter_size * self.filter_size, time_bins)
495 | comlex_filter_ss = comlex_filter_ss.view(batch, freq_bins, 2, self.filter_size * self.filter_size, time_bins)
496 | comlex_filter_ss = comlex_filter_ss.view(batch, freq_bins, 2, self.filter_size, self.filter_size, time_bins)
497 | comlex_filter_ss = comlex_filter_ss.permute(0, 2, 5, 1, 3, 4)
498 | covariance_ss = get_covariance_v2(spectrograms, comlex_filter_ss, self.filter_size)
499 | covariance_ss = self.covariance_ln_ss(covariance_ss)
500 | covariance_ss = covariance_ss.unsqueeze(dim=4)
501 |
502 | comlex_filter_nn = comlex_filter_nn.view(batch, freq_bins, 2 * self.filter_size * self.filter_size, time_bins)
503 | comlex_filter_nn = comlex_filter_nn.view(batch, freq_bins, 2, self.filter_size * self.filter_size, time_bins)
504 | comlex_filter_nn = comlex_filter_nn.view(batch, freq_bins, 2, self.filter_size, self.filter_size, time_bins)
505 | comlex_filter_nn = comlex_filter_nn.permute(0, 2, 5, 1, 3, 4)
506 | covariance_nn = get_covariance_v2(spectrograms, comlex_filter_nn, self.filter_size)
507 | covariance_nn = self.covariance_ln_nn(covariance_nn)
508 | covariance_nn = covariance_nn.unsqueeze(dim=4)
509 |
510 | # TODO
511 | covariance_set = torch.cat((covariance_ss, covariance_nn), dim=4) # B,2,T,F,2,6,6
512 |
513 | covariance_set = covariance_set.permute(2, 0, 3, 1, 4, 5, 6)
514 | # (time bins, batch, freq bins, 2, 2, channels, channels)
515 | covariance_set = covariance_set.reshape(time_bins, batch, freq_bins, 2, 2, channels *channels)
516 | covariance_set = covariance_set.reshape(time_bins, batch, freq_bins, 2, 2* channels *channels)
517 | covariance_set = covariance_set.reshape(time_bins, batch, freq_bins, 2* 2* channels *channels)
518 |
519 | covariance_set_doa = covariance_set
520 | covariance_set_doa = covariance_set_doa.permute(1,3,0,2)
521 | convariance_set_doa_list.append(covariance_set_doa) # (B, 144, T, F)
522 |
523 | covariance_set = covariance_set.reshape(time_bins, batch * freq_bins, 2* 2* channels *channels)
524 | covariance_set = covariance_set.permute(1,0,2) # [B*F, T, 144]
525 |
526 | convariance_set_bss_list.append(covariance_set) # [B*F, T, 144]
527 |
528 | '''Branch_1'''
529 | # DoA_1
530 | # as1_freq = self.conv1_doa(convariance_set_doa_list[0]) # [B, 210*n_avb_mics, T, F]
531 | # as1_loc_emb = as1_freq.permute(0, 3, 2, 1) # [B, F, T, 210*n_avb_mics]
532 | # as1_freq = as1_freq.reshape(batch, 210, self.n_avb_mics, time_bins, freq_bins) # [B, 210, n_avb_mics, T, F]
533 | # as1_freq = as1_freq.reshape(batch, 210, self.n_avb_mics*time_bins, freq_bins) # [B, 210, T*n_avb_mics, F]
534 | # as1_freq_emb = as1_freq # [B, 210, T*n_avb_mics, F]
535 | # as1_freq = as1_freq.reshape(batch, 210, time_bins, self.n_avb_mics, freq_bins)
536 | # as1_freq = as1_freq.reshape(batch*self.n_avb_mics, 210, time_bins, freq_bins)
537 | # as1_freq = as1_freq.permute(0, 3, 2, 1) # [B*n_avb_mics, F, T, 210]
538 | # as1_freq_emb = self.conv_emb_doa(as1_freq_emb) # [B, 1, T*n_avb_mics, F]
539 | # as1_freq_emb = as1_freq_emb.squeeze(dim=1) # [B, T*n_avb_mics, F]
540 | # as1_freq_emb = as1_freq_emb.reshape(batch, time_bins, freq_bins, self.n_avb_mics) # [B, T, F, n_avb_mics]
541 | # as1_freq_emb = as1_freq_emb.reshape(batch * freq_bins, time_bins, self.n_avb_mics) # [B*F, T, n_avb_mics]
542 |
543 | ###
544 | as1_freq = self.conv1_doa(convariance_set_doa_list[0]) # [B, 210*n_avb_mics, T, F]
545 | as1_freq = as1_freq.permute(0, 3, 2, 1) # [B, F, T, 210*n_avb_mics]
546 | as1_freq_emb = as1_freq.reshape(batch * freq_bins, time_bins, 210*self.n_avb_mics) # [B*F, T, 210*n_avb_mics]
547 | as1_freq = as1_freq.reshape(batch, freq_bins, time_bins, 210, self.n_avb_mics)
548 | as1_freq = as1_freq.reshape(batch*self.n_avb_mics, freq_bins, time_bins, 210) # [B*n_avb_mics, F, T, 210]
549 |
550 | as_1 = self.conv2_doa(as1_freq) # (B*n_avb_mics, 1, T, 210)
551 | as_1 = as_1.squeeze(dim=1) # [B*n_avb_mics, T, 210]
552 | azis_1, _ = self.gru_doa(as_1) # [B*n_avb_mics, T, 210]
553 | azis_1 = azis_1.reshape(batch, self.n_avb_mics, time_bins, 210) # [B, n_avb_mics, T, 210]
554 | azis_1 = azis_1.permute(0, 2, 1, 3) # [B, T, n_mics=n_avb_mics, 210]
555 | doas_1 = torch.max(azis_1, dim=3)[1]
556 | xy1 = self.triangulation(doas_1) # [B, T, 2]
557 | xy1_emb = torch.repeat_interleave(xy1.unsqueeze(dim=1),repeats=257,dim=1) # [B, F, T, 2]
558 | xy1_emb = xy1_emb.reshape(batch*freq_bins, time_bins, 2) # [B*F, T, 2]
559 |
560 | # BSS_1
561 | convariance_set_with_sps_1 = torch.cat((convariance_set_bss_list[0], as1_freq_emb, xy1_emb), dim=2)
562 | # convariance_set_with_sps_1 = torch.cat((convariance_set_bss_list[0], as1_freq_emb), dim=2)
563 | covariance_set_bss_1 = self.linear_bss_1(convariance_set_with_sps_1) # [B*F, T, 300]
564 | gru_output_w1, _ = self.gru_bss_1(covariance_set_bss_1) # [B*F, T, 300]
565 | gru_output_w1 = gru_output_w1.reshape(batch, freq_bins, time_bins, 300)
566 | gru_output_w1 = gru_output_w1.permute(2, 0, 1, 3)
567 | w1 = self.linear_w1(gru_output_w1) # (time_bins, batch, freq_bins, channels * 2)
568 | w1 = w1.reshape(time_bins, batch, freq_bins, channels, 2) # (time_bins, batch, freq_bins, channels, 2)
569 | beamformer_1 = w1.permute(1, 0, 4, 2, 3) # (batch, time_bins, 2, freq_bins, channels)
570 | beamformer_1 = beamformer_1.unsqueeze(dim=5) # (batch, time_bins, 2, freq_bins, channels, 1)
571 |
572 | '''Branch_2'''
573 | # DoA_2
574 | # as2_freq = self.conv1_doa(convariance_set_doa_list[1]) # [B, 210*n_avb_mics, T, F]
575 | # as2_freq = as2_freq.reshape(batch, 210, self.n_avb_mics, time_bins, freq_bins)
576 | # as2_freq = as2_freq.reshape(batch, 210, self.n_avb_mics*time_bins, freq_bins) # [B, 210, T*n_avb_mics, F]
577 | # as2_freq_emb = as2_freq # [B, 210, T*n_avb_mics, F]
578 | # as2_freq = as2_freq.reshape(batch, 210, time_bins, self.n_avb_mics, freq_bins)
579 | # as2_freq = as2_freq.reshape(batch*self.n_avb_mics, 210, time_bins, freq_bins)
580 | # as2_freq = as2_freq.permute(0, 3, 2, 1) # [B*n_avb_mics, F, T, 210]
581 | # as2_freq_emb = self.conv_emb_doa(as2_freq_emb) # [B, 1, T*n_avb_mics, F]
582 | # as2_freq_emb = as2_freq_emb.squeeze(dim=1) # [B, T*n_avb_mics, F]
583 | # as2_freq_emb = as2_freq_emb.reshape(batch, time_bins, freq_bins, self.n_avb_mics) # [B, T, F, n_avb_mics]
584 | # as2_freq_emb = as2_freq_emb.reshape(batch * freq_bins, time_bins, self.n_avb_mics) # [B*F, T, n_avb_mics]
585 |
586 | ###
587 | as2_freq = self.conv1_doa(convariance_set_doa_list[1]) # [B, 210*n_avb_mics, T, F]
588 | as2_freq = as2_freq.permute(0, 3, 2, 1) # [B, F, T, 210*n_avb_mics]
589 | as2_freq_emb = as2_freq.reshape(batch * freq_bins, time_bins, 210*self.n_avb_mics) # [B*F, T, 210*n_avb_mics]
590 | as2_freq = as2_freq.reshape(batch, freq_bins, time_bins, 210, self.n_avb_mics)
591 | as2_freq = as2_freq.reshape(batch*self.n_avb_mics, freq_bins, time_bins, 210) # [B*n_avb_mics, F, T, 210]
592 |
593 | as_2 = self.conv2_doa(as2_freq) # (B*n_avb_mics, 1, T, 210)
594 | as_2 = as_2.squeeze(dim=1) # [B*n_avb_mics, T, 210]
595 | azis_2, _ = self.gru_doa(as_2) # [B*n_avb_mics, T, 210]
596 | azis_2 = azis_2.reshape(batch, self.n_avb_mics, time_bins, 210) # [B, n_avb_mics, T, 210]
597 | azis_2 = azis_2.permute(0, 2, 1, 3) # [B, T, n_mics=n_avb_mics, 210]
598 | doas_2 = torch.max(azis_2, dim=3)[1]
599 | xy2 = self.triangulation(doas_2) # [B, T, 2]
600 | xy2_emb = torch.repeat_interleave(xy2.unsqueeze(dim=1),repeats=257,dim=1) # [B, F, T, 2]
601 | xy2_emb = xy2_emb.reshape(batch*freq_bins, time_bins, 2) # [B*F, T, 2]
602 |
603 | # BSS_2
604 | convariance_set_with_sps_2 = torch.cat((convariance_set_bss_list[1], as2_freq_emb, xy2_emb), dim=2)
605 | # convariance_set_with_sps_2 = torch.cat((convariance_set_bss_list[1], as2_freq_emb), dim=2)
606 | covariance_set_bss_2 = self.linear_bss_2(convariance_set_with_sps_2)
607 | gru_output_w2, _ = self.gru_bss_2(covariance_set_bss_2)
608 | gru_output_w2 = gru_output_w2.reshape(batch, freq_bins, time_bins, 300)
609 | gru_output_w2 = gru_output_w2.permute(2, 0, 1, 3)
610 | w2 = self.linear_w2(gru_output_w2) # (time_bins, batch, freq_bins, channels * 2)
611 | w2 = w2.reshape(time_bins, batch, freq_bins, channels, 2) # (time_bins, batch, freq_bins, channels, 2)
612 | beamformer_2 = w2.permute(1, 0, 4, 2, 3) # (batch, time_bins, 2, freq_bins, channels)
613 | beamformer_2 = beamformer_2.unsqueeze(dim=5) # (batch, time_bins, 2, freq_bins,channels, 1)
614 |
615 | '''Beamformer Separation'''
616 | spec = torch.unsqueeze(spectrograms, 4) # (batch, channels, 2*freq_bins,time_bins, 1)
617 | # (batch, channels, 2, freq_bins, time bins, 1)
618 | spec = spec.reshape(batch, channels, 2, freq_bins, time_bins, 1)
619 | spec = spec.permute(0, 4, 2, 3, 1, 5) # (batch, time bins, 2, freq_bins, channels, 1)
620 | spec_real = spec[:, :, 0, :, :, :]# (batch, time bins, freq bins, channels, 1)
621 | spec_imag = spec[:, :, 1, :, :, :] # (batch,time bins, freq bins,channels, 1)
622 |
623 | beamformer_list = []
624 | extract_signal_list = []
625 | beamformer_list.append(beamformer_1)
626 | beamformer_list.append(beamformer_2)
627 |
628 | for beamformer in beamformer_list:
629 | beamformer_real = beamformer[:, :, 0, ...] # (batch,time bins, freq_bins,channels, 1)
630 | beamformer_imag = beamformer[:, :, 1, ...] # (batch, time bins, freq bins,channels, 1)
631 | beamformer_real = beamformer_real.permute(0, 1, 2, 4, 3) # (batch, time_ bins, freq_bins,1, channels)
632 | beamformer_imag = beamformer_imag.permute(0, 1, 2, 4, 3) #(batch, time_bins, freqg_bins, 1, channels)
633 |
634 | enhancement_real = torch.matmul(beamformer_real, spec_real) - torch.matmul(beamformer_imag, spec_imag)
635 | enhancement_imag = torch.matmul(beamformer_real, spec_imag) + torch.matmul(beamformer_imag, spec_real)#( batch, time bins, freq bins, 1, 1)
636 |
637 | enhancement_real = enhancement_real.squeeze(dim=-1) # (batch, time_bins, freq_bins, 1)
638 | enhancement_imag = enhancement_imag.squeeze(dim=-1) # (batch, time_bins,freq_bins, 1)
639 |
640 | enhancement_real = enhancement_real.permute(0, 1, 3, 2)
641 | enhancement_imag = enhancement_imag.permute(0, 1, 3, 2)
642 |
643 | enhancement = torch.cat((enhancement_real, enhancement_imag), dim=2) # batch, time_bins, 2, freq_bins
644 | enhancement = enhancement. reshape(batch, time_bins, 2 * freq_bins) # batch, time bins, 2 * freq bins
645 | enhancement = enhancement.permute(0, 2, 1) # batch, 2 * freq bins, time_bins
646 | '''do iSTFT'''
647 | extract_signal = self.istftConv(enhancement) # batch, 1, time_samples
648 | extract_signal_list.append(extract_signal)
649 |
650 | extract_signal_1 = extract_signal_list[0] # [B, 1, T]
651 | extract_signal_2 = extract_signal_list[1]
652 |
653 | return azis_1, azis_2, extract_signal_1, extract_signal_2
654 | # return azis_1, azis_2, xy1, xy2, extract_signal_1, extract_signal_2
655 |
656 | if __name__ == '__main__':
657 | # e1 = np.random.randn(4, 32000)
658 | # e2 = np.random.randn(4, 32000)
659 | # c1 = np.random.randn(4, 32000)
660 | # c2 = np.random.randn(4, 32000)
661 | # print(f'e1.shape {e1.shape} e2.shape {e2.shape}')
662 | # print(f'c1.shape {c1.shape} c2.shape {c2.shape}')
663 | # print(pit_sisdr_numpy(e1, e2, c1, c2))
664 | inputs = torch.randn((4, 6, 64000))
665 | model = Tree()
666 | model.to(torch.device('cpu'))
667 | sps_1, sps_2, es_sig_1, es_sig_2 = model(inputs)
668 | print(f'sps_1.shape {sps_1.shape} sps_2.shape {sps_2.shape}', flush=True)
669 | print(f'es_sig_1.shape {es_sig_1.shape} es_sig_2.shape {es_sig_2.shape}', flush=True)
670 |
671 |
672 |
673 |
--------------------------------------------------------------------------------
/preparation/1_sb_vad.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import sys
3 | sys.path.append("/Work21/2021/fuyanjie/libs/speechbrain/speechbrain/pretrained")
4 | from interfaces import VAD
5 | import os
6 | import glob
7 |
8 | """
9 | RUN this script for trainset, devset and testset, respectively
10 | """
11 |
12 | device = torch.device('cuda')
13 | # device = torch.device('cpu')
14 |
15 | VAD = VAD.from_hparams(source="speechbrain/vad-crdnn-libriparty", savedir="pretrained_models/vad-crdnn-libriparty")
16 | VAD.to(device)
17 |
18 | # wav_path_pattern = '/CDShare3/LibriSpeech/train-clean-100/*/*/*.flac'
19 | wav_path_pattern = '/CDShare3/LibriSpeech/dev-clean/*/*/*.flac'
20 | files = glob.glob(wav_path_pattern)
21 |
22 | # output_folder = '/Work21/2021/fuyanjie/pycode/LaBNet/data/metadata/vad/train-clean-100/'
23 | output_folder = '/Work21/2021/fuyanjie/pycode/LaBNet/data/metadata/vad/dev-clean/'
24 |
25 | for audio_file in files:
26 | try:
27 | print(f'{audio_file}', flush=True)
28 | boundaries = VAD.get_speech_segments(audio_file)
29 |
30 | file_name = str(audio_file).split('/')[-1]
31 | spkid = file_name.split('-')[0]
32 |
33 | save_folder = os.path.join(output_folder, spkid)
34 | if not os.path.exists(save_folder):
35 | os.makedirs(save_folder)
36 | save_path = os.path.join(save_folder, file_name.replace('.flac', '.txt'))
37 | print('save_path ', save_path, flush=True)
38 | # Print the output
39 | VAD.save_boundaries(boundaries, save_path=save_path)
40 | except Exception as e:
41 | print(f'Exception: {e}')
42 | continue
--------------------------------------------------------------------------------
/preparation/2_clip_segments.py:
--------------------------------------------------------------------------------
1 | import os
2 | import numpy as np
3 | import soundfile as sf
4 |
5 | """
6 | RUN this script for trainset, devset and testset, respectively
7 | """
8 |
9 | SR = 16000
10 | SEG_DURATION = 4 # duration in seconds
11 | SEG_LEN = SEG_DURATION * SR
12 |
13 | def clip_train_dev_test_segs(dataset_split):
14 | librispeech_path = f"/CDShare3/LibriSpeech/{dataset_split}"
15 | vad_results_path = f"/Work21/2021/fuyanjie/pycode/LaBNet/data/metadata/vad/{dataset_split}"
16 | output_libri_segments_dir = f"/CDShare3/LibriSpeechSegments/{dataset_split}"
17 |
18 | vad_res_spks = os.listdir(vad_results_path)
19 | for vad_res_spk in vad_res_spks:
20 | spkid = vad_res_spk
21 | vad_res_spk = os.path.join(vad_results_path, vad_res_spk)
22 | vad_res_utts = os.listdir(vad_res_spk)
23 | for vad_res_utt in vad_res_utts:
24 | uttid = vad_res_utt[:-4]
25 | chapid = uttid.split('-')[1]
26 | vad_res_utt = os.path.join(vad_res_spk, vad_res_utt)
27 | lines = open(vad_res_utt, 'r').readlines()
28 | start_idx = None
29 | end_idx = None
30 | if len(lines) == 1:
31 | seg_data = lines[0].split(' ')
32 | if float(seg_data[4]) < SEG_DURATION or seg_data[-1].startswith('N'):
33 | continue
34 | print(f'seg_data {seg_data}', flush=True)
35 | start_idx = 0
36 | end_idx = float(seg_data[4]) * SR
37 | else:
38 | for row_idx, line in enumerate(lines):
39 | seg_data = line.split(' ')
40 | print(f'seg_data {seg_data}', flush=True)
41 | if seg_data[-1].startswith('S'):
42 | duration = float(seg_data[4]) - float(seg_data[2])
43 | if duration > 4:
44 | start_idx = float(seg_data[2]) * SR
45 | end_idx = float(seg_data[4]) * SR
46 | if not start_idx or not end_idx:
47 | continue
48 |
49 | utt_path = os.path.join(librispeech_path, spkid, chapid, uttid + '.flac')
50 | wave_data, sr = sf.read(utt_path)
51 | end_idx = int(start_idx) + SEG_LEN
52 | seg_data = wave_data[int(start_idx):end_idx]
53 | dst_parent_dir = os.path.join(output_libri_segments_dir, spkid, chapid)
54 | os.makedirs(dst_parent_dir, exist_ok=True)
55 | dst_path = os.path.join(dst_parent_dir, uttid + '.flac')
56 | print(f'dst_path {dst_path}', flush=True)
57 | sf.write(dst_path, seg_data, 16000)
58 |
59 | def clip_wer_test_segs(dataset_split):
60 | librispeech_path = f"/CDShare3/LibriSpeech/{dataset_split}"
61 | vad_results_path = f"/Work21/2021/fuyanjie/pycode/LaBNet/data/metadata/vad/{dataset_split}"
62 | output_libri_segments_dir = f"/CDShare3/LibriSpeechSegments/{dataset_split}_wer"
63 |
64 | vad_res_spks = os.listdir(vad_results_path)
65 | vad_res_spks.sort()
66 | index = 0
67 | for vad_res_spk in vad_res_spks:
68 | spkid = vad_res_spk
69 | vad_res_spk = os.path.join(vad_results_path, vad_res_spk)
70 | vad_res_utts = os.listdir(vad_res_spk)
71 | vad_res_utts.sort()
72 | for vad_res_utt in vad_res_utts:
73 | try:
74 | index += 1
75 | random_state = np.random.RandomState(index)
76 |
77 | uttid = vad_res_utt[:-4]
78 | chapid = uttid.split('-')[1]
79 | vad_res_utt = os.path.join(vad_res_spk, vad_res_utt)
80 | lines = open(vad_res_utt, 'r').readlines()
81 | print(f'vad_res_utt {vad_res_utt}', flush=True)
82 |
83 | seg_data = lines[-1].split(' ')
84 | if float(seg_data[4]) > SEG_DURATION:
85 | continue
86 | print(f'seg_data {seg_data}', flush=True)
87 |
88 | utt_path = os.path.join(librispeech_path, spkid, chapid, uttid + '.flac')
89 | wave_data, sr = sf.read(utt_path)
90 | # print(f'{wave_data.shape} {wave_data.shape[-1]}')
91 | if wave_data.shape[-1] > SEG_LEN or wave_data.shape[-1] < SR * 3.5:
92 | continue
93 | # randomly padding to 4 secs long segment
94 | wave_padding_data = np.zeros(SEG_LEN)
95 |
96 | start_idx = random_state.randint(0, SEG_LEN - wave_data.shape[-1])
97 | end_idx = start_idx + len(wave_data)
98 | wave_padding_data[start_idx:end_idx] = wave_data
99 | seg_data = wave_padding_data
100 | print(f'start_idx {start_idx} end_idx {end_idx}', flush=True)
101 |
102 | dst_parent_dir = os.path.join(output_libri_segments_dir, spkid, chapid)
103 | os.makedirs(dst_parent_dir, exist_ok=True)
104 | dst_path = os.path.join(dst_parent_dir, uttid + '.flac')
105 | print(f'dst_path {dst_path}', flush=True)
106 | sf.write(dst_path, seg_data, 16000)
107 | except Exception as e:
108 | print(f'Exception: {e}')
109 | continue
110 |
111 | if __name__ == '__main__':
112 | # dataset_split = 'train-clean-100'
113 | # clip_train_dev_test_segs(dataset_split)
114 | # dataset_split = 'dev-clean'
115 | # clip_train_dev_test_segs(dataset_split)
116 | # dataset_split = 'test-clean'
117 | # clip_train_dev_test_segs(dataset_split)
118 | dataset_split = 'test-clean'
119 | clip_wer_test_segs(dataset_split)
120 |
--------------------------------------------------------------------------------
/preparation/3_generate_list.py:
--------------------------------------------------------------------------------
1 | import librosa
2 | import os
3 | import math
4 | import soundfile as sf
5 |
6 | def generate_flac_list(libri_segments_dir, output_list_path):
7 | spkids = os.listdir(libri_segments_dir)
8 | count = 0
9 | with open(output_list_path, 'w', encoding='utf-8') as output_f:
10 | for spkid in spkids:
11 | spk_dir = os.path.join(libri_segments_dir, spkid)
12 | chapids = os.listdir(spk_dir)
13 | for chapid in chapids:
14 | chap_dir = os.path.join(spk_dir, chapid)
15 | wav_names = os.listdir(chap_dir)
16 | for wav_name in wav_names:
17 | wav_path = os.path.join(chap_dir, wav_name)
18 | print(f'wav_path {wav_path}')
19 | output_f.write(wav_path + '\n')
20 | count += 1
21 | print('Finish count:{} | {}'.format(count, wav_path))
22 |
23 | def generate_spk_list(libri_segments_dir, output_list_path):
24 | spkids = os.listdir(libri_segments_dir)
25 | spkids.sort()
26 | with open(output_list_path, 'w', encoding='utf-8') as output_f:
27 | for spkid in spkids:
28 | output_f.write(spkid + '\n')
29 |
30 | def summarize_transcription(librispeech_path, libri_segments_dir, output_txt_path):
31 | spkids = os.listdir(libri_segments_dir)
32 | count = 0
33 | with open(output_txt_path, 'w', encoding='utf-8') as output_f:
34 | for spkid in spkids:
35 | spk_dir = os.path.join(libri_segments_dir, spkid)
36 | chapids = os.listdir(spk_dir)
37 | for chapid in chapids:
38 | chap_dir = os.path.join(spk_dir, chapid)
39 | wav_names = os.listdir(chap_dir)
40 | uttids = []
41 | for wav_name in wav_names:
42 | uttid = wav_name[:-5]
43 | print(f'uttid {uttid}')
44 | uttids.append(uttid)
45 | src_txt_path = os.path.join(librispeech_path, spkid, chapid, f'{spkid}-{chapid}.trans.txt')
46 | src_txt = open(src_txt_path, 'r').readlines()
47 | for line in src_txt:
48 | line = line.strip()
49 | uttid, txt = line.split(' ', 1)
50 | print(f'uttid: {uttid} txt: {txt}')
51 | if uttid in uttids:
52 | output_f.write(uttid + ' ' + txt + '\n')
53 | count += 1
54 | print('Finish count:{} | {}'.format(count, uttid))
55 |
56 |
57 | if __name__ == '__main__':
58 | # dataset_split = 'test-clean'
59 | dataset_split = 'test-clean_wer'
60 | libri_segments_dir = f'/CDShare3/LibriSpeechSegments/{dataset_split}'
61 | output_flac_list_path = f'/Work21/2021/fuyanjie/pycode/LaBNet/data/libri_segments_list/{dataset_split}.lst'
62 | output_spk_list_path = f'/Work21/2021/fuyanjie/pycode/LaBNet/data/libri_segments_list/{dataset_split}_spk.lst'
63 | generate_flac_list(libri_segments_dir, output_flac_list_path)
64 | generate_spk_list(libri_segments_dir, output_spk_list_path)
65 |
66 | librispeech_path = f"/CDShare3/LibriSpeech/test-clean"
67 | libri_segments_dir = '/CDShare3/LibriSpeechSegments/test-clean_wer'
68 | output_txt_path = '/CDShare3/LibriSpeechSegments/test-clean_wer/test-clean_wer.txt'
69 | summarize_transcription(librispeech_path, libri_segments_dir, output_txt_path)
--------------------------------------------------------------------------------
/preparation/libri_sim_code/4_gen_simulated_room.py:
--------------------------------------------------------------------------------
1 | import math
2 | import multiprocessing as mp
3 | import os
4 | import random
5 | import re
6 | import shutil
7 | import time
8 | from concurrent.futures.process import ProcessPoolExecutor
9 | from functools import partial
10 | from joblib import Parallel, delayed
11 | import sys
12 | import wave
13 | import glob
14 | sys.path.append("/Work21/2021/fuyanjie/pycode/LaBNet/libri_sim_code")
15 |
16 | import numpy as np
17 | import soundfile as sf
18 |
19 | from gen_room_para import gen_room_para, gen_mulchannel_data_random, gen_mulchannel_data_angle
20 |
21 | MAX_WORKERS = 10
22 | SEED = 42
23 |
24 | def get_first_level_folder(dir):
25 | folder_list = []
26 | for entry in os.scandir(dir):
27 | if entry.is_dir():
28 | folder_list.append(entry.path)
29 |
30 | return folder_list
31 |
32 |
33 | def generate_wav_list_from_lst_file(lst_file):
34 | with open(lst_file, "r", encoding='utf-8-sig') as f:
35 | file_list = f.readlines()
36 |
37 | return file_list
38 |
39 |
40 | def save_audio_separately(audio, path, fs):
41 | channels, length = audio.shape
42 |
43 | for channel in range(channels):
44 | suffix = '_multichannel_' + str(channel) + '.wav'
45 |
46 | out_data = np.reshape(audio[channel, :], [length, 1])
47 |
48 | out_data = out_data.astype(np.int16)
49 |
50 | with wave.open(path+suffix, 'wb') as f:
51 | f.setframerate(fs)
52 | f.setsampwidth(2)
53 | f.setnchannels(1)
54 | f.writeframes(out_data.tostring())
55 |
56 |
57 | def __sim_stationary_noise(folder, max_gen_num, wav_list, fs, speech_length):
58 | room_para_path = os.path.join(folder, 'room_para.npy')
59 | room_para = np.load(room_para_path, allow_pickle=True).item()
60 |
61 | # used_wav_num = random.randint(5, 10)
62 | used_wav_num = 1
63 | wav_samples = random.sample(wav_list, used_wav_num)
64 | print(f'num of wav_samples {len(wav_samples)}')
65 |
66 | # judge if multi-channel stationary noise wav files exist
67 | # file_list = os.listdir(os.path.join(folder, 'stationary_noise'))
68 | st_noise_dir = os.path.join(folder, 'stationary_noise')
69 | if os.path.exists(st_noise_dir) and len(os.listdir(st_noise_dir)) > 0:
70 | print(f'{st_noise_dir} is not empty!')
71 | return
72 |
73 | for num in range(max_gen_num):
74 | # 生成多个多通道平稳噪声数据
75 | mulchannel_audio_data_list = []
76 | for wav_file in wav_samples:
77 | multichannel_audio_data, _, angle_degree = gen_mulchannel_data_random(wav_file.strip(),
78 | room_para,
79 | folder,
80 | audio_type=0,
81 | fs=fs,
82 | segment_length=speech_length)
83 | multichannel_audio_data = multichannel_audio_data[:, 0:fs * speech_length]
84 | mulchannel_audio_data_list.append(multichannel_audio_data)
85 |
86 | # 对生成数据幅度进行一下调整,再进行叠加
87 | out_mulchannel_audio_data = np.zeros_like(mulchannel_audio_data_list[0], dtype=np.int16)
88 | for data in mulchannel_audio_data_list:
89 | out_mulchannel_audio_data += data
90 |
91 | # 将生成好的数据进行保存
92 | mic_num, _ = out_mulchannel_audio_data.shape
93 | save_folder = os.path.join(folder, 'stationary_noise')
94 | output_file_path = os.path.join(save_folder, 'stationary_noise_{}'.format(num))
95 | save_audio_separately(out_mulchannel_audio_data, output_file_path, fs=fs)
96 |
97 |
98 | def sim_stationary_noise(base_dir, stationary_noise_lst_file, sim_room_num, max_stationary_noise_num, fs, room_transpose_prob, speech_length):
99 | '''
100 | 利用多个平稳噪声模拟真实环境下的多通道平稳噪声,每个房间就仿真一条数据,主要目的是为了更好模拟不同环境下的平稳噪声
101 | :param base_dir: 根目录,用于保存不同房间的数据
102 | :param stationary_noise_lst_file: 平稳噪声列表文件
103 | :param sim_room_num: 模拟不同房间的数目
104 | :param max_stationary_noise_num: 最多使用平稳噪声的数目
105 | :param fs:
106 | :return:
107 | '''
108 | for i in range(sim_room_num):
109 | _ = gen_room_para(base_dir, room_transpose_prob=room_transpose_prob)
110 |
111 | room_folders = get_first_level_folder(base_dir)
112 | wav_list = list(generate_wav_list_from_lst_file(stationary_noise_lst_file))
113 |
114 | Parallel(n_jobs=MAX_WORKERS)(delayed(__sim_stationary_noise)(room_folder, max_stationary_noise_num, wav_list, fs, speech_length) for room_folder in room_folders)
115 | # with ProcessPoolExecutor(MAX_WORKERS) as ex:
116 | # func = partial(__sim_stationary_noise, max_gen_num=max_stationary_noise_num, wav_list=wav_list,
117 | # fs=fs, speech_length=speech_length)
118 | # ex.map(func, room_folders)
119 |
120 |
121 | def __sim_speech(seed_idx, folder, libri_segments_dir, fs, cover_angle_range, multi_list, segment_length, speaker_list, angular_spacing):
122 | random_state = np.random.RandomState(seed_idx * SEED)
123 |
124 | room_para_path = os.path.join(folder, 'room_para.npy')
125 | room_para = np.load(room_para_path, allow_pickle=True).item()
126 |
127 | # if room_para['room_dim'][1] < 5:
128 | # cover_angle_range = [20, 160]
129 | # elif room_para['room_dim'][1] >= 5 and room_para['room_dim'][1] < 7:
130 | # cover_angle_range = [15, 165]
131 | # elif room_para['room_dim'][1] >= 7:
132 | # cover_angle_range = [10, 170]
133 | # 声明多通道人声数据保存路径
134 | mulchannel_speech_folder = os.path.join(folder, 'speech')
135 |
136 | cover_angle_num = (cover_angle_range[1] - cover_angle_range[0]) // angular_spacing
137 |
138 | speaker_folder = ""
139 | speaker_folders = []
140 | speaker_lsts = []
141 | seen_speaker_lsts = []
142 |
143 | with open(speaker_list) as fid:
144 | for line in fid:
145 | seen_speaker_lsts.append(line.strip())
146 |
147 | if not multi_list:
148 | speaker_folder = libri_segments_dir
149 | print(f'speaker_folder {speaker_folder}', flush=True)
150 | speaker_lst = seen_speaker_lsts
151 | print(f'speaker_lst {speaker_lst}', flush=True)
152 | speaker_idx_lst = np.arange(len(speaker_lst))
153 | random_state.shuffle(speaker_idx_lst)
154 | speaker_idx_lst = speaker_idx_lst[:cover_angle_num * 2]
155 |
156 | # get the wav_id list
157 | wav_id_file_path = os.path.join(folder, 'speech_wav_id_lst.lst')
158 | if os.path.exists(wav_id_file_path):
159 | wav_id_lst = []
160 | with open(wav_id_file_path, 'r', encoding='utf-8') as f:
161 | wav_id_set = f.readlines()
162 |
163 | for wav_id in wav_id_set:
164 | wav_id = wav_id.strip()
165 | wav_id_lst.append(wav_id)
166 | else:
167 | wav_id_lst = []
168 | angle = cover_angle_range[0]
169 | index = 0
170 | while True:
171 | index %= len(speaker_idx_lst)
172 | k = speaker_idx_lst[index]
173 | index += 1
174 | wav_lst = glob.glob(os.path.join(speaker_folder, speaker_lst[k]) + '/*/*.flac')
175 | wav_name = random.sample(wav_lst, 1)[0]
176 |
177 | if speaker_lst[k] not in wav_id_lst:
178 | wav_path = os.path.join(speaker_folder, speaker_lst[k])
179 | wav_path = os.path.join(wav_name.split('-')[1], wav_name)
180 |
181 | # if angle >= 55:
182 | # angular_spacing = 5
183 | # if angle >= 120:
184 | # angular_spacing = 10
185 | # random_range = random.randint(0, angular_spacing - 1)
186 | # random_angle = angle + random_range
187 | random_angle = angle
188 |
189 |
190 | for dis_idx in range(3):
191 | multichannel_audio_data, wav_id, distance = gen_mulchannel_data_angle(wav_path,
192 | room_para,
193 | folder,
194 | angle=random_angle,
195 | distance_flag=dis_idx,
196 | fs=fs,
197 | segment_length=segment_length,
198 | audio_type=1)
199 |
200 | max_speech_value = np.max(np.abs(multichannel_audio_data))
201 |
202 |
203 | if max_speech_value > 32767:
204 | multichannel_audio_data = multichannel_audio_data / max_speech_value * 30000
205 | out_mulchannel_audio_data = multichannel_audio_data
206 |
207 |
208 | # 生成文件保存路径
209 | if dis_idx == 0:
210 | distance_type = "close"
211 | elif dis_idx == 1:
212 | distance_type = "middle"
213 | else:
214 | distance_type = "far"
215 | file_name = "{}-{}m-{}".format(wav_id, distance, distance_type)
216 | angle_speech_folder = os.path.join(mulchannel_speech_folder, f"{random_angle}-{wav_id.split('-')[0]}")
217 | os.makedirs(angle_speech_folder, exist_ok=True)
218 | save_file_path = os.path.join(angle_speech_folder, file_name)
219 |
220 | save_audio_separately(out_mulchannel_audio_data, save_file_path, fs=fs)
221 | print(save_file_path + " finish!")
222 |
223 | wav_id_lst.append(wav_id)
224 | angle = angle + angular_spacing
225 | if angle >= cover_angle_range[1] + 1 - angular_spacing:
226 | break
227 | else:
228 | continue
229 | # wait for all the wav simulation finish, write wav_id_lst in the wav_id_file_path
230 | with open(wav_id_file_path, 'w', encoding='utf-8') as f:
231 | for wav_id in wav_id_lst:
232 | f.write(wav_id + '\n')
233 |
234 | def sim_speech(base_dir, libri_segments_dir, fs, cover_angle_range, segment_length, speaker_list,
235 | angular_spacing):
236 | '''
237 | 模拟多通道人声数据
238 | :param base_dir: 根目录
239 | :param libri_segments_dir: 单通道人声文件夹
240 | :param max_wav_num:
241 | :param fs:
242 | :return:
243 | '''
244 | room_folders = get_first_level_folder(base_dir)
245 |
246 | Parallel(n_jobs=MAX_WORKERS)(delayed(__sim_speech)(seed_idx, folder, libri_segments_dir, fs, cover_angle_range, False, segment_length, speaker_list, angular_spacing) for seed_idx, folder in enumerate(room_folders))
247 |
248 | # with ProcessPoolExecutor(MAX_WORKERS) as ex:
249 | # func = partial(__sim_speech, libri_segments_dir=libri_segments_dir, fs=fs, cover_angle_range=cover_angle_range, multi_list=False,
250 | # segment_length=segment_length, speaker_list=speaker_list, angular_spacing=angular_spacing)
251 | # ex.map(func, room_folders)
252 | # debug
253 | # for folder in room_folders:
254 | # __sim_speech(folder, libri_segments_dir, fs, cover_angle_range, False, segment_length, speaker_list, angular_spacing)
255 | # debug
256 |
257 |
258 | def __sim_non_stationary_noise(folder, sim_wav_num, wav_list, fs, cover_angle_range, speech_length, angular_spacing):
259 | room_para_path = os.path.join(folder, 'room_para.npy')
260 | room_para = np.load(room_para_path, allow_pickle=True).item()
261 |
262 | speech_path = os.path.join(folder, 'speech')
263 | angle_of_speech = os.listdir(speech_path)
264 | angle_of_speech = list(map(int, angle_of_speech))
265 | angle_of_speech.sort()
266 | print(f'angle_list_of_speech: {angle_of_speech}')
267 |
268 | # 声明多通道非平稳噪声数据保存路径
269 | mulchannel_nonstationary_noise_folder = os.path.join(folder, 'nonstationary_noise')
270 |
271 | cover_angle_num = (cover_angle_range[1] - cover_angle_range[0]) / angular_spacing
272 | cover_angle_num = math.floor(cover_angle_num)
273 |
274 | non_stationary_list = wav_list
275 | np.random.shuffle(non_stationary_list)
276 | non_stationary_list = non_stationary_list[:3 * cover_angle_num]
277 |
278 | angle = angle_of_speech[0]
279 | index = 0
280 | for wav in non_stationary_list:
281 | multichannel_audio_data, wav_id, distance = gen_mulchannel_data_angle(wav.strip(),
282 | room_para,
283 | folder,
284 | angle=angle,
285 | distance_flag=index % 3,
286 | fs=fs,
287 | segment_length=speech_length,
288 | audio_type=2)
289 |
290 | # out_mulchannel_audio_data = multichannel_audio_data - np.mean(multichannel_audio_data, axis=0)
291 | out_mulchannel_audio_data = multichannel_audio_data
292 |
293 | # 生成文件保存路径
294 | if index % 3 == 0:
295 | distance_type = "close"
296 | elif index % 3 == 1:
297 | distance_type = "middle"
298 | else:
299 | distance_type = "far"
300 | file_name = "{}-{}m-{}".format(wav_id, distance, distance_type)
301 | angle_speech_folder = os.path.join(mulchannel_nonstationary_noise_folder, str(angle))
302 |
303 | save_file_path = os.path.join(angle_speech_folder, file_name)
304 |
305 | save_audio_separately(out_mulchannel_audio_data, save_file_path, fs=fs)
306 | print(save_file_path + " finish!")
307 |
308 | if index % 3 == 2:
309 | angle = angle + angular_spacing
310 | index = index + 1
311 |
312 |
313 |
314 | def sim_non_stationary_noise(base_dir, mono_nonstationary_noise_lst_file, max_wav_num, fs, cover_angle_range,
315 | speech_length, angular_spacing):
316 | '''
317 | 模拟多通道非平稳噪声
318 | :param base_dir: 根目录
319 | :param mono_nonstationary_noise_lst_file: 单通道非平稳噪声文件列表文件
320 | :param max_wav_num:
321 | :param fs: 采样率
322 | :return:
323 | '''
324 | room_folders = get_first_level_folder(base_dir)
325 |
326 | wav_list = list(generate_wav_list_from_lst_file(mono_nonstationary_noise_lst_file))
327 | if len(wav_list) > max_wav_num:
328 | sim_wav_num = max_wav_num
329 | else:
330 | sim_wav_num = len(wav_list)
331 |
332 | with ProcessPoolExecutor(MAX_WORKERS) as ex:
333 | func = partial(__sim_non_stationary_noise, sim_wav_num=sim_wav_num, wav_list=wav_list, fs=fs,
334 | cover_angle_range=cover_angle_range, speech_length=speech_length,
335 | angular_spacing=angular_spacing)
336 | ex.map(func, room_folders)
337 |
338 |
339 | def single_proc(stationary_noise_lst, libri_segments_dir, non_stationary_noise_lst, save_path,
340 | sim_room_num, stationary_noise_num, fs, speech_length, cover_angle_range, room_transpose_prob, speaker_list, augular_spacing):
341 | print("MAX_WORKERS:", MAX_WORKERS)
342 |
343 | # Start timing¬
344 | start_time = time.time()
345 |
346 | # make directory of output data
347 | if not os.path.exists(save_path):
348 | os.makedirs(save_path)
349 | else:
350 | print(f'{save_path} already exists!')
351 | shutil.rmtree(save_path)
352 | print(f'remove {save_path}')
353 |
354 | # generate room parameters and stationary noise
355 | sim_stationary_noise(save_path, stationary_noise_lst, sim_room_num, stationary_noise_num, fs, room_transpose_prob, speech_length)
356 | print('Finish sim_stationary_noise')
357 |
358 | # generate multi-channel speech
359 | sim_speech(save_path, libri_segments_dir, fs, cover_angle_range, speech_length, speaker_list, augular_spacing)
360 | print('Finish sim_speech')
361 |
362 | # DO NOT INVOKE FOR NOW!
363 | # generate multi-channel non-stationary noise
364 | # sim_non_stationary_noise(save_path, non_stationary_noise_lst, non_stationary_num, fs, cover_angle_range, speech_length, augular_spacing)
365 | # print('Finish sim_non_stationary_noise')
366 |
367 | # End timing
368 | print('time spent: %s mins' % str((time.time() - start_time) / 60.0))
369 |
370 |
371 | if __name__ == '__main__':
372 | '''
373 | convert single channel format to multi-channel(6-channel) format of single voice.
374 |
375 | :param stationary_noise_lst: contains the absolute path of stationary noise .wav
376 | :param libri_segments_dir: contains clean audio files
377 | :param non_stationary_noise_lst: contains the absolute path of non-stationary noise .wav
378 | :param save_path: the output path of multi-channel data
379 | :param sim_room_num: the number of simulated rooms, each room contains specified number of stationary noise, speech, and non-stationary noise
380 | :param stationary_noise_num: the upper bound of the kind of stationary noise we choose
381 | :param speech_num: the number of simulated speech in each room
382 | :param non_stationary_num: the number of simulated non-stationary noise in each room
383 | :param fs: sample rate
384 | :return:
385 | '''
386 |
387 | # 设置路径参数
388 | # dataset_split = "train-clean-100"
389 | # dataset_split = "dev-clean"
390 | # dataset_split = "test-clean"
391 | dataset_split = "test-clean_wer"
392 | stationary_noise_lst = '/Work21/2020/yinhaoran/VCTK_simulated_data/list/clean_speech_3.lst'
393 | libri_segments_dir = f'/CDShare3/LibriSpeechSegments/{dataset_split}'
394 | non_stationary_noise_lst = '/non_stationary_noise.lst'
395 |
396 | speaker_lst = f'/Work21/2021/fuyanjie/pycode/LaBNet/data/libri_segments_list/{dataset_split}_spk.lst'
397 |
398 | # 设定合成参数
399 | sim_room_num = 10
400 | stationary_noise_num = 1
401 | fs = 16000
402 | speech_length = 4
403 | cover_angle_range = [0, 180]
404 | angular_spacing = 1 # 角度最小间隔
405 | room_transpose_prob = 0.5
406 |
407 | save_path = f'/CDShare3/Libri-SIM/rooms_0129/{dataset_split}_{sim_room_num}rooms'
408 |
409 | single_proc(stationary_noise_lst, libri_segments_dir, non_stationary_noise_lst, save_path, sim_room_num,
410 | stationary_noise_num, fs, speech_length, cover_angle_range, room_transpose_prob,
411 | speaker_lst, angular_spacing)
412 |
413 |
--------------------------------------------------------------------------------
/preparation/libri_sim_code/5_generate_json.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 _*-
2 | from itertools import groupby
3 | import json
4 | import os
5 | import pickle
6 | import random
7 | from acoustics.signal import highpass
8 |
9 | import librosa
10 | import numpy as np
11 | import soundfile as sf
12 |
13 | SEED = 7
14 | random.seed(SEED)
15 | sr = 16000
16 |
17 | def audioread(path, fs=16000):
18 | wave_data, sr = sf.read(path)
19 | if sr != fs:
20 | wave_data = librosa.resample(wave_data, sr, fs)
21 | return wave_data
22 |
23 |
24 | def generate_vad_label(orig_signal, sr = 16000, win_len = 0.032, hop_len = 0.016):
25 | original_signal = orig_signal / np.max(orig_signal) * 25000
26 | original_signal = highpass(original_signal, 100, sr, order =8)
27 |
28 | vad = np.ones(int(len(original_signal)/(hop_len * sr)))
29 |
30 | frame_shift = int(hop_len * sr) # 256
31 | frame_len = int(win_len * sr) # 512
32 |
33 | value_threshold = 110
34 |
35 | sig_100ms_len = int(0.01 * sr)
36 | frame_max_value = np.max(original_signal[:sig_100ms_len])
37 | if frame_max_value > value_threshold:
38 | value_threshold = frame_max_value
39 |
40 | for i in range(len(vad)):
41 | frame_data = original_signal[i * frame_shift : (i + 1) * frame_shift] # old: i -> i+1, changed: i -> i + length
42 | frame_data = np.abs(frame_data)
43 | frame_data = np.where(frame_data > value_threshold,0,1)
44 | if np.sum(frame_data) > frame_shift * 0.9 and vad[i] == 1:
45 | vad[i] = 0
46 |
47 | mid_len_speech = round(0.1 / hop_len + 0.1)
48 | mid_len_non_speech = round(0.05 / hop_len + 0.1)
49 | for i in range(len(vad)):
50 | if i < len(vad) - mid_len_speech - 2:
51 | if vad[i] == 0 and vad[i+mid_len_speech+1] == 0 and sum(vad[i+1:i+mid_len_speech+1] select_angle_min:
87 | available_list.append([select_angle_min, select_angle - min_interval])
88 | if select_angle + min_interval < select_angle_max:
89 | available_list.append([select_angle + min_interval, select_angle_max])
90 | return result
91 |
92 | def data_mix_angle_wav_cos(generate_sample_num, max_source_num, input_single_source_folder_path, out_folder_path, add_noise=0.2):
93 | '''
94 | 从多个混合音频中分离出一个目标角度的音频
95 | :param generate_sample_num:
96 | :param max_source_num:
97 | :param input_single_source_folder_path:
98 | :param out_folder_path:
99 | :param add_noise:
100 | :return:
101 | '''
102 | # 3 audio types for one room
103 | stationary_noise_flag = 'stationary_noise'
104 | speech_flag = 'speech'
105 | # non_stationary_noise_flag = 'nonstationary_noise'
106 |
107 | all_log = {}
108 | num_samples = np.zeros(4)
109 | max_num = 0
110 | dists = []
111 | sqrt_sample_num = int(np.sqrt(generate_sample_num))
112 | if not os.path.exists(out_folder_path):
113 | for folder_idx in range(sqrt_sample_num + 1):
114 | os.makedirs(os.path.join(out_folder_path, f'{folder_idx*sqrt_sample_num}-{(folder_idx+1)*sqrt_sample_num-1}'), exist_ok=True)
115 | else:
116 | exist_folders = os.listdir(out_folder_path)
117 | for folder in exist_folders:
118 | num_part = folder.split('_')[0]
119 | num = int(num_part.split('-')[1])
120 | if num > max_num:
121 | max_num = num
122 | print('existing samples: ', max_num)
123 |
124 | sample_pos = 0
125 | sample_idx = 0
126 | try:
127 | while 1:
128 | if sample_pos >= generate_sample_num:
129 | print(f'num_samples < 15: {num_samples[0]} 15-45 {num_samples[1]} 45-90 {num_samples[2]} >90 {num_samples[3]}', )
130 | break
131 | sample_log = {}
132 |
133 | random.seed(sample_idx)
134 | random_state = np.random.RandomState(sample_idx)
135 | sample_idx += 1
136 |
137 | # randomly choose a room
138 | rooms = os.listdir(input_single_source_folder_path)
139 | room = rooms[random.randint(0, len(rooms) - 1)]
140 | file_1st = input_single_source_folder_path + os.sep + room
141 | # get RIR
142 | tmp = room.split('_')
143 | rir = float(tmp[-1])
144 | file_2nd = file_1st # no reverb
145 | sample_log['room'] = room
146 | sample_log['rir'] = rir
147 | speech = file_1st + os.sep + speech_flag
148 | # non_stationary = file_1st + os.sep + non_stationary_noise_flag
149 | stationary = file_1st + os.sep + stationary_noise_flag
150 |
151 | stationary_noise_log = {}
152 | stationary_list = os.listdir(stationary)
153 | choose_stationary = random.sample(stationary_list, 1)[0]
154 |
155 | stationary_noise_log["wave_path"] = stationary + os.sep + choose_stationary.split('multichannel')[0] + 'multichannel'
156 |
157 | SNR = [10,20]
158 |
159 | stationary_noise_log["SNR"] = random.randint(SNR[0], SNR[1])
160 | sample_log["stationary_noise"] = stationary_noise_log
161 |
162 | if not os.path.exists(speech):
163 | continue
164 | all_speech = os.listdir(speech)
165 | # print("all_speech ", all_speech)
166 |
167 | if len(all_speech) < max_source_num:
168 | continue
169 |
170 | source_list = []
171 | angle_list = []
172 | spkid_list = []
173 | available_list = all_speech
174 | for i in range(max_source_num):
175 | chosen_subfolder = random.sample(available_list, 1)[0]
176 | chosen_angle, chosen_spkid = chosen_subfolder.split('-')
177 | source_list.append(chosen_subfolder)
178 | angle_list.append(chosen_angle)
179 | spkid_list.append(chosen_spkid)
180 | new_available_list = []
181 | for available_subfolder in available_list:
182 | available_angle, available_spkid = available_subfolder.split('-')
183 | if available_spkid not in spkid_list:
184 | # if np.abs(int(available_angle)-int(chosen_angle))>5 and available_spkid not in spkid_list:
185 | new_available_list.append(available_subfolder)
186 | available_list = new_available_list
187 |
188 | SIR = [-10, 10]
189 |
190 | for index, source in enumerate(source_list):
191 | angle = float(source.split('-')[0])
192 | sample_source_log = {}
193 | # 从某个房间的某种混响下选取 single_source_num 个角度进行混合,每个角度选取一个 wav 文件,保证角度之间的 wav 不重复
194 | wav_path = speech + os.sep + source_list[index]
195 |
196 | choosen_wav_list = os.listdir(wav_path)
197 | if index == 1:
198 | if 'far' in choosen_wav:
199 | close_or_middle = random_state.choice(['close', 'middle', 'far'], 1, p=[0.4, 0.3, 0.3])[0]
200 | choosen_wav = [wavname for wavname in choosen_wav_list if close_or_middle in wavname][0]
201 | else:
202 | choosen_wav = [wavname for wavname in choosen_wav_list if 'far' in wavname][0]
203 | else:
204 | choosen_wav = random.sample(choosen_wav_list, 1)[0]
205 |
206 | choosen_wav_path = choosen_wav.split('multichannel')
207 | wav_path = wav_path + os.sep + choosen_wav_path[0] + 'multichannel'
208 | sample_source_log['wave_path'] = wav_path
209 | sample_source_log['azimuth'] = angle
210 |
211 | # compute azimuth w.r.t. all mics
212 | s2m_dist = float(wav_path.split('/')[-1].split('-')[3].replace('m', ''))
213 | print(f"s2m_dist {s2m_dist} wav_path {wav_path}")
214 | mic_itvals = [0.14, 0.1, 0.06]
215 | rad = angle / 180.0 * np.pi
216 | for idx, mic_itval in enumerate(mic_itvals):
217 | third_side = np.sqrt(mic_itval ** 2 + s2m_dist ** 2 - 2 * mic_itval * s2m_dist * np.cos(rad))
218 | azi_rad = np.arccos(np.clip((third_side ** 2 + mic_itval ** 2 - s2m_dist ** 2) / (2 * third_side * mic_itval), -1+1e-8, 1-1e-8))
219 | azimuth = azi_rad * 180.0 / np.pi
220 | if idx == 0:
221 | sample_source_log['azimuth1'] = round(180 - round(azimuth, 2), 2)
222 | elif idx == 1:
223 | sample_source_log['azimuth2'] = round(180 - round(azimuth, 2), 2)
224 | elif idx == 2:
225 | sample_source_log['azimuth3'] = round(180 - round(azimuth, 2), 2)
226 | rad = (180 - angle) / 180.0 * np.pi
227 | for idx, mic_itval in enumerate(mic_itvals):
228 | third_side = np.sqrt(mic_itval ** 2 + s2m_dist ** 2 - 2 * mic_itval * s2m_dist * np.cos(rad))
229 | azi_rad = np.arccos(np.clip((third_side ** 2 + mic_itval ** 2 - s2m_dist ** 2) / (2 * third_side * mic_itval), -1+1e-8, 1-1e-8))
230 | azimuth = azi_rad * 180.0 / np.pi
231 | if idx == 0:
232 | sample_source_log['azimuth6'] = round(azimuth, 2)
233 | elif idx == 1:
234 | sample_source_log['azimuth5'] = round(azimuth, 2)
235 | elif idx == 2:
236 | sample_source_log['azimuth4'] = round(azimuth, 2)
237 |
238 | if index != 0:
239 | sample_source_log["SIR"] = random.randint(SIR[0], SIR[1])
240 | wave = audioread(wav_path + '_0.wav')
241 | wave = wave[0:4*sr] # 4s
242 | vad_label = generate_vad_label(wave)
243 |
244 | sample_source_log['vad_label'] = list(vad_label)
245 | sample_log["source" + str(index)] = sample_source_log
246 |
247 | angular_dist = abs(int(sample_log['source0']['azimuth']) - int(sample_log['source1']['azimuth']))
248 | # if angular_dist <= 5:
249 | # continue
250 | if angular_dist > 15:
251 | if np.random.rand() > 0.5:
252 | continue
253 | # source-to-microphone distance
254 | s2m_dist1 = float(sample_log['source0']['wave_path'].split('/')[-1].split('-')[3].replace('m', '')) * 100
255 | s2m_dist2 = float(sample_log['source1']['wave_path'].split('/')[-1].split('-')[3].replace('m', '')) * 100
256 | sample_log['source0']['s2m_dist'] = int(s2m_dist1)
257 | sample_log['source1']['s2m_dist'] = int(s2m_dist2)
258 | # distance between two sources
259 | social_dist = np.round(np.sqrt(np.square(s2m_dist1) + np.square(s2m_dist2) - 2 * s2m_dist1 * s2m_dist2 * np.cos(angular_dist / 180 * np.pi)), 2)
260 | sample_log['social_dist'] = social_dist
261 | # print(f's2m_dist1 {int(s2m_dist1)} s2m_dist2 {int(s2m_dist2)} social_dist {social_dist}', flush=True)
262 |
263 | if social_dist <= 100:
264 | continue
265 | if angular_dist <= 15:
266 | num_samples[0] += 1
267 | elif angular_dist > 15 and angular_dist < 45:
268 | num_samples[1] += 1
269 | elif angular_dist >= 45 and angular_dist < 90:
270 | num_samples[2] += 1
271 | elif angular_dist >= 90:
272 | num_samples[3] += 1
273 |
274 | sample_pos += 1
275 | dists.append(int(s2m_dist1))
276 | dists.append(int(s2m_dist2))
277 | print(f'sample_pos {sample_pos} source_list {source_list} angular_dist {angular_dist} s2m_dist1 {int(s2m_dist1)} s2m_dist2 {int(s2m_dist2)} social_dist {social_dist}', flush=True)
278 |
279 | folder_idx = (max_num + sample_pos) // sqrt_sample_num
280 | output_subfolder = out_folder_path + os.sep + f'{folder_idx*sqrt_sample_num}-{(folder_idx+1)*sqrt_sample_num-1}'
281 | write_file_path = output_subfolder + os.sep + f'sample-{max_num+sample_pos}-' + room + '.json'
282 | os.makedirs(output_subfolder, exist_ok=True)
283 | with open(write_file_path, 'w', encoding='utf-8') as f:
284 | f.write(json.dumps(sample_log, ensure_ascii=False))
285 | except Exception as e:
286 | print(f'e {e}')
287 |
288 | print('----- Statistics about the source-to-microphone distance -----')
289 | for k, g in groupby(sorted(dists), key=lambda x: x//50):
290 | print('{}-{}: {}'.format(k*50, (k+1)*50-1, len(list(g))))
291 | save_path = os.path.dirname(out_folder_path) + os.sep + out_folder_path.split('/')[-1] + '.pkl'
292 | dists_dict = {"dists": dists}
293 | pkl_file = open(save_path, 'wb')
294 | pickle.dump(dists_dict, pkl_file)
295 |
296 |
297 | if __name__ == '__main__':
298 | # set_sample_num = 40000
299 | set_sample_num = 3000
300 | set_source_max_num = 2
301 |
302 | # dataset_split = "train-clean-100"
303 | # dataset_split = "dev-clean"
304 | dataset_split = "test-clean_0226"
305 | # dataset_split = "test-clean_wer"
306 | # input_single_source_folder_path = f'/CDShare3/Libri-SIM/rooms_0129/{dataset_split}_10rooms' # 包含多个房间的输入目录
307 | input_single_source_folder_path = f'/CDShare3/Libri-SIM/rooms_0129/test-clean_10rooms' # 包含多个房间的输入目录
308 | out_folder_path = f'/CDShare3/Libri-SIM/jsons_0129/{dataset_split}' # json输出目录
309 | data_mix_angle_wav_cos(set_sample_num, set_source_max_num, input_single_source_folder_path,
310 | out_folder_path, add_noise=0.0)
311 |
312 |
313 |
314 |
--------------------------------------------------------------------------------
/preparation/libri_sim_code/6_json_2_list.py:
--------------------------------------------------------------------------------
1 | import os
2 | import datetime
3 |
4 | def generate_list(input_dir, ouput_dir, data_split):
5 | date = datetime.datetime.now().strftime("%m%d")
6 | os.makedirs(ouput_dir, exist_ok=True)
7 | output_wav_lst = os.path.join(ouput_dir, '{}_{}.lst'.format(data_split, date))
8 | with open(output_wav_lst, 'w', encoding='utf-8') as output_f:
9 | save_num = 0
10 | if os.path.exists(input_dir):
11 | subfolder_list = os.listdir(input_dir)
12 | subfolder_list = [os.path.join(input_dir, subfolder_name) for subfolder_name in subfolder_list]
13 | for subfolder in subfolder_list:
14 | file_path_list = os.listdir(subfolder)
15 | for file_path in file_path_list:
16 | output_f.write(subfolder+ os.sep+ file_path.strip()+'\n')
17 | save_num += 1
18 | print('Finish save: {}'.format(save_num))
19 |
20 |
21 | if __name__ == '__main__':
22 | # data_split = 'test-clean_wer'
23 | data_split = 'test-clean_0226'
24 | # data_split = 'dev-clean'
25 | # data_split = 'train-clean-100'
26 | # input_dir = f'/local02/fuyanjie/Libri-SIM/jsons/{data_split}'
27 | input_dir = f'/CDShare3/Libri-SIM/jsons_0129/{data_split}'
28 | ouput_dir = '/Work21/2021/fuyanjie/pycode/LaBNet/data/exp_list'
29 | generate_list(input_dir, ouput_dir, data_split)
--------------------------------------------------------------------------------
/preparation/libri_sim_code/gen_room_para.py:
--------------------------------------------------------------------------------
1 | import os
2 | import random
3 | import re
4 |
5 | import pyroomacoustics as pra
6 | import numpy as np
7 | import soundfile as sf
8 |
9 | MIN_ROOM_WIDTH= 3
10 | MAX_ROOM_WIDTH = 9
11 | MIN_ROOM_LEN = 4
12 | MAX_ROOM_LEN = 12
13 | MIN_ROOM_HEIGHT = 2.5
14 | MAX_ROOM_HEIGHT = 5
15 |
16 | EPS = 1e-8
17 | SEED = 77
18 |
19 | # 随机生成一个房间参数,生成对应的文件夹,并保存房间参数
20 | def gen_room_para(dir, room_transpose_prob):
21 | '''
22 | :param dir: the save path of room
23 | :param room_transpose_prob: the probability of whether to switch the room length and the room width
24 | :return:
25 | '''
26 |
27 | room_para = dict()
28 |
29 | if random.uniform(0, 1) < room_transpose_prob:
30 | room_length = random.randint(MIN_ROOM_LEN, MAX_ROOM_LEN)
31 | room_width = np.round(random.uniform(max(room_length / 2, MIN_ROOM_WIDTH), room_length), 2)
32 | else:
33 | room_width = random.randint(MIN_ROOM_LEN, MAX_ROOM_LEN)
34 | room_length = np.round(random.uniform(max(room_width / 2, MIN_ROOM_WIDTH), room_width), 2)
35 |
36 | room_height = np.round(random.uniform(MIN_ROOM_HEIGHT, MAX_ROOM_HEIGHT), 2)
37 |
38 | room_para['room_dim'] = [room_length, room_width, room_height]
39 |
40 | max_room_size = max(room_length, room_width)
41 | # 根据房间大小随机生成rt60
42 | if max_room_size >= 4 and max_room_size < 8:
43 | rt60_tgt = random.uniform(0.3, 0.6)
44 | elif max_room_size >= 8 and max_room_size < 10:
45 | rt60_tgt = random.uniform(0.4, 0.7)
46 | elif max_room_size >= 10:
47 | rt60_tgt = random.uniform(0.5, 0.8)
48 |
49 | rt60_tgt = np.round(rt60_tgt, 3)
50 |
51 | room_para['rt60'] = rt60_tgt
52 |
53 | folder_name = 'room_{}_{}_{}_rt60_{}'.format(room_length, room_width, room_height, rt60_tgt)
54 |
55 | folder_path = os.path.join(dir, folder_name)
56 |
57 | if not os.path.exists(folder_path):
58 | os.makedirs(folder_path)
59 |
60 | # 保存房间参数
61 | room_para_file_path = os.path.join(folder_path, 'room_para.npy')
62 | np.save(room_para_file_path, room_para)
63 |
64 | return room_para
65 |
66 |
67 | def gen_mulchannel_data_random(wave_file_path, room_para, folder, audio_type, fs, segment_length):
68 | '''
69 | 利用 Pyroomacoustics 生成多通道音频文件
70 | :param wave_file_path: 单通道音频文件路径
71 | :param room_para: 房间参数
72 | :param folder: 保存生成多通道声音文件的文件夹路径
73 | :param audio_type: 0:平稳噪声,1:人声,2:非平稳噪声
74 | :param fs: 音频采样率
75 | :return: 多通道音频data
76 | '''
77 | # 根据房间信息生成麦克风阵列位置
78 | room_dim = room_para['room_dim']
79 | rt60_tgt = room_para['rt60']
80 | room_length = room_dim[0]
81 | room_width = room_dim[1]
82 | room_height = room_dim[2]
83 | mic_locations = np.c_[
84 | [0.5, room_width / 2 - 0.14, 2],
85 | [0.5, room_width / 2 - 0.1, 2],
86 | [0.5, room_width / 2 - 0.06, 2],
87 | [0.5, room_width / 2 + 0.06, 2],
88 | [0.5, room_width / 2 + 0.1, 2],
89 | [0.5, room_width / 2 + 0.14, 2],
90 | ]
91 |
92 | # We invert Sabine's formula to obtain the parameters for the ISM simulator
93 | e_absorption, max_order = pra.inverse_sabine(rt60_tgt, room_dim)
94 | # 根据参数创建房间
95 | room = pra.ShoeBox(room_dim, fs=fs, materials=pra.Material(e_absorption), max_order=max_order, air_absorption=True, humidity=50)
96 | audio_data, sr = sf.read(wave_file_path, dtype=np.int16)
97 |
98 | target_length = segment_length * sr
99 | if len(audio_data) < target_length:
100 | pad_audio_data = np.zeros(target_length)
101 |
102 | start = random.randint(0, target_length - len(audio_data))
103 | end = start + len(audio_data)
104 |
105 | pad_audio_data[start:end] = audio_data
106 | audio_data = pad_audio_data
107 |
108 | if sr != fs:
109 | raise ValueError("input wav file samplerate is not {}".format(fs))
110 |
111 | # 根据 wave 文件名获取说话人ID
112 | wave_file_name = wave_file_path.split('/')[-1]
113 |
114 | # 随机生成一个声源角度及距离
115 | if audio_type == 0:
116 | source_location = np.array([random.uniform(0, room_length),
117 | random.uniform(0, room_width),
118 | random.uniform(0, room_height)])
119 | elif audio_type == 1:
120 | source_location = np.array([random.uniform(mic_locations[0][0], room_length),
121 | random.uniform(0.5, room_width - 0.5),
122 | random.uniform(1.4, 1.8)])
123 | else:
124 | source_location = np.array([random.uniform(0.5, room_length),
125 | random.uniform(0, room_width),
126 | random.uniform(0, room_height)])
127 | if source_location[1] < room_width / 2:
128 | target_angle = np.arctan((source_location[0] - 0.5) / (room_width / 2 - source_location[1]))
129 | else:
130 | target_angle = np.pi / 2 + np.arctan((source_location[1] - room_width / 2) / (source_location[0] - 0.5))
131 |
132 | # 将弧度转为度
133 | angle_degree = int(target_angle * 180 / np.pi)
134 |
135 | # 生成多通道数据
136 | c = 345
137 | dist = np.linalg.norm(source_location - mic_locations[:, 0])
138 |
139 | if audio_type == 0:
140 | delay = 0
141 | else:
142 | delay = dist / c
143 |
144 | # 将声源放置在房间中
145 | room.add_source(source_location, signal=audio_data, delay=delay)
146 |
147 | # 将麦克风阵列放置在房间中
148 | room.add_microphone_array(mic_locations)
149 |
150 | # Run the simulation
151 | room.simulate()
152 |
153 | # 得到仿真的语音信号
154 | orig_max_value = np.max(np.abs(audio_data))
155 | multichannel_audio_data = room.mic_array.signals[:, 0:len(audio_data)]
156 | # multichannel_audio_data = multichannel_audio_data.astype(np.int16)
157 |
158 | multichannel_audio_data = multichannel_audio_data / np.max(np.abs(multichannel_audio_data)) * orig_max_value
159 | multichannel_audio_data = multichannel_audio_data.astype(np.int16)
160 |
161 | # print(dist, rt60_tgt, max_order, orig_max_value, np.max(np.abs(multichannel_audio_data)))
162 |
163 | # 生成对应的文件夹
164 | if audio_type == 0:
165 | new_folder = os.path.join(folder, 'stationary_noise')
166 | elif audio_type == 1:
167 | new_folder = os.path.join(folder, 'speech')
168 | else:
169 | new_folder = os.path.join(folder, 'nonstationary_noise')
170 |
171 | if not os.path.exists(new_folder):
172 | os.makedirs(new_folder)
173 |
174 | # 生成对应文件名
175 | if audio_type == 0:
176 | # wav_id = wave_file_name.replace('.wav', '')
177 | return multichannel_audio_data, -1, angle_degree
178 | elif audio_type == 1:
179 | wav_id = re.findall('\d+', wave_file_name.split('/')[-1])[0]
180 | # wav_id = wave_file_name.replace('.wav', '') # for FYJ
181 | return multichannel_audio_data, wav_id, angle_degree
182 | else:
183 | wav_id = wave_file_name.replace('.wav', '')
184 | return multichannel_audio_data, wav_id, angle_degree
185 |
186 | def gen_mulchannel_data_angle(wave_file_path, room_para, folder, angle, distance_flag, fs, segment_length, audio_type):
187 | '''
188 | 利用 Pyroomacoustics 生成多通道音频文件
189 | :param wave_file_path: 单通道音频文件路径
190 | :param room_para: 房间参数
191 | :param folder: 保存生成多通道声音文件的文件夹路径
192 | :param audio_type: 0:平稳噪声,1:人声,2:非平稳噪声
193 | :param fs: 音频采样率
194 | :return: 多通道音频data
195 | '''
196 | # 根据房间信息生成麦克风阵列位置
197 | room_dim = room_para['room_dim']
198 | rt60_tgt = room_para['rt60']
199 | room_length = room_dim[0]
200 | room_width = room_dim[1]
201 | room_height = room_dim[2]
202 | room_mid = room_width / 2
203 | mic_locations = np.c_[
204 | [0.5, room_width / 2 - 0.14, 2],
205 | [0.5, room_width / 2 - 0.1, 2],
206 | [0.5, room_width / 2 - 0.06, 2],
207 | [0.5, room_width / 2 + 0.06, 2],
208 | [0.5, room_width / 2 + 0.1, 2],
209 | [0.5, room_width / 2 + 0.14, 2],
210 | ]
211 |
212 | # We invert Sabine's formula to obtain the parameters for the ISM simulator
213 | e_absorption, max_order = pra.inverse_sabine(rt60_tgt, room_dim)
214 | # 根据参数创建房间
215 | room = pra.ShoeBox(room_dim, fs=fs, materials=pra.Material(e_absorption), max_order=max_order, air_absorption=True, humidity=50)
216 |
217 | audio_data, sr = sf.read(wave_file_path, dtype=np.int16)
218 |
219 | target_length = segment_length * sr
220 | if len(audio_data) < target_length:
221 | pad_audio_data = np.zeros(target_length)
222 |
223 | start = random.randint(0, target_length - len(audio_data))
224 | end = start + len(audio_data)
225 |
226 | pad_audio_data[start:end] = audio_data
227 | audio_data = pad_audio_data
228 |
229 | if sr != fs:
230 | raise ValueError("input wav file samplerate is not {}".format(fs))
231 |
232 | # 根据 wave 文件名获取说话人ID
233 | wave_file_name = wave_file_path.split('/')[-1]
234 | min_distance = 0.5
235 |
236 | # 随机生成一个声源角度及距离
237 | if angle < 90:
238 | rad = angle / 180 * np.pi
239 | max_distance = min(room_mid / (np.cos(rad) + EPS), (room_length - 0.5) / (np.sin(rad) + EPS)) - 0.5
240 | one_third_distance = (max_distance - min_distance) / 3
241 | # relative_distance = random.uniform(distance_flag * one_third_distance, (distance_flag + 1) * one_third_distance)
242 | relative_distance = max(0, random.normalvariate(mu = (distance_flag + 0.5) * one_third_distance, sigma = one_third_distance / 6))
243 | distance = min_distance + relative_distance
244 | distance = round(distance, 2)
245 | if distance > 8:
246 | rand_temp = random.random()
247 | if rand_temp < 0.1:
248 | distance = round(random.uniform(5, 5.5), 2)
249 | elif rand_temp >= 0.1 and rand_temp < 0.2:
250 | distance = round(random.uniform(5.5, 6), 2)
251 | elif rand_temp >= 0.2 and rand_temp < 0.35:
252 | distance = round(random.uniform(6, 6.5), 2)
253 | elif rand_temp >= 0.35 and rand_temp < 0.55:
254 | distance = round(random.uniform(6.5, 7), 2)
255 | elif rand_temp >= 0.55 and rand_temp < 0.75:
256 | distance = round(random.uniform(7, 7.5), 2)
257 | elif rand_temp >= 0.75:
258 | distance = round(random.uniform(7.5, 8), 2)
259 | source_location = np.array([distance * np.sin(rad) + 0.5,
260 | room_mid - distance * np.cos(rad),
261 | random.uniform(1.4, 1.8)])
262 | elif angle == 90:
263 | max_distance = room_length - 1
264 | one_third_distance = (max_distance - min_distance) / 3
265 | # relative_distance = random.uniform(distance_flag * one_third_distance, (distance_flag + 1) * one_third_distance)
266 | relative_distance = max(0, random.normalvariate(mu = (distance_flag + 0.5) * one_third_distance, sigma = one_third_distance / 6))
267 | distance = min_distance + relative_distance
268 | distance = round(distance, 2)
269 | if distance > 8:
270 | rand_temp = random.random()
271 | if rand_temp < 0.1:
272 | distance = round(random.uniform(5, 5.5), 2)
273 | elif rand_temp >= 0.1 and rand_temp < 0.2:
274 | distance = round(random.uniform(5.5, 6), 2)
275 | elif rand_temp >= 0.2 and rand_temp < 0.35:
276 | distance = round(random.uniform(6, 6.5), 2)
277 | elif rand_temp >= 0.35 and rand_temp < 0.55:
278 | distance = round(random.uniform(6.5, 7), 2)
279 | elif rand_temp >= 0.55 and rand_temp < 0.75:
280 | distance = round(random.uniform(7, 7.5), 2)
281 | elif rand_temp >= 0.75:
282 | distance = round(random.uniform(7.5, 8), 2)
283 | source_location = np.array([distance + 0.5,
284 | room_mid,
285 | random.uniform(1.4, 1.8)])
286 | else:
287 | rad = (180 - angle) / 180 * np.pi
288 | max_distance = min(room_mid / (np.cos(rad) + EPS), (room_length - 0.5) / (np.sin(rad) + EPS)) - 0.5
289 | one_third_distance = (max_distance - min_distance) / 3
290 | # relative_distance = random.uniform(distance_flag * one_third_distance, (distance_flag + 1) * one_third_distance)
291 | relative_distance = max(0, random.normalvariate(mu = (distance_flag + 0.5) * one_third_distance, sigma = one_third_distance / 6))
292 | distance = min_distance + relative_distance
293 | distance = round(distance, 2)
294 | if distance > 8:
295 | rand_temp = random.random()
296 | if rand_temp < 0.1:
297 | distance = round(random.uniform(5, 5.5), 2)
298 | elif rand_temp >= 0.1 and rand_temp < 0.2:
299 | distance = round(random.uniform(5.5, 6), 2)
300 | elif rand_temp >= 0.2 and rand_temp < 0.35:
301 | distance = round(random.uniform(6, 6.5), 2)
302 | elif rand_temp >= 0.35 and rand_temp < 0.55:
303 | distance = round(random.uniform(6.5, 7), 2)
304 | elif rand_temp >= 0.55 and rand_temp < 0.75:
305 | distance = round(random.uniform(7, 7.5), 2)
306 | elif rand_temp >= 0.75:
307 | distance = round(random.uniform(7.5, 8), 2)
308 | source_location = np.array([distance * np.sin(rad) + 0.5,
309 | room_mid + distance * np.cos(rad),
310 | random.uniform(1.4, 1.8)])
311 |
312 | # 生成多通道数据
313 | c = 343
314 | dist = np.linalg.norm(source_location - mic_locations[:, 0])
315 |
316 | delay = dist / c
317 |
318 | # 将声源放置在房间中
319 | room.add_source(source_location, signal=audio_data, delay=delay)
320 |
321 | # 将麦克风阵列放置在房间中
322 | room.add_microphone_array(mic_locations)
323 |
324 | # Run the simulation
325 | room.simulate()
326 |
327 | # 得到仿真的语音信号
328 | orig_max_value = np.max(np.abs(audio_data))
329 | multichannel_audio_data = room.mic_array.signals[:, 0:len(audio_data)]
330 |
331 | multichannel_audio_data = multichannel_audio_data / np.max(np.abs(multichannel_audio_data)) * orig_max_value
332 | multichannel_audio_data = multichannel_audio_data.astype(np.int16)
333 |
334 | # print(dist, rt60_tgt, max_order, orig_max_value, np.max(np.abs(multichannel_audio_data)))
335 |
336 | # 生成对应的文件夹
337 | if audio_type == 0:
338 | new_folder = os.path.join(folder, 'stationary_noise')
339 | elif audio_type == 1:
340 | new_folder = os.path.join(folder, 'speech')
341 | else:
342 | new_folder = os.path.join(folder, 'nonstationary_noise')
343 |
344 | if not os.path.exists(new_folder):
345 | os.makedirs(new_folder)
346 |
347 | ### TODO
348 | wav_id = wave_file_name.split(".")[0]
349 |
350 | return multichannel_audio_data, wav_id, distance
351 |
352 | def gen_mulchannel_data(wave_file_path, room_para, folder, audio_type=0, fs=16000):
353 | '''
354 | 利用 Pyroomacoustics 生成多通道音频文件
355 | :param wave_file_path: 单通道音频文件路径
356 | :param room_para: 房间参数
357 | :param folder: 保存生成多通道声音文件的文件夹路径
358 | :param audio_type: 0:平稳噪声,1:人声,2:非平稳噪声
359 | :param fs: 音频采样率
360 | :return: 多通道音频data
361 | '''
362 | # 根据房间信息生成麦克风阵列位置
363 | room_dim = room_para['room_dim']
364 | rt60_tgt = room_para['rt60']
365 | room_length = room_dim[0]
366 | room_width = room_dim[1]
367 | room_height = room_dim[2]
368 | mic_locations = np.c_[
369 | [0.5, room_width / 2 - 0.07, 1],
370 | [0.5, room_width / 2 - 0.035, 1],
371 | [0.5, room_width / 2, 1],
372 | [0.5, room_width / 2 + 0.035, 1],
373 | [0.5, room_width / 2 + 0.07, 1],
374 | [0.5, room_width / 2 + 0.105, 1],
375 | ]
376 |
377 | # We invert Sabine's formula to obtain the parameters for the ISM simulator
378 | e_absorption, max_order = pra.inverse_sabine(rt60_tgt, room_dim)
379 | # 根据参数创建房间
380 | room = pra.ShoeBox(room_dim, fs=fs, materials=pra.Material(e_absorption), max_order=max_order, air_absorption=True, humidity=50)
381 | audio_data, sr = sf.read(wave_file_path, dtype=np.int16)
382 | print("audio_data.shape = {}, sr = {}".format(audio_data.shape, sr))
383 | if sr != fs:
384 | raise ValueError("input wav file samplerate is not {}".format(fs))
385 |
386 | # 根据 wave 文件名获取说话人ID
387 | wave_file_name = wave_file_path.split('/')[-1]
388 |
389 | # 随机生成一个声源角度及距离
390 | if audio_type == 0:
391 | source_location = np.array([random.uniform(0, room_length),
392 | random.uniform(0, room_width),
393 | random.uniform(0, room_height)])
394 | elif audio_type == 1:
395 | source_location = np.array([random.uniform(mic_locations[0][0], room_length),
396 | random.uniform(0.5, room_width - 0.5),
397 | random.uniform(1.4, 1.8)])
398 | else:
399 | source_location = np.array([random.uniform(0.5, room_length),
400 | random.uniform(0, room_width),
401 | random.uniform(0, room_height)])
402 | if source_location[1] < room_width / 2:
403 | target_angle = np.arctan((source_location[0] - 0.5) / (room_width / 2 - source_location[1]))
404 | else:
405 | target_angle = np.pi / 2 + np.arctan((source_location[1] - room_width / 2) / (source_location[0] - 0.5))
406 |
407 |
408 | # 将弧度转为度
409 | angle_degree = int(target_angle * 180 / np.pi)
410 |
411 | # 生成多通道数据
412 | c = 345
413 | dist = np.linalg.norm(source_location - mic_locations[:, 0])
414 |
415 |
416 | if audio_type == 0:
417 | delay = 0
418 | else:
419 | delay = dist / c
420 |
421 | # 将声源放置在房间中
422 | room.add_source(source_location, signal=audio_data, delay=delay)
423 |
424 | # 将麦克风阵列放置在房间中
425 | room.add_microphone_array(mic_locations)
426 |
427 | # Run the simulation
428 | room.simulate()
429 |
430 | # 得到仿真的语音信号
431 | orig_max_value = np.max(np.abs(audio_data))
432 | multichannel_audio_data = room.mic_array.signals[:, 0:len(audio_data)]
433 | # multichannel_audio_data = multichannel_audio_data.astype(np.int16)
434 |
435 | multichannel_audio_data = multichannel_audio_data / np.max(np.abs(multichannel_audio_data)) * orig_max_value
436 | multichannel_audio_data = multichannel_audio_data.astype(np.int16)
437 |
438 | # print(dist, rt60_tgt, max_order, orig_max_value, np.max(np.abs(multichannel_audio_data)))
439 |
440 | # 生成对应的文件夹
441 | if audio_type == 0:
442 | new_folder = os.path.join(folder, 'stationary_noise')
443 | elif audio_type == 1:
444 | new_folder = os.path.join(folder, 'speech')
445 | else:
446 | new_folder = os.path.join(folder, 'nonstationary_noise')
447 |
448 | if not os.path.exists(new_folder):
449 | os.makedirs(new_folder)
450 |
451 | # 生成对应文件名
452 | if audio_type == 0:
453 | wav_id = wave_file_name.replace('.wav', '')
454 | return multichannel_audio_data, wav_id, angle_degree
455 | elif audio_type == 1:
456 | # wav_id = re.findall('\d+', wave_file_name.split('/')[-1])[0]
457 | wav_id = wave_file_name.replace('.wav', '')
458 | return multichannel_audio_data, wav_id, angle_degree
459 | else:
460 | wav_id = wave_file_name.replace('.wav', '')
461 | return multichannel_audio_data, wav_id, angle_degree
462 |
--------------------------------------------------------------------------------
/preparation/libri_spkid2gender.py:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 |
4 | libri_spkinfo_path = "/CDShare3/LibriSpeech/SPEAKERS.TXT"
5 | spkid2gender_path = "/Work21/2021/fuyanjie/pycode/LaBNet/data/libri_spkid2gender.json"
6 | lines = open(libri_spkinfo_path, "r").readlines()
7 | kv = dict()
8 |
9 | for idx, line in enumerate(lines):
10 | if idx < 12:
11 | continue
12 | cols = line.split('|')
13 | print(f'{cols} ')
14 | spkid = cols[0].strip()
15 | gender = cols[1].strip()
16 | kv[spkid] = gender
17 | print(f'{spkid}: {kv[spkid]} ')
18 |
19 | f = open(spkid2gender_path, 'w')
20 | f.write(json.dumps(kv))
21 | f.close()
22 |
--------------------------------------------------------------------------------
/test.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #$ -S /bin/bash
3 |
4 | #here you'd best to change testjob as username
5 | #$ -N test
6 |
7 | #cwd define the work environment,files(username.o) will generate here
8 | #$ -cwd
9 |
10 | # merge stdo and stde to one file
11 | #$ -j y
12 |
13 | # resource requesting, e.g. for gpu use
14 | #$ -l h=gpu05
15 | echo `hostname`
16 |
17 | echo "job start time: `date`"
18 | # start whatever your job below, e.g., python, matlab, etc.
19 | #ADD YOUR COMMAND HERE,LIKE python3 main.py
20 | #chmod a+x run.sh.
21 |
22 | gpuid=2
23 | echo "gpuid: ${gpuid}"
24 | CUDA_VISIBLE_DEVICES=$gpuid /Work21/2021/fuyanjie/anaconda3/envs/torch1.8+cu111/bin/python test/test.py \
25 | --batch-size 5 \
26 | --ckpt-path "/path/to/your/checkpoint.pt" \
27 | --tt-clean "/Work21/2021/fuyanjie/pycode/LaBNet/data/exp_list/test-clean_0130.lst" \
28 | # --write-wav True
29 |
30 |
31 | sleep 10
32 | echo "job end time:`date`"
33 |
--------------------------------------------------------------------------------
/tools/misc.py:
--------------------------------------------------------------------------------
1 |
2 | import torch
3 | import torch.nn as nn
4 | import numpy as np
5 | import os
6 | import sys
7 | import soundfile as sf
8 |
9 |
10 | def load_checkpoint(checkpoint_path,use_cuda) :
11 | if use_cuda:
12 | checkpoint = torch.load(checkpoint_path)
13 | else:
14 | checkpoint = torch.load(
15 | checkpoint_path,map_location=lambda storage, loc: storage)
16 | return checkpoint
17 |
18 |
19 | def get_learning_rate(optimizer):
20 | """Get learning rate"""
21 | return optimizer.param_groups[0]["lr"]
22 |
23 | def reload_for_eval(model,checkpoint_dir, use_cuda) :
24 | ckpt_name = os.path.join(checkpoint_dir,'checkpoint_decode')
25 | if not os.path.exists(ckpt_name):
26 | print(f'file does not exists: {ckpt_name}')
27 | exit(1)
28 | if os.path.isfile(ckpt_name):
29 | with open(ckpt_name,'r') as f:
30 | model_name = f.readline().strip()
31 | checkpoint_path = os.path.join(checkpoint_dir, model_name)
32 | print(f'use model file: {checkpoint_path}')
33 | checkpoint = load_checkpoint(checkpoint_path,use_cuda)
34 | print(checkpoint['model'].keys( ))
35 | model.load_state_dict(checkpoint ['model'], strict=True)
36 | print('=> Reload well-trained model {} for decoding.'. format(model_name))
37 |
38 |
39 | def reload_model(model, optimizer, checkpoint_dir, use_cuda=True, strict=True):
40 | ckpt_name = os.path.join(checkpoint_dir, 'checkpoint')
41 | if os.path.isfile(ckpt_name):
42 | with open(ckpt_name,'r') as f:
43 | model_name = f.readline().strip()
44 | checkpoint_path = os.path.join(checkpoint_dir, model_name)
45 | checkpoint = load_checkpoint(checkpoint_path, use_cuda)
46 | model.load_state_dict(checkpoint['model'],strict=strict)
47 | # optimizer.load state dict(checkpoint [ 'optimizer' ])
48 | epoch = checkpoint['epoch']
49 | step = checkpoint['step']
50 | print ('=>Reload previous model and optimizer.')
51 | else:
52 | print('[!] checkpoint directory is empty. Train a new model ...')
53 | epoch = 0
54 | step = 0
55 | return epoch, step
56 |
57 | def save_checkpoint(model, optimizer, epoch, step, checkpoint_dir, val_loss):
58 | checkpoint_path = os.path.join(
59 | checkpoint_dir, 'model.ckpt-{}-{}.pt'.format(epoch, val_loss))
60 | torch.save({'model' : model.state_dict(),
61 | 'optimizer' : optimizer.state_dict(),
62 | 'epoch' : epoch,
63 | 'step' : step}, checkpoint_path)
64 | with open(os.path.join(checkpoint_dir, 'checkpoint'),'w' ) as f:
65 | f.write('model.ckpt-{}-{}.pt'.format(epoch, val_loss))
66 | print("=>Save checkpoint:", checkpoint_path)
67 |
68 |
69 | def setup_lr(opt,lr):
70 | for param_group in opt.param_groups :
71 | param_group['lr'] = lr
72 |
--------------------------------------------------------------------------------
/train.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #$ -S /bin/bash
3 |
4 | #here you'd best to change testjob as username
5 | #$ -N ProStage2
6 |
7 | # resource requesting, e.g. for gpu use
8 | #$ -l h=gpu07
9 |
10 | #cwd define the work environment,files(username.o) will generate here
11 | #$ -cwd
12 |
13 | # merge stdo and stde to one file
14 | #$ -j y
15 |
16 | echo "job start time: `date`"
17 | # start whatever your job below, e.g., python, matlab, etc.
18 | #ADD YOUR COMMAND HERE,LIKE python3 main.py
19 | #chmod a+x run.sh.
20 |
21 | echo `hostname`
22 |
23 | gpuid=1
24 | echo "gpuid: ${gpuid}"
25 |
26 | CUDA_VISIBLE_DEVICES=1 \
27 | /Work18/2020/lijunjie/anaconda3/envs/torch1.8/bin/python train/train.py \
28 | --batch-size 4 \
29 | --n_avb_mics 2 \
30 | --exp-dir "/Work21/2021/fuyanjie/pycode/LaBNetPro/exp/exp0210-tri2" \
31 | --tr-clean "/Work21/2021/fuyanjie/pycode/LaBNet/data/exp_list/train-clean-100_0130.lst" \
32 | --cv-clean "/Work21/2021/fuyanjie/pycode/LaBNet/data/exp_list/dev-clean_0130.lst" \
33 | --alpha 1 \
34 | --beta 10
35 | #| tee -a "ProStage1.log"
36 |
37 | # gpuid=2
38 | # batch_size=4
39 | # echo "gpuid: ${gpuid}"
40 | # CUDA_VISIBLE_DEVICES=$gpuid \
41 | # /Work18/2020/lijunjie/anaconda3/envs/torch1.8/bin/python train/train.py \
42 | # --num-gpu 1 \
43 | # --batch-size $batch_size \
44 | # --exp-dir "/Work21/2021/fuyanjie/pycode/LaBNet/exp/exp0117_4mics" \
45 | # --log-dir "/Work21/2021/fuyanjie/pycode/LaBNet/exp/exp0117_4mics/log" \
46 | # --tr-clean "/Work21/2021/fuyanjie/pycode/LaBNet/data/exp_list/train-clean-100_0117.lst" \
47 | # --cv-clean "/Work21/2021/fuyanjie/pycode/LaBNet/data/exp_list/dev-clean_0117.lst" \
48 | # --alpha 1 \
49 | # --beta 10 | tee -a "/Work21/2021/fuyanjie/pycode/LaBNet/exp/exp0117_4mics/log/stage2.txt"
50 |
51 | echo "job end time:`date`"
52 |
--------------------------------------------------------------------------------
/train/train.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | sys.path.append("/Work21/2021/fuyanjie/pycode/LaBNetPro")
4 | import torch
5 | import torch.nn as nn
6 | import numpy as np
7 | import argparse
8 | import torch.optim as optim
9 | import time
10 | import logging
11 | from tools.misc import get_learning_rate, save_checkpoint, reload_model, setup_lr
12 | from utils.utils import doa_err_2_source
13 | from model.Tree import Tree, si_sdr_loss, wsdr_loss
14 | from dataloader.dataloader import static_loader
15 |
16 | def load_obj(obj, device):
17 | """
18 | Offload tensor object in obj to cuda device
19 | """
20 |
21 | def cuda(obj):
22 | return obj.to(device, dtype=torch.float32) if isinstance(obj, torch.Tensor) else obj
23 |
24 | if isinstance(obj, dict):
25 | return {key: load_obj(obj[key], device) for key in obj}
26 | elif isinstance(obj, list):
27 | return [load_obj(val, device) for val in obj]
28 | else:
29 | return cuda(obj)
30 |
31 | def validation(model, args, lr, epoch, device):
32 | dataloader = static_loader(
33 | clean_scp=args.cv_clean,
34 | batch_size=args.batch_size,
35 | shuffle=False,
36 | num_workers=args.num_threads,
37 | sample_rate=args.sample_rate,
38 | data_mix_info=None,
39 | n_avb_mics=args.n_avb_mics
40 | )
41 |
42 |
43 | num_batch = len(dataloader)
44 | print("Len dataloader ", num_batch)
45 | stime = time.time()
46 |
47 | mse_loss = nn.MSELoss()
48 | num_target = 0
49 | num_acc = 0
50 | num_pred = 0
51 | sum_err = 0.0
52 | loss_total = 0.0
53 | loss_as_1_total = 0.0
54 | loss_as_2_total = 0.0
55 | loss_sig_1_total = 0.0
56 | loss_sig_2_total = 0.0
57 | MAE_total = 0
58 | MAE_1_total = 0
59 | MAE_2_total = 0
60 |
61 | with torch.no_grad():
62 | model.eval()
63 | for idx, egs in enumerate(dataloader):
64 | # load to gpu
65 | egs = load_obj(egs, device)
66 | inputs = egs["mixed_data"] # [B, C, T]
67 | gt_AS_arr = egs["doa_as_array"] # [B, T, S, n_mics, 210]
68 | gt_azi_arr = egs["doa_idx_array"] # [B, T, S, n_mics]
69 | target_1 = egs["target_1"] # [B, T]
70 | target_2 = egs["target_2"] # [B, T]
71 |
72 | es_AS_1, es_AS_2, es_sig_1, es_sig_2 = model(inputs)
73 | es_AS_1 = es_AS_1[:, 0:249, :, :] # [B, T, n_avb_mics, F]
74 | es_AS_2 = es_AS_2[:, 0:249, :, :] # [B, T, n_avb_mics, F]
75 |
76 | loss_as_1 = mse_loss(es_AS_1, gt_AS_arr[:, :, 0, :, :])
77 | loss_as_2 = mse_loss(es_AS_2, gt_AS_arr[:, :, 1, :, :])
78 | loss_sig_1 = wsdr_loss(es_sig_1, target_1, target_2)
79 | loss_sig_2 = wsdr_loss(es_sig_2, target_2, target_1)
80 |
81 | # weighted
82 | loss_as_1 = loss_as_1 * args.w_azimuth
83 | loss_as_2 = loss_as_2 * args.w_azimuth
84 | loss_sig_1 = loss_sig_1 * args.w_separation
85 | loss_sig_2 = loss_sig_2 * args.w_separation
86 |
87 | loss = loss_as_1 + loss_as_2 + loss_sig_1 + loss_sig_2
88 |
89 | mae_1, mae_2, num_acc_1, num_acc_2, num_pred_1, num_pred_2 = doa_err_2_source(gt_azi_arr, es_AS_1, es_AS_2)
90 | mae = (mae_1 + mae_2)/2
91 | num_acc += num_acc_1 + num_acc_2
92 | num_pred += num_pred_1 + num_pred_2
93 | sum_err += mae_1 * num_pred_1 + mae_2 * num_pred_2
94 |
95 | loss_total += loss.data.cpu()
96 | loss_as_1_total += loss_as_1.data.cpu()
97 | loss_as_2_total += loss_as_2.data.cpu()
98 | loss_sig_1_total += loss_sig_1.data.cpu()
99 | loss_sig_2_total += loss_sig_2.data.cpu()
100 | MAE_total += mae
101 | MAE_1_total += mae_1
102 | MAE_2_total += mae_2
103 |
104 | del inputs, gt_AS_arr, es_AS_1, es_AS_2, loss, loss_as_1, loss_as_2, loss_sig_1, loss_sig_2, mae, mae_1, mae_2
105 |
106 | if not num_pred == 0:
107 | print('DOA Overall ACC frame-level {:2.4f} '.format(num_acc / num_pred))
108 | print('DOA Overall MAE frame-level {:2.4f} '.format(sum_err / num_pred))
109 | print(f'TOTAL pred frames: DOA {num_pred}')
110 |
111 | etime = time.time()
112 | eplashed = (etime - stime) / num_batch
113 |
114 | loss_avg = loss_total / num_batch
115 | loss_as_1_avg = loss_as_1_total / num_batch
116 | loss_as_2_avg = loss_as_2_total / num_batch
117 | loss_sig_1_avg = loss_sig_1_total / num_batch
118 | loss_sig_2_avg = loss_sig_2_total / num_batch
119 | MAE_avg = MAE_total / num_batch
120 | MAE_1_avg = MAE_1_total / num_batch
121 | MAE_2_avg = MAE_2_total / num_batch
122 |
123 | print('CKPT {} '
124 | '| {:2.3f}s/batch | time {:2.1f}mins '
125 | '| loss {:2.6f} | loss_as {:2.6f} | loss_sig {:2.6f} '
126 | '| loss_as_1 {:2.6f} | loss_as_2 {:2.6f} | loss_sig_1 {:2.6f} | loss_sig_2 {:2.6f} '
127 | '| MAE {:2.4f} | MAE_1 {:2.4f} | MAE_2 {:2.4f} '.format(
128 | epoch,
129 | eplashed,
130 | (etime - stime) / 60.0,
131 | loss_avg,
132 | loss_as_1_avg + loss_as_2_avg,
133 | loss_sig_1_avg + loss_sig_2_avg,
134 | loss_as_1_avg,
135 | loss_as_2_avg,
136 | loss_sig_1_avg,
137 | loss_sig_2_avg,
138 | MAE_avg,
139 | MAE_1_avg,
140 | MAE_2_avg,
141 | ))
142 | sys.stdout.flush()
143 | return loss_avg
144 |
145 |
146 | def train_process(model, args, device, writer, mix_info_list):
147 | print('preparing data... args.segment_length = ', args.segment_length)
148 | # torch.cuda.empty_cache()
149 | dataloader = static_loader(
150 | clean_scp=args.tr_clean,
151 | batch_size=args.batch_size,
152 | shuffle=True,
153 | num_workers=args.num_threads,
154 | sample_rate=args.sample_rate,
155 | data_mix_info=None,
156 | n_avb_mics=args.n_avb_mics
157 | )
158 | print_freq = 2000
159 | num_batch = len(dataloader)
160 | print("num_batch ", num_batch)
161 | print(f'args.num_gpu {args.num_gpu} {type(args.num_gpu)}')
162 | # multi-gpu
163 | if(args.num_gpu > 1):
164 | params = model.module.get_params(args.weight_decay)
165 | # single-gpu
166 | else:
167 | params = model.get_params(args.weight_decay)
168 |
169 | optimizer = optim.Adam(params, lr=args.learn_rate)
170 | scheduler = optim.lr_scheduler.ReduceLROnPlateau(
171 | optimizer, 'min', factor=0.5, patience=2, verbose=True)
172 |
173 | if args.retrain:
174 | start_epoch, step = reload_model(model, optimizer, args.exp_dir,
175 | args.use_cuda)
176 | else:
177 | start_epoch, step = 0, 0
178 |
179 | print('---------PRERUN-----------')
180 | print('(Initialization)')
181 |
182 |
183 | warmup_epoch = 1
184 | check_steps = 100 * print_freq
185 | warmup_lr = args.learn_rate / (2 ** warmup_epoch)
186 |
187 | model.to(device)
188 |
189 | mse_loss = nn.MSELoss()
190 |
191 | for epoch in range(start_epoch, args.max_epoch):
192 | torch.manual_seed(args.seed + epoch)
193 | if args.use_cuda:
194 | torch.cuda.manual_seed(args.seed + epoch)
195 | model.train()
196 | loss_total = 0.0
197 | loss_print = 0.0
198 | loss_as_1_total = 0.0
199 | loss_as_1_print = 0.0
200 | loss_as_2_total = 0.0
201 | loss_as_2_print = 0.0
202 | loss_sig_1_total = 0.0
203 | loss_sig_1_print = 0.0
204 | loss_sig_2_total = 0.0
205 | loss_sig_2_print = 0.0
206 | stime = time.time()
207 | if epoch == 0 and warmup_epoch > 0:
208 | print(
209 | 'Use warmup stragery,and the lr is set to {:.5f} '.format(warmup_lr))
210 | setup_lr(optimizer, warmup_lr)
211 | warmup_lr *= 2
212 | elif epoch == warmup_epoch:
213 | print('The warmup was end,and the lr is set to {:.5f}'.format(
214 | args.learn_rate))
215 | setup_lr(optimizer, args.learn_rate)
216 |
217 | lr = get_learning_rate(optimizer)
218 | for idx, egs in enumerate(dataloader):
219 | batch_start = time.time()
220 |
221 | # load to gpu
222 | egs = load_obj(egs, device)
223 | inputs = egs["mixed_data"] # [B, C, T]
224 | gt_AS_arr = egs["doa_as_array"] # [B, T, S, n_mics, 210]
225 | gt_azi_arr = egs["doa_idx_array"] # [B, T, S, n_mics]
226 | target_1 = egs["target_1"] # [B, T]
227 | target_2 = egs["target_2"] # [B, T]
228 |
229 | model.zero_grad()
230 | es_AS_1, es_AS_2, es_sig_1, es_sig_2 = model(inputs)
231 |
232 | es_AS_1 = es_AS_1[:, 0:249, :, :] # [B, T, n_avb_mics, F]
233 | es_AS_2 = es_AS_2[:, 0:249, :, :] # [B, T, n_avb_mics, F]
234 |
235 | loss_as_1 = mse_loss(es_AS_1, gt_AS_arr[:, :, 0, :, :])
236 | loss_as_2 = mse_loss(es_AS_2, gt_AS_arr[:, :, 1, :, :])
237 | loss_sig_1 = wsdr_loss(es_sig_1, target_1, target_2)
238 | loss_sig_2 = wsdr_loss(es_sig_2, target_2, target_1)
239 |
240 | # weighted
241 | loss_as_1 = loss_as_1 * args.w_azimuth
242 | loss_as_2 = loss_as_2 * args.w_azimuth
243 | loss_sig_1 = loss_sig_1 * args.w_separation
244 | loss_sig_2 = loss_sig_2 * args.w_separation
245 |
246 | loss = loss_as_1 + loss_as_2 + loss_sig_1 + loss_sig_2
247 |
248 | loss.backward()
249 |
250 | nn.utils.clip_grad_norm_(model.parameters(), args.clip_grad_norm)
251 |
252 | optimizer.step()
253 |
254 | step += 1
255 | loss_total += loss.data.cpu()
256 | loss_print += loss.data.cpu()
257 | loss_as_1_total += loss_as_1.data.cpu()
258 | loss_as_1_print += loss_as_1.data.cpu()
259 | loss_as_2_total += loss_as_2.data.cpu()
260 | loss_as_2_print += loss_as_2.data.cpu()
261 | loss_sig_1_total += loss_sig_1.data.cpu()
262 | loss_sig_1_print += loss_sig_1.data.cpu()
263 | loss_sig_2_total += loss_sig_2.data.cpu()
264 | loss_sig_2_print += loss_sig_2.data.cpu()
265 |
266 | if (idx + 1) % print_freq == 0:
267 | batch_time = time.time() - batch_start
268 | avg_time = (time.time() - stime)/(idx + 1)
269 | loss_print_avg = loss_print / print_freq
270 | loss_as_1_print_avg = loss_as_1_print / print_freq
271 | loss_as_2_print_avg = loss_as_2_print / print_freq
272 | loss_sig_1_print_avg = loss_sig_1_print / print_freq
273 | loss_sig_2_print_avg = loss_sig_2_print / print_freq
274 |
275 | print('Epoch {:3d}/{:3d} | batches {:5d}/{:5d} | lr {:1.4e} | Current {:2.3f}s/batches '
276 | '| AVG {:2.3f}s/batches | loss {:2.6f} | loss_as {:2.6f} | loss_sig {:2.6f} '
277 | '| loss_as_1 {:2.6f} | loss_as_2 {:2.6f} | loss_sig_1 {:2.6f} | loss_sig_2 {:2.6f}'.format(
278 | epoch + 1, args.max_epoch, idx + 1, num_batch, lr,
279 | batch_time, avg_time, loss_print_avg, loss_as_1_print_avg + loss_as_2_print_avg,
280 | loss_sig_1_print_avg + loss_sig_2_print_avg,
281 | loss_as_1_print_avg, loss_as_2_print_avg,
282 | loss_sig_1_print_avg, loss_sig_2_print_avg), flush=True)
283 | # sys.stdout.flush()
284 | loss_print = 0.0
285 | loss_as_1_print = 0.0
286 | loss_as_2_print = 0.0
287 | loss_sig_1_print = 0.0
288 | loss_sig_2_print = 0.0
289 |
290 | eplashed = time.time() - stime
291 | loss_avg = loss_total / (step - (epoch) * num_batch)
292 | loss_as_1_avg = loss_as_1_total / (step - (epoch) * num_batch)
293 | loss_as_2_avg = loss_as_2_total / (step - (epoch) * num_batch)
294 | loss_sig_1_avg = loss_sig_1_total / (step - (epoch) * num_batch)
295 | loss_sig_2_avg = loss_sig_2_total / (step - (epoch) * num_batch)
296 |
297 | print(
298 | 'Training AVG.LOSS |'
299 | 'Epoch {:3d}/{:3d} | lr {:1.4e} | '
300 | '{:2.3f}s/batch | time {:3.2f}mins | '
301 | 'loss {:2.6f} | loss_as {:2.6f} | loss_sig {:2.6f} '
302 | 'loss_as_1 {:2.6f} | loss_as_2 {:2.6f} | loss_sig_1 {:2.6f} | loss_sig_2 {:2.6f}'.format(
303 | epoch + 1,
304 | args.max_epoch,
305 | lr,
306 | eplashed / check_steps,
307 | eplashed / 60.0,
308 | loss_avg,
309 | loss_as_1_avg + loss_as_2_avg,
310 | loss_sig_1_avg + loss_sig_2_avg,
311 | loss_as_1_avg,
312 | loss_as_2_avg,
313 | loss_sig_1_avg,
314 | loss_sig_2_avg,
315 | ), flush=True)
316 | val_loss = validation(model, args, lr, epoch, device)
317 | model.train()
318 |
319 | # if iteration after warmup_epoch,reset lr sechel to normal
320 | if epoch >= warmup_epoch:
321 | print('Rejected !!! The best is {:2.6f} '.format(scheduler.best))
322 | logging.info(' Rejected !!! The best is {:2.6f} model epoch = {:3d} '.format(
323 | scheduler.best, epoch))
324 | save_checkpoint(model, optimizer, epoch + 1,
325 | step, args.exp_dir, val_loss)
326 | scheduler.step(val_loss)
327 | sys.stdout.flush()
328 | else:
329 | save_checkpoint(model, optimizer, epoch + 1,
330 | step, args.exp_dir, val_loss)
331 |
332 |
333 | def main(args):
334 | cuda_flag = 1
335 | device = torch.device('cuda' if cuda_flag else 'cpu')
336 | torch.cuda.set_device(0)
337 | model = Tree(n_avb_mics=args.n_avb_mics)
338 |
339 | if not os.path.exists(args.exp_dir):
340 | os.mkdir(args.exp_dir)
341 | if not os.path.exists(os.path.join(args.exp_dir, 'log')):
342 | os.mkdir(os.path.join(args.exp_dir, 'log'))
343 |
344 | k = sum(p.numel() for p in model.parameters() if p.requires_grad)
345 | print('# of parameters:', k, flush=True)
346 |
347 | print("=" * 40, "Model Structures", "=" * 40)
348 | for module_name, m in model.named_modules():
349 | if module_name == '':
350 | print(m)
351 | print("=" * 98)
352 |
353 | model.to(device)
354 | if torch.cuda.device_count() > 1:
355 | model = torch.nn.DataParallel(model)
356 |
357 | train_process(model, FLAGS, device, 0, mix_info_list=None)
358 |
359 |
360 | if __name__ == '__main__':
361 | parser = argparse.ArgumentParser('PyTorch Version Enhancement')
362 | # model path
363 | parser.add_argument(
364 | '--exp-dir',
365 | dest='exp_dir',
366 | type=str,
367 | default='/Work21/2021/fuyanjie/pycode/MIMO_DBnet/1-10/exp0915',
368 | help='the exp dir')
369 | parser.add_argument(
370 | '--log-dir',
371 | dest='log_dir',
372 | type=str,
373 | default='/Work21/2021/fuyanjie/pycode/MIMO_DBnet/1-10/exp0915/log',
374 | help='the random seed')
375 |
376 | # data path
377 | parser.add_argument(
378 | '--tr-clean',
379 | dest='tr_clean',
380 | type=str,
381 | default='/Work21/2021/fuyanjie/pycode/LaBNetwoDE/data/exp_list/train-clean-100_1126.lst',
382 | help='the train clean data list')
383 | parser.add_argument(
384 | '--cv-clean ',
385 | dest='cv_clean',
386 | type=str,
387 | default='/Work21/2021/fuyanjie/pycode/LaBNetwoDE/data/exp_list/dev-clean_1126.lst',
388 | help='the validation clean data list')
389 | # train process configuration
390 | parser.add_argument(
391 | '--segment_length',
392 | dest='segment_length',
393 | type=int,
394 | default=4,
395 | help='the segment length')
396 | parser.add_argument(
397 | '--learn-rate',
398 | dest='learn_rate',
399 | type=float,
400 | default=1e-4,
401 | help='the learning rate in training')
402 | parser.add_argument(
403 | '--max-epoch',
404 | dest='max_epoch',
405 | type=int,
406 | default=100,
407 | help='the max epochs ')
408 | parser.add_argument(
409 | '--dropout',
410 | dest='dropout',
411 | type=float,
412 | default=0.4,
413 | help='the probility of dropout')
414 | parser.add_argument(
415 | '--batch-size',
416 | dest='batch_size',
417 | type=int,
418 | default=1,
419 | help='the batch size in train')
420 | parser.add_argument(
421 | '--use-cuda',
422 | dest='use_cuda',
423 | default=1,
424 | type=int,
425 | help='use cuda')
426 | parser.add_argument(
427 | '--seed',
428 | dest='seed',
429 | type=int,
430 | default=20,
431 | help='the random seed')
432 | parser.add_argument(
433 | '--num-threads',
434 | dest='num_threads',
435 | type=int,
436 | default=10)
437 | parser.add_argument(
438 | '--num-gpu',
439 | dest='num_gpu',
440 | type=int,
441 | default=1,
442 | help='the num gpus to use')
443 | parser.add_argument(
444 | '--weight-decay',
445 | dest='weight_decay',
446 | type=float,
447 | default=0.0000001)
448 | parser.add_argument(
449 | '--clip-grad-norm',
450 | dest='clip_grad_norm',
451 | type=float,
452 | default=3)
453 | parser.add_argument(
454 | '--sample-rate',
455 | dest='sample_rate',
456 | type=int,
457 | default=16000)
458 | parser.add_argument(
459 | '--alpha',
460 | dest='w_azimuth',
461 | type=float,
462 | default=1)
463 | parser.add_argument(
464 | '--beta',
465 | dest='w_separation',
466 | type=float,
467 | default=10)
468 | parser.add_argument(
469 | '--n_avb_mics',
470 | dest='n_avb_mics',
471 | type=int,
472 | default=2)
473 | parser.add_argument('--retrain', dest='retrain', type=int, default=1)
474 | FLAGS, _ = parser.parse_known_args()
475 | FLAGS.use_cuda = FLAGS.use_cuda and torch.cuda.is_available()
476 | print('torch.cuda.is_available(): ', torch.cuda.is_available())
477 | os.makedirs(FLAGS.exp_dir, exist_ok=True)
478 | np.random.seed(FLAGS.seed)
479 | torch.manual_seed(FLAGS.seed)
480 |
481 | torch.cuda.manual_seed(FLAGS.seed)
482 | import pprint
483 |
484 | pp = pprint.PrettyPrinter()
485 | pp.pprint(FLAGS.__dict__)
486 | main(FLAGS)
487 |
--------------------------------------------------------------------------------
/utils/utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import numpy as np
3 | import torch
4 | from pesq import pesq
5 | import soundfile as sf
6 | import librosa
7 | from itertools import permutations, product
8 |
9 |
10 | time_bins = 249
11 | batch = 4
12 | EPS = 1e-8
13 |
14 | def write_wav(fname, samps, fs=16000, normalize=True):
15 | """
16 | Write wav files in int16, support single/multi-channel
17 | """
18 | #if normalize:
19 | # samps = samps * MAX_INT16
20 | ## scipy.io.wavfile.write could write single/multi-channel files
21 | ## for multi-channel, accept ndarray [Nsamples, Nchannels]
22 | #if samps.ndim != 1 and samps.shape[0] < samps.shape[1]:
23 | # samps = np.transpose(samps)
24 | # samps = np.squeeze(samps)
25 | ## same as MATLAB and kaldi
26 | #samps_int16 = samps.astype(np.int16)
27 | #fdir = os.path.dirname(fname)
28 | #if fdir and not os.path.exists(fdir):
29 | # os.makedirs(fdir)
30 | ## NOTE: librosa 0.6.0 seems could not write non-float narray
31 | ## so use scipy.io.wavfile instead
32 | #wf.write(fname, fs, samps_int16)
33 |
34 | # wham and whamr mixture and clean data are float 32, can not use scipy.io.wavfile to read and write int16
35 | # change to soundfile to read and write, although reference speech is int16, soundfile still can read and outputs as float
36 | # soundfile also supports multi-channel files, given two-dimensional audio data (frames x channels)
37 | fdir = os.path.dirname(fname)
38 | if fdir and not os.path.exists(fdir):
39 | os.makedirs(fdir)
40 | sf.write(fname, samps, fs, subtype='FLOAT')
41 |
42 | def doa_err_2_source(gt_azi_arr, es_as_1, es_as_2):
43 | """
44 | gt_azi_arr: # [B, T, S, n_avb_mics=2]
45 | es_as_1 / es_as_2: [B, T, n_avb_mics=2, F] F: feature dimension of the likelihood-based coding
46 | """
47 |
48 | gt_azi_1 = gt_azi_arr[:, :, 0, :] # B, T, n_avb_mics
49 | gt_azi_2 = gt_azi_arr[:, :, 1, :] # B, T, n_avb_mics
50 | es_azi_1 = torch.max(es_as_1, 3)[1] # B, T, n_avb_mics
51 | es_azi_2 = torch.max(es_as_2, 3)[1] # B, T, n_avb_mics
52 |
53 | mask_1 = torch.ones((es_azi_1.shape[0], es_azi_1.shape[1], es_azi_1.shape[2]), device=es_as_1.device) # filter -1 value
54 | mask_2 = torch.ones((es_azi_2.shape[0], es_azi_2.shape[1], es_azi_2.shape[2]), device=es_as_1.device)
55 | mask_1[gt_azi_1 == -1] = 0
56 | mask_2[gt_azi_2 == -1] = 0
57 | masked_gt_azi_1 = gt_azi_1 * mask_1 # B, T, n_avb_mics
58 | masked_gt_azi_2 = gt_azi_2 * mask_2
59 | masked_es_azi_1 = es_azi_1 * mask_1
60 | masked_es_azi_2 = es_azi_2 * mask_2
61 | abs_err_azi_1 = torch.abs(masked_gt_azi_1-masked_es_azi_1)
62 | abs_err_azi_2 = torch.abs(masked_gt_azi_2-masked_es_azi_2)
63 | num_pred_1 = mask_1.sum()
64 | num_pred_2 = mask_2.sum()
65 | mae_1 = torch.sum(abs_err_azi_1) / num_pred_1 # [1]
66 | mae_2 = torch.sum(abs_err_azi_2) / num_pred_2 # [1]
67 | num_acc_1 = torch.where(abs_err_azi_1 <= 5, 1, 0).sum() - torch.sum(mask_1 == 0)
68 | num_acc_2 = torch.where(abs_err_azi_2 <= 5, 1, 0).sum() - torch.sum(mask_2 == 0)
69 |
70 | return mae_1, mae_2, num_acc_1, num_acc_2, num_pred_1, num_pred_2
71 |
72 | def dist_err_2_source(gt_dist_arr, es_ds_1, es_ds_2, dist_tolerance=20):
73 | """
74 | gt_dist_arr: [B, T, S]
75 | es_ds_1 / es_ds_2: [B, T, F] F: feature dimension of the likelihood-based coding
76 | """
77 | gt_dist_1 = gt_dist_arr[:, :, 0] # B, T
78 | gt_dist_2 = gt_dist_arr[:, :, 1] # B, T
79 | es_dist_1 = torch.max(es_ds_1, 2)[1] # B, T
80 | es_dist_2 = torch.max(es_ds_2, 2)[1] # B, T
81 |
82 | mask_1 = torch.ones((es_dist_1.shape[0], es_dist_1.shape[1]), device=es_ds_1.device) # filter -1 value
83 | mask_2 = torch.ones((es_dist_2.shape[0], es_dist_2.shape[1]), device=es_ds_1.device)
84 | mask_1[gt_dist_1 == -1] = 0
85 | mask_2[gt_dist_2 == -1] = 0
86 | masked_gt_dist_1 = gt_dist_1 * mask_1 # B, T
87 | masked_gt_dist_2 = gt_dist_2 * mask_2
88 | masked_es_dist_1 = es_dist_1 * mask_1
89 | masked_es_dist_2 = es_dist_2 * mask_2
90 | abs_err_azi_1 = torch.abs(masked_gt_dist_1-masked_es_dist_1)
91 | abs_err_azi_2 = torch.abs(masked_gt_dist_2-masked_es_dist_2)
92 | num_pred_1 = mask_1.sum()
93 | num_pred_2 = mask_2.sum()
94 | mae_1 = torch.sum(abs_err_azi_1) / num_pred_1 # [1]
95 | mae_2 = torch.sum(abs_err_azi_2) / num_pred_2 # [1]
96 | num_acc_1 = torch.where(abs_err_azi_1 <= dist_tolerance, 1, 0).sum() - torch.sum(mask_1 == 0)
97 | num_acc_2 = torch.where(abs_err_azi_2 <= dist_tolerance, 1, 0).sum() - torch.sum(mask_2 == 0)
98 |
99 | return mae_1, mae_2, num_acc_1, num_acc_2, num_pred_1, num_pred_2
100 |
101 |
102 | def cal_si_snr(source, estimate_source):
103 | """Calculate SI-SNR without PIT training.
104 | Args:
105 | source: [B, C, T] a tensor
106 | estimate_source: [B, C, T] a tensor
107 | B:batch_size C: channel T:lenght of audio
108 | in this case C==1 only single channel
109 | """
110 | # assert source.size() == estimate_source.size()
111 | B, C, T = source.size()
112 |
113 | # Step 1. Zero-mean norm
114 | # num_samples = source_lengths.view(-1, 1, 1).float() ?# [B, 1, 1]
115 | mean_target = torch.sum(source, dim=2, keepdim=True) / T
116 | mean_estimate = torch.sum(estimate_source, dim=2, keepdim=True) / T
117 | zero_mean_target = source - mean_target
118 | zero_mean_estimate = estimate_source - mean_estimate
119 |
120 |
121 | # Step 2. SI-SNR without PIT
122 | # reshape to use broadcast
123 | s_target = zero_mean_target # [B, C, T]
124 | s_estimate = zero_mean_estimate # [B, C, T]
125 | # s_target = source
126 | # s_estimate = estimate_source
127 |
128 |
129 | # s_target = s / ||s||^2
130 | pair_wise_dot = torch.sum(s_estimate * s_target, dim=2, keepdim=True) # [B, C, 1]
131 | s_target_energy = torch.sum(s_target ** 2, dim=2, keepdim=True) + EPS # [B, C, 1]
132 | pair_wise_proj = pair_wise_dot * s_target / s_target_energy # [B, C, T]
133 | # print('s_target:',pair_wise_proj[0][0][0:10])
134 | # e_noise = s' - s_target
135 | e_noise = s_estimate - pair_wise_proj # [B, C, T]
136 |
137 | # SI-SNR = 10 * log_10(||s_target||^2 / ||e_noise||^2)
138 | pair_wise_si_snr = torch.sum(pair_wise_proj ** 2, dim=2) / (torch.sum(e_noise ** 2, dim=2) + EPS)
139 | pair_wise_si_snr = 10 * torch.log10(pair_wise_si_snr + EPS) # [B, C]
140 |
141 | # print('888',pair_wise_si_snr.shape)
142 | si_snr = torch.mean(pair_wise_si_snr, dim=0)
143 |
144 | # si_snr = torch.sum(pair_wise_si_snr,dim=0)
145 |
146 | return round(float(si_snr.cpu().numpy()[0]),4)
147 |
148 | def cal_si_snr_np(source, estimate_source):
149 | """Calculate SI-SNR without PIT training.
150 | Args:
151 | source: [B, C, T] a tensor
152 | estimate_source: [B, C, T] a tensor
153 | B:batch_size C: channel T:lenght of audio
154 | in this case C==1 only single channel
155 | """
156 | # assert source.size() == estimate_source.size()
157 | B, C, T = source.shape
158 |
159 | # Step 1. Zero-mean norm
160 | # num_samples = source_lengths.view(-1, 1, 1).float() ?# [B, 1, 1]
161 | mean_target = np.sum(source, axis=2, keepdims=True) / T
162 | mean_estimate = np.sum(estimate_source, axis=2, keepdims=True) / T
163 | zero_mean_target = source - mean_target
164 | zero_mean_estimate = estimate_source - mean_estimate
165 |
166 |
167 | # Step 2. SI-SNR without PIT
168 | # reshape to use broadcast
169 | s_target = zero_mean_target # [B, C, T]
170 | s_estimate = zero_mean_estimate # [B, C, T]
171 | # s_target = source
172 | # s_estimate = estimate_source
173 |
174 |
175 | # s_target = s / ||s||^2
176 | pair_wise_dot = np.sum(s_estimate * s_target, axis=2, keepdims=True) # [B, C, 1]
177 | s_target_energy = np.sum(s_target ** 2, axis=2, keepdims=True) + EPS # [B, C, 1]
178 | pair_wise_proj = pair_wise_dot * s_target / s_target_energy # [B, C, T]
179 | # print('s_target:',pair_wise_proj[0][0][0:10])
180 | # e_noise = s' - s_target
181 | e_noise = s_estimate - pair_wise_proj # [B, C, T]
182 |
183 | # SI-SNR = 10 * log_10(||s_target||^2 / ||e_noise||^2)
184 | pair_wise_si_snr = np.sum(pair_wise_proj ** 2, axis=2) / (np.sum(e_noise ** 2, axis=2) + EPS)
185 | pair_wise_si_snr = 10 * np.log10(pair_wise_si_snr + EPS) # [B, C]
186 |
187 | # print('888',pair_wise_si_snr.shape)
188 | si_snr = np.mean(pair_wise_si_snr, axis=0)
189 |
190 | # si_snr = np.sum(pair_wise_si_snr,axis=0)
191 |
192 | return round(float(si_snr[0]),4)
193 |
194 | def pow_p_norm(signal):
195 | """Compute 2 Norm"""
196 | return torch.pow(torch.norm(signal, p=2, dim=-1, keepdim=True), 2)
197 |
198 | def pow_norm(s1, s2):
199 | return torch.sum(s1 * s2, dim=-1, keepdim=True)
200 |
201 | def remove_dc(signal):
202 | """Normalized to zero mean"""
203 | mean = torch.mean(signal, dim=-1, keepdim=True)
204 | signal = signal - mean
205 | return signal
206 |
207 | def si_sdr(estimated, original):
208 | # estimated = remove_dc(estimated)
209 | # original = remove_dc(original)
210 | target = pow_norm(estimated, original) * original / (pow_p_norm(original) + EPS)
211 | noise = estimated - target
212 | sdr = 10 * torch.log10(pow_p_norm(target) / (pow_p_norm(noise) + EPS) + EPS)
213 | return sdr.squeeze_(dim=-1)
214 |
215 | # Minimize negative SI-SDR
216 | def permute_si_sdr(est, src):
217 | """ Caculate SI-SDR with PIT.
218 | Args:
219 | est: [batch_size, nspk, length]
220 | src: [batch_size, nspk, length]
221 | """
222 | assert est.size() == src.size()
223 | nspk = est.size(1)
224 | # reshape source to [batch_size, 1, nspk, length]
225 | src = torch.unsqueeze(src, dim=1)
226 | # reshape estimation to [batch_size, nspk, 1, length]
227 | est = torch.unsqueeze(est, dim=2)
228 | pair_wise_sdr = si_sdr(est, src) # [batch_size, nspk, nspk]
229 | # permutation, [nspk!, nspk]
230 | perms = torch.tensor(list(permutations(range(nspk))), dtype=torch.long)
231 | index = torch.unsqueeze(perms, dim=-1)
232 | # one-hot, [nspk!, nspk, nspk]
233 | perms_one_hot = torch.zeros((*perms.size(), nspk)).scatter_(-1, index, 1)
234 | perms_one_hot = perms_one_hot.to(est.device)
235 | # einsum([batch_size, nspk, nspk], [nspk!, nspk, nspk]) -> [batch_size, nspk!]
236 | sdr_set = torch.einsum('bij,pij->bp', [pair_wise_sdr, perms_one_hot])
237 | # max_sdr_idx = torch.argmax(sdr_set, dim=-1)
238 | max_sdr, _ = torch.max(sdr_set, dim=-1)
239 | avg_loss = 0.0 - torch.mean(max_sdr / nspk)
240 | return avg_loss
241 |
242 | def assignment_si_sdr(est, ref):
243 | """ Solve the assignment problem when computing SI-SDR.
244 | Args:
245 | est: [batch_size, est_num_sources=3, length]
246 | ref: [batch_size, ref_num_sources=2, length]
247 | """
248 | ref_num_sources = ref.size(1)
249 | est_num_sources = est.size(1)
250 | losses = []
251 | idxs = []
252 | # This itertools call returns all possible assignments from estimates to
253 | # references, E.g. itertools.product(range(2), repeat=3) produces:
254 | # (0, 0, 0)
255 | # (0, 0, 1)
256 | # (0, 1, 0)
257 | # (0, 1, 1)
258 | # (1, 0, 0)
259 | # (1, 0, 1)
260 | # (1, 1, 0)
261 | # (1, 1, 1)
262 | for idx in product(range(ref_num_sources), repeat=est_num_sources):
263 | # mix_matrix's shape: [1, ref_num_sources, est_num_sources]
264 | mix_matrix = torch.unsqueeze(torch.nn.functional.one_hot(torch.tensor(idx), num_classes=ref_num_sources).transpose(1,0).float(), dim=0)
265 | # estimate_mixed's shape: [batch, ref_num_sources, ...].
266 | estimate_mixed = torch.matmul(mix_matrix, est)
267 | # losses[0]: [batch, ref_num_sources]
268 | losses.append(torch.mean(si_sdr(estimate_mixed, ref), dim=1, keepdim=True))
269 | idxs.append(idx)
270 | loss_matrix = torch.cat(losses, dim=1)
271 | # loss_matrix's shape: [batch, len(idxs)].
272 | idx_argmin = torch.argmin(loss_matrix, dim=1)
273 | idx_argmin = torch.unsqueeze(idx_argmin, 1)
274 | # idx_argmin's shape: [batch, 1].
275 |
276 | def th_gather_1d(x, indices):
277 | x_gather = torch.index_select(x, 1, indices)
278 | return x_gather
279 | def th_gather_2d(param, indices):
280 | # param: [batch, row_size, col_size]
281 | # indices: [batch, 2]
282 | # return: [batch, horizon]
283 | indices = indices[:, 1]
284 | return torch.stack([param[i, indices[i]] for i in range(indices.shape[0])], 0)
285 |
286 | print(f'loss_matrix {loss_matrix.shape}')
287 | print(f'loss_matrix {loss_matrix}')
288 | print(f'A idx_argmin {idx_argmin.shape}')
289 | print(f'A idx_argmin {idx_argmin}')
290 | loss_best_mixture = torch.gather(loss_matrix, 1, idx_argmin).squeeze() # [B]
291 | print(f'loss_best_mixture {loss_best_mixture.shape}')
292 | print(f'loss_best_mixture {loss_best_mixture}')
293 | # idxs_tf [len(idxs), est_num_sources]
294 | idxs_tf = torch.cat([torch.unsqueeze(torch.tensor(idx), dim=0) for idx in idxs], dim=0)
295 | idxs_tf = torch.unsqueeze(idxs_tf, 0).repeat(batch, 1, 1)
296 | print(f'idxs_tf {idxs_tf.shape}')
297 | # idxs_tf's shape: [batch, len(idxs), est_num_sources].
298 | idx_argmin = torch.stack([idx_argmin for i in range(est_num_sources)], dim=-1)
299 | print(f'B idx_argmin {idx_argmin.shape}')
300 | print(f'B idx_argmin {idx_argmin}')
301 | idxs_best = torch.gather(idxs_tf, 1, idx_argmin).squeeze()
302 | # idxs_best is shape [batch, est_num_sources].
303 | print(f'idxs_best {idxs_best.shape}')
304 | mix_matrix = torch.nn.functional.one_hot(idxs_best, num_classes=ref_num_sources).to(torch.float32)
305 | print(f'mix_matrix {mix_matrix.shape}')
306 | # mix_matrix's shape [batch, ref_num_sources, est_num_sources].
307 |
308 | return loss_best_mixture, mix_matrix
309 |
310 | def cal_pesq(source, estimate_source):
311 | """Calculate PESQ without PIT training.
312 | Args:
313 | source: [B, T]
314 | estimate_source: [B, T]
315 | """
316 | # assert source.size() == estimate_source.size()
317 |
318 | sr = 16000
319 | # print(source.shape)
320 | batch_size, _ = source.shape
321 | pesq_sum = 0
322 | for batch_idx in range(batch_size):
323 | pesq_sum += pesq(sr, source[batch_idx, :], estimate_source[batch_idx, :], 'wb')
324 |
325 | return (pesq_sum / batch_size)
326 |
327 | def audioread(path, segment=64000, fs = 16000):
328 | wave_data, sr = sf.read(path)
329 | if sr != fs:
330 | wave_data = librosa.resample(wave_data,sr,fs)
331 | return wave_data
332 |
333 | def loss_energy(x, eps=1e-8, fs=16000):
334 | # [B, T]
335 | """
336 | Arguments:
337 | x: estimated signal, [B, T] tensor
338 | average by duration (seconds)
339 | """
340 | return torch.mean(10 * torch.log10(pow_p_norm(x) * fs / x.shape[-1] + eps))
341 |
342 | def split_spec_into_subbands(sig, freq_bound, win_size, hop_size, fs=16000):
343 | """
344 | Args:
345 | sig: [ch, T]
346 | """
347 | import apkit
348 | # tf.shape: [C, num_frames, win_size] tf.dtype: complex128
349 | tf = apkit.stft(sig, apkit.cola_hamming, win_size, hop_size, last_sample=True)
350 | # trim freq bins
351 |
352 | fbin_bound = int(freq_bound * win_size / fs)
353 | tf_below = tf[:,:, :fbin_bound] # 0-4kHz
354 | tf_above = tf[:,:, fbin_bound:] # > 4kHz
355 | return tf_below, tf_above
356 |
357 | def split_spec_into_subbands_timedomain(sig, freq_bound, win_size, hop_size, fs=16000):
358 | """
359 | Args:
360 | sig: [ch, T]
361 | """
362 | import apkit
363 | # tf.shape: [C, num_frames, win_size] tf.dtype: complex128
364 | tf = apkit.stft(sig, apkit.cola_hamming, win_size, hop_size, last_sample=True)
365 | # trim freq bins
366 | fbin_bound = int(freq_bound * win_size / fs)
367 |
368 | tf_below = tf[:,:, :fbin_bound] # 0-4kHz
369 | tf_above = tf[:,:, fbin_bound:] # > 4kHz
370 |
371 | tf_below = np.pad(tf_below, ((0, 0), (0, 0), (0, win_size-fbin_bound)))
372 | tf_above = np.pad(tf_above, ((0, 0), (0, 0), (fbin_bound, 0)))
373 | # tf_below.shape: [C, num_frames, win_size] tf_above.shape: [C, num_frames, win_size]
374 | sig_below = apkit.istft(tf_below, hop_size) # [C, T]
375 | sig_above = apkit.istft(tf_above, hop_size) # [C, T]
376 |
377 | # write_wav("/Work21/2021/fuyanjie/pycode/MIMO_DBnet/1-10new/testlt4k.wav", sig_below[0])
378 | # write_wav("/Work21/2021/fuyanjie/pycode/MIMO_DBnet/1-10new/testgt4k.wav", sig_above[0])
379 | return sig_below, sig_above
380 |
381 | if __name__ == '__main__':
382 | # e1 = np.random.randn(1, 64000)
383 | # e2 = np.random.randn(1, 1, 32000)
384 | # c1 = np.random.randn(1, 1, 32000)
385 | # c2 = np.random.randn(1, 1, 32000)
386 | # print(f'e1.shape {e1.shape} e2.shape {e2.shape}')
387 | # print(f'c1.shape {c1.shape} c2.shape {c2.shape}')
388 | # print(cal_si_snr_np(e1, c1))
389 | # print(cal_si_snr_np(e2, c2))
390 | # es 71, 82
391 | gt_azi_arr = torch.tensor([[[62,62]]])
392 | # print(f'{gt_azi_arr.shape} {es_as_1.shape} {es_as_2.shape}')
393 | # print(doa_err_2_source(gt_azi_arr, es_as_1, es_as_2))
--------------------------------------------------------------------------------