├── LICENSE ├── README.md ├── data └── wsj0_2mix_extr │ └── wav8k │ └── max │ ├── cv │ ├── aux │ │ ├── 01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav │ │ ├── 01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav │ │ ├── 01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav │ │ └── 01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav │ ├── mix │ │ ├── 01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav │ │ ├── 01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav │ │ ├── 01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav │ │ └── 01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav │ └── s1 │ │ ├── 01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav │ │ ├── 01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav │ │ ├── 01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav │ │ └── 01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav │ ├── tr │ ├── aux │ │ ├── 01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav │ │ ├── 01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav │ │ ├── 01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav │ │ └── 01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav │ ├── mix │ │ ├── 01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav │ │ ├── 01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav │ │ ├── 01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav │ │ └── 01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav │ └── s1 │ │ ├── 01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav │ │ ├── 01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav │ │ ├── 01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav │ │ └── 01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav │ └── tt │ ├── aux │ ├── 01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav │ ├── 01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav │ ├── 01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav │ └── 01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav │ ├── mix │ ├── 01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav │ ├── 01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav │ ├── 01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav │ └── 01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav │ └── s1 │ ├── 01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav │ ├── 01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav │ ├── 01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav │ └── 01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav ├── decode.py ├── extract_feats.py ├── extract_feats_test.py ├── model ├── __init__.py ├── __init__.pyc ├── model.py └── model.pyc ├── run.sh ├── run_data_generation.sh ├── simulation ├── mix_2_spk_cv_extr.txt ├── mix_2_spk_tr_extr.txt ├── mix_2_spk_tt_extr.txt └── simulate_2spk_mix.m ├── train.py ├── utils ├── __init__.py ├── __init__.pyc ├── audioread.py ├── audioread.pyc ├── comp_dynamic_feature.py ├── comp_dynamic_feature.pyc ├── normhamming.py ├── normhamming.pyc ├── paddedFIFO_batch.py ├── paddedFIFO_batch.pyc ├── read_list.py ├── read_list.pyc ├── sigproc.py └── sigproc.pyc └── verification └── keys ├── clean_set └── trials ├── mixture_set └── trials └── readme /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 | # Target Speaker Extraction and Verification for Multi-talker Speech 2 | 3 | The codes here are speaker extraction, where only target speaker's voice will be extracted given this target speaker's characteristics. In paper 2), we use a small network to jointly learn target speaker's characteristics from a different utterance of target speaker. You also can replace the network by using i-vector, or x-vector network. 4 | 5 | If you are interested in speech separation to get all the speaker's voices in the mixture, please move to https://github.com/xuchenglin28/speech_separation 6 | 7 | ## Papers 8 | 9 | Please cite: 10 | 11 | 1) Chenglin Xu, Wei Rao, Xiong Xiao, Eng Siong Chng and Haizhou Li, "SINGLE CHANNEL SPEECH SEPARATION WITH CONSTRAINED UTTERANCE LEVEL PERMUTATION INVARIANT TRAINING USING GRID LSTM", in Proc. of ICASSP 2018, pp 6-10. 12 | 2) Chenglin Xu, Wei Rao, Eng Siong Chng, and Haizhou Li, "Optimization of Speaker Extraction Neural Network with Magnitude and Temporal Spectrum Approximation Loss", in Proc. of ICASSP 2019, pp 6990-6994. 13 | 3) Wei Rao, Chenglin Xu, Eng Siong Chng, and Haizhou Li, "Target Speaker Extraction for Multi-Talker Speaker Verification", in Proc. of Interspeech 2019, pp.1273-1277. 14 | 15 | ## Data Generation: 16 | 17 | If you are using wsj0 to simulate data as in the paper 2) and 3), please read the code in run_data_generation.sh for detials, and change the path accordingly. 18 | 19 | The list of files and SNRs for {training, development and test sets} are in simulation/mix_2_spk_{tr,cv,tt}\_extr.txt. In the files, the first column is the utterance of the target speaker to generate mixture and also used as target clean to supervise the network learning. The seconde column is the interference speaker to generate the mixture. The third column is the taget speaker's another utterane to obtain speaker's characteristics. 20 | 21 | After run the .sh script, there will be 3 folders {mix, aux, s1} for the three sets {tr, cv, tt}. The mix folder is the mixture speech, aux folder is the utterances to obtain speaker's characteristics, and s1 is the folder of target clean. In all three folders, the names are cosistent for each example. 22 | 23 | ## Speaker Extraction 24 | 25 | This part includes feature extraction, model training, run-time inference. Please read the run.sh code for detail and revise accordingly. 26 | 27 | noisy_dir: the folder where your simulated data is. For example, "data/wsj0_2mix_extr/wav8k/max", under this path, there will be three folder for training, development and test sets (tr, cv, tt). In each set, there will be three folder with names of (mix, aux, s1) as described in Data Genration part. 28 | 29 | (The folder name for training and development set has been hard code. If you want to use differnt forlder name, please change parameters in read_list() function in train.py) 30 | 31 | After given the path to the noisy_dir, you can just run the code to extract feature, train model, and do run-time inference. 32 | 33 | run.sh 34 | 35 | ### If you want to repeat the results in the published paper, you need to set the dur=0 in run.sh. Because variant utterances are used without fixing the duration of the utterances. 36 | 37 | ## Speaker Verification: 38 | 39 | Here we only provide the key files for the paper 3) on speaker verification. Please read the paper for details. 40 | 41 | verification/keys: key files of simulated trials for multi-talker speaker verification system. 42 | 43 | ## Environments: 44 | 45 | python: 2.7 46 | 47 | Tensorflow: 1.12 (some API are older version, but compatiable by 1.12) 48 | 49 | ## Contact 50 | 51 | e-mail: xuchenglin28@gmail.com 52 | 53 | ## Licence 54 | 55 | The code and models in this repository are licensed under the GNU General Public License Version 3. 56 | 57 | ## Citation 58 | If you would like to cite, use this : 59 | ```BibTex 60 | @inproceedings{xu2018single, 61 | title={Single channel speech separation with constrained utterance level permutation invariant training using grid lstm}, 62 | author={Xu, Chenglin and Rao, Wei and Xiao, Xiong and Chng, Eng Siong and Li, Haizhou}, 63 | booktitle={IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)}, 64 | pages={6--10}, 65 | year={2018} 66 | } 67 | @inproceedings{xu2019optimization, 68 | title={Optimization of speaker extraction neural network with magnitude and temporal spectrum approximation loss}, 69 | author={Xu, Chenglin and Rao, Wei and Chng, Eng Siong and Li, Haizhou}, 70 | booktitle={IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)}, 71 | pages={6990--6994}, 72 | year={2019} 73 | } 74 | @inproceedings{rao2019target, 75 | title={Target speaker extraction for multi-talker speaker verification}, 76 | author={Rao, Wei and Xu, Chenglin and Chng, Eng Siong and Li, Haizhou}, 77 | booktitle={Proc. Of INTERSPEECH}, 78 | pages={1273--1277}, 79 | year={2019} 80 | } 81 | ``` 82 | -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/cv/aux/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/cv/aux/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/cv/aux/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/cv/aux/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/cv/aux/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/cv/aux/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/cv/aux/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/cv/aux/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/cv/mix/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/cv/mix/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/cv/mix/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/cv/mix/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/cv/mix/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/cv/mix/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/cv/mix/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/cv/mix/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/cv/s1/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/cv/s1/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/cv/s1/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/cv/s1/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/cv/s1/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/cv/s1/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/cv/s1/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/cv/s1/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tr/aux/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tr/aux/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tr/aux/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tr/aux/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tr/aux/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tr/aux/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tr/aux/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tr/aux/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tr/mix/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tr/mix/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tr/mix/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tr/mix/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tr/mix/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tr/mix/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tr/mix/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tr/mix/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tr/s1/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tr/s1/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tr/s1/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tr/s1/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tr/s1/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tr/s1/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tr/s1/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tr/s1/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tt/aux/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tt/aux/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tt/aux/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tt/aux/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tt/aux/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tt/aux/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tt/aux/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tt/aux/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tt/mix/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tt/mix/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tt/mix/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tt/mix/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tt/mix/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tt/mix/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tt/mix/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tt/mix/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tt/s1/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tt/s1/01aa010b_0.97482_209a010p_-0.97482_01ao0319.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tt/s1/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tt/s1/01aa010b_1.4476_20aa010p_-1.4476_01ao0305.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tt/s1/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tt/s1/01aa010e_1.5667_20pc010f_-1.5667_01aa010j.wav -------------------------------------------------------------------------------- /data/wsj0_2mix_extr/wav8k/max/tt/s1/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/data/wsj0_2mix_extr/wav8k/max/tt/s1/01aa010e_1.6244_401c021d_-1.6244_01ac020a.wav -------------------------------------------------------------------------------- /decode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2017 Xu Chenglin(NTU, Singapore) 5 | # Updated by Chenglin, Dec 2018 6 | 7 | from __future__ import absolute_import 8 | from __future__ import division 9 | from __future__ import print_function 10 | 11 | import argparse 12 | import os, sys, re, struct, time 13 | import pprint 14 | import numpy as np 15 | import tensorflow as tf 16 | from model.model import Model 17 | from utils.paddedFIFO_batch import paddedFIFO_batch 18 | from utils.read_list import read_list 19 | 20 | from utils.audioread import audioread 21 | from utils.sigproc import framesig,magspec,deframesig 22 | from utils.normhamming import normhamming 23 | import scipy.io.wavfile as wav 24 | 25 | FLAGS = None 26 | 27 | def reconstruct(enhan_spec, noisy_file): 28 | 29 | rate, sig, nb_bits = audioread(noisy_file) 30 | frames = framesig(sig, FLAGS.FFT_LEN, FLAGS.FRAME_SHIFT, lambda x: normhamming(x), True) 31 | phase_noisy, mag_noisy = magspec(frames, FLAGS.FFT_LEN) 32 | 33 | spec_comp = enhan_spec * np.exp(phase_noisy * 1j) 34 | enhan_frames = np.fft.irfft(spec_comp) 35 | enhan_sig = deframesig(enhan_frames, len(sig), FLAGS.FFT_LEN, FLAGS.FRAME_SHIFT, lambda x: normhamming(x)) 36 | enhan_sig = enhan_sig / np.max(np.abs(enhan_sig)) * np.max(np.abs(sig)) 37 | 38 | enhan_sig = np.round(enhan_sig * float(2 ** (nb_bits - 1))) 39 | if nb_bits == 16: 40 | enhan_sig = enhan_sig.astype(np.int16) 41 | elif nb_bits == 32: 42 | enhan_sig = enhan_sig.astype(np.int32) 43 | 44 | return enhan_sig, rate 45 | 46 | def decode(): 47 | tfrecords_list, num_batches = read_list(FLAGS.lists_dir, FLAGS.data_type, FLAGS.batch_size) 48 | 49 | with tf.Graph().as_default(): 50 | with tf.device('/cpu:0'): 51 | with tf.name_scope('input'): 52 | cmvn = np.load(FLAGS.inputs_cmvn) 53 | cmvn_aux = np.load(FLAGS.inputs_cmvn.replace('cmvn', 'cmvn_aux')) 54 | if FLAGS.with_labels: 55 | inputs, inputs_cmvn, inputs_cmvn_aux, labels, lengths, lengths_aux = paddedFIFO_batch(tfrecords_list, FLAGS.batch_size, 56 | FLAGS.input_size, FLAGS.output_size, cmvn=cmvn, cmvn_aux=cmvn_aux, with_labels=FLAGS.with_labels, 57 | num_enqueuing_threads=1, num_epochs=1, shuffle=False) 58 | else: 59 | inputs, inputs_cmvn, inputs_cmvn_aux, lengths, lengths_aux = paddedFIFO_batch(tfrecords_list, FLAGS.batch_size, 60 | FLAGS.input_size, FLAGS.output_size, cmvn=cmvn, cmvn_aux=cmvn_aux, with_labels=FLAGS.with_labels, 61 | num_enqueuing_threads=1, num_epochs=1, shuffle=False) 62 | labels = None 63 | 64 | with tf.name_scope('model'): 65 | model = Model(FLAGS, inputs, inputs_cmvn, inputs_cmvn_aux, labels, lengths, lengths_aux, infer=True) 66 | 67 | init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) 68 | sess = tf.Session() 69 | sess.run(init) 70 | 71 | checkpoint = tf.train.get_checkpoint_state(FLAGS.save_model_dir) 72 | if checkpoint and checkpoint.model_checkpoint_path: 73 | tf.logging.info("Restore best model from " + checkpoint.model_checkpoint_path) 74 | model.saver.restore(sess, checkpoint.model_checkpoint_path) 75 | else: 76 | tf.logging.fatal("Checkpoint is not found, please check the best model save path is correct.") 77 | sys.exit(-1) 78 | 79 | coord = tf.train.Coordinator() 80 | threads = tf.train.start_queue_runners(sess=sess, coord=coord) 81 | try: 82 | for batch in xrange(num_batches): 83 | if coord.should_stop(): 84 | break 85 | 86 | sep, mag_lengths = sess.run([model._sep, model._lengths]) 87 | for i in xrange(FLAGS.batch_size): 88 | filename = tfrecords_list[FLAGS.batch_size*batch+i] 89 | (_, name) = os.path.split(filename) 90 | (uttid, _) = os.path.splitext(name) 91 | noisy_file = os.path.join(FLAGS.noisy_dir, uttid + '.wav') 92 | enhan_sig, rate = reconstruct(np.squeeze(sep[i,:mag_lengths[i],:]), noisy_file) 93 | savepath = os.path.join(FLAGS.rec_dir, uttid + '.wav') 94 | wav.write(savepath, rate, enhan_sig) 95 | 96 | if (batch+1) % 100 == 0: 97 | tf.logging.info("Number of batch processed: %d." % (batch+1)) 98 | 99 | except Exception, e: 100 | coord.request_stop(e) 101 | finally: 102 | coord.request_stop() 103 | coord.join(threads) 104 | sess.close() 105 | 106 | def main(_): 107 | if not os.path.exists(FLAGS.save_model_dir): 108 | tf.logging.fatal("The best model path is not exist, please check.") 109 | sys.exit(-1) 110 | 111 | if not os.path.exists(FLAGS.noisy_dir): 112 | tf.logging.fatal("The mixture speech path is not exist, please check. Use the phase of the mixture to reconstruct the separated speech.") 113 | sys.exit(-1) 114 | 115 | if not os.path.exists(FLAGS.rec_dir): 116 | os.makedirs(FLAGS.rec_dir) 117 | 118 | decode() 119 | 120 | if __name__ == "__main__": 121 | tf.logging.set_verbosity(tf.logging.INFO) 122 | parser = argparse.ArgumentParser() 123 | parser.add_argument( 124 | '--lists_dir', 125 | type=str, 126 | default='tmp/', 127 | help="List to show where the data is." 128 | ) 129 | parser.add_argument( 130 | '--inputs_cmvn', 131 | type=str, 132 | default='tfrecords/tr_cmvn.npz', 133 | help="The global cmvn to normalize the inputs." 134 | ) 135 | parser.add_argument( 136 | '--noisy_dir', 137 | type=str, 138 | default='min/tt/mixed', 139 | help="The directory where the mixture speech is." 140 | ) 141 | parser.add_argument( 142 | '--data_type', 143 | type=str, 144 | default='tt', 145 | help="The data type to decode (default is tt, it's the folder name where the mixture speech is saved)." 146 | ) 147 | parser.add_argument( 148 | '--rec_dir', 149 | type=str, 150 | default='data/wav/rec/model_name', 151 | help="The directory where the separated speech is saved." 152 | ) 153 | parser.add_argument( 154 | '--with_labels', 155 | type=int, 156 | default=1, 157 | help='Whether the clean labels are included in the tfrecords.' 158 | ) 159 | parser.add_argument( 160 | '--input_size', 161 | type=int, 162 | default=129, 163 | help="Input feature dimension (default 129 for 8kHz sampling rate)." 164 | ) 165 | parser.add_argument( 166 | '--output_size', 167 | type=int, 168 | default=129, 169 | help="Output dimension (mask dimension, default 129 for 8kHz sampling rate)." 170 | ) 171 | parser.add_argument( 172 | '--rnn_size', 173 | type=int, 174 | default=896, 175 | help="Number of units in a rnn layer." 176 | ) 177 | parser.add_argument( 178 | '--rnn_num_layers', 179 | type=int, 180 | default=3, 181 | help="Number of rnn layers." 182 | ) 183 | parser.add_argument( 184 | '--model_type', 185 | type=str, 186 | default='BLSTM', 187 | help="RNN model type." 188 | ) 189 | parser.add_argument( 190 | '--mask_type', 191 | type=str, 192 | default='relu', 193 | help="Mask avtivation funciton, now only support sigmoid or relu" 194 | ) 195 | parser.add_argument( 196 | '--aux_hidden_size', 197 | type=int, 198 | default=512, 199 | help="The dimension of hidden layer in auxillary network." 200 | ) 201 | parser.add_argument( 202 | '--aux_output_size', 203 | type=int, 204 | default=30, 205 | help="The dimension of output layer in auxillary network, equals to the number of sub-layers in the adapt layer." 206 | ) 207 | parser.add_argument( 208 | '--batch_size', 209 | type=int, 210 | default=16, 211 | help="Minibatch size." 212 | ) 213 | parser.add_argument( 214 | '--num_threads', 215 | type=int, 216 | default=12, 217 | help='Number of threads for paralleling.' 218 | ) 219 | parser.add_argument( 220 | '--save_model_dir', 221 | type=str, 222 | default='exp/model_name', 223 | help="Directory to save the training model in every epoch." 224 | ) 225 | parser.add_argument( 226 | '--keep_prob', 227 | type=float, 228 | default=0.5, 229 | help="Keep probability for training with a dropout (default: 1-dropout_rate)." 230 | ) 231 | parser.add_argument( 232 | '--FFT_LEN', 233 | type=int, 234 | default=256, 235 | help="The length of FFT." 236 | ) 237 | parser.add_argument( 238 | '--FRAME_SHIFT', 239 | type=int, 240 | default=64, 241 | help="The frame shift." 242 | ) 243 | FLAGS, unparsed = parser.parse_known_args() 244 | pp = pprint.PrettyPrinter() 245 | pp.pprint(FLAGS.__dict__) 246 | sys.stdout.flush() 247 | tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) 248 | -------------------------------------------------------------------------------- /extract_feats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2017 Chenglin Xu (NTU, Singapore) 5 | # Updated by Chenglin, Dec 2018, Jul 2019 6 | 7 | """ 8 | 1. Extract features (magnitude, log magnitude) 9 | 2. Converts to TFRecords format 10 | 3. Calculate global CMVN (same as kaldi). 11 | """ 12 | 13 | from __future__ import absolute_import 14 | from __future__ import division 15 | from __future__ import print_function 16 | 17 | import argparse 18 | import multiprocessing 19 | import os,sys 20 | import numpy as np 21 | import tensorflow as tf 22 | 23 | from utils.audioread import audioread 24 | from utils.sigproc import framesig,magspec 25 | from utils.normhamming import normhamming 26 | import time 27 | 28 | def make_sequence(feats, feats_aux, labels=None): 29 | """ 30 | Return a sequence for given feats and corresponding labels (optional for test) 31 | Args: 32 | feats: input feature vectors (i.e. magnitude of mixture speech) 33 | feats_aux: inputs to auxilary network to learn target speaker representation 34 | labels1: reference labels for target sepaker 35 | Returns: 36 | A tf.train.SequenceExample 37 | """ 38 | 39 | inputs = [tf.train.Feature(float_list=tf.train.FloatList(value=feat)) for feat in feats] 40 | inputs_aux = [tf.train.Feature(float_list=tf.train.FloatList(value=feat_aux)) for feat_aux in feats_aux] 41 | if labels is not None: 42 | targets = [tf.train.Feature(float_list=tf.train.FloatList(value=label)) for label in labels] 43 | feature_list = { 44 | 'inputs': tf.train.FeatureList(feature=inputs), 45 | 'inputs_aux': tf.train.FeatureList(feature=inputs_aux), 46 | 'labels': tf.train.FeatureList(feature=targets) 47 | } 48 | else: 49 | feature_list = { 50 | 'inputs': tf.train.FeatureList(feature=inputs), 51 | 'inputs_aux': tf.train.FeatureList(feature=inputs_aux) 52 | } 53 | 54 | feature_lists = tf.train.FeatureLists(feature_list=feature_list) 55 | return tf.train.SequenceExample(feature_lists=feature_lists) 56 | 57 | def cal_phase_mag(filename, dur=None): 58 | ''' 59 | extract phase and feats for one utterance 60 | ''' 61 | 62 | rate, sig, _ = audioread(filename) 63 | if dur != 0: 64 | sig = sig[:rate*dur] 65 | frames = framesig(sig, FLAGS.FFT_LEN, FLAGS.FRAME_SHIFT, lambda x: normhamming(x), True) 66 | phase, feats = magspec(frames, FLAGS.FFT_LEN) 67 | 68 | return phase, feats 69 | 70 | def cal_intermedia_mean_var(feats): 71 | mean_feats = np.sum(feats, 0) 72 | var_feats = np.sum(np.square(feats), 0) 73 | return str(np.shape(feats)[0])+'+'+' '.join(str(mean_feat) for mean_feat in mean_feats)+'+'+' '.join(str(var_feat) for var_feat in var_feats) 74 | 75 | def extract_mag_feats(item, mean_var_dict, mean_var_dict_aux): 76 | tokens = item.strip().split() 77 | 78 | (_, name) = os.path.split(tokens[0]) 79 | (uttid, _) = os.path.splitext(name) 80 | # extract feats for mixture 81 | phase_mix, feats = cal_phase_mag(tokens[0], dur=FLAGS.dur) 82 | mean_var_dict[uttid] = cal_intermedia_mean_var(feats) 83 | 84 | (_, name_aux) = os.path.split(tokens[1]) 85 | (uttid_aux, _) = os.path.splitext(name_aux) 86 | tokens_aux = uttid_aux.split('-') 87 | # extract auxiliary feats for auxiliary network 88 | phase_aux, feats_aux = cal_phase_mag(tokens[1], dur=FLAGS.dur) 89 | # calculate intermediates for mean and variance for auxiliary inputs, save to kaldi vector format 90 | mean_var_dict_aux[uttid] = cal_intermedia_mean_var(feats_aux) 91 | 92 | # extract mag for clean as labels 93 | if FLAGS.with_labels: 94 | # extract feats for mixture 95 | phase_clean, labels = cal_phase_mag(tokens[2], dur=FLAGS.dur) 96 | 97 | if FLAGS.apply_psm: 98 | labels = labels * np.cos(phase_mix - phase_clean) 99 | else: 100 | labels = None 101 | 102 | # tfrecords to save the sequency consisting of feats and labels (optional for test) 103 | tfrecords_name = os.path.join(FLAGS.output_dir, FLAGS.data_type, uttid+".tfrecords") 104 | writer = tf.python_io.TFRecordWriter(tfrecords_name) 105 | # write feats and labels into tfrecords 106 | writer.write(make_sequence(feats, feats_aux, labels).SerializeToString()) 107 | 108 | return mean_var_dict, mean_var_dict_aux 109 | 110 | def cal_global_mean_std(filename, mean_var_dict): 111 | cmvn = np.zeros((2, int(FLAGS.FFT_LEN/2+1)), dtype=np.float32) 112 | frames = 0.0 113 | for line in mean_var_dict: 114 | tokens = line.strip().split('+') 115 | frames += float(tokens[0]) 116 | utt_mean_tokens = tokens[1].strip().split() 117 | cmvn[0] += [np.float32(i) for i in utt_mean_tokens] 118 | utt_var_tokens = tokens[2].strip().split() 119 | cmvn[1] += [np.float32(i) for i in utt_var_tokens] 120 | 121 | mean = cmvn[0] / frames 122 | var = cmvn[1] / frames - mean ** 2 123 | var[var<=0] = 1.0e-20 124 | std = np.sqrt(var) 125 | 126 | print(mean) 127 | print(std) 128 | np.savez(filename, mean_inputs=mean, stddev_inputs=std) 129 | 130 | def main(unused_argv): 131 | print('Extract starts ...') 132 | print(time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())) 133 | 134 | if not os.path.exists(os.path.join(FLAGS.output_dir, FLAGS.data_type)): 135 | os.makedirs(os.path.join(FLAGS.output_dir, FLAGS.data_type)) 136 | 137 | lists = open(FLAGS.list_path).readlines() 138 | 139 | # check whether the cmvn file for training exist, remove if exist. 140 | if os.path.exists(FLAGS.inputs_cmvn): 141 | os.remove(FLAGS.inputs_cmvn) 142 | if os.path.exists(FLAGS.inputs_cmvn.replace('cmvn', 'cmvn_aux')): 143 | os.remove(FLAGS.inputs_cmvn.replace('cmvn', 'cmvn_aux')) 144 | 145 | mean_var_dict = multiprocessing.Manager().dict() 146 | mean_var_dict_aux = multiprocessing.Manager().dict() 147 | pool = multiprocessing.Pool(FLAGS.num_threads) 148 | workers = [] 149 | for item in lists: 150 | workers.append(pool.apply_async(extract_mag_feats(item, mean_var_dict, mean_var_dict_aux))) 151 | pool.close() 152 | pool.join() 153 | 154 | # convert the utterance level intermediates for mean and var to global mean and std, then save 155 | cal_global_mean_std(FLAGS.inputs_cmvn, mean_var_dict.values()) 156 | cal_global_mean_std(FLAGS.inputs_cmvn.replace('cmvn', 'cmvn_aux'), mean_var_dict_aux.values()) 157 | 158 | print(time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())) 159 | print('Extract ends.') 160 | 161 | if __name__ == '__main__': 162 | parser = argparse.ArgumentParser() 163 | parser.add_argument( 164 | '--with_labels', 165 | type=int, 166 | default=1, 167 | help='Whether extract features for the targets as labels, default to prepare labels.') 168 | parser.add_argument( 169 | '--data_type', 170 | type=str, 171 | default='tr', 172 | help='tr, cv, tt.') 173 | parser.add_argument( 174 | '--apply_psm', 175 | type=int, 176 | default=1, 177 | help='Whether use phase sensitive mask.') 178 | parser.add_argument( 179 | '--inputs_cmvn', 180 | type=str, 181 | default='data/inputs_utts.cmvn', 182 | help='Path to save CMVN for the inputs' 183 | ) 184 | parser.add_argument( 185 | '--list_path', 186 | type=str, 187 | default='lists/tr_mix.lst', 188 | help='List of the paired mix, aux, clean data' 189 | ) 190 | parser.add_argument( 191 | '--output_dir', 192 | type=str, 193 | default='data/tfrecords', 194 | help='Directory to save the features into tfrecords format' 195 | ) 196 | parser.add_argument( 197 | '--FFT_LEN', 198 | type=int, 199 | default=512, 200 | help='The length of fft window.' 201 | ) 202 | parser.add_argument( 203 | '--FRAME_SHIFT', 204 | type=int, 205 | default=256, 206 | help='The shift of samples when calculating fft.' 207 | ) 208 | parser.add_argument( 209 | '--num_threads', 210 | type=int, 211 | default=10, 212 | help='The number of threads to convert tfrecords files.' 213 | ) 214 | parser.add_argument( 215 | '--dur', 216 | type=int, 217 | default=0, 218 | help='Duration of each file, cut to fixed length wav for mix, aux, clean' 219 | ) 220 | FLAGS, unparsed = parser.parse_known_args() 221 | tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) 222 | -------------------------------------------------------------------------------- /extract_feats_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2017 Chenglin Xu (NTU, Singapore) 5 | # Updated by Chenglin, Dec 2018 6 | 7 | """ 8 | 1. Extract features (magnitude, log magnitude) 9 | 2. Converts to TFRecords format 10 | 3. Calculate global CMVN (same as kaldi). 11 | """ 12 | 13 | from __future__ import absolute_import 14 | from __future__ import division 15 | from __future__ import print_function 16 | 17 | import argparse 18 | import multiprocessing 19 | import os,sys 20 | import numpy as np 21 | import tensorflow as tf 22 | 23 | from utils.audioread import audioread 24 | from utils.sigproc import framesig,magspec 25 | from utils.normhamming import normhamming 26 | import time 27 | 28 | def make_sequence(feats, feats_aux): 29 | """ 30 | Return a sequence for given feats and corresponding labels (optional for test) 31 | Args: 32 | feats: input feature vectors (i.e. magnitude of mixture speech) 33 | feats_aux: inputs to auxilary network to learn target speaker representation 34 | labels1: reference labels for target sepaker 35 | Returns: 36 | A tf.train.SequenceExample 37 | """ 38 | 39 | inputs = [tf.train.Feature(float_list=tf.train.FloatList(value=feat)) for feat in feats] 40 | inputs_aux = [tf.train.Feature(float_list=tf.train.FloatList(value=feat_aux)) for feat_aux in feats_aux] 41 | feature_list = { 42 | 'inputs': tf.train.FeatureList(feature=inputs), 43 | 'inputs_aux': tf.train.FeatureList(feature=inputs_aux) 44 | } 45 | 46 | feature_lists = tf.train.FeatureLists(feature_list=feature_list) 47 | return tf.train.SequenceExample(feature_lists=feature_lists) 48 | 49 | def cal_phase_mag(filename): 50 | ''' 51 | extract phase and feats for one utterance 52 | ''' 53 | 54 | rate, sig, _ = audioread(filename) 55 | frames = framesig(sig, FLAGS.FFT_LEN, FLAGS.FRAME_SHIFT, lambda x: normhamming(x), True) 56 | phase, feats = magspec(frames, FLAGS.FFT_LEN) 57 | 58 | return phase, feats 59 | 60 | def extract_mag_feats(item): 61 | tokens = item.strip().split() 62 | 63 | (_, name) = os.path.split(tokens[0]) 64 | (uttid, _) = os.path.splitext(name) #mixed or noisy utterance 65 | # extract feats for mixture 66 | phase_mix, feats = cal_phase_mag(tokens[0]) 67 | 68 | (_, name_aux) = os.path.split(tokens[1]) 69 | (uttid_aux, _) = os.path.splitext(name_aux) 70 | tokens_aux = uttid_aux.split('_') 71 | # extract auxiliary feats for auxiliary network 72 | phase_aux, feats_aux = cal_phase_mag(tokens[1]) 73 | 74 | # tfrecords to save the sequency consisting of feats and labels (optional for test) 75 | tfrecords_name = os.path.join(FLAGS.output_dir, FLAGS.data_type, uttid+".tfrecords") 76 | writer = tf.python_io.TFRecordWriter(tfrecords_name) 77 | # write feats and labels into tfrecords 78 | writer.write(make_sequence(feats, feats_aux).SerializeToString()) 79 | 80 | def main(unused_argv): 81 | print('Extract starts ...') 82 | print(time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())) 83 | 84 | if not os.path.exists(os.path.join(FLAGS.output_dir, FLAGS.data_type)): 85 | os.makedirs(os.path.join(FLAGS.output_dir, FLAGS.data_type)) 86 | 87 | lists = open(FLAGS.list_path).readlines() 88 | 89 | pool = multiprocessing.Pool(FLAGS.num_threads) 90 | workers = [] 91 | for item in lists: 92 | workers.append(pool.apply_async(extract_mag_feats(item))) 93 | pool.close() 94 | pool.join() 95 | 96 | print(time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())) 97 | print('Extract ends.') 98 | 99 | if __name__ == '__main__': 100 | parser = argparse.ArgumentParser() 101 | parser.add_argument( 102 | '--data_type', 103 | type=str, 104 | default='tr', 105 | help='tr, cv, tt.') 106 | parser.add_argument( 107 | '--list_path', 108 | type=str, 109 | default='lists/rm4_tr.lst', 110 | help='List of the paired mix, aux, clean data' 111 | ) 112 | parser.add_argument( 113 | '--output_dir', 114 | type=str, 115 | default='data/tfrecords', 116 | help='Directory to save the features into tfrecords format' 117 | ) 118 | parser.add_argument( 119 | '--FFT_LEN', 120 | type=int, 121 | default=512, 122 | help='The length of fft window.' 123 | ) 124 | parser.add_argument( 125 | '--FRAME_SHIFT', 126 | type=int, 127 | default=256, 128 | help='The shift of samples when calculating fft.' 129 | ) 130 | parser.add_argument( 131 | '--num_threads', 132 | type=int, 133 | default=10, 134 | help='The number of threads to convert tfrecords files.' 135 | ) 136 | FLAGS, unparsed = parser.parse_known_args() 137 | tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) 138 | -------------------------------------------------------------------------------- /model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/model/__init__.py -------------------------------------------------------------------------------- /model/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/model/__init__.pyc -------------------------------------------------------------------------------- /model/model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2017 Xu Chenglin(NTU, Singapore) 5 | # Updated by Chenglin, Dec 2018 6 | 7 | """ 8 | 1. Build speech separation network structure 9 | 2. Calculate the objective loss 10 | """ 11 | 12 | from __future__ import absolute_import 13 | from __future__ import division 14 | from __future__ import print_function 15 | 16 | import tensorflow as tf 17 | from tensorflow.contrib.rnn.python.ops import rnn 18 | from utils.comp_dynamic_feature import comp_dynamic_feature 19 | 20 | class Model(object): 21 | 22 | def __init__(self, config, inputs, inputs_norm, inputs_norm_aux, labels=None, lengths=None, lengths_aux=None, infer=False): 23 | self._config = config 24 | self._mixed = inputs 25 | self._inputs = inputs_norm 26 | self._inputs_aux = inputs_norm_aux 27 | if labels is not None: 28 | self._labels = labels 29 | self._lengths = lengths 30 | self._lengths_aux = lengths_aux 31 | self._infer = infer 32 | 33 | self.build_model() 34 | 35 | def build_model(self): 36 | self.build_net() 37 | if self._infer: return 38 | self.cal_loss() 39 | if tf.get_variable_scope().reuse: return 40 | 41 | self._lr = tf.Variable(0.0, trainable=False) 42 | tvars = tf.trainable_variables() 43 | grads, _ = tf.clip_by_global_norm(tf.gradients(self._loss, tvars), self._config.max_grad_norm) 44 | optimizer = tf.train.AdamOptimizer(self._lr) 45 | self._train_op = optimizer.apply_gradients(zip(grads, tvars)) 46 | 47 | # build auxiliary network, since this speaker embedding network can be used on top of extected speech for speaker verification 48 | # we are going to share weights 49 | def build_net_aux(self, inputs, lengths): 50 | outputs = tf.reshape(inputs, [self._config.batch_size, -1, self._config.input_size]) 51 | # BLSTM layer 52 | with tf.variable_scope('blstm_aux'): 53 | def lstm_cell(): 54 | if not self._infer and self._config.keep_prob < 1.0: 55 | return tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.BasicLSTMCell(self._config.aux_hidden_size), output_keep_prob=self._config.keep_prob) 56 | else: 57 | return tf.contrib.rnn.BasicLSTMCell(self._config.aux_hidden_size) 58 | 59 | # tf.nn.rnn_cell.MultiRNNCell in r1.12 60 | lstm_fw_cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(self._config.rnn_num_layers)], state_is_tuple=True) 61 | lstm_bw_cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(self._config.rnn_num_layers)], state_is_tuple=True) 62 | lstm_fw_cell = self._unpack_cell(lstm_fw_cell) 63 | lstm_bw_cell = self._unpack_cell(lstm_bw_cell) 64 | outputs, fw_final_states, bw_final_states = rnn.stack_bidirectional_dynamic_rnn(cells_fw=lstm_fw_cell, cells_bw=lstm_bw_cell, inputs=outputs, dtype=tf.float32, 65 | sequence_length=lengths) 66 | outputs = tf.reshape(outputs, [-1, 2*self._config.aux_hidden_size]) # transform blstm outputs into right output size 67 | 68 | with tf.variable_scope('layer2_aux'): 69 | weights2, biases2 = self._weight_and_bias(2*self._config.aux_hidden_size, self._config.aux_hidden_size) 70 | outputs = tf.nn.relu(tf.matmul(outputs, weights2) + biases2) 71 | 72 | with tf.variable_scope('layer3_aux'): 73 | weights3, biases3 = self._weight_and_bias(self._config.aux_hidden_size, self._config.aux_output_size) 74 | outputs = tf.matmul(outputs, weights3) + biases3 75 | outputs = tf.reshape(outputs, [self._config.batch_size, -1, self._config.aux_output_size]) 76 | # average over the frames to get the speaker embedding 77 | spk_embed = tf.reduce_sum(outputs, 1)/tf.reshape(tf.to_float(self._lengths_aux), (-1,1)) 78 | 79 | return spk_embed 80 | 81 | def build_net(self): 82 | 83 | # build auxiliary network to get the speaker embedding used for speaker extraction network 84 | with tf.variable_scope('spk_embed') as scope: 85 | spk_embed_aux = self.build_net_aux(self._inputs_aux, self._lengths_aux) 86 | 87 | outputs = tf.reshape(self._inputs, [self._config.batch_size, -1, self._config.input_size]) 88 | # BLSTM layer 89 | with tf.variable_scope('blstm'): 90 | def lstm_cell(): 91 | if not self._infer and self._config.keep_prob < 1.0: 92 | return tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.BasicLSTMCell(self._config.rnn_size), output_keep_prob=self._config.keep_prob) 93 | else: 94 | return tf.contrib.rnn.BasicLSTMCell(self._config.rnn_size) 95 | 96 | # tf.nn.rnn_cell.MultiRNNCell in r1.12 97 | lstm_fw_cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(self._config.rnn_num_layers)], state_is_tuple=True) 98 | lstm_bw_cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(self._config.rnn_num_layers)], state_is_tuple=True) 99 | lstm_fw_cell = self._unpack_cell(lstm_fw_cell) 100 | lstm_bw_cell = self._unpack_cell(lstm_bw_cell) 101 | outputs, fw_final_states, bw_final_states = rnn.stack_bidirectional_dynamic_rnn(cells_fw=lstm_fw_cell, cells_bw=lstm_bw_cell, inputs=outputs, dtype=tf.float32, 102 | sequence_length=self._lengths) 103 | 104 | # speaker adaptation layer by concat the output from auxiliary network 105 | with tf.variable_scope('adapt_concat'): 106 | outputs = tf.reshape(outputs, [self._config.batch_size, -1, 2*self._config.rnn_size]) 107 | frame_num = tf.shape(outputs)[1] 108 | spk_embed = tf.transpose(tf.reshape(tf.tile(tf.reshape(spk_embed_aux, (-1, 1)), (frame_num, 1)), (frame_num, self._config.batch_size, self._config.aux_output_size)), perm=[1,0,2]) 109 | 110 | outputs = tf.concat([outputs, spk_embed], 2) 111 | 112 | # remove the part out of the lenghts when concate speaker embeddings 113 | outputs = tf.multiply(tf.expand_dims(tf.sequence_mask(self._lengths, dtype=tf.float32), -1), outputs) 114 | concat_dim = 2*self._config.rnn_size+self._config.aux_output_size 115 | 116 | outputs = tf.reshape(outputs, [-1, concat_dim]) 117 | 118 | 119 | # one more fully connected layer 120 | with tf.variable_scope('fc1'): 121 | weights1, biases1 = self._weight_and_bias(concat_dim, self._config.rnn_size) 122 | outputs = tf.nn.relu(tf.matmul(outputs, weights1) + biases1) 123 | 124 | outputs = tf.reshape(outputs, [self._config.batch_size, -1, self._config.rnn_size]) 125 | 126 | # BLSTM layer 127 | with tf.variable_scope('blstm2'): 128 | def lstm_cell(): 129 | if not self._infer and self._config.keep_prob < 1.0: 130 | return tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.BasicLSTMCell(self._config.rnn_size), output_keep_prob=self._config.keep_prob) 131 | else: 132 | return tf.contrib.rnn.BasicLSTMCell(self._config.rnn_size) 133 | 134 | # tf.nn.rnn_cell.MultiRNNCell in r1.12 135 | lstm_fw_cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(self._config.rnn_num_layers)], state_is_tuple=True) 136 | lstm_bw_cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(self._config.rnn_num_layers)], state_is_tuple=True) 137 | lstm_fw_cell = self._unpack_cell(lstm_fw_cell) 138 | lstm_bw_cell = self._unpack_cell(lstm_bw_cell) 139 | outputs, fw_final_states, bw_final_states = rnn.stack_bidirectional_dynamic_rnn(cells_fw=lstm_fw_cell, cells_bw=lstm_bw_cell, inputs=outputs, dtype=tf.float32, 140 | sequence_length=self._lengths) 141 | outputs = tf.reshape(outputs, [-1, 2*self._config.rnn_size]) 142 | 143 | # one more fully connected layer 144 | with tf.variable_scope('fc2'): 145 | weights2, biases2 = self._weight_and_bias(2*self._config.rnn_size, self._config.rnn_size) 146 | outputs = tf.nn.relu(tf.matmul(outputs, weights2) + biases2) 147 | 148 | # Mask estimation layer 149 | with tf.variable_scope('mask'): 150 | weights_m, biases_m = self._weight_and_bias(self._config.rnn_size, self._config.output_size) 151 | if self._config.mask_type.lower() == 'relu': 152 | mask = tf.nn.relu(tf.matmul(outputs, weights_m) + biases_m) 153 | else: 154 | mask = tf.nn.sigmoid(tf.matmul(outputs, weights_m) + biases_m) 155 | 156 | self._mask = tf.reshape(mask, [self._config.batch_size, -1, self._config.output_size]) 157 | 158 | self._sep = self._mask * self._mixed 159 | 160 | self.saver = tf.train.Saver(tf.trainable_variables(), max_to_keep=50) 161 | 162 | def cal_loss(self): 163 | if self._config.mag_factor > 0.0: 164 | cost = tf.reduce_sum(tf.reduce_sum(tf.abs(tf.pow(self._sep - self._labels, self._config.power_num)), 1), 1) 165 | #cost = tf.reduce_mean(tf.reduce_sum(tf.abs(tf.pow(self._sep - self._labels, self._config.power_num)), 1), 1) 166 | cost = tf.multiply(self._config.mag_factor, cost) 167 | else: 168 | cost = 0.0 169 | 170 | if self._config.del_factor > 0.0: 171 | sep_delta = comp_dynamic_feature(self._sep, self._config.dynamic_win, self._config.batch_size, self._lengths) 172 | labels_delta = comp_dynamic_feature(self._labels, self._config.dynamic_win, self._config.batch_size, self._lengths) 173 | cost_del = tf.reduce_sum(tf.reduce_sum(tf.abs(tf.pow(sep_delta - labels_delta, self._config.power_num)), 1), 1) 174 | #cost_del = tf.reduce_mean(tf.reduce_sum(tf.abs(tf.pow(sep_delta - labels_delta, self._config.power_num)), 1), 1) 175 | cost += tf.multiply(self._config.del_factor, cost_del) 176 | 177 | if self._config.acc_factor > 0.0: 178 | sep_acc = comp_dynamic_feature(sep_delta, self._config.dynamic_win, self._config.batch_size, self._lengths) 179 | labels_acc = comp_dynamic_feature(labels_delta, self._config.dynamic_win, self._config.batch_size, self._lengths) 180 | cost_acc = tf.reduce_sum(tf.reduce_sum(tf.abs(tf.pow(sep_acc - labels_acc, self._config.power_num)), 1), 1) 181 | #cost_acc = tf.reduce_mean(tf.reduce_sum(tf.abs(tf.pow(sep_acc - labels_acc, self._config.power_num)), 1), 1) 182 | cost += tf.multiply(self._config.acc_factor, cost_acc) 183 | 184 | self._loss = tf.reduce_mean(tf.div(cost, tf.to_float(self._lengths))) 185 | 186 | def _weight_and_bias(self, input_size, output_size): 187 | weights = tf.get_variable('weights', [input_size, output_size], initializer=tf.random_normal_initializer(stddev=0.01)) 188 | biases = tf.get_variable('biases', [output_size], initializer=tf.constant_initializer(0.0)) 189 | return weights, biases 190 | 191 | def _unpack_cell(self, cell): 192 | if isinstance(cell,tf.contrib.rnn.MultiRNNCell): 193 | return cell._cells 194 | else: 195 | return [cell] 196 | -------------------------------------------------------------------------------- /model/model.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/model/model.pyc -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | # Copyright 2017 4 | # Author: Chenglin Xu (NTU, Singapore) 5 | # Email: xuchenglin28@gmail.com 6 | # Updated by Chenglin, Dec 2018, Jul 2019 7 | #Please cite: 8 | # Chenglin Xu, Wei Rao, Xiong Xiao, Eng Siong Chng and Haizhou Li, "SINGLE CHANNEL SPEECH SEPARATION WITH CONSTRAINED UTTERANCE LEVEL PERMUTATION INVARIANT TRAINING USING GRID LSTM", in Proc. of ICASSP 2018, pp 6-10. 9 | # Chenglin Xu, Wei Rao, Eng Siong Chng, and Haizhou Li, "Optimization of Speaker Extraction Neural Network with Magnitude and Temporal Spectrum Approximation Loss", in ICASSP 2019. 10 | # Wei Rao, Chenglin Xu, Eng Siong Chng, and Haizhou Li, "Target Speaker Extraction for Overlapped Multi-Talker Speaker Verification", in Interspeech 2019. 11 | 12 | step=1 13 | gpu_id=$1 #'0', '1' 14 | 15 | # Paths for reading wav and saving features 16 | noisy_dir=data/wsj0_2mix_extr/wav8k/max 17 | rec_dir=data/rec #save extraced speech 18 | tfrecords_dir=data/tfrecords/mag_mix 19 | 20 | # Configure for feature extraction 21 | FFT_LEN=256 22 | FRAME_SHIFT=128 23 | with_labels=1 # set to 0 when run-time inference, no available labels 24 | apply_psm=1 25 | dur=4 # whether cut the utterances of training and development sets into segments. 0 should be set during run-time (NO CUT) 26 | 27 | # Configure for network 28 | rnn_num_layers=1 29 | input_size=129 30 | output_size=129 31 | rnn_size=512 32 | model_type=BLSTM 33 | mask_type=relu 34 | 35 | aux_hidden_size=256 36 | aux_output_size=30 37 | 38 | # Configure for objective function 39 | mag_factor=1.0 40 | del_factor=4.5 41 | acc_factor=10.0 42 | dynamic_win=2 43 | power_num=2 # mean square error (=2) or mean absolute error (=1) 44 | 45 | # Configure for training 46 | TF_CPP_MIN_LOG_LEVEL=1 47 | tr_batch_size=2 # [change to situable size according to your GPU memory] 48 | tt_batch_size=1 49 | keep_prob=0.5 50 | learning_rate=0.0005 51 | lr_reduction_factor=0.7 52 | min_epochs=50 53 | max_epochs=200 54 | num_threads=10 55 | 56 | # Path to save model and reconstructed wav 57 | name=Mag_Mix_Cat_${model_type}_${rnn_num_layers}_${rnn_size}_a${aux_hidden_size}_${aux_output_size}_${mask_type}_del${del_factor}_acc${acc_factor}_win${dynamic_win}_L${power_num} 58 | save_model_dir=exp/$name/ 59 | 60 | lists_dir=./tmp/mag_lists_mix 61 | mkdir -p $lists_dir 62 | 63 | echo "FRAME_SHIFT=$FRAME_SHIFT" > config.py 64 | 65 | ################################################# 66 | # generate data before run this script. 67 | # data simulation script, run_data_generation.sh 68 | ################################################# 69 | 70 | if [ $step -le 1 ]; then 71 | echo "Prepare data" 72 | for x in tr cv tt; do 73 | ls $noisy_dir/$x/mix/*.wav | awk '{a=$1; gsub("/mix/", "/aux/", $1); b=$1; gsub("/aux/", "/s1/", $1); printf("%s %s %s\n", a, b, $1)}' > ${lists_dir}/${x}_mix.lst & 74 | done 75 | wait 76 | 77 | for x in tr cv; do 78 | python extract_feats.py --data_type=$x --inputs_cmvn=$tfrecords_dir/${x}_cmvn.npz --with_labels=$with_labels --apply_psm=$apply_psm --list_path=${lists_dir}/${x}_mix.lst --output_dir=$tfrecords_dir --FFT_LEN=$FFT_LEN --FRAME_SHIFT=$FRAME_SHIFT --num_threads=$num_threads --dur=$dur & 79 | done 80 | wait 81 | echo "Prepare data done." 82 | fi 83 | 84 | # Training 85 | if [ $step -le 2 ]; then 86 | echo "Model training starts." 87 | # sort the tfrecord files by size in order to group the utterances with similar length into a minibatch 88 | for x in tr cv; do 89 | ls -Sr $tfrecords_dir/${x}/*.tfrecords > $lists_dir/${x}.lst & 90 | done 91 | wait 92 | shuffle=0 93 | command="python train.py --lists_dir=$lists_dir --save_model_dir=$save_model_dir --with_labels=$with_labels --rnn_num_layers=$rnn_num_layers --rnn_size=$rnn_size \ 94 | --input_size=$input_size --output_size=$output_size --mask_type=$mask_type --aux_hidden_size=$aux_hidden_size --aux_output_size=$aux_output_size \ 95 | --batch_size=$tr_batch_size --lr_reduction_factor=$lr_reduction_factor --learning_rate=$learning_rate --keep_prob=$keep_prob \ 96 | --inputs_cmvn=$tfrecords_dir/tr_cmvn.npz --min_epochs=$min_epochs --max_epochs=$max_epochs --num_threads=$num_threads \ 97 | --del_factor=$del_factor --acc_factor=$acc_factor --dynamic_win=$dynamic_win --mag_factor=$mag_factor --power_num=$power_num --shuffle=$shuffle " 98 | 99 | echo $command 100 | CUDA_VISIBLE_DEVICES=$gpu_id TF_CPP_MIN_LOG_LEVEL=$TF_CPP_MIN_LOG_LEVEL $command 101 | echo "Model training ends." 102 | fi 103 | 104 | ###################################### 105 | # Prepare data and decode for tt 106 | ###################################### 107 | if [ $step -le 3 ]; then 108 | echo "Prepare data" 109 | lists_name=tt 110 | mkdir -p $tfrecords_dir/${lists_name} 111 | python extract_feats_test.py --data_type=${lists_name} --list_path=${lists_dir}/${lists_name}_mix.lst --output_dir=$tfrecords_dir --FFT_LEN=$FFT_LEN --FRAME_SHIFT=$FRAME_SHIFT --num_threads=$num_threads 112 | echo "Prepare data done." 113 | fi 114 | 115 | # Decoding 116 | if [ $step -le 4 ]; then 117 | 118 | echo "Start Decoding." 119 | lists_name=tt 120 | find $tfrecords_dir/$lists_name/ -iname "*.tfrecords" > $lists_dir/${lists_name}.lst 121 | num_threads=1 122 | with_labels=0 123 | inputs_cmvn=$tfrecords_dir/tr_cmvn.npz 124 | mkdir -p $rec_dir 125 | 126 | decode_cmd="python -u decode.py --lists_dir=$lists_dir --data_type=${lists_name} --noisy_dir=$noisy_dir/$lists_name/mix --save_model_dir=$save_model_dir --with_labels=$with_labels \ 127 | --rec_dir=$rec_dir/$lists_name/$name --rnn_num_layers=$rnn_num_layers --rnn_size=$rnn_size --input_size=$input_size --output_size=$output_size --aux_hidden_size=$aux_hidden_size \ 128 | --aux_output_size=$aux_output_size --mask_type=$mask_type --keep_prob=$keep_prob --batch_size=$tt_batch_size --inputs_cmvn=$inputs_cmvn \ 129 | --num_threads=$num_threads --FFT_LEN=$FFT_LEN --FRAME_SHIFT=$FRAME_SHIFT --power_num=$power_num " 130 | 131 | echo $decode_cmd 132 | CUDA_VISIBLE_DEVICES="" TF_CPP_MIN_LOG_LEVEL=$TF_CPP_MIN_LOG_LEVEL $decode_cmd 133 | 134 | echo "Decoding ends" 135 | fi 136 | -------------------------------------------------------------------------------- /run_data_generation.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | # Copyright 2018 Chenglin Xu (NTU, Singapore) 4 | # 5 | # Speech extraction code for data simultation, model training and testing. (model related code will be released later) 6 | # 7 | # Please cite: 8 | # 1. Chenglin Xu, Wei Rao, Eng Siong Chng, and Haizhou Li, "Optimization of Speaker Extraction Neural Network with Magnitude and Temporal Spectrum Approximation Loss", submitted to ICASSP 2019. 9 | # 2. Wei Rao, Chenglin Xu, Eng Siong Chng, and Haizhou Li, "Target Speaker Extraction for Overlapped Multi-Talker Speaker Verification", submitted to ICASSP 2019. 10 | 11 | step=0 12 | 13 | 14 | if [ $step -le 0 ]; then 15 | 16 | #1. Assume that WSJ0's wv1 sphere files is converted to wav files. The folder 17 | # structure and file name are kept same under wsj0/, e.g., 18 | # 'ORG_PATH/wsj0/si_tr_s/01t/01to030v.wv1' is converted to wav and 19 | # stored in 'YOUR_PATH/wsj0/si_tr_s/01t/01to030v.wv1'. 20 | # Relevant data ('si_tr_s', 'si_dt_05' and 'si_et_05') are under YOUR_PATH/wsj0/ 21 | #2. Put 'voicebox' toolbox in current folder. (http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html) 22 | #3. Set your 'YOUR_PATH' and 'OUTPUT_PATH' properly, then run this script in Matlab. 23 | # (The max lenght of the wav will be kept when generate the mixture. The sampling rate will be 8kHz.) 24 | 25 | echo "Start to simulate data." 26 | 27 | cd ./simulation 28 | wsj0root='./data/wsj/' #YOUR_PATH 29 | output_dir='./data/wsj0_2mix_extr/wav8k' #OUTPUT_PATH to save simulated data 30 | fs8k=8000 31 | min_max='max' 32 | 33 | for data_type in tr cv tt; do 34 | matlab -nodesktop -nosplash -r "addpath('./voicebox'); simulate_2spk_mix('$data_type', '$wsj0root', '$output_dir', $fs8k, '$min_max'); exit;" & 35 | done 36 | wait 37 | 38 | cd ../ 39 | fi 40 | -------------------------------------------------------------------------------- /simulation/simulate_2spk_mix.m: -------------------------------------------------------------------------------- 1 | function simulate_2spk_mix(data_type, wsj0root, output_dir, fs8k, min_max) 2 | % Simulate 2-speaker mixture data for speaker extraction. 3 | % Call: 4 | % simulate_2spk_mix(data_type, wsj0root, output_dir, fs8k, min_max) 5 | % e.g., simulate_2spk_mix('tt', '/media/clx214/data/wsj/', '/media/clx214/data/wsj0_2mix_extr_tmp/wav8k', 8000, 'max') 6 | % Paras: 7 | % data_type: data set to generate, (tr|cv|tt), e.g., 'tt' 8 | % wsj0root: YOUR_PATH/, the folder containing converted wsj0/, e.g., '/media/clx214/data/wsj/' 9 | % output_dir: the folder to save simulated data for extraction, e.g., '/media/clx214/data/wsj0_2mix_extr_tmp/wav8k' 10 | % fs8k: sampling rate of the simulated data, e.g., 8000 11 | % min_max: get the mininium or maximum wav length, when simulating mixture data, e.g, 'max' 12 | % 13 | % The code is based on "create_wav_2speakers_extr.m" from "http://www.merl.com/demos/deep-clustering" 14 | % 15 | % 1. Assume that WSJ0's wv1 sphere files is converted to wav files. The folder 16 | % structure and file name are kept same under wsj0/, e.g., 17 | % ORG_PATH/wsj0/si_tr_s/01t/01to030v.wv1 is converted to wav and 18 | % stored in YOUR_PATH/wsj0/si_tr_s/01t/01to030v.wv1. 19 | % Relevant data ('si_tr_s', 'si_dt_05' and 'si_et_05') are under YOUR_PATH/wsj0/ 20 | % 2. Put 'voicebox' toolbox in current folder. (http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html) 21 | % 3. Set your 'YOUR_PATH' and 'OUTPUT_PATH' properly, then run this script in Matlab. 22 | % (The max lenght of the wav will be kept when generate the mixture. The sampling rate will be 8kHz.) 23 | % 24 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 25 | % Copyright (C) 2016 Mitsubishi Electric Research Labs 26 | % (Jonathan Le Roux, John R. Hershey, Zhuo Chen) 27 | % Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) 28 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 29 | % 30 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 31 | %Copyright 2018 Chenglin Xu, Nanyang Technological University, Singapore 32 | % 33 | %Licensed under the Apache License, Version 2.0 (the "License"); 34 | %you may not use this file except in compliance with the License. 35 | %You may obtain a copy of the License at 36 | % 37 | % http://www.apache.org/licenses/LICENSE-2.0 38 | % 39 | %Unless required by applicable law or agreed to in writing, software 40 | %distributed under the License is distributed on an "AS IS" BASIS, 41 | %WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 42 | %See the License for the specific language governing permissions and 43 | %limitations under the License. 44 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 45 | 46 | if ~exist([output_dir '/' min_max '/' data_type],'dir') 47 | mkdir([output_dir '/' min_max '/' data_type]); 48 | end 49 | mkdir([output_dir '/' min_max '/' data_type '/s1/']); 50 | mkdir([output_dir '/' min_max '/' data_type '/aux/']); 51 | mkdir([output_dir '/' min_max '/' data_type '/mix/']); 52 | 53 | TaskFile = ['mix_2_spk_' data_type '_extr.txt']; 54 | fid = fopen(TaskFile,'r'); 55 | C = textscan(fid,'%s %f %s %f %s'); 56 | num_files = length(C{1}); 57 | 58 | fprintf(1,'Start to generate data for %s\n', [min_max '_' data_type]); 59 | for i = 1:num_files 60 | [inwav1_dir,invwav1_name,inwav1_ext] = fileparts(C{1}{i}); 61 | [inwav2_dir,invwav2_name,inwav2_ext] = fileparts(C{3}{i}); 62 | [inwav_aux_dir,invwav_aux_name,inwav_aux_ext] = fileparts(C{5}{i}); 63 | 64 | inwav1_snr = C{2}(i); 65 | inwav2_snr = C{4}(i); 66 | mix_name = [invwav1_name,'_',num2str(inwav1_snr),'_',invwav2_name,'_',num2str(inwav2_snr),'_',invwav_aux_name]; 67 | 68 | % get input wavs 69 | [s1, fs] = audioread([wsj0root C{1}{i}]); 70 | s2 = audioread([wsj0root C{3}{i}]); 71 | s_aux = audioread([wsj0root C{5}{i}]); 72 | 73 | % resample, normalize to 8 kHz file 74 | s1_8k = resample(s1,fs8k,fs); 75 | [s1_8k,lev1] = activlev(s1_8k,fs8k,'n'); % y_norm = y /sqrt(lev); 76 | s2_8k = resample(s2,fs8k,fs); 77 | [s2_8k,lev2] = activlev(s2_8k,fs8k,'n'); 78 | s_aux_8k = resample(s_aux,fs8k,fs); 79 | [s_aux_8k,lev_aux] = activlev(s_aux_8k,fs8k,'n'); 80 | 81 | weight_1 = 10^(inwav1_snr/20); 82 | weight_2 = 10^(inwav2_snr/20); 83 | 84 | s1_8k = weight_1 * s1_8k; 85 | s2_8k = weight_2 * s2_8k; 86 | 87 | switch min_max 88 | case 'max' 89 | mix_8k_length = max(length(s1_8k),length(s2_8k)); 90 | s1_8k = cat(1,s1_8k,zeros(mix_8k_length - length(s1_8k),1)); 91 | s2_8k = cat(1,s2_8k,zeros(mix_8k_length - length(s2_8k),1)); 92 | case 'min' 93 | mix_8k_length = min(length(s1_8k),length(s2_8k)); 94 | s1_8k = s1_8k(1:mix_8k_length); 95 | s2_8k = s2_8k(1:mix_8k_length); 96 | end 97 | mix_8k = s1_8k + s2_8k; 98 | 99 | max_amp_8k = max(cat(1,abs(mix_8k(:)),abs(s1_8k(:)),abs(s2_8k(:)),abs(s_aux_8k(:)))); 100 | mix_scaling_8k = 1/max_amp_8k*0.9; 101 | s1_8k = mix_scaling_8k * s1_8k; 102 | mix_8k = mix_scaling_8k * mix_8k; 103 | s_aux_8k = mix_scaling_8k * s_aux_8k; 104 | 105 | audiowrite([output_dir '/' min_max '/' data_type '/s1/' mix_name '.wav'],s1_8k,fs8k); 106 | audiowrite([output_dir '/' min_max '/' data_type '/aux/' mix_name '.wav'],s_aux_8k,fs8k); 107 | audiowrite([output_dir '/' min_max '/' data_type '/mix/' mix_name '.wav'],mix_8k,fs8k); 108 | end 109 | fclose(fid); 110 | fprintf(1,'End of generating data for %s\n', [min_max '_' data_type]); 111 | end 112 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2017 Xu Chenglin(NTU, Singapore) 5 | # Updated by Chenglin, Dec 2018, Jul 2019 6 | 7 | from __future__ import absolute_import 8 | from __future__ import division 9 | from __future__ import print_function 10 | 11 | import argparse 12 | import os 13 | import sys 14 | import time 15 | from datetime import datetime 16 | import pprint 17 | 18 | import numpy as np 19 | import tensorflow as tf 20 | import tensorflow.contrib.slim as slim 21 | from model.model import Model 22 | from utils.paddedFIFO_batch import paddedFIFO_batch 23 | from utils.read_list import read_list 24 | 25 | FLAGS = None 26 | 27 | def show_all_variables(): 28 | model_vars = tf.trainable_variables() 29 | slim.model_analyzer.analyze_vars(model_vars, print_info=True) 30 | sys.stdout.flush() 31 | 32 | def run_one_epoch(sess, coord, model, num_batches, is_eval): 33 | #Train/Eval one epoch of the model on the given data. 34 | loss = 0.0 35 | for batch in xrange(num_batches): 36 | if coord.should_stop(): 37 | break 38 | if is_eval: 39 | loss_batch = sess.run(model._loss) 40 | else: 41 | _, loss_batch = sess.run([model._train_op, model._loss]) 42 | loss += loss_batch 43 | 44 | if (batch+1) % 100 == 0: 45 | if is_eval: 46 | tf.logging.info("BATCH %d: EVAL AVG.LOSS %.4f at %s" % (batch+1, loss/(batch+1), datetime.now())) 47 | else: 48 | lr = sess.run(model._lr) 49 | tf.logging.info("BATCH %d: TRAIN AVG.LOSS %.4f with a learning rate %e at %s" % (batch+1, loss/(batch+1), lr, datetime.now())) 50 | loss /= num_batches 51 | 52 | return loss 53 | 54 | def train(): 55 | tr_tfrecords_list, tr_num_batches = read_list(FLAGS.lists_dir, "tr", FLAGS.batch_size) 56 | val_tfrecords_list, val_num_batches = read_list(FLAGS.lists_dir, "cv", FLAGS.batch_size) 57 | 58 | with tf.Graph().as_default(): 59 | with tf.device('/cpu:0'): 60 | with tf.name_scope('input'): 61 | cmvn = np.load(FLAGS.inputs_cmvn) 62 | cmvn_aux = np.load(FLAGS.inputs_cmvn.replace('cmvn', 'cmvn_aux')) 63 | tr_inputs, tr_inputs_cmvn, tr_inputs_cmvn_aux, tr_labels, tr_lengths, tr_lengths_aux = paddedFIFO_batch(tr_tfrecords_list, FLAGS.batch_size, 64 | FLAGS.input_size, FLAGS.output_size, cmvn=cmvn, cmvn_aux=cmvn_aux, with_labels=FLAGS.with_labels, 65 | num_enqueuing_threads=FLAGS.num_threads, num_epochs=FLAGS.max_epochs, shuffle=FLAGS.shuffle) 66 | val_inputs, val_inputs_cmvn, val_inputs_cmvn_aux, val_labels, val_lengths, val_lengths_aux = paddedFIFO_batch(val_tfrecords_list, FLAGS.batch_size, 67 | FLAGS.input_size, FLAGS.output_size, cmvn=cmvn, cmvn_aux=cmvn_aux, with_labels=FLAGS.with_labels, 68 | num_enqueuing_threads=FLAGS.num_threads, num_epochs=FLAGS.max_epochs+1, shuffle=False) 69 | 70 | with tf.name_scope('model'): 71 | tr_model = Model(FLAGS, tr_inputs, tr_inputs_cmvn, tr_inputs_cmvn_aux, tr_labels, tr_lengths, tr_lengths_aux, infer=False) 72 | tf.get_variable_scope().reuse_variables() 73 | val_model = Model(FLAGS, val_inputs, val_inputs_cmvn, val_inputs_cmvn_aux, val_labels, val_lengths, val_lengths_aux, infer=False) 74 | 75 | show_all_variables() 76 | init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) 77 | config = tf.ConfigProto() 78 | config.gpu_options.allow_growth = True 79 | config.allow_soft_placement = True 80 | sess = tf.Session(config=config) 81 | sess.run(init) 82 | 83 | checkpoint = tf.train.get_checkpoint_state(FLAGS.save_model_dir) 84 | if checkpoint and checkpoint.model_checkpoint_path: 85 | tf.logging.info("Restore last saved model from " + checkpoint.model_checkpoint_path) 86 | tr_model.saver.restore(sess, checkpoint.model_checkpoint_path) 87 | best_model_path = checkpoint.model_checkpoint_path 88 | 89 | iter_idx = best_model_path.find('iter') 90 | mark_idx = best_model_path.find('_', iter_idx) 91 | start_iter = int(float(best_model_path[iter_idx+4:mark_idx])) 92 | 93 | lr_idx = best_model_path.find('lr') 94 | lr_mark_idx = best_model_path.find('_', lr_idx) 95 | FLAGS.learning_rate = float(best_model_path[lr_idx+2:lr_mark_idx]) 96 | 97 | cv_idx = best_model_path.find('cv') 98 | cv_restore = float(best_model_path[cv_idx+2:]) 99 | resume_training = 1 100 | else: 101 | start_iter = 0 102 | resume_training = 0 103 | 104 | coord = tf.train.Coordinator() 105 | threads = tf.train.start_queue_runners(sess=sess, coord=coord) 106 | try: 107 | # Eval the init model to obtain the init loss on the development set before training. 108 | if resume_training: 109 | prev_val_loss = cv_restore 110 | else: 111 | prev_val_loss = run_one_epoch(sess, coord, val_model, val_num_batches, is_eval=True) 112 | tf.logging.info("INIT EVAL AVG.LOSS %.4f at %s" % (prev_val_loss, datetime.now())) 113 | 114 | sess.run(tf.assign(tr_model._lr, FLAGS.learning_rate)) 115 | for epoch in xrange(start_iter, FLAGS.max_epochs): 116 | start_time = time.time() 117 | 118 | # Training for one epoch 119 | tr_loss = run_one_epoch(sess, coord, tr_model, tr_num_batches, is_eval=False) 120 | 121 | # Evaluating on the development set using the updated model 122 | val_loss = run_one_epoch(sess, coord, val_model, val_num_batches, is_eval=True) 123 | end_time = time.time() 124 | 125 | model_name = "nnet_iter%d_lr%e_tr%.4f_cv%.4f" % (epoch+1, FLAGS.learning_rate, tr_loss, val_loss) 126 | model_path = os.path.join(FLAGS.save_model_dir, model_name) 127 | rel_impr = (prev_val_loss - val_loss) / prev_val_loss 128 | if val_loss < prev_val_loss: 129 | tr_model.saver.save(sess, model_path) 130 | prev_val_loss = val_loss 131 | best_model_path = model_path 132 | tf.logging.info("ITER %d: TRAIN AVG.LOSS %.4f, CROSSVAL AVG.LOSS %.4f, LR %e, %s, %s USED TIME: %.2fs" % ( 133 | epoch+1, tr_loss, val_loss, FLAGS.learning_rate, "ACCEPTED", model_name, end_time-start_time)) 134 | else: 135 | tf.logging.info("ITER %d: TRAIN AVG.LOSS %.4f, CROSSVAL AVG.LOSS %.4f, LR %e, %s, %s USED TIME: %.2fs" % ( 136 | epoch+1, tr_loss, val_loss, FLAGS.learning_rate, "REJECTED", model_name, end_time-start_time)) 137 | tr_model.saver.restore(sess, best_model_path) 138 | 139 | # Reduce the learning rate when the relative improvement is lower than the threshold 140 | if rel_impr < FLAGS.reduce_lr_threshold: 141 | FLAGS.learning_rate *= FLAGS.lr_reduction_factor 142 | sess.run(tf.assign(tr_model._lr, FLAGS.learning_rate)) 143 | 144 | # Stop the training when the relative improvement is lower than the threshold 145 | if rel_impr < FLAGS.stop_threshold: 146 | if epoch+1 < FLAGS.min_epochs: 147 | tf.logging.info("Continue to train the model with a minimum epoch of %d" % FLAGS.min_epochs) 148 | continue 149 | else: 150 | tf.logging.info("The relative improvement is lower than the stopping threshold, stop training at a relative improvement of %f" % rel_impr) 151 | break 152 | except Exception, e: 153 | coord.request_stop(e) 154 | finally: 155 | coord.request_stop() 156 | coord.join(threads) 157 | sess.close() 158 | 159 | def main(_): 160 | if not os.path.exists(FLAGS.save_model_dir): 161 | os.makedirs(FLAGS.save_model_dir) 162 | train() 163 | 164 | if __name__ == "__main__": 165 | tf.logging.set_verbosity(tf.logging.INFO) 166 | parser = argparse.ArgumentParser() 167 | parser.add_argument( 168 | '--lists_dir', 169 | type=str, 170 | default='tmp/', 171 | help="List to show where the data is." 172 | ) 173 | parser.add_argument( 174 | '--with_labels', 175 | type=int, 176 | default=1, 177 | help='Whether the clean labels are included in the tfrecords.' 178 | ) 179 | parser.add_argument( 180 | '--inputs_cmvn', 181 | type=str, 182 | default='tfrecords/tr_cmvn.npz', 183 | help="The global cmvn to normalize the inputs." 184 | ) 185 | parser.add_argument( 186 | '--input_size', 187 | type=int, 188 | default=129, 189 | help="Input feature dimension (default 129 for 8kHz sampling rate)." 190 | ) 191 | parser.add_argument( 192 | '--output_size', 193 | type=int, 194 | default=129, 195 | help="Output dimension (mask dimension, default 129 for 8kHz sampling rate)." 196 | ) 197 | parser.add_argument( 198 | '--aux_hidden_size', 199 | type=int, 200 | default=512, 201 | help="The dimension of hidden layer in auxillary network." 202 | ) 203 | parser.add_argument( 204 | '--aux_output_size', 205 | type=int, 206 | default=30, 207 | help="The dimension of output layer in auxillary network, equals to the number of sub-layers in the adapt layer." 208 | ) 209 | parser.add_argument( 210 | '--rnn_size', 211 | type=int, 212 | default=896, 213 | help="Number of units in a rnn layer." 214 | ) 215 | parser.add_argument( 216 | '--rnn_num_layers', 217 | type=int, 218 | default=3, 219 | help="Number of rnn layers." 220 | ) 221 | parser.add_argument( 222 | '--mask_type', 223 | type=str, 224 | default='relu', 225 | help="Mask avtivation funciton, now only support sigmoid or relu" 226 | ) 227 | parser.add_argument( 228 | '--batch_size', 229 | type=int, 230 | default=16, 231 | help="Minibatch size." 232 | ) 233 | parser.add_argument( 234 | '--learning_rate', 235 | type=float, 236 | default=0.0005, 237 | help="Initial learning rate." 238 | ) 239 | parser.add_argument( 240 | '--min_epochs', 241 | type=int, 242 | default=30, 243 | help="Minimum epochs when training the model." 244 | ) 245 | parser.add_argument( 246 | '--max_epochs', 247 | type=int, 248 | default=100, 249 | help="Maximum epochs when training the model." 250 | ) 251 | parser.add_argument( 252 | '--lr_reduction_factor', 253 | type=float, 254 | default=0.5, 255 | help="Factor for reducing the learning rate." 256 | ) 257 | parser.add_argument( 258 | '--reduce_lr_threshold', 259 | type=float, 260 | default=0.0, 261 | help="Threshold to decide when to reduce the learning rate." 262 | ) 263 | parser.add_argument( 264 | '--stop_threshold', 265 | type=float, 266 | default=0.0001, 267 | help="Threshold to decide when to stop training." 268 | ) 269 | parser.add_argument( 270 | '--num_threads', 271 | type=int, 272 | default=12, 273 | help='Number of threads for paralleling.' 274 | ) 275 | parser.add_argument( 276 | '--save_model_dir', 277 | type=str, 278 | default='exp/model_name', 279 | help="Directory to save the training model in every epoch." 280 | ) 281 | parser.add_argument( 282 | '--keep_prob', 283 | type=float, 284 | default=0.7, 285 | help="Keep probability for training with a dropout (default: 1-dropout_rate)." 286 | ) 287 | parser.add_argument( 288 | '--max_grad_norm', 289 | type=float, 290 | default=5.0, 291 | help="The max gradient normalization." 292 | ) 293 | parser.add_argument( 294 | '--del_factor', 295 | type=float, 296 | default=0.0, 297 | help="weight for delta objective function, if larger than 0, delta objective function is applied." 298 | ) 299 | parser.add_argument( 300 | '--acc_factor', 301 | type=float, 302 | default=0.0, 303 | help="weight for acceleration objective function, if larger than 0, delta objective function is applied." 304 | ) 305 | parser.add_argument( 306 | '--dynamic_win', 307 | type=int, 308 | default=2, 309 | help="window size of the order in calculation of dynamic objective functions, default is 2." 310 | ) 311 | parser.add_argument( 312 | '--mag_factor', 313 | type=float, 314 | default=0.0, 315 | help="weight for static (i.e., magnitude) objective function, if larger than 0, static objective function is applied." 316 | ) 317 | parser.add_argument( 318 | '--shuffle', 319 | type=int, 320 | default=0, 321 | help="Whether shuffle data." 322 | ) 323 | parser.add_argument( 324 | '--power_num', 325 | type=int, 326 | default=2, 327 | help="The power to calculate the loss, if set to 2, it's squared L2, if set to 1, it's L1." 328 | ) 329 | FLAGS, unparsed = parser.parse_known_args() 330 | pp = pprint.PrettyPrinter() 331 | pp.pprint(FLAGS.__dict__) 332 | sys.stdout.flush() 333 | tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) 334 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/utils/__init__.py -------------------------------------------------------------------------------- /utils/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/utils/__init__.pyc -------------------------------------------------------------------------------- /utils/audioread.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2017 Chenglin Xu 5 | # Updated by Chenglin, Dec 2018, Jul 2019 6 | 7 | """ 8 | audioread function, same as matlab 9 | """ 10 | 11 | import scipy.io.wavfile as wav 12 | 13 | def audioread(filename): 14 | (rate,sig) = wav.read(filename) 15 | if sig.dtype == 'int16': 16 | nb_bits = 16 17 | elif sig.dtype == 'int32': 18 | nb_bits = 32 19 | sig = sig / float(2 ** (nb_bits - 1)) 20 | 21 | return rate, sig, nb_bits 22 | -------------------------------------------------------------------------------- /utils/audioread.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/utils/audioread.pyc -------------------------------------------------------------------------------- /utils/comp_dynamic_feature.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2017 Chenglin Xu (NTU,Singapore) 5 | 6 | 7 | """Utility functions for computing dynamic features.""" 8 | 9 | import tensorflow as tf 10 | #import numpy as np 11 | 12 | def comp_dynamic_feature(inputs, DELTAWINDOW, Batch_size, lengths): 13 | #sess = tf.Session() 14 | #N_bat = tf.shape(inputs) 15 | #print sess.run(N_bat[0]) 16 | #print sess.run(tf.size(inputs)) 17 | #inputs = tf.contrib.util.constant_value(inputs) 18 | #print(inputs) 19 | #outputs = tf.zeros(N_bat, dtype=tf.float32) 20 | #for i in range(N_bat[0]): 21 | # tmp = comp_delta(inputs[i,:,:], DELTAWINDOW) 22 | # outputs[i,:,:] = tmp; 23 | #return tf.convert_to_tensor(outputs) 24 | #N_bat, N_vec, N_cep = np.shape(tf.contrib.util.constant_value(inputs)) 25 | #print Batch_size 26 | #outputs = tf.Variable(inputs, trainable=False) 27 | outputs = [] 28 | for i in range(Batch_size): 29 | tmp = comp_delta(inputs[i,:lengths[i],:], DELTAWINDOW, lengths[i]) 30 | #with tf.Session() as sess: 31 | # print(sess.run(tmp)) 32 | #outputs[i,:,:] = tmp; 33 | #tf.assign(outputs[i,:,:],tf.convert_to_tensor(tmp)); 34 | tmp1 = tf.pad(tmp, [[0,tf.reduce_max(lengths)-lengths[i]],[0,0]], "CONSTANT") 35 | outputs.append(tmp1) 36 | #print(outputs) 37 | return tf.convert_to_tensor(outputs) 38 | 39 | 40 | #def comp_delta(static_coef, DELTAWINDOW): 41 | # N_vec, N_cep = np.shape(static_coef) 42 | # static_coef = np.repeat(static_coef, np.r_[DELTAWINDOW+1,[1]*(N_vec-2),DELTAWINDOW+1], 0) 43 | # 44 | # delta_coef = 0.0 45 | # i = DELTAWINDOW+1 46 | # denom = np.sum(np.power(range(1,DELTAWINDOW+1),2))*2.0 47 | # for j in range(1,DELTAWINDOW+1): 48 | # delta_coef += j/denom*(static_coef[i+j-1:i+j+N_vec-1,:]-static_coef[i-j-1:i-j+N_vec-1,:]) 49 | # return delta_coef 50 | 51 | def comp_delta(feat, N, length): 52 | """Compute delta features from a feature vector sequence. 53 | Args: 54 | feat: A numpy array of size (NUMFRAMES by number of features) containing features. Each row holds 1 feature vector. 55 | N: For each frame, calculate delta features based on preceding and following N frames. 56 | Returns: 57 | A numpy array of size (NUMFRAMES by number of features) containing delta features. Each row holds 1 delta feature vector. 58 | """ 59 | #NUMFRAMES= tf.shape(feat) 60 | #with tf.Session() as sess: 61 | # sess.run(NUMFRAMES) 62 | #print(tf.size(feat)) 63 | #print feat 64 | #feat = np.concatenate(([feat[0] for i in range(N)], feat, [feat[-1] for i in range(N)])) 65 | feat = tf.concat([[feat[0] for i in range(N)], feat, [feat[-1] for i in range(N)]], 0) 66 | #with tf.Session() as sess: 67 | # sess.run(tf.initialize_all_variables()) 68 | # print(sess.run(tf.shape(feat))) 69 | # print(sess.run(length)) 70 | denom = sum([2*i*i for i in range(1,N+1)]) 71 | #dfeat = [] 72 | #for j in tf.range(length): 73 | # #dfeat.append(np.sum([n*feat[N+j+n] for n in range(-1*N,N+1)], axis=0)/denom) 74 | # dfeat.append(tf.reduce_sum([n*feat[N+j+n] for n in range(-1*N,N+1)], axis=0)/denom) 75 | dfeat = tf.reduce_sum([j*(feat[N+1+j-1:N+1+j+length-1,:]-feat[N+1-j-1:N+1-j+length-1,:]) for j in range(1,N+1)], axis=0)/denom 76 | return tf.convert_to_tensor(dfeat) 77 | 78 | #def main(): 79 | # #delta_coef = comp_dynamic_feature(np.array([[[1.0,2],[3,4],[5,6],[7,8]],[[1.0,2],[3,4],[5,6],[7,8]]]), 2, 2) 80 | # #print delta_coef 81 | # sess = tf.Session() 82 | # delta_coef = comp_dynamic_feature(tf.convert_to_tensor([[[1.0,2],[3,4],[5,6],[7,8],[0,0]],[[1.0,2],[3,4],[5,6],[7,8],[9,10]]], dtype=tf.float32), 2, 2, [4,5]) 83 | # print(sess.run(delta_coef)) 84 | # sess.close() 85 | # 86 | #if __name__ == '__main__': 87 | # main() 88 | 89 | #def main(): 90 | # 91 | # #delta_coef = comp_delta([[1.0,2],[3,4],[5,6],[7,8]], 2) 92 | # delta_coef = comp_dynamic_feature(np.array([[[1.0,2],[3,4],[5,6],[7,8]],[[1.0,2],[3,4],[5,6],[7,8]]]), 2) 93 | # print delta_coef 94 | # 95 | #if __name__ == '__main__': 96 | # main() 97 | -------------------------------------------------------------------------------- /utils/comp_dynamic_feature.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/utils/comp_dynamic_feature.pyc -------------------------------------------------------------------------------- /utils/normhamming.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2017 Chenglin Xu 5 | 6 | """ 7 | normalized square root hamming periodic window 8 | """ 9 | 10 | import numpy 11 | from scipy.signal import hamming 12 | from config import * 13 | 14 | #FRAME_SHIFT=64 15 | def normhamming(fft_len): 16 | win = numpy.sqrt(hamming(fft_len, False)) 17 | win = win/numpy.sqrt(numpy.sum(numpy.power(win[0:fft_len:FRAME_SHIFT],2))) 18 | return win 19 | -------------------------------------------------------------------------------- /utils/normhamming.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/utils/normhamming.pyc -------------------------------------------------------------------------------- /utils/paddedFIFO_batch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2017 Xu Chenglin(NTU, Singapore) 5 | # Updated by Chenglin, Dec 2018, Jul 2019 6 | 7 | import tensorflow as tf 8 | 9 | def paddedFIFO_batch(file_list, batch_size, input_size, output_size, cmvn=None, cmvn_aux=None, with_labels=1, num_enqueuing_threads=4, 10 | num_epochs=1, capacity=1000, shuffle=False): 11 | """ 12 | Pad several utterances (batch_size) into a batch with the length equal to the longest by zero. 13 | Args: 14 | file_list: A list of TFRecord files (to speed up, the list is sorted according of the utt length). 15 | batch_size: The number of sequential examples in a batch. 16 | input_size: The dimension of input feature. 17 | output_size: The dimension of target reference. 18 | cmvn: The mean and standard deviation used to normalize the input feature. 19 | num_enqueuing_threads: The number of threads used to enqueue. 20 | num_epochs: The number of epochs to train the model. 21 | shuffle: Whether to shuffle the utts. 22 | Returns: 23 | inputs: The input mixture ([batch_size, time_steps, input_size]). 24 | inputs_norm: The inputs to main network, which are normalized mixture ([batch_size, time_steps, input_size]). 25 | inputs_norm_aux: The normalized inputs to auxiliary network([batch_size, time_steps, input_size]). 26 | labels: The target reference of speaker 1 ([batch_size, time_steps, input_size]). 27 | length: The length of each utt before padding [batch_size]. 28 | length_aux: The length of each auxiliary utt before padding [batch_size]. 29 | """ 30 | 31 | file_queue = tf.train.string_input_producer(file_list, num_epochs=num_epochs, shuffle=shuffle) 32 | reader = tf.TFRecordReader() 33 | _, serialized_example = reader.read(file_queue) 34 | 35 | if with_labels: 36 | sequence_features = { 37 | 'inputs': tf.FixedLenSequenceFeature(shape=[input_size], dtype=tf.float32), 38 | 'inputs_aux': tf.FixedLenSequenceFeature(shape=[input_size], dtype=tf.float32), 39 | 'labels': tf.FixedLenSequenceFeature(shape=[output_size], dtype=tf.float32) 40 | } 41 | else: 42 | sequence_features = { 43 | 'inputs': tf.FixedLenSequenceFeature(shape=[input_size], dtype=tf.float32), 44 | 'inputs_aux': tf.FixedLenSequenceFeature(shape=[input_size], dtype=tf.float32) 45 | } 46 | _, sequence = tf.parse_single_sequence_example(serialized_example, sequence_features=sequence_features) 47 | length = tf.shape(sequence['inputs'])[0] 48 | length_aux = tf.shape(sequence['inputs_aux'])[0] 49 | if cmvn is not None and cmvn_aux is not None: 50 | # global mean and std 51 | inputs_norm = (sequence['inputs'] - cmvn['mean_inputs']) / (cmvn['stddev_inputs'] + 0.000001) 52 | inputs_norm_aux = (sequence['inputs_aux'] - cmvn_aux['mean_inputs']) / (cmvn_aux['stddev_inputs'] + 0.000001) 53 | else: 54 | mean, var = tf.nn.moments(sequence['inputs'], axes=[0]) 55 | inputs_norm = (sequence['inputs'] - mean) / (tf.sqrt(var) + 0.000001) 56 | 57 | mean_aux, var_aux = tf.nn.moments(sequence['inputs_aux'], axes=[0]) 58 | inputs_norm_aux = (sequence['inputs_aux'] - mean_aux) / (tf.sqrt(var_aux) + 0.000001) 59 | 60 | if with_labels: 61 | # tf.io.PaddingFIFOQueue in r1.12 62 | queue = tf.PaddingFIFOQueue(capacity=capacity, dtypes=[tf.float32, tf.float32, tf.float32, tf.float32, tf.int32, tf.int32], 63 | shapes=[(None, input_size), (None, input_size), (None, input_size), (None, output_size), (), ()]) 64 | enqueue_ops = [queue.enqueue([sequence['inputs'], inputs_norm, inputs_norm_aux, sequence['labels'], length, length_aux])] * num_enqueuing_threads 65 | else: 66 | # tf.io.PaddingFIFOQueue in r1.12 67 | queue = tf.PaddingFIFOQueue(capacity=capacity, dtypes=[tf.float32, tf.float32, tf.float32, tf.int32, tf.int32], 68 | shapes=[(None, input_size), (None, input_size), (None, input_size), (), ()]) 69 | enqueue_ops = [queue.enqueue([sequence['inputs'], inputs_norm, inputs_norm_aux, length, length_aux])] * num_enqueuing_threads 70 | 71 | tf.train.add_queue_runner(tf.train.QueueRunner(queue, enqueue_ops)) 72 | return queue.dequeue_many(batch_size) 73 | -------------------------------------------------------------------------------- /utils/paddedFIFO_batch.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/utils/paddedFIFO_batch.pyc -------------------------------------------------------------------------------- /utils/read_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2017 Chenglin Xu (NTU, Singapore) 5 | 6 | """ 7 | Build the BLSTM and Grid LSTM model for cuPIT monaural speech separation. 8 | Please cite: 9 | Chenglin Xu, Wei Rao, Xiong Xiao, Eng Siong Chng and Haizhou Li, 10 | "SINGLE CHANNEL SPEECH SEPARATION WITH CONSTRAINED UTTERANCE LEVEL PERMUTATION INVARIANT TRAINING USING GRID LSTM", 11 | in ICASSP 2018. 12 | """ 13 | 14 | import os, sys 15 | import numpy as np 16 | import tensorflow as tf 17 | 18 | def read_list(lists_dir, name, batch_size): 19 | file_name = os.path.join(lists_dir, name + ".lst") 20 | if not os.path.exists(file_name): 21 | tf.logging.fatal("The file list %s doesn't exist", file_name) 22 | sys.exit(-1) 23 | lines = open(file_name, 'r').readlines() 24 | tfrecords_list = [] 25 | for line in lines: 26 | utt_id = line.strip().split()[0] 27 | if not os.path.exists(utt_id): 28 | tf.logging.fatal("TFRecords file %s doesn't exist", utt_id) 29 | sys.exit(-1) 30 | tfrecords_list.append(utt_id) 31 | num_batches = int(np.ceil(len(tfrecords_list) / batch_size)) 32 | 33 | return tfrecords_list, num_batches 34 | 35 | -------------------------------------------------------------------------------- /utils/read_list.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/utils/read_list.pyc -------------------------------------------------------------------------------- /utils/sigproc.py: -------------------------------------------------------------------------------- 1 | # This file includes routines for basic signal processing including framing and computing power spectra. 2 | # Author: James Lyons 2012 3 | # 4 | # Revised By: Chenglin Xu (NTU, Singapore 2017) 5 | 6 | import decimal 7 | 8 | import numpy 9 | import math 10 | import logging 11 | 12 | 13 | def round_half_up(number): 14 | return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP)) 15 | 16 | 17 | def rolling_window(a, window, step=1): 18 | # http://ellisvalentiner.com/post/2017-03-21-np-strides-trick 19 | shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) 20 | strides = a.strides + (a.strides[-1],) 21 | return numpy.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)[::step] 22 | 23 | 24 | def framesig(sig, frame_len, frame_step, winfunc=lambda x: numpy.ones((x,)), stride_trick=True): 25 | """Frame a signal into overlapping frames. 26 | 27 | :param sig: the audio signal to frame. 28 | :param frame_len: length of each frame measured in samples. 29 | :param frame_step: number of samples after the start of the previous frame that the next frame should begin. 30 | :param winfunc: the analysis window to apply to each frame. By default no window is applied. 31 | :param stride_trick: use stride trick to compute the rolling window and window multiplication faster 32 | :returns: an array of frames. Size is NUMFRAMES by frame_len. 33 | """ 34 | slen = len(sig) 35 | frame_len = int(round_half_up(frame_len)) 36 | frame_step = int(round_half_up(frame_step)) 37 | if slen <= frame_len: 38 | numframes = 1 39 | else: 40 | numframes = 1 + int(math.ceil((1.0 * slen - frame_len) / frame_step)) 41 | 42 | padlen = int((numframes - 1) * frame_step + frame_len) 43 | 44 | zeros = numpy.zeros((padlen - slen,)) 45 | padsignal = numpy.concatenate((sig, zeros)) 46 | if stride_trick: 47 | win = winfunc(frame_len) 48 | frames = rolling_window(padsignal, window=frame_len, step=frame_step) 49 | else: 50 | indices = numpy.tile(numpy.arange(0, frame_len), (numframes, 1)) + numpy.tile( 51 | numpy.arange(0, numframes * frame_step, frame_step), (frame_len, 1)).T 52 | indices = numpy.array(indices, dtype=numpy.int32) 53 | frames = padsignal[indices] 54 | win = numpy.tile(winfunc(frame_len), (numframes, 1)) 55 | 56 | return frames * win 57 | 58 | 59 | def deframesig(frames, siglen, frame_len, frame_step, winfunc=lambda x: numpy.ones((x,))): 60 | """Does overlap-add procedure to undo the action of framesig. 61 | 62 | :param frames: the array of frames. 63 | :param siglen: the length of the desired signal, use 0 if unknown. Output will be truncated to siglen samples. 64 | :param frame_len: length of each frame measured in samples. 65 | :param frame_step: number of samples after the start of the previous frame that the next frame should begin. 66 | :param winfunc: the analysis window to apply to each frame. By default no window is applied. 67 | :returns: a 1-D signal. 68 | """ 69 | frame_len = round_half_up(frame_len) 70 | frame_step = round_half_up(frame_step) 71 | numframes = numpy.shape(frames)[0] 72 | assert numpy.shape(frames)[1] == frame_len, '"frames" matrix is wrong size, 2nd dim is not equal to frame_len' 73 | 74 | indices = numpy.tile(numpy.arange(0, frame_len), (numframes, 1)) + numpy.tile( 75 | numpy.arange(0, numframes * frame_step, frame_step), (frame_len, 1)).T 76 | indices = numpy.array(indices, dtype=numpy.int32) 77 | padlen = (numframes - 1) * frame_step + frame_len 78 | 79 | if siglen <= 0: siglen = padlen 80 | 81 | rec_signal = numpy.zeros((padlen,)) 82 | window_correction = numpy.zeros((padlen,)) 83 | win = winfunc(frame_len) 84 | 85 | for i in range(0, numframes): 86 | window_correction[indices[i, :]] = window_correction[ 87 | indices[i, :]] + win + 1e-15 # add a little bit so it is never zero 88 | rec_signal[indices[i, :]] = rec_signal[indices[i, :]] + frames[i, :] 89 | 90 | rec_signal = rec_signal / window_correction 91 | return rec_signal[0:siglen] 92 | 93 | 94 | def magspec(frames, NFFT): 95 | """Compute the magnitude spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1). 96 | 97 | :param frames: the array of frames. Each row is a frame. 98 | :param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded. 99 | :returns: If frames is an NxD matrix, output will be Nx(NFFT/2+1). Each row will be the magnitude spectrum of the corresponding frame. 100 | """ 101 | if numpy.shape(frames)[1] > NFFT: 102 | logging.warn( 103 | 'frame length (%d) is greater than FFT size (%d), frame will be truncated. Increase NFFT to avoid.', 104 | numpy.shape(frames)[1], NFFT) 105 | complex_spec = numpy.fft.rfft(frames, NFFT) 106 | return numpy.angle(complex_spec), numpy.absolute(complex_spec) 107 | 108 | 109 | def powspec(frames, NFFT): 110 | """Compute the power spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1). 111 | 112 | :param frames: the array of frames. Each row is a frame. 113 | :param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded. 114 | :returns: If frames is an NxD matrix, output will be Nx(NFFT/2+1). Each row will be the power spectrum of the corresponding frame. 115 | """ 116 | return 1.0 / NFFT * numpy.square(magspec(frames, NFFT)) 117 | 118 | 119 | def logpowspec(frames, NFFT, norm=1): 120 | """Compute the log power spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1). 121 | 122 | :param frames: the array of frames. Each row is a frame. 123 | :param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded. 124 | :param norm: If norm=1, the log power spectrum is normalised so that the max value (across all frames) is 0. 125 | :returns: If frames is an NxD matrix, output will be Nx(NFFT/2+1). Each row will be the log power spectrum of the corresponding frame. 126 | """ 127 | ps = powspec(frames, NFFT); 128 | ps[ps <= 1e-30] = 1e-30 129 | lps = 10 * numpy.log10(ps) 130 | if norm: 131 | return lps - numpy.max(lps) 132 | else: 133 | return lps 134 | 135 | 136 | def preemphasis(signal, coeff=0.95): 137 | """perform preemphasis on the input signal. 138 | 139 | :param signal: The signal to filter. 140 | :param coeff: The preemphasis coefficient. 0 is no filter, default is 0.95. 141 | :returns: the filtered signal. 142 | """ 143 | return numpy.append(signal[0], signal[1:] - coeff * signal[:-1]) 144 | 145 | -------------------------------------------------------------------------------- /utils/sigproc.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xuchenglin28/speaker_extraction/7aeb899a4c2daf9e8680d72193edad4e9d3a280c/utils/sigproc.pyc -------------------------------------------------------------------------------- /verification/keys/readme: -------------------------------------------------------------------------------- 1 | # Copyright 2018, Wei Rao 2 | 3 | Please cite: 4 | Wei Rao, Chenglin Xu, Eng Siong Chng, and Haizhou Li, "Target Speaker Extraction for Overlapped Multi-Talker Speaker Verification", submitted to ICASSP 2019. 5 | 6 | In the paper, 7 | 1. the EER for Test on Clean use the trials under clean_set/trials 8 | 2. the EER for Test on Mixture use the trials under mixture_set/trials 9 | 3. The EER for Test on Mixture with Target Speaker Extraction Module use the trials under mixture_set/trials, for each trial, the enroll and test data are sent to speaker extraction, then the extracted speech is used as test wav for speaker verification together with the enroll wav. 10 | --------------------------------------------------------------------------------