├── LICENSE ├── LICENSE_ORI ├── README.md ├── README_EN.md ├── infer.py ├── input └── put wav files here ├── labels └── put speaker feature audio file here, one folder per speaker ├── model └── put infer model here ├── mvector ├── MODIFICATION_STATEMENT ├── __init__.py ├── data_utils │ ├── __init__.py │ ├── audio.py │ ├── featurizer.py │ └── utils.py ├── models │ ├── __init__.py │ ├── ecapa_tdnn.py │ ├── fc.py │ ├── loss.py │ ├── pooling.py │ ├── res2net.py │ ├── resnet_se.py │ └── tdnn.py ├── predict.py └── utils │ ├── __init__.py │ ├── logger.py │ └── utils.py └── requirements.txt /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 | -------------------------------------------------------------------------------- /LICENSE_ORI: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

Audio Dataset VPR Classifier

3 |
音频数据集声纹识别分类器
4 |
5 |

6 | 7 | 8 | 9 | 10 |

11 | 12 | 简体中文 | [English](https://github.com/2DIPW/audio_dataset_vpr/blob/master/README_EN.md) 13 | 14 | ## 🚩 简介 15 | 一个基于声纹识别模型对音频数据集按说话人自动分类的数据集筛选辅助工具,仅需为每个说话人准备数条代表性的语音片段,可用于辅助 VITS/SoVITS/Diff-SVC/RVC/DDSP-SVC 等语音模型数据集的制作。 16 | 17 | 基于 [yeyupiaoling/VoiceprintRecognition-Pytorch](https://github.com/yeyupiaoling/VoiceprintRecognition-Pytorch) 修改,增加了批量声纹识别功能,优化了说话人的判定机制,并能将识别结果保存为可导入 [2DIPW/audio_dataset_screener](https://github.com/2DIPW/audio_dataset_screener) 中进行进一步手工筛选的 JSON 工程文件。相比原项目删除了所有与模型训练相关的源码,故如需训练自己的模型请使用原项目。 18 | 19 | 此项目为实验性项目,不保证使用效果,仅供学习与交流,并非为生产环境准备。 20 | 21 | ## 📥 部署 22 | ### 克隆 23 | ```shell 24 | git clone https://github.com/2DIPW/audio_dataset_vpr.git 25 | cd audio_dataset_vpr 26 | ``` 27 | ### 创建虚拟环境(可选,以Anaconda为例) 28 | ```sheel 29 | conda create -n ad-vpr python=3.8 30 | conda activate ad-vpr 31 | ``` 32 | ### 安装PyTorch 33 | - 根据需求安装 PyTorch,详见[官网](https://pytorch.org/get-started/locally),以下为 pip 安装 PyTorch-CUDA 版本的示例。如果已经安装,请跳过。 34 | ```shell 35 | pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 36 | ``` 37 | ### 安装其他依赖 38 | ```shell 39 | pip install -r requirements.txt 40 | ``` 41 | ### 配置声纹识别模型 42 | 默认参数下,你需要将模型文件`model.pt`、`model.state`、`optimizer.pt`及配置文件`config.yml`置于`model`目录。你也可以通过指定`-m`和`-c`参数读取其他路径下的模型及配置文件。 43 | 44 | - 你可以从 Hugging Face 下载我基于 [zhvoice](https://aistudio.baidu.com/aistudio/datasetdetail/133922) 数据集训练的 EcapaTdnn 模型:[2DIPW/VPR_zhvoice_EcapaTdnn](https://huggingface.co/2DIPW/VPR_zhvoice_EcapaTdnn/tree/main) 45 | - 或者下载[原项目作者 yeyupiaoling 训练的更多模型](https://github.com/yeyupiaoling/VoiceprintRecognition-Pytorch#%E6%A8%A1%E5%9E%8B%E4%B8%8B%E8%BD%BD) 46 | - 或者基于原项目[训练自己的模型](https://github.com/yeyupiaoling/VoiceprintRecognition-Pytorch#%E5%88%9B%E5%BB%BA%E6%95%B0%E6%8D%AE) 47 | 48 | 声纹识别模型的质量与识别效果直接相关,你可以自行尝试摸索最佳的模型。 49 | ## 🗝 使用方法 50 | ### 准备音频特征库 51 | - 对于每个说话人,选取几段最具代表性的语音片段,按以下文件结构放入`labels`目录。每个说话人建立一个子目录,目录名为说话人名称,文件名不做要求。 52 | - 由于代码是根据相似度大于给定阈值的特征片段数量来判定说话人的,请保证每个说话人特征语音片段**数量相等**。 53 | - 如果你想将声纹识别结果用于 Audio Dataset Screener 的后续手工筛选,说话人不应超过5位,否则序号大于5的说话人会被 Audio Dataset Screener 自动忽略。 54 | 55 | ``` 56 | labels 57 | ├───speaker1 58 | │ ├───xxx1-xxx1.wav 59 | │ ├───... 60 | │ └───xxx1-xxx4.wav 61 | └───speaker2 62 | ├───xxx2-xxx1.wav 63 | ├───... 64 | └───xxx2-xxx4.wav 65 | ``` 66 | ### 准备待分类的音频文件 67 | - 默认参数下,你需要将所有待分类的音频片段(wav格式)放入`input`目录。你也可以通过指定`-i`参数读取其他路径下的音频片段。 68 | ### 运行识别分类 69 | - 使用`infer.py` 70 | ```shell 71 | python infer.py 72 | ``` 73 | 可指定的参数: 74 | - `-m` | `--model_path`: 存放声纹识别模型的目录。默认值:`model/` 75 | - `-c` | `--configs`: 模型配置文件的路径。默认值:`model/config.yml` 76 | - `-d` | `--device`: 推理设备,gpu或cpu。默认值:`gpu` 77 | - `-l` | `--label_path`: 存放音频特征库的目录。默认值:`labels/` 78 | - `-t` | `--threshold`: 判定阈值,若置信度大于该值则认为特征相符。默认值:`0.6` 79 | - `-i` | `--input_path`: 存放待分类音频文件的目录。默认值:`input/` 80 | - `-o` | `--output_path`: 存放分类结果的目录。默认值:`output/` 81 | - `-k` | `--keep_unrecognized`: 不移动未识别的音频文件。默认值:不启用 82 | 83 | - 识别结束后,输入的音频文件将会被移动至`output`目录下的以`VPR_Result_YYYYMMDD_HHMMSS`格式命名的目录中,识别为不同说话人的音频文件将会移动至对应说话人名称的目录,未被识别的音频文件会移至`Unrecognized`文件夹。 84 | - 识别结果也将保存为`result.json`文件,可使用 Audio Dataset Screener 导入进行进一步的手工筛选。 85 | 86 | ## ⚖ 开源协议 87 | 原项目基于 [Apache License 2.0](https://github.com/yeyupiaoling/VoiceprintRecognition-Pytorch/blob/develop/LICENSE) 开源,按照该协议,本项目中原项目的源码附带文件修改说明(MODIFICATION_STATEMENT)。 88 | 89 | 本项目基于 [GNU General Public License v3.0](https://github.com/2DIPW/audio_dataset_vpr/blob/master/LICENSE) 开源 90 | 91 | *世界因开源更精彩* 92 | ## 📃 参考文献 93 | ``` 94 | @inproceedings{desplanques2020ecapa, 95 | title={{ECAPA-TDNN: Emphasized Channel Attention, propagation and aggregation in TDNN based speaker verification}}, 96 | author={Desplanques, Brecht and Thienpondt, Jenthe and Demuynck, Kris}, 97 | booktitle={Interspeech 2020}, 98 | pages={3830--3834}, 99 | year={2020} 100 | } 101 | ``` -------------------------------------------------------------------------------- /README_EN.md: -------------------------------------------------------------------------------- 1 |
2 |

Audio Dataset VPR Classifier

3 |
A voiceprint recognition classifier for audio dataset
4 |
5 |

6 | 7 | 8 | 9 | 10 |

11 | 12 | [简体中文](https://github.com/2DIPW/audio_dataset_vpr/blob/master/README.md) | English 13 | 14 | ## 🚩 Introduction 15 | A dataset screening tool that automatically classifies audio dataset by speaker based on voiceprint recognition model. To use it, you just need to prepare several representative voice clips for each speaker. It can be used to assist the make of dataset for speech models such as VITS/SoVITS/Diff-SVC/RVC/DDSP-SVC. 16 | 17 | This project is modified by [yeyupiaoling/VoiceprintRecognition-Pytorch](https://github.com/yeyupiaoling/VoiceprintRecognition-Pytorch), which added batch processing feature, optimized the speaker judgment rule, and can save the recognition results as a [2DIPW/audio_dataset_screener]( https://github.com/2DIPW/audio_dataset_screener) JSON project file for further manual screening. Compared with the original project, all codes related to model training have been deleted, so if you need to train your own model, you should use the original project. 18 | 19 | This project is experimental and does not guarantee the effect. It is only for learning and communication, not for production environment. 20 | 21 | ## 📥 Deploy 22 | ### Clone 23 | ```shell 24 | git clone https://github.com/2DIPW/audio_dataset_vpr.git 25 | cd audio_dataset_vpr 26 | ``` 27 | ### Create a virtual environment (optional, take Anaconda as an example) 28 | ```sheel 29 | conda create -n ad-vpr python=3.8 30 | conda activate ad-vpr 31 | ``` 32 | ### Install PyTorch 33 | - Install PyTorch according to your needs, see [official website](https://pytorch.org/get-started/locally) for details, the following is an example of using pip to install PyTorch-CUDA. Skip if already installed. 34 | ```shell 35 | pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 36 | ``` 37 | ### Install other requirements 38 | ```shell 39 | pip install -r requirements.txt 40 | ``` 41 | ### Configure the voiceprint recognition model 42 | Under the default parameters, you need to put the model files `model.pt`, `model.state`, `optimizer.pt` and the configuration file `config.yml` in the `model` directory. You can also use model and configuration files in other paths by specifying `-m` and `-c` parameters. 43 | 44 | - You can download the EcapaTdnn model I trained on [zhvoice](https://aistudio.baidu.com/aistudio/datasetdetail/133922) dataset from Hugging Face: [2DIPW/VPR_zhvoice_EcapaTdnn](https://huggingface.co/2DIPW/VPR_zhvoice_EcapaTdnn/tree/main) 45 | - Or download [more models trained by the original project author yeyupiaoling](https://github.com/yeyupiaoling/VoiceprintRecognition-Pytorch#%E6%A8%A1%E5%9E%8B%E4%B8%8B%E8%BD%BD) 46 | - Or [train your own model using the original project](https://github.com/yeyupiaoling/VoiceprintRecognition-Pytorch#%E5%88%9B%E5%BB%BA%E6%95%B0%E6%8D%AE) 47 | 48 | The quality of voiceprint recognition is directly related to the quality of the model, you can try to find the best model by yourself. 49 | ## 🗝 How to use 50 | ### Prepare audio feature library 51 | - For each speaker, select several most representative speech segments and put them into the `labels` directory according to the following structure. Create one subdirectory for each speaker, the directory name is the speaker name, and the file name is arbitrary. 52 | - Since the code determines the speaker based on the number of feature segments whose similarity is greater than the given threshold, please ensure that the number of feature segments **equal** for each speaker. 53 | - If you want to use the voiceprint recognition results for further manual screening by Audio Dataset Screener, the number of speakers should not exceed 5, otherwise speakers with serial numbers greater than 5 will be automatically ignored by Audio Dataset Screener. 54 | 55 | ``` 56 | labels 57 | ├───speaker1 58 | │ ├───xxx1-xxx1.wav 59 | │ ├───... 60 | │ └───xxx1-xxx4.wav 61 | └───speaker2 62 | ├───xxx2-xxx1.wav 63 | ├───... 64 | └───xxx2-xxx4.wav 65 | ``` 66 | ### Prepare audio files for classification 67 | - With the default parameters, you need to put all the audio files (wav format) into the `input` directory. You can also load audio files in other paths by specifying the `-i` parameter. 68 | ### Run the recognition 69 | - Using `infer.py` 70 | ```shell 71 | python infer.py 72 | ``` 73 | Parameters that can be specified: 74 | - `-m` | `--model_path`: Path to model. Default: `model/` 75 | - `-c` | `--configs`: Path to model config file. Default: `model/config.yml` 76 | - `-d` | `--device`: Device to use, gpu or cpu. Default: `gpu` 77 | - `-l` | `--label_path`: Path to Voice feature library. Default: `labels/` 78 | - `-t` | `--threshold`: Threshold for judging compliance. Default: `0.6` 79 | - `-i` | `--input_path`: Path to input files. Default: `input/` 80 | - `-o` | `--output_path`: Path to output files. Default: `output/` 81 | - `-k` | `--keep_unrecognized`: Do not move unrecognized files. Default: Disabled 82 | 83 | - After the process is complete, the input audio files will be moved to the directory named in the `VPR_Result_YYYYMMDD_HHMMSS` format in the `output` directory, and the audio files recognized as different speakers will be moved to the directories named after the speakers, unrecognized audio files will be moved to the `Unrecognized` folder. 84 | - The recognition results will also be saved as a `result.json` file, which can be imported using Audio Dataset Screener for further manual screening. 85 | 86 | ## ⚖ License 87 | The original project is licensed under [Apache License 2.0](https://github.com/yeyupiaoling/VoiceprintRecognition-Pytorch/blob/develop/LICENSE) . According to the license, my project contains the MODIFICATION_STATEMENT. 88 | 89 | This project is licensed under [GNU General Public License v3.0](https://github.com/2DIPW/audio_dataset_vpr/blob/master/LICENSE) . 90 | 91 | *Open source leads the world to a brighter future.* 92 | ## 📃 References 93 | ``` 94 | @inproceedings{desplanques2020ecapa, 95 | title={{ECAPA-TDNN: Emphasized Channel Attention, propagation and aggregation in TDNN based speaker verification}}, 96 | author={Desplanques, Brecht and Thienpondt, Jenthe and Demuynck, Kris}, 97 | booktitle={Interspeech 2020}, 98 | pages={3830--3834}, 99 | year={2020} 100 | } 101 | ``` -------------------------------------------------------------------------------- /infer.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import json 4 | import shutil 5 | from datetime import datetime 6 | from mvector.predict import MVectorPredictor 7 | 8 | 9 | def if_not_mkdir(path): 10 | if not os.path.exists(path): 11 | os.mkdir(path) 12 | 13 | 14 | def about(): 15 | print(r""" 16 | ___ ___ ____ __ __ _ ______ ____ 17 | / | __ ______/ (_)___ / __ \____ _/ /_____ _________ / /_ | | / / __ \/ __ \ 18 | / /| |/ / / / __ / / __ \ / / / / __ `/ __/ __ `/ ___/ _ \/ __/ | | / / /_/ / /_/ / 19 | / ___ / /_/ / /_/ / / /_/ / / /_/ / /_/ / /_/ /_/ (__ ) __/ /_ | |/ / ____/ _, _/ 20 | /_/ |_\__,_/\__,_/_/\____/ /_____/\__,_/\__/\__,_/____/\___/\__/ |___/_/ /_/ |_| 21 | 22 | Audio Dataset Voiceprint Recognition Classifier by 2DIPW based on yeyupiaoling/VoiceprintRecognition-Pytorch 23 | Licensed under GNU General Public License v3. Open source leads the world to a brighter future! 24 | 25 | """) 26 | 27 | 28 | if __name__ == "__main__": 29 | about() 30 | parser = argparse.ArgumentParser() 31 | parser.add_argument('-m', '--model_path', type=str, default="model/", help="Path to model.") 32 | parser.add_argument('-c', '--configs', type=str, default="model/config.yml", help="Path to model config file.") 33 | parser.add_argument('-d', '--device', type=str, default="gpu", help='Device to use, gpu or cpu.') 34 | parser.add_argument('-l', '--label_path', type=str, default="labels/", help="Path to Voice feature library.") 35 | parser.add_argument('-t', '--threshold', type=float, default=0.6, help="Threshold for judging compliance.") 36 | parser.add_argument('-i', '--input_path', type=str, default="input/", help="Path to input files.") 37 | parser.add_argument('-o', '--output_path', type=str, default="output/", help="Path to output files.") 38 | parser.add_argument('-k', '--keep_unrecognized', action='store_true', default=False, 39 | help='Do not move unrecognized files.') 40 | 41 | args = parser.parse_args() 42 | 43 | predictor = MVectorPredictor(configs=args.configs, 44 | threshold=args.threshold, 45 | label_path=args.label_path, 46 | model_path=args.model_path, 47 | use_gpu=True if args.device == "gpu" else False) 48 | 49 | if not os.path.exists(args.input_path): 50 | raise Exception("Input path not existed.") 51 | 52 | # Get labels dict from label_path 53 | labels_list = [f for f in os.listdir(args.label_path) if os.path.isdir(os.path.join(args.label_path, f))] 54 | labels_dict = {} 55 | for i, label in enumerate(labels_list): 56 | labels_dict[label] = i + 1 57 | print(f"Feature labels:{labels_dict}") 58 | 59 | # Get input files list from input_path 60 | input_files = [] 61 | for root, dirs, files in os.walk(args.input_path): 62 | input_files += [os.path.abspath(os.path.join(root, f)) for f in files if f.split('.')[-1].upper() in ["WAV"]] 63 | 64 | input_files_amount = len(input_files) 65 | 66 | result_dicts_list = [] 67 | 68 | for i, file in enumerate(input_files): 69 | try: 70 | label, similarity = predictor.recognition(audio_data=file) 71 | if label: 72 | print( 73 | f"\033[32m[{i + 1}/{input_files_amount}]\033[0m \033[33m{os.path.basename(file)}\033[0m is recognized as speaker \033[31m{label}\033[0m, the max similarity is \033[34m{similarity}\033[0m.") 74 | result_dicts_list.append( 75 | {"Filepath": file, "Label": labels_dict[label], "Similarity": float(similarity)}) 76 | else: 77 | print( 78 | f"\033[32m[{i + 1}/{input_files_amount}]\033[0m \033[33m{os.path.basename(file)}\033[0m could not be recognized as any speaker.") 79 | result_dicts_list.append( 80 | {"Filepath": file, "Label": 0, "Similarity": 0}) 81 | except Exception as e: 82 | print( 83 | f"\033[32m[{i + 1}/{input_files_amount}]\033[0m An error occurred while processing \033[33m{os.path.basename(file)}\033[0m : {e}") 84 | 85 | output_path_for_this_run = os.path.join(args.output_path, datetime.now().strftime("VPR_Result_%Y%m%d_%H%M%S")) 86 | if_not_mkdir(output_path_for_this_run) 87 | json_path = os.path.abspath(os.path.join(output_path_for_this_run, "result.json")) 88 | 89 | # Move input files to category folders 90 | print("Moving input files to category folders...") 91 | folder_list_without_unrecognized = [os.path.abspath(os.path.join(output_path_for_this_run, label)) for label in 92 | labels_list] 93 | folder_list = [os.path.abspath( 94 | os.path.join(output_path_for_this_run, "Unrecognized"))] + folder_list_without_unrecognized 95 | 96 | for folder in folder_list: 97 | if_not_mkdir(folder) 98 | for result in result_dicts_list: 99 | if args.keep_unrecognized and result["Label"] == 0: 100 | continue 101 | destination_folder = folder_list[result["Label"]] 102 | try: 103 | shutil.move(result["Filepath"], destination_folder) 104 | result["Filepath"] = os.path.abspath(os.path.join(destination_folder, os.path.basename(result["Filepath"]))) 105 | except Exception as e: 106 | print(e) 107 | 108 | # Write result json file to output_path 109 | with open(json_path, "w") as f: 110 | json.dump({"Labels": {str(i + 1): folder for i, folder in enumerate(folder_list_without_unrecognized)}, 111 | "Files": result_dicts_list}, f, indent=4) 112 | print(f"Result json is saved as {json_path}") 113 | -------------------------------------------------------------------------------- /input/put wav files here: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2DIPW/audio_dataset_vpr/1b88767aa5792762626989d64910e599fc4a6bd9/input/put wav files here -------------------------------------------------------------------------------- /labels/put speaker feature audio file here, one folder per speaker: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2DIPW/audio_dataset_vpr/1b88767aa5792762626989d64910e599fc4a6bd9/labels/put speaker feature audio file here, one folder per speaker -------------------------------------------------------------------------------- /model/put infer model here: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2DIPW/audio_dataset_vpr/1b88767aa5792762626989d64910e599fc4a6bd9/model/put infer model here -------------------------------------------------------------------------------- /mvector/MODIFICATION_STATEMENT: -------------------------------------------------------------------------------- 1 | ORI THIS 2 | -------------------------------- 3 | data_utils data_utils 4 | +augmentor | 5 | +__init__.py = +__init__.py 6 | +audio.py = +audio.py 7 | +collate_fn.py >> | 8 | +featurizer.py = +featurizer.py 9 | +reader.py >> | 10 | \utils.py = \utils.py 11 | metric 12 | +__init__.py >> 13 | \metrics.py >> 14 | models models 15 | +__init__.py = +__init__.py 16 | +ecapa_tdnn.py = +ecapa_tdnn.py 17 | +fc.py = +fc.py 18 | +loss.py = +loss.py 19 | +pooling.py = +pooling.py 20 | +res2net.py = +res2net.py 21 | +resnet_se.py = +resnet_se.py 22 | \tdnn.py = \tdnn.py 23 | utils utils 24 | +__init__.py = +__init__.py 25 | +logger.py = +logger.py 26 | +record.py >> | 27 | \utils.py <> \utils.py 28 | __init__.py = __init__.py 29 | predict.py <> predict.py 30 | trainer.py >> 31 | -------------------------------- 32 | 33 | File: utils\utils.py 34 | 6 from mvector.utils.logger import setup_logger +- 35 | 7 36 | 8 logger = setup_logger(__name__) 37 | 9 38 | 10 39 | 11 def print_arguments(args=None, configs=None): 40 | 12 if args: 41 | 13 logger.info("----------- 额外配置参数 -----------") 42 | 14 for arg, value in sorted(vars(args).items()): 43 | 15 logger.info("%s: %s" % (arg, value)) 44 | 16 logger.info("------------------------------------------------") 45 | 17 if configs: 46 | 18 logger.info("----------- 配置文件参数 -----------") 47 | 19 for arg, value in sorted(configs.items()): 48 | 20 if isinstance(value, dict): 49 | 21 logger.info(f"{arg}:") 50 | 22 for a, v in sorted(value.items()): 51 | 23 if isinstance(v, dict): 52 | 24 logger.info(f"\t{a}:") 53 | 25 for a1, v1 in sorted(v.items()): 54 | 26 logger.info("\t\t%s: %s" % (a1, v1)) 55 | 27 else: 56 | 28 logger.info("\t%s: %s" % (a, v)) 57 | 29 else: 58 | 30 logger.info("%s: %s" % (arg, value)) 59 | 31 logger.info("------------------------------------------------") 60 | 32 61 | 33 62 | 34 def add_arguments(argname, type, default, help, argparser, **kwargs): 63 | 35 type = distutils.util.strtobool if type == bool else type 64 | 36 argparser.add_argument("--" + argname, 65 | 37 default=default, 66 | 38 type=type, 67 | 39 help=help + ' 默认: %(default)s.', 68 | 40 **kwargs) 69 | 41 70 | ------------------------------------------------------------------------------- 71 | 72 | File: predict.py 73 | 2 import pickle +- 74 | 3 import shutil 75 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 76 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 77 | 21 from mvector.utils.utils import dict_to_object, print_arguments <> 19 from mvector.utils.utils import dict_to_object 78 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 79 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 80 | 30 audio_db_path=None, <> 28 label_path=None, 81 | 31 model_path='models/ecapa_tdnn_spectrogram/best_model/', 29 model_path='./model', 82 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 83 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 84 | 37 :param audio_db_path: 声纹库路径 <> 35 :param label_path: 声纹库路径 85 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 86 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 87 | 42 assert (torch.cuda.is_available()), 'GPU不可用' <> 40 assert (torch.cuda.is_available()), 'GPU not available.' 88 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 89 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 90 | 54 print_arguments(configs=configs) +- 91 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 92 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 93 | 57 '【警告】,您貌似使用了旧的配置文件,如果你同时使用了旧的模型,这是错误的,请重新下载或者重新训练,否则只能回滚代码。' <> 54 'You are using an old version of model which is no longer supported.' 94 | 58 assert self.configs.use_model in SUPPORT_MODEL, f'没有该模型:{self.configs.use_model}' 55 assert self.configs.use_model in SUPPORT_MODEL, f'Model not existed:{self.configs.use_model}' 95 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 96 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 97 | 71 raise Exception(f'{self.configs.use_model} 模型不存在!') <> 68 raise Exception(f'{self.configs.use_model} model not existed!') 98 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 99 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 100 | 77 assert os.path.exists(model_path), f"{model_path} 模型不存在!" <> 74 assert os.path.exists(model_path), f"{model_path} model not existed!" 101 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 102 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 103 | 83 print(f"成功加载模型参数:{model_path}") <> 80 print(f"Model loaded successfully:{model_path}") 104 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 105 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 106 | 94 self.audio_db_path = audio_db_path <> 91 self.audio_db_path = label_path 107 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 108 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 109 | 96 self.audio_indexes_path = os.path.join(audio_db_path, "audio_indexes.bin") +- 110 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 111 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 112 | 100 # 加载声纹特征索引 +- 113 | 101 def __load_face_indexes(self): 114 | 102 # 如果存在声纹特征索引文件就加载 115 | 103 if not os.path.exists(self.audio_indexes_path): return 116 | 104 with open(self.audio_indexes_path, "rb") as f: 117 | 105 indexes = pickle.load(f) 118 | 106 self.users_name = indexes["users_name"] 119 | 107 self.audio_feature = indexes["faces_feature"] 120 | 108 self.users_audio_path = indexes["users_image_path"] 121 | 109 122 | 110 # 保存声纹特征索引 123 | 111 def __write_index(self): 124 | 112 with open(self.audio_indexes_path, "wb") as f: 125 | 113 pickle.dump({"users_name": self.users_name, 126 | 114 "faces_feature": self.audio_feature, 127 | 115 "users_image_path": self.users_audio_path}, f) 128 | 116 129 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 130 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 131 | 120 self.__load_face_indexes() +- 132 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 133 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 134 | 125 if not os.path.isdir(audio_dir):continue <> 103 if not os.path.isdir(audio_dir): continue 135 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 136 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 137 | 130 logger.info('正在加载声纹库数据...') <> 108 print("Loading voice feature library...") 138 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 139 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 140 | 157 assert len(self.audio_feature) == len(self.users_name) == len(self.users_audio_path), '加载的数量对不上!' <> 135 assert len(self.audio_feature) == len(self.users_name) == len(self.users_audio_path), 'Labels count conflict.' 141 | 158 # 将声纹特征保存到索引文件中 136 print("Voice feature library loaded successfully.") 142 | 159 self.__write_index() 143 | 160 logger.info('声纹库数据加载完成!') 144 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 145 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 146 | 164 labels = [] <> 140 results = [] 147 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 148 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 149 | 179 max_label = None <> 155 results.append({"label": None, "similarity": None}) 150 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 151 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 152 | 182 labels.append(max_label) <> 158 idx_for_max_label = [i for i, x in enumerate(self.users_name) if x == max_label] 153 | 159 similarity_for_max_label = max(abs_similarity[idx_for_max_label]) 154 | 160 results.append({"label": max_label, "similarity": similarity_for_max_label}) 155 | 183 return labels 161 return results 156 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 157 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 158 | 203 f'音频太短,最小应该为{self.configs.dataset_conf.min_duration}s,当前音频为{audio_segment.duration}s' <> 181 f'Audio segment too short,minimum is {self.configs.dataset_conf.min_duration}s,current is{audio_segment.duration}s' 159 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 160 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 161 | 254 input_lens_ratio.append(seq_length/max_audio_length) <> 232 input_lens_ratio.append(seq_length / max_audio_length) 162 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 163 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 164 | 262 # 声纹对比 +- 165 | 263 def contrast(self, audio_data1, audio_data2): 166 | 264 feature1 = self.predict(audio_data1) 167 | 265 feature2 = self.predict(audio_data2) 168 | 266 # 对角余弦值 169 | 267 dist = np.dot(feature1, feature2) / (np.linalg.norm(feature1) * np.linalg.norm(feature2)) 170 | 268 return dist 171 | 269 172 | 270 def register(self, 173 | 271 user_name, 174 | 272 audio_data, 175 | 273 sample_rate=16000): 176 | 274 """声纹注册 177 | 275 :param user_name: 注册用户的名字 178 | 276 :param audio_data: 需要识别的数据,支持文件路径,文件对象,字节,numpy。如果是字节的话,必须是完整的字节文件 179 | 277 :param sample_rate: 如果传入的事numpy数据,需要指定采样率 180 | 278 :return: 识别的文本结果和解码的得分数 181 | 279 """ 182 | 280 # 加载音频文件 183 | 281 if isinstance(audio_data, str): 184 | 282 audio_segment = AudioSegment.from_file(audio_data) 185 | 283 elif isinstance(audio_data, BufferedReader): 186 | 284 audio_segment = AudioSegment.from_file(audio_data) 187 | 285 elif isinstance(audio_data, np.ndarray): 188 | 286 audio_segment = AudioSegment.from_ndarray(audio_data, sample_rate) 189 | 287 elif isinstance(audio_data, bytes): 190 | 288 audio_segment = AudioSegment.from_bytes(audio_data) 191 | 289 else: 192 | 290 raise Exception(f'不支持该数据类型,当前数据类型为:{type(audio_data)}') 193 | 291 feature = self.predict(audio_data=audio_segment.samples, sample_rate=audio_segment.sample_rate) 194 | 292 if self.audio_feature is None: 195 | 293 self.audio_feature = feature 196 | 294 else: 197 | 295 self.audio_feature = np.vstack((self.audio_feature, feature)) 198 | 296 # 保存 199 | 297 if not os.path.exists(os.path.join(self.audio_db_path, user_name)): 200 | 298 audio_path = os.path.join(self.audio_db_path, user_name, '0.wav') 201 | 299 else: 202 | 300 audio_path = os.path.join(self.audio_db_path, user_name, 203 | 301 f'{len(os.listdir(os.path.join(self.audio_db_path, user_name)))}.wav') 204 | 302 os.makedirs(os.path.dirname(audio_path), exist_ok=True) 205 | 303 audio_segment.to_wav_file(audio_path) 206 | 304 self.users_audio_path.append(audio_path.replace('\\', '/')) 207 | 305 self.users_name.append(user_name) 208 | 306 self.__write_index() 209 | 307 return True, "注册成功" 210 | 308 211 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 212 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 213 | 319 name = self.__retrieval(np_feature=[feature])[0] <> 250 result = self.__retrieval(np_feature=[feature])[0] 214 | 320 return name 215 | 321 216 | 322 def remove_user(self, user_name): 217 | 323 """删除用户 218 | 324 219 | 325 :param user_name: 用户名 220 | 326 :return: 221 | 327 """ 222 | 328 if user_name in self.users_name: 251 return result["label"], result["similarity"] 223 | 329 indexes = [i for i in range(len(self.users_name)) if self.users_name[i] == user_name] 224 | 330 for index in sorted(indexes, reverse=True): 225 | 331 del self.users_name[index] 226 | 332 del self.users_audio_path[index] 227 | 333 self.audio_feature = np.delete(self.audio_feature, index, axis=0) 228 | 334 self.__write_index() 229 | 335 shutil.rmtree(os.path.join(self.audio_db_path, user_name)) 230 | 336 return True 231 | 337 else: 232 | 338 return False 233 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 234 | 235 | -------------------------------------------------------------------------------- /mvector/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.3.9" 2 | # 项目支持的模型 3 | SUPPORT_MODEL = ['ecapa_tdnn', 'EcapaTdnn', 'Res2Net', 'ResNetSE', 'TDNN'] 4 | -------------------------------------------------------------------------------- /mvector/data_utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2DIPW/audio_dataset_vpr/1b88767aa5792762626989d64910e599fc4a6bd9/mvector/data_utils/__init__.py -------------------------------------------------------------------------------- /mvector/data_utils/audio.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import io 3 | import os 4 | import random 5 | 6 | import numpy as np 7 | import resampy 8 | import soundfile 9 | 10 | from mvector.data_utils.utils import buf_to_float, vad, decode_audio 11 | 12 | 13 | class AudioSegment(object): 14 | """Monaural audio segment abstraction. 15 | 16 | :param samples: Audio samples [num_samples x num_channels]. 17 | :type samples: ndarray.float32 18 | :param sample_rate: Audio sample rate. 19 | :type sample_rate: int 20 | :raises TypeError: If the sample data type is not float or int. 21 | """ 22 | 23 | def __init__(self, samples, sample_rate): 24 | """Create audio segment from samples. 25 | 26 | Samples are convert float32 internally, with int scaled to [-1, 1]. 27 | """ 28 | self._samples = self._convert_samples_to_float32(samples) 29 | self._sample_rate = sample_rate 30 | if self._samples.ndim >= 2: 31 | self._samples = np.mean(self._samples, 1) 32 | 33 | def __eq__(self, other): 34 | """返回两个对象是否相等""" 35 | if type(other) is not type(self): 36 | return False 37 | if self._sample_rate != other._sample_rate: 38 | return False 39 | if self._samples.shape != other._samples.shape: 40 | return False 41 | if np.any(self.samples != other._samples): 42 | return False 43 | return True 44 | 45 | def __ne__(self, other): 46 | """返回两个对象是否不相等""" 47 | return not self.__eq__(other) 48 | 49 | def __str__(self): 50 | """返回该音频的信息""" 51 | return ("%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, " 52 | "rms=%.2fdB" % (type(self), self.num_samples, self.sample_rate, self.duration, self.rms_db)) 53 | 54 | @classmethod 55 | def from_file(cls, file): 56 | """从音频文件创建音频段 57 | 58 | :param file: 文件路径,或者文件对象 59 | :type file: str, BufferedReader 60 | :return: 音频片段实例 61 | :rtype: AudioSegment 62 | """ 63 | assert os.path.exists(file), f'文件不存在,请检查路径:{file}' 64 | try: 65 | samples, sample_rate = soundfile.read(file, dtype='float32') 66 | except: 67 | # 支持更多格式数据 68 | sample_rate = 16000 69 | samples = decode_audio(file=file, sample_rate=sample_rate) 70 | return cls(samples, sample_rate) 71 | 72 | @classmethod 73 | def slice_from_file(cls, file, start=None, end=None): 74 | """只加载一小段音频,而不需要将整个文件加载到内存中,这是非常浪费的。 75 | 76 | :param file: 输入音频文件路径或文件对象 77 | :type file: str|file 78 | :param start: 开始时间,单位为秒。如果start是负的,则它从末尾开始计算。如果没有提供,这个函数将从最开始读取。 79 | :type start: float 80 | :param end: 结束时间,单位为秒。如果end是负的,则它从末尾开始计算。如果没有提供,默认的行为是读取到文件的末尾。 81 | :type end: float 82 | :return: AudioSegment输入音频文件的指定片的实例。 83 | :rtype: AudioSegment 84 | :raise ValueError: 如开始或结束的设定不正确,例如时间不允许。 85 | """ 86 | sndfile = soundfile.SoundFile(file) 87 | sample_rate = sndfile.samplerate 88 | duration = round(float(len(sndfile)) / sample_rate, 3) 89 | start = 0. if start is None else round(start, 3) 90 | end = duration if end is None else round(end, 3) 91 | # 从末尾开始计 92 | if start < 0.0: start += duration 93 | if end < 0.0: end += duration 94 | # 保证数据不越界 95 | if start < 0.0: start = 0.0 96 | if end > duration: end = duration 97 | if end < 0.0: 98 | raise ValueError("切片结束位置(%f s)越界" % end) 99 | if start > end: 100 | raise ValueError("切片开始位置(%f s)晚于切片结束位置(%f s)" % (start, end)) 101 | start_frame = int(start * sample_rate) 102 | end_frame = int(end * sample_rate) 103 | sndfile.seek(start_frame) 104 | data = sndfile.read(frames=end_frame - start_frame, dtype='float32') 105 | return cls(data, sample_rate) 106 | 107 | @classmethod 108 | def from_bytes(cls, data): 109 | """从包含音频样本的字节创建音频段 110 | 111 | :param data: 包含音频样本的字节 112 | :type data: bytes 113 | :return: 音频部分实例 114 | :rtype: AudioSegment 115 | """ 116 | samples, sample_rate = soundfile.read(io.BytesIO(data), dtype='float32') 117 | return cls(samples, sample_rate) 118 | 119 | @classmethod 120 | def from_pcm_bytes(cls, data, channels=1, samp_width=2, sample_rate=16000): 121 | """从包含无格式PCM音频的字节创建音频 122 | 123 | :param data: 包含音频样本的字节 124 | :type data: bytes 125 | :param channels: 音频的通道数 126 | :type channels: int 127 | :param samp_width: 音频采样的宽度,如np.int16为2 128 | :type samp_width: int 129 | :param sample_rate: 音频样本采样率 130 | :type sample_rate: int 131 | :return: 音频部分实例 132 | :rtype: AudioSegment 133 | """ 134 | samples = buf_to_float(data, n_bytes=samp_width) 135 | if channels > 1: 136 | samples = samples.reshape(-1, channels) 137 | return cls(samples, sample_rate) 138 | 139 | @classmethod 140 | def from_ndarray(cls, data, sample_rate=16000): 141 | """从numpy.ndarray创建音频段 142 | 143 | :param data: numpy.ndarray类型的音频数据 144 | :type data: ndarray 145 | :param sample_rate: 音频样本采样率 146 | :type sample_rate: int 147 | :return: 音频部分实例 148 | :rtype: AudioSegment 149 | """ 150 | return cls(data, sample_rate) 151 | 152 | @classmethod 153 | def concatenate(cls, *segments): 154 | """将任意数量的音频片段连接在一起 155 | 156 | :param *segments: 输入音频片段被连接 157 | :type *segments: tuple of AudioSegment 158 | :return: Audio segment instance as concatenating results. 159 | :rtype: AudioSegment 160 | :raises ValueError: If the number of segments is zero, or if the 161 | sample_rate of any segments does not match. 162 | :raises TypeError: If any segment is not AudioSegment instance. 163 | """ 164 | # Perform basic sanity-checks. 165 | if len(segments) == 0: 166 | raise ValueError("没有音频片段被给予连接") 167 | sample_rate = segments[0]._sample_rate 168 | for seg in segments: 169 | if sample_rate != seg._sample_rate: 170 | raise ValueError("能用不同的采样率连接片段") 171 | if type(seg) is not cls: 172 | raise TypeError("只有相同类型的音频片段可以连接") 173 | samples = np.concatenate([seg.samples for seg in segments]) 174 | return cls(samples, sample_rate) 175 | 176 | @classmethod 177 | def make_silence(cls, duration, sample_rate): 178 | """创建给定持续时间和采样率的静音音频段 179 | 180 | :param duration: 静音的时间,以秒为单位 181 | :type duration: float 182 | :param sample_rate: 音频采样率 183 | :type sample_rate: float 184 | :return: 给定持续时间的静音AudioSegment实例 185 | :rtype: AudioSegment 186 | """ 187 | samples = np.zeros(int(duration * sample_rate)) 188 | return cls(samples, sample_rate) 189 | 190 | def to_wav_file(self, filepath, dtype='float32'): 191 | """保存音频段到磁盘为wav文件 192 | 193 | :param filepath: WAV文件路径或文件对象,以保存音频段 194 | :type filepath: str|file 195 | :param dtype: Subtype for audio file. Options: 'int16', 'int32', 196 | 'float32', 'float64'. Default is 'float32'. 197 | :type dtype: str 198 | :raises TypeError: If dtype is not supported. 199 | """ 200 | samples = self._convert_samples_from_float32(self._samples, dtype) 201 | subtype_map = { 202 | 'int16': 'PCM_16', 203 | 'int32': 'PCM_32', 204 | 'float32': 'FLOAT', 205 | 'float64': 'DOUBLE' 206 | } 207 | soundfile.write( 208 | filepath, 209 | samples, 210 | self._sample_rate, 211 | format='WAV', 212 | subtype=subtype_map[dtype]) 213 | 214 | def superimpose(self, other): 215 | """将另一个段的样本添加到这个段的样本中(以样本方式添加,而不是段连接)。 216 | 217 | :param other: 包含样品的片段被添加进去 218 | :type other: AudioSegments 219 | :raise TypeError: 如果两个片段的类型不匹配 220 | :raise ValueError: 不能添加不同类型的段 221 | """ 222 | if not isinstance(other, type(self)): 223 | raise TypeError("不能添加不同类型的段: %s 和 %s" % (type(self), type(other))) 224 | if self._sample_rate != other._sample_rate: 225 | raise ValueError("采样率必须匹配才能添加片段") 226 | if len(self._samples) != len(other._samples): 227 | raise ValueError("段长度必须匹配才能添加段") 228 | self._samples += other._samples 229 | 230 | def to_bytes(self, dtype='float32'): 231 | """创建包含音频内容的字节字符串 232 | 233 | :param dtype: Data type for export samples. Options: 'int16', 'int32', 234 | 'float32', 'float64'. Default is 'float32'. 235 | :type dtype: str 236 | :return: Byte string containing audio content. 237 | :rtype: str 238 | """ 239 | samples = self._convert_samples_from_float32(self._samples, dtype) 240 | return samples.tostring() 241 | 242 | def to(self, dtype='int16'): 243 | """类型转换 244 | 245 | :param dtype: Data type for export samples. Options: 'int16', 'int32', 246 | 'float32', 'float64'. Default is 'float32'. 247 | :type dtype: str 248 | :return: np.ndarray containing `dtype` audio content. 249 | :rtype: str 250 | """ 251 | samples = self._convert_samples_from_float32(self._samples, dtype) 252 | return samples 253 | 254 | def gain_db(self, gain): 255 | """对音频施加分贝增益。 256 | 257 | Note that this is an in-place transformation. 258 | 259 | :param gain: Gain in decibels to apply to samples. 260 | :type gain: float|1darray 261 | """ 262 | self._samples *= 10.**(gain / 20.) 263 | 264 | def change_speed(self, speed_rate): 265 | """通过线性插值改变音频速度 266 | 267 | :param speed_rate: Rate of speed change: 268 | speed_rate > 1.0, speed up the audio; 269 | speed_rate = 1.0, unchanged; 270 | speed_rate < 1.0, slow down the audio; 271 | speed_rate <= 0.0, not allowed, raise ValueError. 272 | :type speed_rate: float 273 | :raises ValueError: If speed_rate <= 0.0. 274 | """ 275 | if speed_rate == 1.0: 276 | return 277 | if speed_rate <= 0: 278 | raise ValueError("速度速率应大于零") 279 | old_length = self._samples.shape[0] 280 | new_length = int(old_length / speed_rate) 281 | old_indices = np.arange(old_length) 282 | new_indices = np.linspace(start=0, stop=old_length, num=new_length) 283 | self._samples = np.interp(new_indices, old_indices, self._samples).astype(np.float32) 284 | 285 | def normalize(self, target_db=-20, max_gain_db=300.0): 286 | """将音频归一化,使其具有所需的有效值(以分贝为单位) 287 | 288 | :param target_db: Target RMS value in decibels. This value should be 289 | less than 0.0 as 0.0 is full-scale audio. 290 | :type target_db: float 291 | :param max_gain_db: Max amount of gain in dB that can be applied for 292 | normalization. This is to prevent nans when 293 | attempting to normalize a signal consisting of 294 | all zeros. 295 | :type max_gain_db: float 296 | :raises ValueError: If the required gain to normalize the segment to 297 | the target_db value exceeds max_gain_db. 298 | """ 299 | if -np.inf == self.rms_db: return 300 | gain = target_db - self.rms_db 301 | if gain > max_gain_db: 302 | raise ValueError( 303 | "无法将段规范化到 %f dB,因为可能的增益已经超过max_gain_db (%f dB)" % (target_db, max_gain_db)) 304 | self.gain_db(min(max_gain_db, target_db - self.rms_db)) 305 | 306 | def resample(self, target_sample_rate, filter='kaiser_best'): 307 | """按目标采样率重新采样音频 308 | 309 | Note that this is an in-place transformation. 310 | 311 | :param target_sample_rate: Target sample rate. 312 | :type target_sample_rate: int 313 | :param filter: The resampling filter to use one of {'kaiser_best', 'kaiser_fast'}. 314 | :type filter: str 315 | """ 316 | self._samples = resampy.resample(self.samples, self.sample_rate, target_sample_rate, filter=filter) 317 | self._sample_rate = target_sample_rate 318 | 319 | def pad_silence(self, duration, sides='both'): 320 | """在这个音频样本上加一段静音 321 | 322 | Note that this is an in-place transformation. 323 | 324 | :param duration: Length of silence in seconds to pad. 325 | :type duration: float 326 | :param sides: Position for padding: 327 | 'beginning' - adds silence in the beginning; 328 | 'end' - adds silence in the end; 329 | 'both' - adds silence in both the beginning and the end. 330 | :type sides: str 331 | :raises ValueError: If sides is not supported. 332 | """ 333 | if duration == 0.0: 334 | return self 335 | cls = type(self) 336 | silence = self.make_silence(duration, self._sample_rate) 337 | if sides == "beginning": 338 | padded = cls.concatenate(silence, self) 339 | elif sides == "end": 340 | padded = cls.concatenate(self, silence) 341 | elif sides == "both": 342 | padded = cls.concatenate(silence, self, silence) 343 | else: 344 | raise ValueError("Unknown value for the sides %s" % sides) 345 | self._samples = padded._samples 346 | 347 | def shift(self, shift_ms): 348 | """音频偏移。如果shift_ms为正,则随时间提前移位;如果为负,则随时间延迟移位。填补静音以保持持续时间不变。 349 | 350 | Note that this is an in-place transformation. 351 | 352 | :param shift_ms: Shift time in millseconds. If positive, shift with 353 | time advance; if negative; shift with time delay. 354 | :type shift_ms: float 355 | :raises ValueError: If shift_ms is longer than audio duration. 356 | """ 357 | if abs(shift_ms) / 1000.0 > self.duration: 358 | raise ValueError("shift_ms的绝对值应该小于音频持续时间") 359 | shift_samples = int(shift_ms * self._sample_rate / 1000) 360 | if shift_samples > 0: 361 | # time advance 362 | self._samples[:-shift_samples] = self._samples[shift_samples:] 363 | self._samples[-shift_samples:] = 0 364 | elif shift_samples < 0: 365 | # time delay 366 | self._samples[-shift_samples:] = self._samples[:shift_samples] 367 | self._samples[:-shift_samples] = 0 368 | 369 | def subsegment(self, start_sec=None, end_sec=None): 370 | """在给定的边界之间切割音频片段 371 | 372 | Note that this is an in-place transformation. 373 | 374 | :param start_sec: Beginning of subsegment in seconds. 375 | :type start_sec: float 376 | :param end_sec: End of subsegment in seconds. 377 | :type end_sec: float 378 | :raise ValueError: If start_sec or end_sec is incorrectly set, e.g. out 379 | of bounds in time. 380 | """ 381 | start_sec = 0.0 if start_sec is None else start_sec 382 | end_sec = self.duration if end_sec is None else end_sec 383 | if start_sec < 0.0: 384 | start_sec = self.duration + start_sec 385 | if end_sec < 0.0: 386 | end_sec = self.duration + end_sec 387 | if start_sec < 0.0: 388 | raise ValueError("切片起始位置(%f s)越界" % start_sec) 389 | if end_sec < 0.0: 390 | raise ValueError("切片结束位置(%f s)越界" % end_sec) 391 | if start_sec > end_sec: 392 | raise ValueError("切片的起始位置(%f s)晚于结束位置(%f s)" % (start_sec, end_sec)) 393 | if end_sec > self.duration: 394 | raise ValueError("切片结束位置(%f s)越界(> %f s)" % (end_sec, self.duration)) 395 | start_sample = int(round(start_sec * self._sample_rate)) 396 | end_sample = int(round(end_sec * self._sample_rate)) 397 | self._samples = self._samples[start_sample:end_sample] 398 | 399 | def random_subsegment(self, subsegment_length): 400 | """随机剪切指定长度的音频片段 401 | 402 | Note that this is an in-place transformation. 403 | 404 | :param subsegment_length: Subsegment length in seconds. 405 | :type subsegment_length: float 406 | :raises ValueError: If the length of subsegment is greater than 407 | the origineal segemnt. 408 | """ 409 | if subsegment_length > self.duration: 410 | raise ValueError("Length of subsegment must not be greater " 411 | "than original segment.") 412 | start_time = random.uniform(0.0, self.duration - subsegment_length) 413 | self.subsegment(start_time, start_time + subsegment_length) 414 | 415 | def add_noise(self, 416 | noise, 417 | snr_dB, 418 | max_gain_db=300.0): 419 | """以特定的信噪比添加给定的噪声段。如果噪声段比该噪声段长,则从该噪声段中采样匹配长度的随机子段。 420 | 421 | Note that this is an in-place transformation. 422 | 423 | :param noise: Noise signal to add. 424 | :type noise: AudioSegment 425 | :param snr_dB: Signal-to-Noise Ratio, in decibels. 426 | :type snr_dB: float 427 | :param max_gain_db: Maximum amount of gain to apply to noise signal 428 | before adding it in. This is to prevent attempting 429 | to apply infinite gain to a zero signal. 430 | :type max_gain_db: float 431 | :raises ValueError: If the sample rate does not match between the two 432 | audio segments, or if the duration of noise segments 433 | is shorter than original audio segments. 434 | """ 435 | if noise.sample_rate != self.sample_rate: 436 | raise ValueError("噪声采样率(%d Hz)不等于基信号采样率(%d Hz)" % (noise.sample_rate, self.sample_rate)) 437 | if noise.duration < self.duration: 438 | raise ValueError("噪声信号(%f秒)必须至少与基信号(%f秒)一样长" % (noise.duration, self.duration)) 439 | noise_gain_db = min(self.rms_db - noise.rms_db - snr_dB, max_gain_db) 440 | noise_new = copy.deepcopy(noise) 441 | noise_new.random_subsegment(self.duration) 442 | noise_new.gain_db(noise_gain_db) 443 | self.superimpose(noise_new) 444 | 445 | def vad(self, top_db=20, overlap=200): 446 | self._samples = vad(wav=self._samples, top_db=top_db, overlap=overlap) 447 | 448 | def crop(self, duration, mode='eval'): 449 | if self.duration > duration: 450 | if mode == 'train': 451 | self.random_subsegment(duration) 452 | else: 453 | self.subsegment(end_sec=duration) 454 | 455 | @property 456 | def samples(self): 457 | """返回音频样本 458 | 459 | :return: Audio samples. 460 | :rtype: ndarray 461 | """ 462 | return self._samples.copy() 463 | 464 | @property 465 | def sample_rate(self): 466 | """返回音频采样率 467 | 468 | :return: Audio sample rate. 469 | :rtype: int 470 | """ 471 | return self._sample_rate 472 | 473 | @property 474 | def num_samples(self): 475 | """返回样品数量 476 | 477 | :return: Number of samples. 478 | :rtype: int 479 | """ 480 | return self._samples.shape[0] 481 | 482 | @property 483 | def duration(self): 484 | """返回音频持续时间 485 | 486 | :return: Audio duration in seconds. 487 | :rtype: float 488 | """ 489 | return self._samples.shape[0] / float(self._sample_rate) 490 | 491 | @property 492 | def rms_db(self): 493 | """返回以分贝为单位的音频均方根能量 494 | 495 | :return: Root mean square energy in decibels. 496 | :rtype: float 497 | """ 498 | # square root => multiply by 10 instead of 20 for dBs 499 | mean_square = np.mean(self._samples ** 2) 500 | return 10 * np.log10(mean_square) 501 | 502 | def _convert_samples_to_float32(self, samples): 503 | """Convert sample type to float32. 504 | 505 | Audio sample type is usually integer or float-point. 506 | Integers will be scaled to [-1, 1] in float32. 507 | """ 508 | float32_samples = samples.astype('float32') 509 | if samples.dtype in np.sctypes['int']: 510 | bits = np.iinfo(samples.dtype).bits 511 | float32_samples *= (1. / 2 ** (bits - 1)) 512 | elif samples.dtype in np.sctypes['float']: 513 | pass 514 | else: 515 | raise TypeError("Unsupported sample type: %s." % samples.dtype) 516 | return float32_samples 517 | 518 | def _convert_samples_from_float32(self, samples, dtype): 519 | """Convert sample type from float32 to dtype. 520 | 521 | Audio sample type is usually integer or float-point. For integer 522 | type, float32 will be rescaled from [-1, 1] to the maximum range 523 | supported by the integer type. 524 | 525 | This is for writing a audio file. 526 | """ 527 | dtype = np.dtype(dtype) 528 | output_samples = samples.copy() 529 | if dtype in np.sctypes['int']: 530 | bits = np.iinfo(dtype).bits 531 | output_samples *= (2 ** (bits - 1) / 1.) 532 | min_val = np.iinfo(dtype).min 533 | max_val = np.iinfo(dtype).max 534 | output_samples[output_samples > max_val] = max_val 535 | output_samples[output_samples < min_val] = min_val 536 | elif samples.dtype in np.sctypes['float']: 537 | min_val = np.finfo(dtype).min 538 | max_val = np.finfo(dtype).max 539 | output_samples[output_samples > max_val] = max_val 540 | output_samples[output_samples < min_val] = min_val 541 | else: 542 | raise TypeError("Unsupported sample type: %s." % samples.dtype) 543 | return output_samples.astype(dtype) 544 | -------------------------------------------------------------------------------- /mvector/data_utils/featurizer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torchaudio.transforms import MelSpectrogram, Spectrogram, MFCC 4 | 5 | 6 | class AudioFeaturizer(nn.Module): 7 | """音频特征器 8 | 9 | :param feature_method: 所使用的预处理方法 10 | :type feature_method: str 11 | :param feature_conf: 预处理方法的参数 12 | :type feature_conf: dict 13 | """ 14 | 15 | def __init__(self, feature_method='MelSpectrogram', feature_conf={}): 16 | super().__init__() 17 | self._feature_conf = feature_conf 18 | self._feature_method = feature_method 19 | if feature_method == 'MelSpectrogram': 20 | self.feat_fun = MelSpectrogram(**feature_conf) 21 | elif feature_method == 'Spectrogram': 22 | self.feat_fun = Spectrogram(**feature_conf) 23 | elif feature_method == 'MFCC': 24 | melkwargs = feature_conf.copy() 25 | del melkwargs['sample_rate'] 26 | del melkwargs['n_mfcc'] 27 | self.feat_fun = MFCC(sample_rate=self._feature_conf.sample_rate, 28 | n_mfcc=self._feature_conf.n_mfcc, 29 | melkwargs=melkwargs) 30 | else: 31 | raise Exception(f'预处理方法 {self._feature_method} 不存在!') 32 | 33 | def forward(self, waveforms, input_lens_ratio): 34 | """从AudioSegment中提取音频特征 35 | 36 | :param waveforms: Audio segment to extract features from. 37 | :type waveforms: AudioSegment 38 | :param input_lens_ratio: input length ratio 39 | :type input_lens_ratio: tensor 40 | :return: Spectrogram audio feature in 2darray. 41 | :rtype: ndarray 42 | """ 43 | feature = self.feat_fun(waveforms) 44 | feature = feature.transpose(2, 1) 45 | # 归一化 46 | mean = torch.mean(feature, 1, keepdim=True) 47 | std = torch.std(feature, 1, keepdim=True) 48 | feature = (feature - mean) / (std + 1e-5) 49 | # 对掩码比例进行扩展 50 | input_lens = (input_lens_ratio * feature.shape[1]) 51 | mask_lens = torch.round(input_lens).long() 52 | mask_lens = mask_lens.unsqueeze(1) 53 | input_lens = input_lens.int() 54 | # 生成掩码张量 55 | idxs = torch.arange(feature.shape[1], device=feature.device).repeat(feature.shape[0], 1) 56 | mask = idxs < mask_lens 57 | mask = mask.unsqueeze(-1) 58 | # 对特征进行掩码操作 59 | feature_masked = torch.where(mask, feature, torch.zeros_like(feature)) 60 | return feature_masked, input_lens 61 | 62 | @property 63 | def feature_dim(self): 64 | """返回特征大小 65 | 66 | :return: 特征大小 67 | :rtype: int 68 | """ 69 | if self._feature_method == 'LogMelSpectrogram': 70 | return self._feature_conf.n_mels 71 | elif self._feature_method == 'MelSpectrogram': 72 | return self._feature_conf.n_mels 73 | elif self._feature_method == 'Spectrogram': 74 | return self._feature_conf.n_fft // 2 + 1 75 | elif self._feature_method == 'MFCC': 76 | return self._feature_conf.n_mfcc 77 | else: 78 | raise Exception('没有{}预处理方法'.format(self._feature_method)) 79 | -------------------------------------------------------------------------------- /mvector/data_utils/utils.py: -------------------------------------------------------------------------------- 1 | import io 2 | import itertools 3 | 4 | import av 5 | import librosa 6 | import numpy as np 7 | import torch 8 | 9 | 10 | def vad(wav, top_db=20, overlap=200): 11 | # Split an audio signal into non-silent intervals 12 | intervals = librosa.effects.split(wav, top_db=top_db) 13 | if len(intervals) == 0: 14 | return wav 15 | wav_output = [np.array([])] 16 | for sliced in intervals: 17 | seg = wav[sliced[0]:sliced[1]] 18 | if len(seg) < 2 * overlap: 19 | wav_output[-1] = np.concatenate((wav_output[-1], seg)) 20 | else: 21 | wav_output.append(seg) 22 | wav_output = [x for x in wav_output if len(x) > 0] 23 | 24 | if len(wav_output) == 1: 25 | wav_output = wav_output[0] 26 | else: 27 | wav_output = concatenate(wav_output) 28 | return wav_output 29 | 30 | 31 | def concatenate(wave, overlap=200): 32 | total_len = sum([len(x) for x in wave]) 33 | unfolded = np.zeros(total_len) 34 | 35 | # Equal power crossfade 36 | window = np.hanning(2 * overlap) 37 | fade_in = window[:overlap] 38 | fade_out = window[-overlap:] 39 | 40 | end = total_len 41 | for i in range(1, len(wave)): 42 | prev = wave[i - 1] 43 | curr = wave[i] 44 | 45 | if i == 1: 46 | end = len(prev) 47 | unfolded[:end] += prev 48 | 49 | max_idx = 0 50 | max_corr = 0 51 | pattern = prev[-overlap:] 52 | # slide the curr batch to match with the pattern of previous one 53 | for j in range(overlap): 54 | match = curr[j:j + overlap] 55 | corr = np.sum(pattern * match) / [(np.sqrt(np.sum(pattern ** 2)) * np.sqrt(np.sum(match ** 2))) + 1e-8] 56 | if corr > max_corr: 57 | max_idx = j 58 | max_corr = corr 59 | 60 | # Apply the gain to the overlap samples 61 | start = end - overlap 62 | unfolded[start:end] *= fade_out 63 | end = start + (len(curr) - max_idx) 64 | curr[max_idx:max_idx + overlap] *= fade_in 65 | unfolded[start:end] += curr[max_idx:] 66 | return unfolded[:end] 67 | 68 | 69 | def decode_audio(file, sample_rate: int = 16000): 70 | """读取音频,主要用于兜底读取,支持各种数据格式 71 | 72 | Args: 73 | file: Path to the input file or a file-like object. 74 | sample_rate: Resample the audio to this sample rate. 75 | 76 | Returns: 77 | A float32 Numpy array. 78 | """ 79 | resampler = av.audio.resampler.AudioResampler(format="s16", layout="mono", rate=sample_rate) 80 | 81 | raw_buffer = io.BytesIO() 82 | dtype = None 83 | 84 | with av.open(file, metadata_errors="ignore") as container: 85 | frames = container.decode(audio=0) 86 | frames = _ignore_invalid_frames(frames) 87 | frames = _group_frames(frames, 500000) 88 | frames = _resample_frames(frames, resampler) 89 | 90 | for frame in frames: 91 | array = frame.to_ndarray() 92 | dtype = array.dtype 93 | raw_buffer.write(array) 94 | 95 | audio = np.frombuffer(raw_buffer.getbuffer(), dtype=dtype) 96 | 97 | # Convert s16 back to f32. 98 | return audio.astype(np.float32) / 32768.0 99 | 100 | 101 | def _ignore_invalid_frames(frames): 102 | iterator = iter(frames) 103 | 104 | while True: 105 | try: 106 | yield next(iterator) 107 | except StopIteration: 108 | break 109 | except av.error.InvalidDataError: 110 | continue 111 | 112 | 113 | def _group_frames(frames, num_samples=None): 114 | fifo = av.audio.fifo.AudioFifo() 115 | 116 | for frame in frames: 117 | frame.pts = None # Ignore timestamp check. 118 | fifo.write(frame) 119 | 120 | if num_samples is not None and fifo.samples >= num_samples: 121 | yield fifo.read() 122 | 123 | if fifo.samples > 0: 124 | yield fifo.read() 125 | 126 | 127 | def _resample_frames(frames, resampler): 128 | # Add None to flush the resampler. 129 | for frame in itertools.chain(frames, [None]): 130 | yield from resampler.resample(frame) 131 | 132 | 133 | # 将音频流转换为numpy 134 | def buf_to_float(x, n_bytes=2, dtype=np.float32): 135 | """Convert an integer buffer to floating point values. 136 | This is primarily useful when loading integer-valued wav data 137 | into numpy arrays. 138 | 139 | Parameters 140 | ---------- 141 | x : np.ndarray [dtype=int] 142 | The integer-valued data buffer 143 | 144 | n_bytes : int [1, 2, 4] 145 | The number of bytes per sample in ``x`` 146 | 147 | dtype : numeric type 148 | The target output type (default: 32-bit float) 149 | 150 | Returns 151 | ------- 152 | x_float : np.ndarray [dtype=float] 153 | The input data buffer cast to floating point 154 | """ 155 | 156 | # Invert the scale of the data 157 | scale = 1.0 / float(1 << ((8 * n_bytes) - 1)) 158 | 159 | # Construct the format string 160 | fmt = " relu -> bn 34 | sp = self.convs[i](sp) 35 | sp = self.bns[i](F.relu(sp)) 36 | out.append(sp) 37 | if self.scale != 1: 38 | out.append(spx[self.nums]) 39 | out = torch.cat(out, dim=1) 40 | return out 41 | 42 | 43 | class Conv1dReluBn(nn.Module): 44 | def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=False): 45 | super().__init__() 46 | self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, stride, padding, dilation, bias=bias) 47 | self.bn = nn.BatchNorm1d(out_channels) 48 | 49 | def forward(self, x): 50 | return self.bn(F.relu(self.conv(x))) 51 | 52 | 53 | class SE_Connect(nn.Module): 54 | def __init__(self, channels, s=2): 55 | super().__init__() 56 | assert channels % s == 0, "{} % {} != 0".format(channels, s) 57 | self.linear1 = nn.Linear(channels, channels // s) 58 | self.linear2 = nn.Linear(channels // s, channels) 59 | 60 | def forward(self, x): 61 | out = x.mean(dim=2) 62 | out = F.relu(self.linear1(out)) 63 | out = torch.sigmoid(self.linear2(out)) 64 | out = x * out.unsqueeze(2) 65 | return out 66 | 67 | 68 | def SE_Res2Block(channels, kernel_size, stride, padding, dilation, scale): 69 | return nn.Sequential( 70 | Conv1dReluBn(channels, channels, kernel_size=1, stride=1, padding=0), 71 | Res2Conv1dReluBn(channels, kernel_size, stride, padding, dilation, scale=scale), 72 | Conv1dReluBn(channels, channels, kernel_size=1, stride=1, padding=0), 73 | SE_Connect(channels) 74 | ) 75 | 76 | 77 | class EcapaTdnn(nn.Module): 78 | def __init__(self, input_size=80, channels=512, embd_dim=192, pooling_type="ASP"): 79 | super().__init__() 80 | self.layer1 = Conv1dReluBn(input_size, channels, kernel_size=5, padding=2, dilation=1) 81 | self.layer2 = SE_Res2Block(channels, kernel_size=3, stride=1, padding=2, dilation=2, scale=8) 82 | self.layer3 = SE_Res2Block(channels, kernel_size=3, stride=1, padding=3, dilation=3, scale=8) 83 | self.layer4 = SE_Res2Block(channels, kernel_size=3, stride=1, padding=4, dilation=4, scale=8) 84 | 85 | cat_channels = channels * 3 86 | self.emb_size = embd_dim 87 | self.conv = nn.Conv1d(cat_channels, cat_channels, kernel_size=1) 88 | if pooling_type == "ASP": 89 | self.pooling = AttentiveStatsPool(cat_channels, 128) 90 | self.bn1 = nn.BatchNorm1d(cat_channels * 2) 91 | self.linear = nn.Linear(cat_channels * 2, embd_dim) 92 | self.bn2 = nn.BatchNorm1d(embd_dim) 93 | elif pooling_type == "SAP": 94 | self.pooling = SelfAttentivePooling(cat_channels, 128) 95 | self.bn1 = nn.BatchNorm1d(cat_channels) 96 | self.linear = nn.Linear(cat_channels, embd_dim) 97 | self.bn2 = nn.BatchNorm1d(embd_dim) 98 | elif pooling_type == "TAP": 99 | self.pooling = TemporalAveragePooling() 100 | self.bn1 = nn.BatchNorm1d(cat_channels) 101 | self.linear = nn.Linear(cat_channels, embd_dim) 102 | self.bn2 = nn.BatchNorm1d(embd_dim) 103 | elif pooling_type == "TSP": 104 | self.pooling = TemporalStatisticsPooling() 105 | self.bn1 = nn.BatchNorm1d(cat_channels * 2) 106 | self.linear = nn.Linear(cat_channels * 2, embd_dim) 107 | self.bn2 = nn.BatchNorm1d(embd_dim) 108 | else: 109 | raise Exception(f'没有{pooling_type}池化层!') 110 | 111 | def forward(self, x): 112 | """ 113 | Compute embeddings. 114 | 115 | Args: 116 | x (torch.Tensor): Input data with shape (N, time, freq). 117 | 118 | Returns: 119 | torch.Tensor: Output embeddings with shape (N, self.emb_size, 1) 120 | """ 121 | x = x.transpose(2, 1) 122 | out1 = self.layer1(x) 123 | out2 = self.layer2(out1) + out1 124 | out3 = self.layer3(out1 + out2) + out1 + out2 125 | out4 = self.layer4(out1 + out2 + out3) + out1 + out2 + out3 126 | 127 | out = torch.cat([out2, out3, out4], dim=1) 128 | out = F.relu(self.conv(out)) 129 | out = self.bn1(self.pooling(out)) 130 | out = self.bn2(self.linear(out)) 131 | return out 132 | -------------------------------------------------------------------------------- /mvector/models/fc.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from torch.nn import Parameter 5 | 6 | 7 | class SpeakerIdetification(nn.Module): 8 | def __init__( 9 | self, 10 | backbone, 11 | num_class=1, 12 | loss_type='AAMLoss', 13 | lin_blocks=0, 14 | lin_neurons=192, 15 | dropout=0.1, ): 16 | """The speaker identification model, which includes the speaker backbone network 17 | and the a linear transform to speaker class num in training 18 | 19 | Args: 20 | backbone (Paddle.nn.Layer class): the speaker identification backbone network model 21 | num_class (_type_): the speaker class num in the training dataset 22 | lin_blocks (int, optional): the linear layer transform between the embedding and the final linear layer. Defaults to 0. 23 | lin_neurons (int, optional): the output dimension of final linear layer. Defaults to 192. 24 | dropout (float, optional): the dropout factor on the embedding. Defaults to 0.1. 25 | """ 26 | super(SpeakerIdetification, self).__init__() 27 | # speaker idenfication backbone network model 28 | # the output of the backbond network is the target embedding 29 | self.backbone = backbone 30 | self.loss_type = loss_type 31 | if dropout > 0: 32 | self.dropout = nn.Dropout(dropout) 33 | else: 34 | self.dropout = None 35 | 36 | # construct the speaker classifer 37 | input_size = self.backbone.emb_size 38 | self.blocks = list() 39 | for i in range(lin_blocks): 40 | self.blocks.extend([ 41 | nn.BatchNorm1d(input_size), 42 | nn.Linear(in_features=input_size, out_features=lin_neurons), 43 | ]) 44 | input_size = lin_neurons 45 | 46 | # the final layer 47 | if self.loss_type == 'AAMLoss': 48 | self.weight = Parameter(torch.FloatTensor(num_class, input_size), requires_grad=True) 49 | nn.init.xavier_normal_(self.weight, gain=1) 50 | elif self.loss_type == 'AMLoss' or self.loss_type == 'ARMLoss': 51 | self.weight = Parameter(torch.FloatTensor(input_size, num_class), requires_grad=True) 52 | nn.init.xavier_normal_(self.weight, gain=1) 53 | elif self.loss_type == 'CELoss': 54 | self.output = nn.Linear(input_size, num_class) 55 | else: 56 | raise Exception(f'没有{self.loss_type}损失函数!') 57 | 58 | def forward(self, x): 59 | """Do the speaker identification model forwrd, 60 | including the speaker embedding model and the classifier model network 61 | 62 | Args: 63 | x (paddle.Tensor): input audio feats, 64 | shape=[batch, times, dimension] 65 | 66 | Returns: 67 | paddle.Tensor: return the logits of the feats 68 | """ 69 | # x.shape: (N, L, C) 70 | x = self.backbone(x) # (N, emb_size) 71 | if self.dropout is not None: 72 | x = self.dropout(x) 73 | 74 | for fc in self.blocks: 75 | x = fc(x) 76 | if self.loss_type == 'AAMLoss': 77 | logits = F.linear(F.normalize(x), F.normalize(self.weight, dim=-1)) 78 | elif self.loss_type == 'AMLoss' or self.loss_type == 'ARMLoss': 79 | x_norm = torch.norm(x, p=2, dim=1, keepdim=True).clamp(min=1e-12) 80 | x_norm = torch.div(x, x_norm) 81 | w_norm = torch.norm(self.weight, p=2, dim=0, keepdim=True).clamp(min=1e-12) 82 | w_norm = torch.div(self.weight, w_norm) 83 | logits = torch.mm(x_norm, w_norm) 84 | else: 85 | logits = self.output(x) 86 | 87 | return logits 88 | -------------------------------------------------------------------------------- /mvector/models/loss.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | 7 | 8 | class AdditiveAngularMargin(nn.Module): 9 | def __init__(self, margin=0.0, scale=1.0, easy_margin=False): 10 | """The Implementation of Additive Angular Margin (AAM) proposed 11 | in the following paper: '''Margin Matters: Towards More Discriminative Deep Neural Network Embeddings for Speaker Recognition''' 12 | (https://arxiv.org/abs/1906.07317) 13 | 14 | Args: 15 | margin (float, optional): margin factor. Defaults to 0.0. 16 | scale (float, optional): scale factor. Defaults to 1.0. 17 | easy_margin (bool, optional): easy_margin flag. Defaults to False. 18 | """ 19 | super(AdditiveAngularMargin, self).__init__() 20 | self.margin = margin 21 | self.scale = scale 22 | self.easy_margin = easy_margin 23 | 24 | self.cos_m = math.cos(self.margin) 25 | self.sin_m = math.sin(self.margin) 26 | self.th = math.cos(math.pi - self.margin) 27 | self.mm = math.sin(math.pi - self.margin) * self.margin 28 | 29 | def forward(self, outputs, targets): 30 | cosine = outputs.float() 31 | sine = torch.sqrt(1.0 - torch.pow(cosine, 2)) 32 | phi = cosine * self.cos_m - sine * self.sin_m 33 | if self.easy_margin: 34 | phi = torch.where(cosine > 0, phi, cosine) 35 | else: 36 | phi = torch.where(cosine > self.th, phi, cosine - self.mm) 37 | outputs = (targets * phi) + ((1.0 - targets) * cosine) 38 | return self.scale * outputs 39 | 40 | 41 | class AAMLoss(nn.Module): 42 | def __init__(self, margin=0.2, scale=30, easy_margin=False): 43 | super(AAMLoss, self).__init__() 44 | self.loss_fn = AdditiveAngularMargin(margin=margin, scale=scale, easy_margin=easy_margin) 45 | self.criterion = torch.nn.KLDivLoss(reduction="sum") 46 | 47 | def forward(self, outputs, targets): 48 | targets = F.one_hot(targets, outputs.shape[1]).float() 49 | predictions = self.loss_fn(outputs, targets) 50 | predictions = F.log_softmax(predictions, dim=1) 51 | loss = self.criterion(predictions, targets) / targets.sum() 52 | return loss 53 | 54 | 55 | class AMLoss(nn.Module): 56 | def __init__(self, margin=0.2, scale=30): 57 | super(AMLoss, self).__init__() 58 | self.m = margin 59 | self.s = scale 60 | self.criterion = torch.nn.CrossEntropyLoss(reduction="sum") 61 | 62 | def forward(self, outputs, targets): 63 | label_view = targets.view(-1, 1) 64 | delt_costh = torch.zeros(outputs.size(), device=targets.device).scatter_(1, label_view, self.m) 65 | costh_m = outputs - delt_costh 66 | predictions = self.s * costh_m 67 | loss = self.criterion(predictions, targets) / targets.shape[0] 68 | return loss 69 | 70 | 71 | class ARMLoss(nn.Module): 72 | def __init__(self, margin=0.2, scale=30): 73 | super(ARMLoss, self).__init__() 74 | self.m = margin 75 | self.s = scale 76 | self.criterion = torch.nn.CrossEntropyLoss(reduction="sum") 77 | 78 | def forward(self, outputs, targets): 79 | label_view = targets.view(-1, 1) 80 | delt_costh = torch.zeros(outputs.size(), device=targets.device).scatter_(1, label_view, self.m) 81 | costh_m = outputs - delt_costh 82 | costh_m_s = self.s * costh_m 83 | delt_costh_m_s = costh_m_s.gather(1, label_view).repeat(1, costh_m_s.size()[1]) 84 | costh_m_s_reduct = costh_m_s - delt_costh_m_s 85 | predictions = torch.where(costh_m_s_reduct < 0.0, torch.zeros_like(costh_m_s), costh_m_s) 86 | loss = self.criterion(predictions, targets) / targets.shape[0] 87 | return loss 88 | 89 | 90 | class CELoss(nn.Module): 91 | def __init__(self): 92 | super(CELoss, self).__init__() 93 | self.criterion = torch.nn.CrossEntropyLoss(reduction="sum") 94 | 95 | def forward(self, outputs, targets): 96 | loss = self.criterion(outputs, targets) / targets.shape[0] 97 | return loss 98 | -------------------------------------------------------------------------------- /mvector/models/pooling.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | 5 | class TemporalAveragePooling(nn.Module): 6 | def __init__(self): 7 | """TAP 8 | Paper: Multi-Task Learning with High-Order Statistics for X-vector based Text-Independent Speaker Verification 9 | Link: https://arxiv.org/pdf/1903.12058.pdf 10 | """ 11 | super(TemporalAveragePooling, self).__init__() 12 | 13 | def forward(self, x): 14 | """Computes Temporal Average Pooling Module 15 | Args: 16 | x (torch.Tensor): Input tensor (#batch, channels, frames). 17 | Returns: 18 | torch.Tensor: Output tensor (#batch, channels) 19 | """ 20 | x = torch.mean(x, dim=2) 21 | return x 22 | 23 | 24 | class TemporalStatisticsPooling(nn.Module): 25 | def __init__(self): 26 | """TSP 27 | Paper: X-vectors: Robust DNN Embeddings for Speaker Recognition 28 | Link: http://www.danielpovey.com/files/2018_icassp_xvectors.pdf 29 | """ 30 | super(TemporalStatisticsPooling, self).__init__() 31 | 32 | def forward(self, x): 33 | """Computes Temporal Statistics Pooling Module 34 | Args: 35 | x (torch.Tensor): Input tensor (#batch, channels, frames). 36 | Returns: 37 | torch.Tensor: Output tensor (#batch, channels*2) 38 | """ 39 | mean = torch.mean(x, dim=2) 40 | var = torch.var(x, dim=2) 41 | x = torch.cat((mean, var), dim=1) 42 | return x 43 | 44 | 45 | class SelfAttentivePooling(nn.Module): 46 | def __init__(self, in_dim, bottleneck_dim=128): 47 | # Use Conv1d with stride == 1 rather than Linear, then we don't need to transpose inputs. 48 | # attention dim = 128 49 | super(SelfAttentivePooling, self).__init__() 50 | self.linear1 = nn.Conv1d(in_dim, bottleneck_dim, kernel_size=1) # equals W and b in the paper 51 | self.linear2 = nn.Conv1d(bottleneck_dim, in_dim, kernel_size=1) # equals V and k in the paper 52 | 53 | def forward(self, x): 54 | # DON'T use ReLU here! In experiments, I find ReLU hard to converge. 55 | alpha = torch.tanh(self.linear1(x)) 56 | alpha = torch.softmax(self.linear2(alpha), dim=2) 57 | mean = torch.sum(alpha * x, dim=2) 58 | return mean 59 | 60 | 61 | class AttentiveStatsPool(nn.Module): 62 | def __init__(self, in_dim, bottleneck_dim=128): 63 | super().__init__() 64 | # Use Conv1d with stride == 1 rather than Linear, then we don't need to transpose inputs. 65 | self.linear1 = nn.Conv1d(in_dim, bottleneck_dim, kernel_size=1) # equals W and b in the paper 66 | self.linear2 = nn.Conv1d(bottleneck_dim, in_dim, kernel_size=1) # equals V and k in the paper 67 | 68 | def forward(self, x): 69 | # DON'T use ReLU here! In experiments, I find ReLU hard to converge. 70 | alpha = torch.tanh(self.linear1(x)) 71 | alpha = torch.softmax(self.linear2(alpha), dim=2) 72 | mean = torch.sum(alpha * x, dim=2) 73 | residuals = torch.sum(alpha * x ** 2, dim=2) - mean ** 2 74 | std = torch.sqrt(residuals.clamp(min=1e-9)) 75 | return torch.cat([mean, std], dim=1) 76 | -------------------------------------------------------------------------------- /mvector/models/res2net.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | import torch 4 | import torch.nn as nn 5 | 6 | from mvector.models.pooling import AttentiveStatsPool, TemporalAveragePooling 7 | from mvector.models.pooling import SelfAttentivePooling, TemporalStatisticsPooling 8 | 9 | 10 | class Bottle2neck(nn.Module): 11 | expansion = 4 12 | 13 | def __init__(self, inplanes, planes, stride=1, downsample=None, baseWidth=26, scale=4, stype='normal'): 14 | """ Constructor 15 | Args: 16 | inplanes: input channel dimensionality 17 | planes: output channel dimensionality 18 | stride: conv stride. Replaces pooling layer. 19 | downsample: None when stride = 1 20 | baseWidth: basic width of conv3x3 21 | scale: number of scale. 22 | type: 'normal': normal set. 'stage': first block of a new stage. 23 | """ 24 | super(Bottle2neck, self).__init__() 25 | 26 | width = int(math.floor(planes * (baseWidth / 64.0))) 27 | self.conv1 = nn.Conv2d(inplanes, width * scale, kernel_size=1, bias=False) 28 | self.bn1 = nn.BatchNorm2d(width * scale) 29 | 30 | if scale == 1: 31 | self.nums = 1 32 | else: 33 | self.nums = scale - 1 34 | if stype == 'stage': 35 | self.pool = nn.AvgPool2d(kernel_size=3, stride=stride, padding=1) 36 | convs = [] 37 | bns = [] 38 | for i in range(self.nums): 39 | convs.append(nn.Conv2d(width, width, kernel_size=3, stride=stride, padding=1, bias=False)) 40 | bns.append(nn.BatchNorm2d(width)) 41 | self.convs = nn.ModuleList(convs) 42 | self.bns = nn.ModuleList(bns) 43 | 44 | self.conv3 = nn.Conv2d(width * scale, planes * self.expansion, kernel_size=1, bias=False) 45 | self.bn3 = nn.BatchNorm2d(planes * self.expansion) 46 | 47 | self.relu = nn.ReLU(inplace=True) 48 | self.downsample = downsample 49 | self.stype = stype 50 | self.scale = scale 51 | self.width = width 52 | 53 | def forward(self, x): 54 | residual = x 55 | 56 | out = self.conv1(x) 57 | out = self.bn1(out) 58 | out = self.relu(out) 59 | 60 | spx = torch.split(out, self.width, 1) 61 | for i in range(self.nums): 62 | if i == 0 or self.stype == 'stage': 63 | sp = spx[i] 64 | else: 65 | sp = sp + spx[i] 66 | sp = self.convs[i](sp) 67 | sp = self.relu(self.bns[i](sp)) 68 | if i == 0: 69 | out = sp 70 | else: 71 | out = torch.cat((out, sp), 1) 72 | if self.scale != 1 and self.stype == 'normal': 73 | out = torch.cat((out, spx[self.nums]), 1) 74 | elif self.scale != 1 and self.stype == 'stage': 75 | out = torch.cat((out, self.pool(spx[self.nums])), 1) 76 | 77 | out = self.conv3(out) 78 | out = self.bn3(out) 79 | 80 | if self.downsample is not None: 81 | residual = self.downsample(x) 82 | 83 | out += residual 84 | out = self.relu(out) 85 | 86 | return out 87 | 88 | 89 | class Res2Net(nn.Module): 90 | 91 | def __init__(self, input_size=80, layers=[3, 4, 6, 3], base_width=26, scale=4, embd_dim=192, pooling_type="ASP"): 92 | self.inplanes = 64 93 | super(Res2Net, self).__init__() 94 | self.base_width = base_width 95 | self.scale = scale 96 | self.emb_size = embd_dim 97 | self.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False) 98 | self.bn1 = nn.BatchNorm2d(64) 99 | self.relu = nn.ReLU(inplace=True) 100 | self.max_pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 101 | self.layer1 = self._make_layer(Bottle2neck, 64, layers[0]) 102 | self.layer2 = self._make_layer(Bottle2neck, 128, layers[1], stride=2) 103 | self.layer3 = self._make_layer(Bottle2neck, 256, layers[2], stride=2) 104 | self.layer4 = self._make_layer(Bottle2neck, 512, layers[3], stride=2) 105 | 106 | cat_channels = 512 * Bottle2neck.expansion * (input_size // 32) 107 | if pooling_type == "ASP": 108 | self.pooling = AttentiveStatsPool(cat_channels, 128) 109 | self.bn2 = nn.BatchNorm1d(cat_channels * 2) 110 | self.linear = nn.Linear(cat_channels * 2, embd_dim) 111 | self.bn3 = nn.BatchNorm1d(embd_dim) 112 | elif pooling_type == "SAP": 113 | self.pooling = SelfAttentivePooling(cat_channels, 128) 114 | self.bn2 = nn.BatchNorm1d(cat_channels) 115 | self.linear = nn.Linear(cat_channels, embd_dim) 116 | self.bn3 = nn.BatchNorm1d(embd_dim) 117 | elif pooling_type == "TAP": 118 | self.pooling = TemporalAveragePooling() 119 | self.bn2 = nn.BatchNorm1d(cat_channels) 120 | self.linear = nn.Linear(cat_channels, embd_dim) 121 | self.bn3 = nn.BatchNorm1d(embd_dim) 122 | elif pooling_type == "TSP": 123 | self.pooling = TemporalStatisticsPooling() 124 | self.bn2 = nn.BatchNorm1d(cat_channels * 2) 125 | self.linear = nn.Linear(cat_channels * 2, embd_dim) 126 | self.bn3 = nn.BatchNorm1d(embd_dim) 127 | else: 128 | raise Exception(f'没有{pooling_type}池化层!') 129 | 130 | for m in self.modules(): 131 | if isinstance(m, nn.Conv2d): 132 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 133 | elif isinstance(m, nn.BatchNorm2d): 134 | nn.init.constant_(m.weight, 1) 135 | nn.init.constant_(m.bias, 0) 136 | 137 | def _make_layer(self, block, planes, blocks, stride=1): 138 | downsample = None 139 | if stride != 1 or self.inplanes != planes * block.expansion: 140 | downsample = nn.Sequential( 141 | nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), 142 | nn.BatchNorm2d(planes * block.expansion), 143 | ) 144 | 145 | layers = [block(self.inplanes, planes, stride, downsample=downsample, 146 | stype='stage', baseWidth=self.base_width, scale=self.scale)] 147 | self.inplanes = planes * block.expansion 148 | for i in range(1, blocks): 149 | layers.append(block(self.inplanes, planes, baseWidth=self.base_width, scale=self.scale)) 150 | 151 | return nn.Sequential(*layers) 152 | 153 | def forward(self, x): 154 | x = x.transpose(2, 1) 155 | x = x.unsqueeze(1) 156 | x = self.conv1(x) 157 | x = self.bn1(x) 158 | x = self.relu(x) 159 | x = self.max_pool(x) 160 | 161 | x = self.layer1(x) 162 | x = self.layer2(x) 163 | x = self.layer3(x) 164 | x = self.layer4(x) 165 | 166 | x = x.reshape(x.shape[0], -1, x.shape[-1]) 167 | 168 | x = self.pooling(x) 169 | x = self.bn2(x) 170 | x = self.linear(x) 171 | x = self.bn3(x) 172 | 173 | return x 174 | -------------------------------------------------------------------------------- /mvector/models/resnet_se.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | 3 | from mvector.models.pooling import AttentiveStatsPool, TemporalAveragePooling 4 | from mvector.models.pooling import SelfAttentivePooling, TemporalStatisticsPooling 5 | 6 | 7 | class SEBasicBlock(nn.Module): 8 | expansion = 1 9 | 10 | def __init__(self, inplanes, planes, stride=1, downsample=None, reduction=8): 11 | super(SEBasicBlock, self).__init__() 12 | self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 13 | self.bn1 = nn.BatchNorm2d(planes) 14 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1, bias=False) 15 | self.bn2 = nn.BatchNorm2d(planes) 16 | self.relu = nn.ReLU(inplace=True) 17 | self.se = SELayer(planes, reduction) 18 | self.downsample = downsample 19 | self.stride = stride 20 | 21 | def forward(self, x): 22 | residual = x 23 | 24 | out = self.conv1(x) 25 | out = self.relu(out) 26 | out = self.bn1(out) 27 | 28 | out = self.conv2(out) 29 | out = self.bn2(out) 30 | out = self.se(out) 31 | 32 | if self.downsample is not None: 33 | residual = self.downsample(x) 34 | 35 | out += residual 36 | out = self.relu(out) 37 | return out 38 | 39 | 40 | class SEBottleneck(nn.Module): 41 | expansion = 4 42 | 43 | def __init__(self, inplanes, planes, stride=1, downsample=None, reduction=8): 44 | super(SEBottleneck, self).__init__() 45 | self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) 46 | self.bn1 = nn.BatchNorm2d(planes) 47 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 48 | self.bn2 = nn.BatchNorm2d(planes) 49 | self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) 50 | self.bn3 = nn.BatchNorm2d(planes * 4) 51 | self.relu = nn.ReLU(inplace=True) 52 | self.se = SELayer(planes * 4, reduction) 53 | self.downsample = downsample 54 | self.stride = stride 55 | 56 | def forward(self, x): 57 | residual = x 58 | 59 | out = self.conv1(x) 60 | out = self.bn1(out) 61 | out = self.relu(out) 62 | 63 | out = self.conv2(out) 64 | out = self.bn2(out) 65 | out = self.relu(out) 66 | 67 | out = self.conv3(out) 68 | out = self.bn3(out) 69 | out = self.se(out) 70 | 71 | if self.downsample is not None: 72 | residual = self.downsample(x) 73 | 74 | out += residual 75 | out = self.relu(out) 76 | 77 | return out 78 | 79 | 80 | class SELayer(nn.Module): 81 | def __init__(self, channel, reduction=8): 82 | super(SELayer, self).__init__() 83 | self.avg_pool = nn.AdaptiveAvgPool2d(1) 84 | self.fc = nn.Sequential( 85 | nn.Linear(channel, channel // reduction), 86 | nn.ReLU(inplace=True), 87 | nn.Linear(channel // reduction, channel), 88 | nn.Sigmoid() 89 | ) 90 | 91 | def forward(self, x): 92 | b, c, _, _ = x.size() 93 | y = self.avg_pool(x).view(b, c) 94 | y = self.fc(y).view(b, c, 1, 1) 95 | return x * y 96 | 97 | 98 | class ResNetSE(nn.Module): 99 | def __init__(self, input_size=80, layers=[3, 4, 6, 3], num_filters=[32, 64, 128, 256], embd_dim=192, 100 | pooling_type="ASP"): 101 | super(ResNetSE, self).__init__() 102 | self.inplanes = num_filters[0] 103 | self.emb_size = embd_dim 104 | self.conv1 = nn.Conv2d(1, num_filters[0], kernel_size=3, stride=(1, 1), padding=1, bias=False) 105 | self.bn1 = nn.BatchNorm2d(num_filters[0]) 106 | self.relu = nn.ReLU(inplace=True) 107 | 108 | self.layer1 = self._make_layer(SEBottleneck, num_filters[0], layers[0]) 109 | self.layer2 = self._make_layer(SEBottleneck, num_filters[1], layers[1], stride=(2, 2)) 110 | self.layer3 = self._make_layer(SEBottleneck, num_filters[2], layers[2], stride=(2, 2)) 111 | self.layer4 = self._make_layer(SEBottleneck, num_filters[3], layers[3], stride=(2, 2)) 112 | 113 | cat_channels = num_filters[3] * SEBottleneck.expansion * (input_size // 8) 114 | if pooling_type == "ASP": 115 | self.pooling = AttentiveStatsPool(cat_channels, 128) 116 | self.bn2 = nn.BatchNorm1d(cat_channels * 2) 117 | self.linear = nn.Linear(cat_channels * 2, embd_dim) 118 | self.bn3 = nn.BatchNorm1d(embd_dim) 119 | elif pooling_type == "SAP": 120 | self.pooling = SelfAttentivePooling(cat_channels, 128) 121 | self.bn2 = nn.BatchNorm1d(cat_channels) 122 | self.linear = nn.Linear(cat_channels, embd_dim) 123 | self.bn3 = nn.BatchNorm1d(embd_dim) 124 | elif pooling_type == "TAP": 125 | self.pooling = TemporalAveragePooling() 126 | self.bn2 = nn.BatchNorm1d(cat_channels) 127 | self.linear = nn.Linear(cat_channels, embd_dim) 128 | self.bn3 = nn.BatchNorm1d(embd_dim) 129 | elif pooling_type == "TSP": 130 | self.pooling = TemporalStatisticsPooling() 131 | self.bn2 = nn.BatchNorm1d(cat_channels * 2) 132 | self.linear = nn.Linear(cat_channels * 2, embd_dim) 133 | self.bn3 = nn.BatchNorm1d(embd_dim) 134 | else: 135 | raise Exception(f'没有{pooling_type}池化层!') 136 | 137 | for m in self.modules(): 138 | if isinstance(m, nn.Conv2d): 139 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 140 | elif isinstance(m, nn.BatchNorm2d): 141 | nn.init.constant_(m.weight, 1) 142 | nn.init.constant_(m.bias, 0) 143 | 144 | def _make_layer(self, block, planes, blocks, stride=1): 145 | downsample = None 146 | if stride != 1 or self.inplanes != planes * block.expansion: 147 | downsample = nn.Sequential( 148 | nn.Conv2d(self.inplanes, planes * block.expansion, 149 | kernel_size=1, stride=stride, bias=False), 150 | nn.BatchNorm2d(planes * block.expansion), 151 | ) 152 | 153 | layers = [block(self.inplanes, planes, stride, downsample)] 154 | self.inplanes = planes * block.expansion 155 | for i in range(1, blocks): 156 | layers.append(block(self.inplanes, planes)) 157 | 158 | return nn.Sequential(*layers) 159 | 160 | def forward(self, x): 161 | x = x.transpose(2, 1) 162 | x = x.unsqueeze(1) 163 | x = self.conv1(x) 164 | x = self.bn1(x) 165 | x = self.relu(x) 166 | 167 | x = self.layer1(x) 168 | x = self.layer2(x) 169 | x = self.layer3(x) 170 | x = self.layer4(x) 171 | 172 | x = x.reshape(x.shape[0], -1, x.shape[-1]) 173 | 174 | x = self.pooling(x) 175 | x = self.bn2(x) 176 | x = self.linear(x) 177 | x = self.bn3(x) 178 | return x 179 | -------------------------------------------------------------------------------- /mvector/models/tdnn.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | from mvector.models.pooling import AttentiveStatsPool, TemporalAveragePooling 6 | from mvector.models.pooling import SelfAttentivePooling, TemporalStatisticsPooling 7 | 8 | 9 | class TDNN(nn.Module): 10 | def __init__(self, input_size=80, channels=512, embd_dim=192, pooling_type="ASP"): 11 | super(TDNN, self).__init__() 12 | self.emb_size = embd_dim 13 | self.td_layer1 = torch.nn.Conv1d(in_channels=input_size, out_channels=512, dilation=1, kernel_size=5, stride=1) 14 | self.bn1 = nn.BatchNorm1d(512) 15 | self.td_layer2 = torch.nn.Conv1d(in_channels=512, out_channels=512, dilation=2, kernel_size=3, stride=1) 16 | self.bn2 = nn.BatchNorm1d(512) 17 | self.td_layer3 = torch.nn.Conv1d(in_channels=512, out_channels=512, dilation=3, kernel_size=3, stride=1) 18 | self.bn3 = nn.BatchNorm1d(512) 19 | self.td_layer4 = torch.nn.Conv1d(in_channels=512, out_channels=512, dilation=1, kernel_size=1, stride=1) 20 | self.bn4 = nn.BatchNorm1d(512) 21 | self.td_layer5 = torch.nn.Conv1d(in_channels=512, out_channels=channels, dilation=1, kernel_size=1, stride=1) 22 | 23 | if pooling_type == "ASP": 24 | self.pooling = AttentiveStatsPool(channels, 128) 25 | self.bn5 = nn.BatchNorm1d(channels * 2) 26 | self.linear = nn.Linear(channels * 2, embd_dim) 27 | self.bn6 = nn.BatchNorm1d(embd_dim) 28 | elif pooling_type == "SAP": 29 | self.pooling = SelfAttentivePooling(channels, 128) 30 | self.bn5 = nn.BatchNorm1d(channels) 31 | self.linear = nn.Linear(channels, embd_dim) 32 | self.bn6 = nn.BatchNorm1d(embd_dim) 33 | elif pooling_type == "TAP": 34 | self.pooling = TemporalAveragePooling() 35 | self.bn5 = nn.BatchNorm1d(channels) 36 | self.linear = nn.Linear(channels, embd_dim) 37 | self.bn6 = nn.BatchNorm1d(embd_dim) 38 | elif pooling_type == "TSP": 39 | self.pooling = TemporalStatisticsPooling() 40 | self.bn5 = nn.BatchNorm1d(channels * 2) 41 | self.linear = nn.Linear(channels * 2, embd_dim) 42 | self.bn6 = nn.BatchNorm1d(embd_dim) 43 | else: 44 | raise Exception(f'没有{pooling_type}池化层!') 45 | 46 | def forward(self, x): 47 | """ 48 | Compute embeddings. 49 | 50 | Args: 51 | x (torch.Tensor): Input data with shape (N, time, freq). 52 | 53 | Returns: 54 | torch.Tensor: Output embeddings with shape (N, self.emb_size, 1) 55 | """ 56 | x = x.transpose(2, 1) 57 | x = F.relu(self.td_layer1(x)) 58 | x = self.bn1(x) 59 | x = F.relu(self.td_layer2(x)) 60 | x = self.bn2(x) 61 | x = F.relu(self.td_layer3(x)) 62 | x = self.bn3(x) 63 | x = F.relu(self.td_layer4(x)) 64 | x = self.bn4(x) 65 | x = F.relu(self.td_layer5(x)) 66 | out = self.bn5(self.pooling(x)) 67 | out = self.bn6(self.linear(out)) 68 | return out 69 | -------------------------------------------------------------------------------- /mvector/predict.py: -------------------------------------------------------------------------------- 1 | # The original author is yeyupiaoling, modified by 2DIPW 2 | import os 3 | from io import BufferedReader 4 | 5 | import numpy as np 6 | import torch 7 | import yaml 8 | from collections import Counter 9 | from sklearn.metrics.pairwise import cosine_similarity 10 | from tqdm import tqdm 11 | 12 | from mvector import SUPPORT_MODEL 13 | from mvector.data_utils.audio import AudioSegment 14 | from mvector.data_utils.featurizer import AudioFeaturizer 15 | from mvector.models.ecapa_tdnn import EcapaTdnn 16 | from mvector.models.fc import SpeakerIdetification 17 | from mvector.models.res2net import Res2Net 18 | from mvector.models.resnet_se import ResNetSE 19 | from mvector.models.tdnn import TDNN 20 | from mvector.utils.logger import setup_logger 21 | from mvector.utils.utils import dict_to_object 22 | 23 | logger = setup_logger(__name__) 24 | 25 | 26 | class MVectorPredictor: 27 | def __init__(self, 28 | configs, 29 | threshold=0.6, 30 | label_path=None, 31 | model_path='./model', 32 | use_gpu=True): 33 | """ 34 | 声纹识别预测工具 35 | :param configs: 配置参数 36 | :param threshold: 判断是否为同一个人的阈值 37 | :param label_path: 声纹库路径 38 | :param model_path: 导出的预测模型文件夹路径 39 | :param use_gpu: 是否使用GPU预测 40 | """ 41 | if use_gpu: 42 | assert (torch.cuda.is_available()), 'GPU not available.' 43 | self.device = torch.device("cuda") 44 | else: 45 | os.environ['CUDA_VISIBLE_DEVICES'] = '-1' 46 | self.device = torch.device("cpu") 47 | # 索引候选数量 48 | # self.cdd_num = 5 49 | self.threshold = threshold 50 | # 读取配置文件 51 | if isinstance(configs, str): 52 | with open(configs, 'r', encoding='utf-8') as f: 53 | configs = yaml.load(f.read(), Loader=yaml.FullLoader) 54 | self.configs = dict_to_object(configs) 55 | assert 'max_duration' in self.configs.dataset_conf, \ 56 | 'You are using an old version of model which is no longer supported.' 57 | assert self.configs.use_model in SUPPORT_MODEL, f'Model not existed:{self.configs.use_model}' 58 | self._audio_featurizer = AudioFeaturizer(feature_conf=self.configs.feature_conf, **self.configs.preprocess_conf) 59 | self._audio_featurizer.to(self.device) 60 | # 获取模型 61 | if self.configs.use_model == 'EcapaTdnn' or self.configs.use_model == 'ecapa_tdnn': 62 | backbone = EcapaTdnn(input_size=self._audio_featurizer.feature_dim, **self.configs.model_conf) 63 | elif self.configs.use_model == 'Res2Net': 64 | backbone = Res2Net(input_size=self._audio_featurizer.feature_dim, **self.configs.model_conf) 65 | elif self.configs.use_model == 'ResNetSE': 66 | backbone = ResNetSE(input_size=self._audio_featurizer.feature_dim, **self.configs.model_conf) 67 | elif self.configs.use_model == 'TDNN': 68 | backbone = TDNN(input_size=self._audio_featurizer.feature_dim, **self.configs.model_conf) 69 | else: 70 | raise Exception(f'{self.configs.use_model} model not existed!') 71 | model = SpeakerIdetification(backbone=backbone, num_class=self.configs.dataset_conf.num_speakers) 72 | model.to(self.device) 73 | # 加载模型 74 | if os.path.isdir(model_path): 75 | model_path = os.path.join(model_path, 'model.pt') 76 | assert os.path.exists(model_path), f"{model_path} model not existed!" 77 | if torch.cuda.is_available() and use_gpu: 78 | model_state_dict = torch.load(model_path) 79 | else: 80 | model_state_dict = torch.load(model_path, map_location='cpu') 81 | model.load_state_dict(model_state_dict) 82 | print(f"Model loaded successfully:{model_path}") 83 | model.eval() 84 | self.predictor = model.backbone 85 | 86 | # 声纹库的声纹特征 87 | self.audio_feature = None 88 | # 声纹特征对应的用户名 89 | self.users_name = [] 90 | # 声纹特征对应的声纹文件路径 91 | self.users_audio_path = [] 92 | # 加载声纹库 93 | self.audio_db_path = label_path 94 | #if self.audio_db_path is not None: 95 | assert (self.audio_db_path is not None), 'Voice feature library path not found.' 96 | # 加载声纹库中的声纹 97 | self.__load_faces(self.audio_db_path) 98 | 99 | # 加载声纹库中的声纹 100 | def __load_faces(self, audio_db_path): 101 | # 先加载声纹特征索引 102 | os.makedirs(audio_db_path, exist_ok=True) 103 | audios_path = [] 104 | for name in os.listdir(audio_db_path): 105 | audio_dir = os.path.join(audio_db_path, name) 106 | if not os.path.isdir(audio_dir): continue 107 | for file in os.listdir(audio_dir): 108 | audios_path.append(os.path.join(audio_dir, file).replace('\\', '/')) 109 | # 声纹库没数据就报错 110 | assert (len(audios_path) > 0), "Voice feature library is empty." 111 | print("Loading voice feature library...") 112 | input_audios = [] 113 | for audio_path in tqdm(audios_path): 114 | # 如果声纹特征已经在索引就跳过 115 | if audio_path in self.users_audio_path: continue 116 | # 读取声纹库音频 117 | audio_segment = self._load_audio(audio_path) 118 | # 获取用户名 119 | user_name = os.path.basename(os.path.dirname(audio_path)) 120 | self.users_name.append(user_name) 121 | self.users_audio_path.append(audio_path) 122 | input_audios.append(audio_segment.samples) 123 | # 处理一批数据 124 | if len(input_audios) == self.configs.dataset_conf.batch_size: 125 | features = self.predict_batch(input_audios) 126 | if self.audio_feature is None: 127 | self.audio_feature = features 128 | else: 129 | self.audio_feature = np.vstack((self.audio_feature, features)) 130 | input_audios = [] 131 | # 处理不满一批的数据 132 | if len(input_audios) != 0: 133 | features = self.predict_batch(input_audios) 134 | if self.audio_feature is None: 135 | self.audio_feature = features 136 | else: 137 | self.audio_feature = np.vstack((self.audio_feature, features)) 138 | assert len(self.audio_feature) == len(self.users_name) == len(self.users_audio_path), 'Labels count conflict.' 139 | print("Voice feature library loaded successfully.") 140 | 141 | # 声纹检索 142 | def __retrieval(self, np_feature): 143 | results = [] 144 | for feature in np_feature: 145 | similarity = cosine_similarity(self.audio_feature, feature[np.newaxis, :]).squeeze() 146 | abs_similarity = np.abs(similarity) 147 | # 获取候选索引 148 | #if len(abs_similarity) < self.cdd_num: 149 | # candidate_idx = np.argpartition(abs_similarity, -len(abs_similarity))[-len(abs_similarity):] 150 | #else: 151 | # candidate_idx = np.argpartition(abs_similarity, -self.cdd_num)[-self.cdd_num:] 152 | # 过滤低于阈值的索引 153 | # remove_idx = np.where(abs_similarity < self.threshold) 154 | # candidate_idx = np.delete(candidate_idx, remove_idx) 155 | candidate_idx = np.where(abs_similarity >= self.threshold) 156 | # 获取标签最多的值 157 | candidate_label_list = list(np.array(self.users_name)[candidate_idx]) 158 | if len(candidate_label_list) == 0: 159 | results.append({"label": None, "similarity": None}) 160 | else: 161 | #max_label = max(candidate_label_list, key=candidate_label_list.count) 162 | # 这里做出的修改是考虑到如果有多个说话人命中的特征片段数量一样,原代码将会判定为顺序最靠前的说话人 163 | # 修改成下面的代码后,将会判定为相似度最大的说话人 164 | counter = Counter(candidate_label_list) 165 | max_count = max(counter.values()) 166 | max_labels = [elem for elem, count in counter.items() if count == max_count] 167 | max_label_dict = {} 168 | for max_label in max_labels: # 对于每个命中的说话人 169 | idx_for_max_label = [i for i, x in enumerate(self.users_name) if x == max_label] # 取其命中的片段的索引 170 | similarity_for_max_label = max(abs_similarity[idx_for_max_label]) # 取其命中的的所有片段中最大的相似度 171 | max_label_dict[max_label] = similarity_for_max_label 172 | result_label = max(zip(max_label_dict.values(), max_label_dict.keys())) # 判断相似度最大的说话人 173 | results.append({"label": result_label[1], "similarity": result_label[0]}) 174 | return results 175 | 176 | def _load_audio(self, audio_data, sample_rate=16000): 177 | """加载音频 178 | :param audio_data: 需要识别的数据,支持文件路径,文件对象,字节,numpy。如果是字节的话,必须是完整的字节文件 179 | :param sample_rate: 如果传入的事numpy数据,需要指定采样率 180 | :return: 识别的文本结果和解码的得分数 181 | """ 182 | # 加载音频文件,并进行预处理 183 | if isinstance(audio_data, str): 184 | audio_segment = AudioSegment.from_file(audio_data) 185 | elif isinstance(audio_data, BufferedReader): 186 | audio_segment = AudioSegment.from_file(audio_data) 187 | elif isinstance(audio_data, np.ndarray): 188 | audio_segment = AudioSegment.from_ndarray(audio_data, sample_rate) 189 | elif isinstance(audio_data, bytes): 190 | audio_segment = AudioSegment.from_bytes(audio_data) 191 | else: 192 | raise Exception(f'不支持该数据类型,当前数据类型为:{type(audio_data)}') 193 | assert audio_segment.duration >= self.configs.dataset_conf.min_duration, \ 194 | f'Audio segment too short,minimum is {self.configs.dataset_conf.min_duration}s,current is{audio_segment.duration}s' 195 | # 重采样 196 | if audio_segment.sample_rate != self.configs.dataset_conf.sample_rate: 197 | audio_segment.resample(self.configs.dataset_conf.sample_rate) 198 | # decibel normalization 199 | if self.configs.dataset_conf.use_dB_normalization: 200 | audio_segment.normalize(target_db=self.configs.dataset_conf.target_dB) 201 | return audio_segment 202 | 203 | def predict(self, 204 | audio_data, 205 | sample_rate=16000): 206 | """预测一个音频的特征 207 | 208 | :param audio_data: 需要识别的数据,支持文件路径,文件对象,字节,numpy。如果是字节的话,必须是完整并带格式的字节文件 209 | :param sample_rate: 如果传入的事numpy数据,需要指定采样率 210 | :return: 声纹特征向量 211 | """ 212 | # 加载音频文件,并进行预处理 213 | input_data = self._load_audio(audio_data=audio_data, sample_rate=sample_rate) 214 | input_data = torch.tensor(input_data.samples, dtype=torch.float32, device=self.device).unsqueeze(0) 215 | input_len_ratio = torch.tensor([1], dtype=torch.float32, device=self.device) 216 | audio_feature, _ = self._audio_featurizer(input_data, input_len_ratio) 217 | # 执行预测 218 | feature = self.predictor(audio_feature).data.cpu().numpy()[0] 219 | return feature 220 | 221 | def predict_batch(self, audios_data, sample_rate=16000): 222 | """预测一批音频的特征 223 | 224 | :param audios_data: 需要识别的数据,支持文件路径,文件对象,字节,numpy。如果是字节的话,必须是完整并带格式的字节文件 225 | :param sample_rate: 如果传入的事numpy数据,需要指定采样率 226 | :return: 声纹特征向量 227 | """ 228 | audios_data1 = [] 229 | for audio_data in audios_data: 230 | # 加载音频文件,并进行预处理 231 | input_data = self._load_audio(audio_data=audio_data, sample_rate=sample_rate) 232 | audios_data1.append(input_data.samples) 233 | # 找出音频长度最长的 234 | batch = sorted(audios_data1, key=lambda a: a.shape[0], reverse=True) 235 | max_audio_length = batch[0].shape[0] 236 | batch_size = len(batch) 237 | # 以最大的长度创建0张量 238 | inputs = np.zeros((batch_size, max_audio_length), dtype='float32') 239 | input_lens_ratio = [] 240 | for x in range(batch_size): 241 | tensor = audios_data1[x] 242 | seq_length = tensor.shape[0] 243 | # 将数据插入都0张量中,实现了padding 244 | inputs[x, :seq_length] = tensor[:] 245 | input_lens_ratio.append(seq_length / max_audio_length) 246 | audios_data = torch.tensor(inputs, dtype=torch.float32, device=self.device) 247 | input_lens_ratio = torch.tensor(input_lens_ratio, dtype=torch.float32, device=self.device) 248 | audio_feature, _ = self._audio_featurizer(audios_data, input_lens_ratio) 249 | # 执行预测 250 | features = self.predictor(audio_feature).data.cpu().numpy() 251 | return features 252 | 253 | def recognition(self, audio_data, threshold=None, sample_rate=16000): 254 | """声纹识别 255 | :param audio_data: 需要识别的数据,支持文件路径,文件对象,字节,numpy。如果是字节的话,必须是完整的字节文件 256 | :param threshold: 判断的阈值,如果为None则用创建对象时使用的阈值 257 | :param sample_rate: 如果传入的事numpy数据,需要指定采样率 258 | :return: 识别的用户名称,如果为None,即没有识别到用户 259 | """ 260 | if threshold: 261 | self.threshold = threshold 262 | feature = self.predict(audio_data, sample_rate=sample_rate) 263 | result = self.__retrieval(np_feature=[feature])[0] 264 | return result["label"], result["similarity"] 265 | -------------------------------------------------------------------------------- /mvector/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2DIPW/audio_dataset_vpr/1b88767aa5792762626989d64910e599fc4a6bd9/mvector/utils/__init__.py -------------------------------------------------------------------------------- /mvector/utils/logger.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import logging 3 | import os 4 | import sys 5 | import termcolor 6 | 7 | __all__ = ['setup_logger'] 8 | 9 | logger_initialized = [] 10 | 11 | 12 | def setup_logger(name, output=None): 13 | """ 14 | Initialize logger and set its verbosity level to INFO. 15 | Args: 16 | output (str): a file name or a directory to save log. If None, will not save log file. 17 | If ends with ".txt" or ".log", assumed to be a file name. 18 | Otherwise, logs will be saved to `output/log.txt`. 19 | name (str): the root module name of this logger 20 | 21 | Returns: 22 | logging.Logger: a logger 23 | """ 24 | logger = logging.getLogger(name) 25 | if name in logger_initialized: 26 | return logger 27 | 28 | logger.setLevel(logging.INFO) 29 | logger.propagate = False 30 | 31 | formatter = ("[%(asctime2)s %(levelname2)s] %(module2)s:%(funcName2)s:%(lineno2)s - %(message2)s") 32 | color_formatter = ColoredFormatter(formatter, datefmt="%m/%d %H:%M:%S") 33 | 34 | ch = logging.StreamHandler(stream=sys.stdout) 35 | ch.setLevel(logging.DEBUG) 36 | ch.setFormatter(color_formatter) 37 | logger.addHandler(ch) 38 | 39 | # file logging: all workers 40 | if output is not None: 41 | if output.endswith(".txt") or output.endswith(".log"): 42 | filename = output 43 | else: 44 | filename = os.path.join(output, "log.txt") 45 | os.makedirs(os.path.dirname(filename)) 46 | fh = logging.FileHandler(filename, mode='a') 47 | fh.setLevel(logging.DEBUG) 48 | fh.setFormatter(logging.Formatter()) 49 | logger.addHandler(fh) 50 | logger_initialized.append(name) 51 | return logger 52 | 53 | 54 | COLORS = { 55 | "WARNING": "yellow", 56 | "INFO": "white", 57 | "DEBUG": "blue", 58 | "CRITICAL": "red", 59 | "ERROR": "red", 60 | } 61 | 62 | 63 | class ColoredFormatter(logging.Formatter): 64 | def __init__(self, fmt, datefmt, use_color=True): 65 | logging.Formatter.__init__(self, fmt, datefmt=datefmt) 66 | self.use_color = use_color 67 | 68 | def format(self, record): 69 | levelname = record.levelname 70 | if self.use_color and levelname in COLORS: 71 | 72 | def colored(text): 73 | return termcolor.colored( 74 | text, 75 | color=COLORS[levelname], 76 | attrs={"bold": True}, 77 | ) 78 | 79 | record.levelname2 = colored("{:<7}".format(record.levelname)) 80 | record.message2 = colored(record.msg) 81 | 82 | asctime2 = datetime.datetime.fromtimestamp(record.created) 83 | record.asctime2 = termcolor.colored(asctime2, color="green") 84 | 85 | record.module2 = termcolor.colored(record.module, color="cyan") 86 | record.funcName2 = termcolor.colored(record.funcName, color="cyan") 87 | record.lineno2 = termcolor.colored(record.lineno, color="cyan") 88 | return logging.Formatter.format(self, record) 89 | 90 | -------------------------------------------------------------------------------- /mvector/utils/utils.py: -------------------------------------------------------------------------------- 1 | import distutils.util 2 | 3 | import numpy as np 4 | from tqdm import tqdm 5 | 6 | 7 | class Dict(dict): 8 | __setattr__ = dict.__setitem__ 9 | __getattr__ = dict.__getitem__ 10 | 11 | 12 | def dict_to_object(dict_obj): 13 | if not isinstance(dict_obj, dict): 14 | return dict_obj 15 | inst = Dict() 16 | for k, v in dict_obj.items(): 17 | inst[k] = dict_to_object(v) 18 | return inst 19 | 20 | 21 | # 根据对角余弦值计算准确率和最优的阈值 22 | def cal_accuracy_threshold(y_score, y_true): 23 | y_score = np.asarray(y_score) 24 | y_true = np.asarray(y_true) 25 | best_accuracy = 0 26 | best_threshold = 0 27 | for i in tqdm(range(0, 100)): 28 | threshold = i * 0.01 29 | y_test = (y_score >= threshold) 30 | acc = np.mean((y_test == y_true).astype(int)) 31 | if acc > best_accuracy: 32 | best_accuracy = acc 33 | best_threshold = threshold 34 | 35 | return best_accuracy, best_threshold 36 | 37 | 38 | # 根据对角余弦值计算准确率 39 | def cal_accuracy(y_score, y_true, threshold=0.5): 40 | y_score = np.asarray(y_score) 41 | y_true = np.asarray(y_true) 42 | y_test = (y_score >= threshold) 43 | accuracy = np.mean((y_test == y_true).astype(int)) 44 | return accuracy 45 | 46 | 47 | # 计算对角余弦值 48 | def cosin_metric(x1, x2): 49 | return np.dot(x1, x2) / (np.linalg.norm(x1) * np.linalg.norm(x2)) 50 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | av 2 | librosa 3 | numpy 4 | pyyaml 5 | tqdm 6 | resampy 7 | scikit_learn 8 | soundfile 9 | termcolor --------------------------------------------------------------------------------