├── .github └── ISSUE_TEMPLATE │ ├── bug.yaml │ └── feature_request.yaml ├── LICENSE ├── README.md ├── asr_gui.py ├── bk_asr ├── ASRData.py ├── BaseASR.py ├── BcutASR.py ├── JianYingASR.py ├── KuaiShouASR.py ├── WhisperASR.py └── __init__.py ├── example.py ├── requirements.txt └── resources ├── main_window-1.1.0.png ├── test.mp3 └── test.srt /.github/ISSUE_TEMPLATE/bug.yaml: -------------------------------------------------------------------------------- 1 | name: Bug 错误 2 | description: Report bugs 反馈程序出现的错误 3 | labels: ["bug"] 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | 感谢您报告问题!请提供以下信息帮助我更好地解决问题。 9 | Thank you for reporting the issue! Using English or Chinese. 10 | 11 | - type: textarea 12 | id: description 13 | attributes: 14 | label: 问题描述 Problem Description 15 | description: | 16 | 请详细描述您遇到的问题。 17 | Please describe in detail the problem you encountered. 18 | validations: 19 | required: true 20 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yaml: -------------------------------------------------------------------------------- 1 | name: Feature Request 功能请求 2 | description: Create the request for a new feature 提出增加新功能的请求 3 | labels: ["enhancement"] 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | ✨ 感谢您提出功能建议!请描述您希望的新功能,对于有用可行的建议我会努力实现的。 9 | 🌟 Thank you for your feature suggestion! Please describe the new feature you expect. Using English or Chinese. 10 | 11 | - type: textarea 12 | id: feature 13 | attributes: 14 | label: 💡 预期的功能 Expected Feature 15 | description: | 16 | 请详细描述您期望添加的功能,包括使用场景和希望达到的效果。 17 | Please describe in detail the feature you want to add, including usage scenarios and desired effects. 18 | validations: 19 | required: true 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | **注意:更多强大功能已经在我另一个项目实现:** 3 | 4 | [VideoCaptioner](https://github.com/WEIFENG2333/VideoCaptioner) 基于 LLM 的智能字幕助手,无需GPU一键高质量字幕视频合成!支持生成、断句、优化、翻译全流程。让视频字幕制作简单高效! 5 | 6 | 7 | # 🎤 AsrTools 8 | 9 | ## 🌟 **特色功能** 10 | 11 | - 🚀 **无需复杂配置**:无需 GPU 和繁琐的本地配置,小白也能轻松使用。 12 | - 🖥️ **高颜值界面**:基于 **PyQt5** 和 **qfluentwidgets**,界面美观且用户友好。 13 | - ⚡ **效率超人**:多线程并发 + 批量处理,文字转换快如闪电。 14 | - 📄 **多格式支持**:支持生成 `.srt` 和 `.txt` 、`ass`字幕文件,满足不同需求。 15 | 16 | 欢迎为项目给上一个 Star ⭐ 。 17 | 18 | **主界面截图示例:** 19 | 20 | 主界面 21 | 22 | 23 | ## 🌟 未来计划(TODO) 24 | 25 | - 🎥 视频直接处理(完成):支持输入视频文件自动转换为音频文件,无需用户手动转换为mp3等音频格式。 26 | - 📄 多样化输出(完成):增加输出格式选择,提供更多字幕格式选项,满足不同用户需求。 27 | - 🔀 一键字幕视频:增加视频自动加字幕功能,一键完成从视频到带字幕视频的全流程。 28 | - 🔗 API 集成:提供 API 接口,允许开发者将 AsrTools 集成到自己的工作流程中。 29 | - ✏️ 字幕编辑器:集成一个简单的字幕编辑界面,允许用户直接修改、调整时间轴和校正识别错误。 30 | 31 | 以上计划均已经实现,请访问 [VideoCaptioner](https://github.com/WEIFENG2333/VideoCaptioner) 32 | 33 | 34 | ### 🖥️ **快速上手** 35 | 36 | 1. **启动应用**:运行下载的可执行文件或通过命令行启动 GUI 界面。 37 | 2. **选择 ASR 引擎**:在下拉菜单中选择你需要使用的 ASR 引擎。 38 | 3. **添加文件**:点击“选择文件”按钮或将文件/文件夹拖拽到指定区域。 39 | 4. **开始处理**:点击“开始处理”按钮,程序将自动开始转换,并在完成后在原音频目录生成 `.srt` 或 `.txt` 字幕文件。(默认保持 3 个线程运行) 40 | 41 | ## 🛠️ **安装指南** 42 | 43 | ### **1. 从发布版本安装** 44 | 45 | 我为 Windows 用户提供了打包好的[Release](https://github.com/WEIFENG2333/AsrTools/releases)版本,下载后解压即可直接使用,无需配置环境。 46 | 47 | 或者从网盘下载: [https://wwwm.lanzoue.com/iUJYZ2clk7xg](https://wwwm.lanzoue.com/iPKZV2eh5ina) 48 | 49 | 运行解压后的 `AsrTools.exe`,即可启动 GUI 界面。 50 | 51 | 52 | ### **2. 从源码安装(开发者)** 53 | 54 | 项目的依赖仅仅为 `requests`。 55 | 56 | 如果您需要 GUI 界面,请额外安装 `PyQt5`, `qfluentwidgets`。 57 | 58 | 如果您想从源码运行,请按照以下步骤操作: 59 | 60 | 1. **克隆仓库并进入项目目录** 61 | 62 | ```bash 63 | git clone https://github.com/WEIFENG2333/AsrTools.git 64 | cd AsrTools 65 | ``` 66 | 67 | 2. **安装依赖并运行** 68 | 69 | - **启动 GUI 界面** 70 | 71 | ```bash 72 | pip install -r requirements.txt 73 | python asr_gui.py 74 | ``` 75 | --- 76 | 77 | ## 日志 78 | - **(v1.1.0)已经增加视频文件支持🎥**:支持直接导入视频文件,自动转换为音频进行处理,无需手动转换。 79 | 80 | ## 📬 **联系与支持** 81 | 82 | - **Issues**:[提交问题](https://github.com/WEIFENG2333/AsrTools/issues) 83 | 84 | 感谢您使用 **AsrTools**!🎉 85 | 86 | 目前项目的相关调用和GUI页面的功能仍在不断完善中... 87 | 88 | 希望这款工具能为您带来便利。😊 89 | 90 | --- 91 | ## Star History 92 | 93 | [![Star History Chart](https://api.star-history.com/svg?repos=WEIFENG2333/AsrTools&type=Date)](https://star-history.com/#WEIFENG2333/AsrTools&Date) 94 | -------------------------------------------------------------------------------- /asr_gui.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | from pathlib import Path 4 | import platform 5 | import subprocess 6 | import sys 7 | import webbrowser 8 | 9 | # FIX: 修复中文路径报错 https://github.com/WEIFENG2333/AsrTools/issues/18 设置QT_QPA_PLATFORM_PLUGIN_PATH 10 | plugin_path = os.path.join(sys.prefix, 'Lib', 'site-packages', 'PyQt5', 'Qt5', 'plugins') 11 | os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path 12 | 13 | from PyQt5.QtCore import Qt, QRunnable, QThreadPool, QObject, pyqtSignal as Signal, pyqtSlot as Slot, QSize, QThread, \ 14 | pyqtSignal 15 | from PyQt5.QtGui import QCursor, QColor, QFont 16 | from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QFileDialog, 17 | QTableWidgetItem, QHeaderView, QSizePolicy) 18 | from qfluentwidgets import (ComboBox, PushButton, LineEdit, TableWidget, FluentIcon as FIF, 19 | Action, RoundMenu, InfoBar, InfoBarPosition, 20 | FluentWindow, BodyLabel, MessageBox) 21 | 22 | from bk_asr.BcutASR import BcutASR 23 | from bk_asr.JianYingASR import JianYingASR 24 | from bk_asr.KuaiShouASR import KuaiShouASR 25 | 26 | # 设置日志配置 27 | logging.basicConfig( 28 | level=logging.INFO, 29 | format='%(asctime)s - %(levelname)s - %(message)s' 30 | ) 31 | 32 | 33 | class WorkerSignals(QObject): 34 | finished = Signal(str, str) 35 | errno = Signal(str, str) 36 | 37 | 38 | class ASRWorker(QRunnable): 39 | """ASR处理工作线程""" 40 | def __init__(self, file_path, asr_engine, export_format): 41 | super().__init__() 42 | self.file_path = file_path 43 | self.asr_engine = asr_engine 44 | self.export_format = export_format 45 | self.signals = WorkerSignals() 46 | 47 | self.audio_path = None 48 | 49 | @Slot() 50 | def run(self): 51 | try: 52 | use_cache = True 53 | 54 | # 检查文件类型,如果不是音频则转换 55 | logging.info("[+]正在进ffmpeg转换") 56 | audio_exts = ['.mp3', '.wav'] 57 | if not any(self.file_path.lower().endswith(ext) for ext in audio_exts): 58 | temp_audio = self.file_path.rsplit(".", 1)[0] + ".mp3" 59 | if not video2audio(self.file_path, temp_audio): 60 | raise Exception("音频转换失败,确保安装ffmpeg") 61 | self.audio_path = temp_audio 62 | else: 63 | self.audio_path = self.file_path 64 | 65 | # 根据选择的 ASR 引擎实例化相应的类 66 | if self.asr_engine == 'B 接口': 67 | asr = BcutASR(self.audio_path, use_cache=use_cache) 68 | elif self.asr_engine == 'J 接口': 69 | asr = JianYingASR(self.audio_path, use_cache=use_cache) 70 | elif self.asr_engine == 'K 接口': 71 | asr = KuaiShouASR(self.audio_path, use_cache=use_cache) 72 | elif self.asr_engine == 'Whisper': 73 | # from bk_asr.WhisperASR import WhisperASR 74 | # asr = WhisperASR(self.file_path, use_cache=use_cache) 75 | raise NotImplementedError("WhisperASR 暂未实现") 76 | else: 77 | raise ValueError(f"未知的 ASR 引擎: {self.asr_engine}") 78 | 79 | logging.info(f"开始处理文件: {self.file_path} 使用引擎: {self.asr_engine}") 80 | result = asr.run() 81 | 82 | # 根据导出格式选择转换方法 83 | save_ext = self.export_format.lower() 84 | if save_ext == 'srt': 85 | result_text = result.to_srt() 86 | elif save_ext == 'ass': 87 | result_text = result.to_ass() 88 | elif save_ext == 'txt': 89 | result_text = result.to_txt() 90 | 91 | logging.info(f"完成处理文件: {self.file_path} 使用引擎: {self.asr_engine}") 92 | save_path = self.file_path.rsplit(".", 1)[0] + "." + save_ext 93 | with open(save_path, "w", encoding="utf-8") as f: 94 | f.write(result_text) 95 | self.signals.finished.emit(self.file_path, result_text) 96 | except Exception as e: 97 | logging.error(f"处理文件 {self.file_path} 时出错: {str(e)}") 98 | self.signals.errno.emit(self.file_path, f"处理时出错: {str(e)}") 99 | 100 | class UpdateCheckerThread(QThread): 101 | msg = pyqtSignal(str, str, str) # 用于发送消息的信号 102 | 103 | def __init__(self, parent=None): 104 | super().__init__(parent) 105 | 106 | def run(self): 107 | try: 108 | from check_update import check_update, check_internet_connection 109 | # 检查互联网连接 110 | if not check_internet_connection(): 111 | self.msg.emit("错误", "无法连接到互联网,请检查网络连接。", "") 112 | return 113 | # 检查更新 114 | config = check_update(self) 115 | if config: 116 | if config['fource']: 117 | self.msg.emit("更新", "检测到新版本,请下载最新版本。", config['update_download_url']) 118 | else: 119 | self.msg.emit("可更新", "检测到新版本,请下载最新版本。", config['update_download_url']) 120 | except Exception as e: 121 | pass 122 | 123 | 124 | class ASRWidget(QWidget): 125 | """ASR处理界面""" 126 | 127 | def __init__(self): 128 | super().__init__() 129 | self.init_ui() 130 | self.max_threads = 3 # 设置最大线程数 131 | self.thread_pool = QThreadPool() 132 | self.thread_pool.setMaxThreadCount(self.max_threads) 133 | self.processing_queue = [] 134 | self.workers = {} # 维护文件路径到worker的映射 135 | 136 | 137 | def init_ui(self): 138 | layout = QVBoxLayout(self) 139 | 140 | # ASR引擎选择区域 141 | engine_layout = QHBoxLayout() 142 | engine_label = BodyLabel("选择接口:", self) 143 | engine_label.setFixedWidth(70) 144 | self.combo_box = ComboBox(self) 145 | self.combo_box.addItems(['B 接口', 'J 接口', 'K 接口', 'Whisper']) 146 | engine_layout.addWidget(engine_label) 147 | engine_layout.addWidget(self.combo_box) 148 | layout.addLayout(engine_layout) 149 | 150 | # 导出格式选择区域 151 | format_layout = QHBoxLayout() 152 | format_label = BodyLabel("导出格式:", self) 153 | format_label.setFixedWidth(70) 154 | self.format_combo = ComboBox(self) 155 | self.format_combo.addItems(['SRT', 'TXT', 'ASS']) 156 | format_layout.addWidget(format_label) 157 | format_layout.addWidget(self.format_combo) 158 | layout.addLayout(format_layout) 159 | 160 | # 文件选择区域 161 | file_layout = QHBoxLayout() 162 | self.file_input = LineEdit(self) 163 | self.file_input.setPlaceholderText("拖拽文件或文件夹到这里") 164 | self.file_input.setReadOnly(True) 165 | self.file_button = PushButton("选择文件", self) 166 | self.file_button.clicked.connect(self.select_file) 167 | file_layout.addWidget(self.file_input) 168 | file_layout.addWidget(self.file_button) 169 | layout.addLayout(file_layout) 170 | 171 | # 文件列表表格 172 | self.table = TableWidget(self) 173 | self.table.setColumnCount(2) 174 | self.table.setHorizontalHeaderLabels(['文件名', '状态']) 175 | self.table.setContextMenuPolicy(Qt.CustomContextMenu) 176 | self.table.customContextMenuRequested.connect(self.show_context_menu) 177 | layout.addWidget(self.table) 178 | 179 | # 设置表格列的拉伸模式 180 | header = self.table.horizontalHeader() 181 | header.setSectionResizeMode(0, QHeaderView.Stretch) 182 | header.setSectionResizeMode(1, QHeaderView.Fixed) 183 | self.table.setColumnWidth(1, 100) 184 | self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) 185 | 186 | # 处理按钮 187 | self.process_button = PushButton("开始处理", self) 188 | self.process_button.clicked.connect(self.process_files) 189 | self.process_button.setEnabled(False) # 初始禁用 190 | layout.addWidget(self.process_button) 191 | 192 | self.setAcceptDrops(True) 193 | 194 | def select_file(self): 195 | """选择文件对话框""" 196 | files, _ = QFileDialog.getOpenFileNames(self, "选择音频或视频文件", "", 197 | "Media Files (*.mp3 *.wav *.ogg *.mp4 *.avi *.mov *.ts)") 198 | for file in files: 199 | self.add_file_to_table(file) 200 | self.update_start_button_state() 201 | 202 | def add_file_to_table(self, file_path): 203 | """将文件添加到表格中""" 204 | if self.find_row_by_file_path(file_path) != -1: 205 | InfoBar.warning( 206 | title='文件已存在', 207 | content=f"文件 {os.path.basename(file_path)} 已经添加到列表中。", 208 | orient=Qt.Horizontal, 209 | isClosable=True, 210 | position=InfoBarPosition.TOP, 211 | duration=2000, 212 | parent=self 213 | ) 214 | return 215 | 216 | row_count = self.table.rowCount() 217 | self.table.insertRow(row_count) 218 | item_filename = self.create_non_editable_item(os.path.basename(file_path)) 219 | item_status = self.create_non_editable_item("未处理") 220 | item_status.setForeground(QColor("gray")) 221 | self.table.setItem(row_count, 0, item_filename) 222 | self.table.setItem(row_count, 1, item_status) 223 | item_filename.setData(Qt.UserRole, file_path) 224 | 225 | def create_non_editable_item(self, text): 226 | """创建不可编辑的表格项""" 227 | item = QTableWidgetItem(text) 228 | item.setFlags(item.flags() & ~Qt.ItemIsEditable) 229 | return item 230 | 231 | def show_context_menu(self, pos): 232 | """显示右键菜单""" 233 | current_row = self.table.rowAt(pos.y()) 234 | if current_row < 0: 235 | return 236 | 237 | self.table.selectRow(current_row) 238 | 239 | menu = RoundMenu(self) 240 | reprocess_action = Action(FIF.SYNC, "重新处理") 241 | delete_action = Action(FIF.DELETE, "删除任务") 242 | open_dir_action = Action(FIF.FOLDER, "打开文件目录") 243 | menu.addActions([reprocess_action, delete_action, open_dir_action]) 244 | 245 | delete_action.triggered.connect(self.delete_selected_row) 246 | open_dir_action.triggered.connect(self.open_file_directory) 247 | reprocess_action.triggered.connect(self.reprocess_selected_file) 248 | 249 | menu.exec(QCursor.pos()) 250 | 251 | def delete_selected_row(self): 252 | """删除选中的行""" 253 | current_row = self.table.currentRow() 254 | if current_row >= 0: 255 | file_path = self.table.item(current_row, 0).data(Qt.UserRole) 256 | if file_path in self.workers: 257 | worker = self.workers[file_path] 258 | worker.signals.finished.disconnect(self.update_table) 259 | worker.signals.errno.disconnect(self.handle_error) 260 | # QThreadPool 不支持直接终止线程,通常需要设计任务可中断 261 | # 这里仅移除引用 262 | self.workers.pop(file_path, None) 263 | self.table.removeRow(current_row) 264 | self.update_start_button_state() 265 | 266 | def open_file_directory(self): 267 | """打开文件所在目录""" 268 | current_row = self.table.currentRow() 269 | if current_row >= 0: 270 | current_item = self.table.item(current_row, 0) 271 | if current_item: 272 | file_path = current_item.data(Qt.UserRole) 273 | directory = os.path.dirname(file_path) 274 | try: 275 | if platform.system() == "Windows": 276 | os.startfile(directory) 277 | elif platform.system() == "Darwin": 278 | subprocess.Popen(["open", directory]) 279 | else: 280 | subprocess.Popen(["xdg-open", directory]) 281 | except Exception as e: 282 | InfoBar.error( 283 | title='无法打开目录', 284 | content=str(e), 285 | orient=Qt.Horizontal, 286 | isClosable=True, 287 | position=InfoBarPosition.TOP, 288 | duration=3000, 289 | parent=self 290 | ) 291 | 292 | def reprocess_selected_file(self): 293 | """重新处理选中的文件""" 294 | current_row = self.table.currentRow() 295 | if current_row >= 0: 296 | file_path = self.table.item(current_row, 0).data(Qt.UserRole) 297 | status = self.table.item(current_row, 1).text() 298 | if status == "处理中": 299 | InfoBar.warning( 300 | title='当前文件正在处理中', 301 | content="请等待当前文件处理完成后再重新处理。", 302 | orient=Qt.Horizontal, 303 | isClosable=True, 304 | position=InfoBarPosition.TOP, 305 | duration=3000, 306 | parent=self 307 | ) 308 | return 309 | self.add_to_queue(file_path) 310 | 311 | def add_to_queue(self, file_path): 312 | """将文件添加到处理队列并更新状态""" 313 | self.processing_queue.append(file_path) 314 | self.process_next_in_queue() 315 | 316 | def process_files(self): 317 | """处理所有未处理的文件""" 318 | for row in range(self.table.rowCount()): 319 | if self.table.item(row, 1).text() == "未处理": 320 | file_path = self.table.item(row, 0).data(Qt.UserRole) 321 | self.processing_queue.append(file_path) 322 | self.process_next_in_queue() 323 | 324 | def process_next_in_queue(self): 325 | """处理队列中的下一个文件""" 326 | while self.thread_pool.activeThreadCount() < self.max_threads and self.processing_queue: 327 | file_path = self.processing_queue.pop(0) 328 | if file_path not in self.workers: 329 | self.process_file(file_path) 330 | 331 | def process_file(self, file_path): 332 | """处理单个文件""" 333 | selected_engine = self.combo_box.currentText() 334 | selected_format = self.format_combo.currentText() 335 | worker = ASRWorker(file_path, selected_engine, selected_format) 336 | worker.signals.finished.connect(self.update_table) 337 | worker.signals.errno.connect(self.handle_error) 338 | self.thread_pool.start(worker) 339 | self.workers[file_path] = worker 340 | 341 | row = self.find_row_by_file_path(file_path) 342 | if row != -1: 343 | status_item = self.create_non_editable_item("处理中") 344 | status_item.setForeground(QColor("orange")) 345 | self.table.setItem(row, 1, status_item) 346 | self.update_start_button_state() 347 | 348 | def update_table(self, file_path, result): 349 | """更新表格中文件的处理状态""" 350 | row = self.find_row_by_file_path(file_path) 351 | if row != -1: 352 | item_status = self.create_non_editable_item("已处理") 353 | item_status.setForeground(QColor("green")) 354 | self.table.setItem(row, 1, item_status) 355 | 356 | InfoBar.success( 357 | title='处理完成', 358 | content=f"文件 {self.table.item(row, 0).text()} 已处理完成", 359 | orient=Qt.Horizontal, 360 | isClosable=True, 361 | position=InfoBarPosition.TOP, 362 | duration=1500, 363 | parent=self 364 | ) 365 | 366 | self.workers.pop(file_path, None) 367 | self.process_next_in_queue() 368 | self.update_start_button_state() 369 | 370 | def handle_error(self, file_path, error_message): 371 | """处理错误信息""" 372 | row = self.find_row_by_file_path(file_path) 373 | if row != -1: 374 | item_status = self.create_non_editable_item("错误") 375 | item_status.setForeground(QColor("red")) 376 | self.table.setItem(row, 1, item_status) 377 | 378 | InfoBar.error( 379 | title='处理出错', 380 | content=error_message, 381 | orient=Qt.Horizontal, 382 | isClosable=True, 383 | position=InfoBarPosition.TOP, 384 | duration=3000, 385 | parent=self 386 | ) 387 | 388 | self.workers.pop(file_path, None) 389 | self.process_next_in_queue() 390 | self.update_start_button_state() 391 | 392 | def find_row_by_file_path(self, file_path): 393 | """根据文件路径查找表格中的行号""" 394 | for row in range(self.table.rowCount()): 395 | item = self.table.item(row, 0) 396 | if item.data(Qt.UserRole) == file_path: 397 | return row 398 | return -1 399 | 400 | def update_start_button_state(self): 401 | """根据文件列表更新开始处理按钮的状态""" 402 | has_unprocessed = any( 403 | self.table.item(row, 1).text() == "未处理" 404 | for row in range(self.table.rowCount()) 405 | ) 406 | self.process_button.setEnabled(has_unprocessed) 407 | 408 | def dragEnterEvent(self, event): 409 | """拖拽进入事件""" 410 | if event.mimeData().hasUrls(): 411 | event.accept() 412 | else: 413 | event.ignore() 414 | 415 | def dropEvent(self, event): 416 | """拖拽释放事件""" 417 | supported_formats = ('.mp3', '.wav', '.ogg', '.flac', '.aac', '.m4a', '.wma', # 音频格式 418 | '.mp4', '.avi', '.mov', '.ts', '.mkv', '.wmv', '.flv', '.webm', '.rmvb') # 视频格式 419 | files = [u.toLocalFile() for u in event.mimeData().urls()] 420 | for file in files: 421 | if os.path.isdir(file): 422 | for root, dirs, files_in_dir in os.walk(file): 423 | for f in files_in_dir: 424 | if f.lower().endswith(supported_formats): 425 | self.add_file_to_table(os.path.join(root, f)) 426 | elif file.lower().endswith(supported_formats): 427 | self.add_file_to_table(file) 428 | self.update_start_button_state() 429 | 430 | 431 | class InfoWidget(QWidget): 432 | """个人信息界面""" 433 | 434 | def __init__(self): 435 | super().__init__() 436 | self.init_ui() 437 | 438 | def init_ui(self): 439 | # GitHub URL 和仓库描述 440 | GITHUB_URL = "https://github.com/WEIFENG2333/AsrTools" 441 | REPO_DESCRIPTION = """ 442 | 🚀 无需复杂配置:无需 GPU 和繁琐的本地配置,小白也能轻松使用。 443 | 🖥️ 高颜值界面:基于 PyQt5 和 qfluentwidgets,界面美观且用户友好。 444 | ⚡ 效率超人:多线程并发 + 批量处理,文字转换快如闪电。 445 | 📄 多格式支持:支持生成 .srt 和 .txt 字幕文件,满足不同需求。 446 | """ 447 | 448 | main_layout = QVBoxLayout(self) 449 | main_layout.setAlignment(Qt.AlignTop) 450 | # main_layout.setSpacing(50) 451 | 452 | # 标题 453 | title_label = BodyLabel(" ASRTools", self) 454 | title_label.setFont(QFont("Segoe UI", 30, QFont.Bold)) 455 | title_label.setAlignment(Qt.AlignCenter) 456 | main_layout.addWidget(title_label) 457 | 458 | # 仓库描述区域 459 | desc_label = BodyLabel(REPO_DESCRIPTION, self) 460 | desc_label.setFont(QFont("Segoe UI", 12)) 461 | main_layout.addWidget(desc_label) 462 | 463 | github_button = PushButton("GitHub 仓库", self) 464 | github_button.setIcon(FIF.GITHUB) 465 | github_button.setIconSize(QSize(20, 20)) 466 | github_button.setMinimumHeight(42) 467 | github_button.clicked.connect(lambda _: webbrowser.open(GITHUB_URL)) 468 | main_layout.addWidget(github_button) 469 | 470 | 471 | class MainWindow(FluentWindow): 472 | """主窗口""" 473 | def __init__(self): 474 | super().__init__() 475 | self.setWindowTitle('ASR Processing Tool') 476 | 477 | # ASR 处理界面 478 | self.asr_widget = ASRWidget() 479 | self.asr_widget.setObjectName("main") 480 | self.addSubInterface(self.asr_widget, FIF.ALBUM, 'ASR Processing') 481 | 482 | # 个人信息界面 483 | self.info_widget = InfoWidget() 484 | self.info_widget.setObjectName("info") # 设置对象名称 485 | self.addSubInterface(self.info_widget, FIF.GITHUB, 'About') 486 | 487 | self.navigationInterface.setExpandWidth(200) 488 | self.resize(800, 600) 489 | 490 | self.update_checker = UpdateCheckerThread(self) 491 | self.update_checker.msg.connect(self.show_msg) 492 | self.update_checker.start() 493 | 494 | def show_msg(self, title, content, update_download_url): 495 | w = MessageBox(title, content, self) 496 | if w.exec() and update_download_url: 497 | webbrowser.open(update_download_url) 498 | if title == "更新": 499 | sys.exit(0) 500 | 501 | def video2audio(input_file: str, output: str = "") -> bool: 502 | """使用ffmpeg将视频转换为音频""" 503 | # 创建output目录 504 | output = Path(output) 505 | output.parent.mkdir(parents=True, exist_ok=True) 506 | output = str(output) 507 | 508 | cmd = [ 509 | 'ffmpeg', 510 | '-i', input_file, 511 | '-ac', '1', 512 | '-f', 'mp3', 513 | '-af', 'aresample=async=1', 514 | '-y', 515 | output 516 | ] 517 | result = subprocess.run(cmd, capture_output=True, check=True, encoding='utf-8', errors='replace') 518 | 519 | if result.returncode == 0 and Path(output).is_file(): 520 | return True 521 | else: 522 | return False 523 | 524 | def start(): 525 | # enable dpi scale 526 | QApplication.setHighDpiScaleFactorRoundingPolicy( 527 | Qt.HighDpiScaleFactorRoundingPolicy.PassThrough) 528 | QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) 529 | QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) 530 | 531 | app = QApplication(sys.argv) 532 | # setTheme(Theme.DARK) # 如果需要深色主题,取消注释此行 533 | window = MainWindow() 534 | window.show() 535 | sys.exit(app.exec()) 536 | 537 | 538 | if __name__ == '__main__': 539 | start() 540 | -------------------------------------------------------------------------------- /bk_asr/ASRData.py: -------------------------------------------------------------------------------- 1 | import json 2 | import re 3 | from typing import List 4 | from pathlib import Path 5 | 6 | class ASRDataSeg: 7 | def __init__(self, text, start_time, end_time): 8 | self.text = text 9 | self.start_time = start_time 10 | self.end_time = end_time 11 | 12 | def to_srt_ts(self) -> str: 13 | """Convert to SRT timestamp format""" 14 | return f"{self._ms_to_srt_time(self.start_time)} --> {self._ms_to_srt_time(self.end_time)}" 15 | 16 | 17 | def to_lrc_ts(self) -> str: 18 | """Convert to LRC timestamp format""" 19 | return f"[{self._ms_to_lrc_time(self.start_time)}]" 20 | 21 | def to_ass_ts(self) -> tuple[str, str]: 22 | """Convert to ASS timestamp format""" 23 | return self._ms_to_ass_ts(self.start_time), self._ms_to_ass_ts(self.end_time) 24 | 25 | def _ms_to_lrc_time(self, ms) -> str: 26 | seconds = ms / 1000 27 | minutes, seconds = divmod(seconds, 60) 28 | return f"{int(minutes):02}:{seconds:.2f}" 29 | 30 | @staticmethod 31 | def _ms_to_srt_time(ms) -> str: 32 | """Convert milliseconds to SRT time format (HH:MM:SS,mmm)""" 33 | total_seconds, milliseconds = divmod(ms, 1000) 34 | minutes, seconds = divmod(total_seconds, 60) 35 | hours, minutes = divmod(minutes, 60) 36 | return f"{int(hours):02}:{int(minutes):02}:{int(seconds):02},{int(milliseconds):03}" 37 | 38 | @staticmethod 39 | def _ms_to_ass_ts(ms) -> str: 40 | """Convert milliseconds to ASS timestamp format (H:MM:SS.cc)""" 41 | total_seconds, milliseconds = divmod(ms, 1000) 42 | minutes, seconds = divmod(total_seconds, 60) 43 | hours, minutes = divmod(minutes, 60) 44 | # ASS格式使用厘秒(1/100秒)而不是毫秒 45 | centiseconds = int(milliseconds / 10) 46 | return f"{int(hours):01}:{int(minutes):02}:{int(seconds):02}.{centiseconds:02}" 47 | 48 | @property 49 | def transcript(self) -> str: 50 | """Return segment text""" 51 | return self.text 52 | 53 | def __str__(self) -> str: 54 | return f"ASRDataSeg({self.text}, {self.start_time}, {self.end_time})" 55 | 56 | 57 | class ASRData: 58 | def __init__(self, segments: List[ASRDataSeg]): 59 | self.segments = segments 60 | 61 | def __iter__(self): 62 | return iter(self.segments) 63 | 64 | def __len__(self) -> int: 65 | return len(self.segments) 66 | 67 | def has_data(self) -> bool: 68 | """Check if there are any utterances""" 69 | return len(self.segments) > 0 70 | 71 | def is_word_timestamp(self) -> bool: 72 | """ 73 | 判断是否是字级时间戳 74 | 规则: 75 | 1. 对于英文,每个segment应该只包含一个单词 76 | 2. 对于中文,每个segment应该只包含一个汉字 77 | 3. 允许20%的误差率 78 | """ 79 | if not self.segments: 80 | return False 81 | 82 | valid_segments = 0 83 | total_segments = len(self.segments) 84 | 85 | for seg in self.segments: 86 | text = seg.text.strip() 87 | # 检查是否只包含一个英文单词或一个汉字 88 | if (len(text.split()) == 1 and text.isascii()) or len(text.strip()) <= 2: 89 | valid_segments += 1 90 | print(f"valid_segments: {valid_segments}, total_segments: {total_segments}") 91 | return (valid_segments / total_segments) >= 0.8 92 | 93 | 94 | def save(self, save_path: str, ass_style: str = None, layout: str = "原文在上") -> None: 95 | """Save the ASRData to a file""" 96 | # 根据文件后缀名选择保存格式 97 | Path(save_path).parent.mkdir(parents=True, exist_ok=True) 98 | if save_path.endswith('.srt'): 99 | self.to_srt(save_path=save_path) 100 | elif save_path.endswith('.txt'): 101 | with open(save_path, 'w', encoding='utf-8') as f: 102 | f.write(self.to_txt()) 103 | elif save_path.endswith('.json'): 104 | with open(save_path, 'w', encoding='utf-8') as f: 105 | json.dump(self.to_json(), f, ensure_ascii=False) 106 | elif save_path.endswith('.ass'): 107 | self.to_ass(save_path=save_path, style_str=ass_style, layout=layout) 108 | else: 109 | raise ValueError(f"Unsupported file extension: {save_path}") 110 | 111 | def to_txt(self) -> str: 112 | """Convert to plain text subtitle format (without timestamps)""" 113 | return "\n".join(seg.transcript for seg in self.segments) 114 | 115 | def to_srt(self, save_path=None) -> str: 116 | """Convert to SRT subtitle format""" 117 | srt_text = "\n".join( 118 | f"{n}\n{seg.to_srt_ts()}\n{seg.transcript}\n" 119 | for n, seg in enumerate(self.segments, 1)) 120 | if save_path: 121 | with open(save_path, 'w', encoding='utf-8') as f: 122 | f.write(srt_text) 123 | return srt_text 124 | 125 | def to_lrc(self, save_path=None) -> str: 126 | """Convert to LRC subtitle format""" 127 | lrc_text = "\n".join( 128 | f"{seg.to_lrc_ts()}{seg.transcript}" for seg in self.segments 129 | ) 130 | if save_path: 131 | with open(save_path, 'w', encoding='utf-8') as f: 132 | f.write(lrc_text) 133 | return lrc_text 134 | 135 | def to_json(self) -> dict: 136 | result_json = {} 137 | for i, segment in enumerate(self.segments, 1): 138 | # 检查是否有换行符 139 | if "\n" in segment.text: 140 | original_subtitle, translated_subtitle = segment.text.split("\n") 141 | else: 142 | original_subtitle, translated_subtitle = segment.text, "" 143 | 144 | result_json[str(i)] = { 145 | "start_time": segment.start_time, 146 | "end_time": segment.end_time, 147 | "original_subtitle": original_subtitle, 148 | "translated_subtitle": translated_subtitle 149 | } 150 | return result_json 151 | 152 | def to_ass(self, style_str: str = None, layout: str = "原文在上", save_path: str = None) -> str: 153 | """转换为ASS字幕格式 154 | 155 | Args: 156 | style_str: ASS样式字符串,为空则使用默认样式 157 | layout: 字幕布局,可选值["译文在上", "原文在上", "仅原文", "仅译文"] 158 | 159 | Returns: 160 | ASS格式字幕内容 161 | """ 162 | # 默认样式 163 | if not style_str: 164 | style_str = ( 165 | "[V4+ Styles]\n" 166 | "Format: Name,Fontname,Fontsize,PrimaryColour,SecondaryColour,OutlineColour,BackColour," 167 | "Bold,Italic,Underline,StrikeOut,ScaleX,ScaleY,Spacing,Angle,BorderStyle,Outline,Shadow," 168 | "Alignment,MarginL,MarginR,MarginV,Encoding\n" 169 | "Style: Default,微软雅黑,66,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,-1,0,0,0,100,100," 170 | "0,0,1,2,0,2,10,10,10,1\n" 171 | "Style: Translate,微软雅黑,40,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,-1,0,0,0,100,100," 172 | "0,0,1,2,0,2,10,10,10,1" 173 | ) 174 | 175 | # 构建ASS文件头 176 | ass_content = ( 177 | "[Script Info]\n" 178 | "; Script generated by VideoCaptioner\n" 179 | "; https://github.com/weifeng2333\n" 180 | "ScriptType: v4.00+\n" 181 | "PlayResX: 1280\n" 182 | "PlayResY: 720\n\n" 183 | f"{style_str}\n\n" 184 | "[Events]\n" 185 | "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n" 186 | ) 187 | 188 | # 根据布局生成对话内容 189 | for seg in self.segments: 190 | start_time = seg.to_ass_ts()[0] 191 | end_time = seg.to_ass_ts()[1] 192 | dialogue_template = 'Dialogue: 0,{},{},{},,0,0,0,,{}\n' 193 | 194 | # 检查是否有换行符分隔的原文和译文 195 | if "\n" in seg.text: 196 | original, translate = seg.text.split("\n") 197 | if layout == "译文在上" and translate: 198 | ass_content += dialogue_template.format(start_time, end_time, "Secondary", original) 199 | ass_content += dialogue_template.format(start_time, end_time, "Default", translate) 200 | elif layout == "原文在上" and translate: 201 | ass_content += dialogue_template.format(start_time, end_time, "Secondary", translate) 202 | ass_content += dialogue_template.format(start_time, end_time, "Default", original) 203 | elif layout == "仅原文": 204 | ass_content += dialogue_template.format(start_time, end_time, "Default", original) 205 | elif layout == "仅译文" and translate: 206 | ass_content += dialogue_template.format(start_time, end_time, "Default", translate) 207 | else: 208 | original = seg.text 209 | ass_content += dialogue_template.format(start_time, end_time, "Default", original) 210 | # 根据布局生成对话行 211 | 212 | if save_path: 213 | with open(save_path, 'w', encoding='utf-8') as f: 214 | f.write(ass_content) 215 | return ass_content 216 | 217 | def merge_segments(self, start_index: int, end_index: int, merged_text: str = None): 218 | """合并从 start_index 到 end_index 的段(包含)。""" 219 | if start_index < 0 or end_index >= len(self.segments) or start_index > end_index: 220 | raise IndexError("无效的段索引。") 221 | merged_start_time = self.segments[start_index].start_time 222 | merged_end_time = self.segments[end_index].end_time 223 | if merged_text is None: 224 | merged_text = ''.join(seg.text for seg in self.segments[start_index:end_index+1]) 225 | merged_seg = ASRDataSeg(merged_text, merged_start_time, merged_end_time) 226 | # 替换 segments[start_index:end_index+1] 为 merged_seg 227 | self.segments[start_index:end_index+1] = [merged_seg] 228 | 229 | def merge_with_next_segment(self, index: int) -> None: 230 | """合并指定索引的段与下一个段。""" 231 | if index < 0 or index >= len(self.segments) - 1: 232 | raise IndexError("索引超出范围或没有下一个段可合并。") 233 | current_seg = self.segments[index] 234 | next_seg = self.segments[index + 1] 235 | 236 | # 合并文本 237 | merged_text = f"{current_seg.text} {next_seg.text}" 238 | merged_start_time = current_seg.start_time 239 | merged_end_time = next_seg.end_time 240 | merged_seg = ASRDataSeg(merged_text, merged_start_time, merged_end_time) 241 | 242 | # 替换当前段为合并后的段 243 | self.segments[index] = merged_seg 244 | # 删除下一个段 245 | del self.segments[index + 1] 246 | 247 | def __str__(self): 248 | return self.to_txt() 249 | 250 | def from_subtitle_file(file_path: str) -> 'ASRData': 251 | """从文件路径加载ASRData实例 252 | 253 | Args: 254 | file_path: 字幕文件路径,支持.srt、.vtt、.ass、.json格式 255 | 256 | Returns: 257 | ASRData: 解析后的ASRData实例 258 | 259 | Raises: 260 | ValueError: 不支持的文件格式或文件读取错误 261 | """ 262 | file_path = Path(file_path) 263 | if not file_path.exists(): 264 | raise FileNotFoundError(f"文件不存在: {file_path}") 265 | 266 | try: 267 | content = file_path.read_text(encoding='utf-8') 268 | except UnicodeDecodeError: 269 | content = file_path.read_text(encoding='gbk') 270 | 271 | suffix = file_path.suffix.lower() 272 | 273 | if suffix == '.srt': 274 | return from_srt(content) 275 | elif suffix == '.vtt': 276 | if '' in content: # YouTube VTT格式包含字级时间戳 277 | return from_youtube_vtt(content) 278 | return from_vtt(content) 279 | elif suffix == '.ass': 280 | return from_ass(content) 281 | elif suffix == '.json': 282 | return from_json(json.loads(content)) 283 | else: 284 | raise ValueError(f"不支持的文件格式: {suffix}") 285 | 286 | def from_json(json_data: dict) -> 'ASRData': 287 | """从JSON数据创建ASRData实例""" 288 | segments = [] 289 | for i in sorted(json_data.keys(), key=int): 290 | segment_data = json_data[i] 291 | text = segment_data['original_subtitle'] 292 | if segment_data['translated_subtitle']: 293 | text += '\n' + segment_data['translated_subtitle'] 294 | segment = ASRDataSeg( 295 | text=text, 296 | start_time=segment_data['start_time'], 297 | end_time=segment_data['end_time'] 298 | ) 299 | segments.append(segment) 300 | return ASRData(segments) 301 | 302 | def from_srt(srt_str: str) -> 'ASRData': 303 | """ 304 | 从SRT格式的字符串创建ASRData实例。 305 | 306 | :param srt_str: 包含SRT格式字幕的字符串。 307 | :return: 解析后的ASRData实例。 308 | """ 309 | segments = [] 310 | srt_time_pattern = re.compile( 311 | r'(\d{2}):(\d{2}):(\d{1,2})[.,](\d{3})\s-->\s(\d{2}):(\d{2}):(\d{1,2})[.,](\d{3})' 312 | ) 313 | 314 | for block in re.split(r'\n\s*\n', srt_str.strip()): 315 | lines = block.splitlines() 316 | if len(lines) < 3: 317 | continue 318 | 319 | match = srt_time_pattern.match(lines[1]) 320 | if not match: 321 | continue 322 | 323 | time_parts = list(map(int, match.groups())) 324 | start_time = sum([ 325 | time_parts[0] * 3600000, 326 | time_parts[1] * 60000, 327 | time_parts[2] * 1000, 328 | time_parts[3] 329 | ]) 330 | end_time = sum([ 331 | time_parts[4] * 3600000, 332 | time_parts[5] * 60000, 333 | time_parts[6] * 1000, 334 | time_parts[7] 335 | ]) 336 | 337 | text = '\n'.join(lines[2:]).strip() 338 | segments.append(ASRDataSeg(text, start_time, end_time)) 339 | 340 | return ASRData(segments) 341 | 342 | def from_vtt(vtt_str: str) -> 'ASRData': 343 | """ 344 | 从YouTube VTT格式的字符串创建ASRData实例。 345 | 346 | :param vtt_str: YouTube VTT格式的字幕字符串 347 | :return: ASRData实例 348 | """ 349 | segments = [] 350 | # 跳过头部元数据 351 | content = vtt_str.split('\n\n')[2:] 352 | 353 | current_text = "" 354 | current_start = 0 355 | current_end = 0 356 | 357 | for block in content: 358 | lines = block.strip().split('\n') 359 | if not lines: 360 | continue 361 | 362 | # 解析时间戳行 363 | timestamp_line = lines[0] 364 | if '-->' not in timestamp_line: 365 | continue 366 | 367 | # 提取开始和结束时间 368 | times = timestamp_line.split(' --> ')[0] 369 | hours, minutes, seconds = times.split(':') 370 | seconds, milliseconds = seconds.split('.') 371 | start_time = (int(hours) * 3600 + int(minutes) * 60 + int(seconds)) * 1000 + int(milliseconds) 372 | 373 | times = timestamp_line.split(' --> ')[1].split()[0] 374 | hours, minutes, seconds = times.split(':') 375 | seconds, milliseconds = seconds.split('.') 376 | end_time = (int(hours) * 3600 + int(minutes) * 60 + int(seconds)) * 1000 + int(milliseconds) 377 | 378 | # 提取并清文本内容 379 | if len(lines) > 1: 380 | text_line = lines[1] 381 | # 移除时间戳和样式标记 382 | cleaned_text = re.sub(r'<\d{2}:\d{2}:\d{2}\.\d{3}>', '', text_line) 383 | cleaned_text = re.sub(r'', '', cleaned_text) 384 | cleaned_text = cleaned_text.strip() 385 | 386 | if cleaned_text and cleaned_text != " ": 387 | segments.append(ASRDataSeg(cleaned_text, start_time, end_time)) 388 | 389 | return ASRData(segments) 390 | 391 | def from_youtube_vtt(vtt_str: str) -> 'ASRData': 392 | """ 393 | 从YouTube VTT格式的字符串创建ASRData实例,提取字级时间戳。 394 | 395 | :param vtt_str: 包含VTT格式字幕的字符串 396 | :return: 解析后的ASRData实例 397 | """ 398 | def parse_timestamp(ts: str) -> int: 399 | """将时间戳字符串转换为毫秒""" 400 | h, m, s = ts.split(':') 401 | return int(float(h) * 3600000 + float(m) * 60000 + float(s) * 1000) 402 | 403 | def split_timestamped_text(text: str) -> List[ASRDataSeg]: 404 | """分离带时间戳的文本为单词段""" 405 | # 匹配 <时间戳>文本 的模式 406 | pattern = re.compile(r'<(\d{2}:\d{2}:\d{2}\.\d{3})>([^<]*)') 407 | matches = list(pattern.finditer(text)) 408 | word_segments = [] 409 | 410 | for i in range(len(matches) - 1): 411 | current_match = matches[i] 412 | next_match = matches[i + 1] 413 | 414 | start_time = parse_timestamp(current_match.group(1)) 415 | end_time = parse_timestamp(next_match.group(1)) 416 | word = current_match.group(2).strip() 417 | 418 | if word: # 只有当文本不为空时才创建segment 419 | word_segments.append(ASRDataSeg(word, start_time, end_time)) 420 | 421 | return word_segments 422 | 423 | segments = [] 424 | # 跳过WEBVTT头部 425 | blocks = re.split(r'\n\n+', vtt_str.strip()) 426 | 427 | # 时间戳匹配模式 428 | timestamp_pattern = re.compile( 429 | r'(\d{2}):(\d{2}):(\d{2}\.\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2}\.\d{3})' 430 | ) 431 | for block in blocks: 432 | lines = block.strip().split('\n') 433 | if not lines: 434 | continue 435 | 436 | # 匹配时间戳行 437 | match = timestamp_pattern.match(lines[0]) 438 | if not match: 439 | continue 440 | 441 | # 计算块的开始和结束时间 442 | block_start_time = ( 443 | int(match.group(1)) * 3600000 + 444 | int(match.group(2)) * 60000 + 445 | float(match.group(3)) * 1000 446 | ) 447 | block_end_time = ( 448 | int(match.group(4)) * 3600000 + 449 | int(match.group(5)) * 60000 + 450 | float(match.group(6)) * 1000 451 | ) 452 | 453 | # 获取文本内容 454 | text = '\n'.join(lines) 455 | 456 | timestamp_row = re.search(r'\n(.*?.*?.*)', block) 457 | if timestamp_row: 458 | text = re.sub(r'|', '', timestamp_row.group(1)) 459 | block_start_time_string = f"{match.group(1)}:{match.group(2)}:{match.group(3)}" 460 | block_end_time_string = f"{match.group(4)}:{match.group(5)}:{match.group(6)}" 461 | text = f"<{block_start_time_string}>{text}<{block_end_time_string}>" 462 | 463 | # 分离每个带时间戳的单词 464 | word_segments = split_timestamped_text(text) 465 | segments.extend(word_segments) 466 | 467 | return ASRData(segments) 468 | 469 | def from_ass(ass_str: str) -> 'ASRData': 470 | """ 471 | 从ASS格式的字符串创建ASRData实例。 472 | 473 | :param ass_str: 包含ASS格式字幕的字符串 474 | :return: ASRData实例 475 | """ 476 | segments = [] 477 | # ASS时间戳格式: H:MM:SS.cc 478 | ass_time_pattern = re.compile(r'Dialogue: \d+,(\d+:\d{2}:\d{2}\.\d{2}),(\d+:\d{2}:\d{2}\.\d{2}),(.*?),.*?,\d+,\d+,\d+,.*?,(.*?)$') 479 | 480 | def parse_ass_time(time_str: str) -> int: 481 | """将ASS时间戳转换为毫秒""" 482 | hours, minutes, seconds = time_str.split(':') 483 | seconds, centiseconds = seconds.split('.') 484 | return (int(hours) * 3600000 + 485 | int(minutes) * 60000 + 486 | int(seconds) * 1000 + 487 | int(centiseconds) * 10) # 厘秒转毫秒 488 | 489 | # 按行处理ASS文件 490 | for line in ass_str.splitlines(): 491 | if line.startswith('Dialogue:'): 492 | match = ass_time_pattern.match(line) 493 | if match: 494 | start_time = parse_ass_time(match.group(1)) 495 | end_time = parse_ass_time(match.group(2)) 496 | text = match.group(4) 497 | 498 | # 清理ASS格式标记 499 | text = re.sub(r'\{[^}]*\}', '', text) # 移除样式标记 {xxx} 500 | text = text.replace('\\N', '\n') # 处理换行符 501 | text = text.strip() 502 | 503 | if text: # 只有当文本不为空时才创建segment 504 | segments.append(ASRDataSeg(text, start_time, end_time)) 505 | 506 | return ASRData(segments) 507 | 508 | if __name__ == '__main__': 509 | ass_style_str = """[V4+ Styles] 510 | Format: Name,Fontname,Fontsize,PrimaryColour,SecondaryColour,OutlineColour,BackColour,Bold,Italic,Underline,StrikeOut,ScaleX,ScaleY,Spacing,Angle,BorderStyle,Outline,Shadow,Alignment,MarginL,MarginR,MarginV,Encoding 511 | Style: Default,微软雅黑,62,&H0017f1be,&H000000FF,&H00000000,&H00000000,-1,0,0,0,100,100,1.0,0,1,0.8,0,2,10,10,10,1 512 | Style: Secondary,微软雅黑,40,&H00ffffff,&H000000FF,&H00000000,&H00000000,-1,0,0,0,100,100,0.0,0,1,0.0,0,2,10,10,10,1""" 513 | # 测试 514 | from pathlib import Path 515 | # vtt_file_path = r"E:\GithubProject\VideoCaptioner\app\work_dir\Setting the record straight\subtitle\original_subtitle.en.vtt" 516 | # vtt_file_path = r"E:\GithubProject\VideoCaptioner\work_dir\Wake up babe a dangerous new open-source AI model is here\subtitle\original.en.vtt" 517 | # asr_data = from_youtube_vtt(Path(vtt_file_path).read_text(encoding="utf-8")) 518 | srt_file_path = r"E:\GithubProject\VideoCaptioner\app\work_dir\低视力音乐助人者_mp4\result_subtitle.srt" 519 | asr_data = from_srt(Path(srt_file_path).read_text(encoding="utf-8")) 520 | 521 | print(asr_data.to_ass(style_str=ass_style_str, save_path=srt_file_path.replace(".srt", ".ass"))) 522 | # pass 523 | # asr_data = ASRData(seg) 524 | # Uncomment to test different formats: 525 | # print(asr_data.to_srt(save_path=vtt_file_path.replace(".vtt", ".srt"))) 526 | # print(asr_data.to_lrc()) 527 | # print(asr_data.to_txt()) 528 | # print(asr_data.to_json()) 529 | # print(asr_data.to_json()) 530 | 531 | 532 | 533 | 534 | -------------------------------------------------------------------------------- /bk_asr/BaseASR.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import os 4 | import zlib 5 | import tempfile 6 | import threading 7 | 8 | from .ASRData import ASRDataSeg, ASRData 9 | 10 | 11 | class BaseASR: 12 | SUPPORTED_SOUND_FORMAT = ["flac", "m4a", "mp3", "wav"] 13 | CACHE_FILE = os.path.join(tempfile.gettempdir(), "bk_asr", "asr_cache.json") 14 | _lock = threading.Lock() 15 | 16 | def __init__(self, audio_path: [str, bytes], use_cache: bool = False): 17 | self.audio_path = audio_path 18 | self.file_binary = None 19 | 20 | self.crc32_hex = None 21 | self.use_cache = use_cache 22 | 23 | self._set_data() 24 | 25 | self.cache = self._load_cache() 26 | 27 | def _load_cache(self): 28 | if not self.use_cache: 29 | return {} 30 | os.makedirs(os.path.dirname(self.CACHE_FILE), exist_ok=True) 31 | with self._lock: 32 | if os.path.exists(self.CACHE_FILE): 33 | try: 34 | with open(self.CACHE_FILE, 'r', encoding='utf-8') as f: 35 | cache = json.load(f) 36 | if isinstance(cache, dict): 37 | return cache 38 | except (json.JSONDecodeError, IOError): 39 | return {} 40 | return {} 41 | 42 | def _save_cache(self): 43 | if not self.use_cache: 44 | return 45 | with self._lock: 46 | try: 47 | with open(self.CACHE_FILE, 'w', encoding='utf-8') as f: 48 | json.dump(self.cache, f, ensure_ascii=False, indent=2) 49 | if os.path.exists(self.CACHE_FILE) and os.path.getsize(self.CACHE_FILE) > 10 * 1024 * 1024: 50 | os.remove(self.CACHE_FILE) 51 | except IOError as e: 52 | logging.error(f"Failed to save cache: {e}") 53 | 54 | def _set_data(self): 55 | if isinstance(self.audio_path, bytes): 56 | self.file_binary = self.audio_path 57 | else: 58 | ext = self.audio_path.split(".")[-1].lower() 59 | assert ext in self.SUPPORTED_SOUND_FORMAT, f"Unsupported sound format: {ext}" 60 | assert os.path.exists(self.audio_path), f"File not found: {self.audio_path}" 61 | with open(self.audio_path, "rb") as f: 62 | self.file_binary = f.read() 63 | crc32_value = zlib.crc32(self.file_binary) & 0xFFFFFFFF 64 | self.crc32_hex = format(crc32_value, '08x') 65 | 66 | def _get_key(self): 67 | return f"{self.__class__.__name__}-{self.crc32_hex}" 68 | 69 | def run(self): 70 | k = self._get_key() 71 | if k in self.cache and self.use_cache: 72 | resp_data = self.cache[k] 73 | else: 74 | resp_data = self._run() 75 | # Cache the result 76 | self.cache[k] = resp_data 77 | self._save_cache() 78 | segments = self._make_segments(resp_data) 79 | return ASRData(segments) 80 | 81 | def _make_segments(self, resp_data: dict) -> list[ASRDataSeg]: 82 | raise NotImplementedError("_make_segments method must be implemented in subclass") 83 | 84 | def _run(self) -> dict: 85 | """ Run the ASR service and return the response data. """ 86 | raise NotImplementedError("_run method must be implemented in subclass") 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /bk_asr/BcutASR.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import time 4 | from os import PathLike 5 | from typing import Optional 6 | 7 | import requests 8 | 9 | from .ASRData import ASRData, ASRDataSeg 10 | from .BaseASR import BaseASR 11 | 12 | 13 | __version__ = "0.0.3" 14 | 15 | API_BASE_URL = "https://member.bilibili.com/x/bcut/rubick-interface" 16 | 17 | # 申请上传 18 | API_REQ_UPLOAD = API_BASE_URL + "/resource/create" 19 | 20 | # 提交上传 21 | API_COMMIT_UPLOAD = API_BASE_URL + "/resource/create/complete" 22 | 23 | # 创建任务 24 | API_CREATE_TASK = API_BASE_URL + "/task" 25 | 26 | # 查询结果 27 | API_QUERY_RESULT = API_BASE_URL + "/task/result" 28 | 29 | 30 | class BcutASR(BaseASR): 31 | """必剪 语音识别接口""" 32 | headers = { 33 | 'User-Agent': 'Bilibili/1.0.0 (https://www.bilibili.com)', 34 | 'Content-Type': 'application/json' 35 | } 36 | 37 | def __init__(self, audio_path: [str, bytes], use_cache: bool = False): 38 | super().__init__(audio_path, use_cache=use_cache) 39 | self.session = requests.Session() 40 | self.task_id = None 41 | self.__etags = [] 42 | 43 | self.__in_boss_key: Optional[str, None] = None 44 | self.__resource_id: Optional[str, None] = None 45 | self.__upload_id: Optional[str, None] = None 46 | self.__upload_urls: Optional[list[str]] = [] 47 | self.__per_size: Optional[int, None] = None 48 | self.__clips: Optional[int, None] = None 49 | 50 | self.__etags: Optional[list[str]] = [] 51 | self.__download_url: Optional[str, None] = None 52 | self.task_id: Optional[str, None] = None 53 | 54 | 55 | def upload(self) -> None: 56 | """申请上传""" 57 | if not self.file_binary: 58 | raise ValueError("none set data") 59 | payload = json.dumps({ 60 | "type": 2, 61 | "name": "audio.mp3", 62 | "size": len(self.file_binary), 63 | "ResourceFileType": "mp3", 64 | "model_id": "8", 65 | }) 66 | 67 | resp = requests.post( 68 | API_REQ_UPLOAD, 69 | data=payload, 70 | headers=self.headers 71 | ) 72 | resp.raise_for_status() 73 | resp = resp.json() 74 | resp_data = resp["data"] 75 | 76 | self.__in_boss_key = resp_data["in_boss_key"] 77 | self.__resource_id = resp_data["resource_id"] 78 | self.__upload_id = resp_data["upload_id"] 79 | self.__upload_urls = resp_data["upload_urls"] 80 | self.__per_size = resp_data["per_size"] 81 | self.__clips = len(resp_data["upload_urls"]) 82 | 83 | logging.info( 84 | f"申请上传成功, 总计大小{resp_data['size'] // 1024}KB, {self.__clips}分片, 分片大小{resp_data['per_size'] // 1024}KB: {self.__in_boss_key}" 85 | ) 86 | self.__upload_part() 87 | self.__commit_upload() 88 | 89 | def __upload_part(self) -> None: 90 | """上传音频数据""" 91 | for clip in range(self.__clips): 92 | start_range = clip * self.__per_size 93 | end_range = (clip + 1) * self.__per_size 94 | logging.info(f"开始上传分片{clip}: {start_range}-{end_range}") 95 | resp = requests.put( 96 | self.__upload_urls[clip], 97 | data=self.file_binary[start_range:end_range], 98 | headers=self.headers 99 | ) 100 | resp.raise_for_status() 101 | etag = resp.headers.get("Etag") 102 | self.__etags.append(etag) 103 | logging.info(f"分片{clip}上传成功: {etag}") 104 | 105 | def __commit_upload(self) -> None: 106 | """提交上传数据""" 107 | data = json.dumps({ 108 | "InBossKey": self.__in_boss_key, 109 | "ResourceId": self.__resource_id, 110 | "Etags": ",".join(self.__etags), 111 | "UploadId": self.__upload_id, 112 | "model_id": "8", 113 | }) 114 | resp = requests.post( 115 | API_COMMIT_UPLOAD, 116 | data=data, 117 | headers=self.headers 118 | ) 119 | resp.raise_for_status() 120 | resp = resp.json() 121 | self.__download_url = resp["data"]["download_url"] 122 | logging.info(f"提交成功") 123 | 124 | def create_task(self) -> str: 125 | """开始创建转换任务""" 126 | resp = requests.post( 127 | API_CREATE_TASK, json={"resource": self.__download_url, "model_id": "8"}, headers=self.headers 128 | ) 129 | resp.raise_for_status() 130 | resp = resp.json() 131 | self.task_id = resp["data"]["task_id"] 132 | logging.info(f"任务已创建: {self.task_id}") 133 | return self.task_id 134 | 135 | def result(self, task_id: Optional[str] = None): 136 | """查询转换结果""" 137 | resp = requests.get(API_QUERY_RESULT, params={"model_id": 7, "task_id": task_id or self.task_id}, headers=self.headers) 138 | resp.raise_for_status() 139 | resp = resp.json() 140 | return resp["data"] 141 | 142 | def _run(self): 143 | self.upload() 144 | self.create_task() 145 | # 轮询检查任务状态 146 | for _ in range(500): 147 | task_resp = self.result() 148 | if task_resp["state"] == 4: 149 | break 150 | time.sleep(1) 151 | logging.info(f"转换成功") 152 | return json.loads(task_resp["result"]) 153 | 154 | def _make_segments(self, resp_data: dict) -> list[ASRDataSeg]: 155 | return [ASRDataSeg(u['transcript'], u['start_time'], u['end_time']) for u in resp_data['utterances']] 156 | 157 | 158 | if __name__ == '__main__': 159 | logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") 160 | # Example usage 161 | audio_file = r"test.mp3" 162 | asr = BcutASR(audio_file) 163 | asr_data = asr.run() 164 | print(asr_data) 165 | -------------------------------------------------------------------------------- /bk_asr/JianYingASR.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import hashlib 3 | import hmac 4 | import json 5 | import os 6 | import time 7 | import uuid 8 | from typing import Dict, Tuple, Union 9 | 10 | import requests 11 | 12 | from .ASRData import ASRDataSeg 13 | from .BaseASR import BaseASR 14 | 15 | 16 | # from ASRData import ASRDataSeg 17 | # from BaseASR import BaseASR 18 | 19 | class JianYingASR(BaseASR): 20 | def __init__(self, audio_path: Union[str, bytes], use_cache: bool = False, need_word_time_stamp: bool = False, 21 | start_time: float = 0, end_time: float = 6000): 22 | super().__init__(audio_path, use_cache) 23 | self.audio_path = audio_path 24 | self.end_time = end_time 25 | self.start_time = start_time 26 | 27 | # AWS credentials 28 | self.session_token = None 29 | self.secret_key = None 30 | self.access_key = None 31 | 32 | # Upload details 33 | self.store_uri = None 34 | self.auth = None 35 | self.upload_id = None 36 | self.session_key = None 37 | self.upload_hosts = None 38 | 39 | self.need_word_time_stamp = need_word_time_stamp 40 | self.tdid = "3943278516897751" if datetime.datetime.now().year != 2024 else f"{uuid.getnode():012d}" 41 | 42 | def submit(self) -> str: 43 | """Submit the task""" 44 | url = "https://lv-pc-api-sinfonlinec.ulikecam.com/lv/v1/audio_subtitle/submit" 45 | payload = { 46 | "adjust_endtime": 200, 47 | "audio": self.store_uri, 48 | "caption_type": 2, 49 | "client_request_id": "45faf98c-160f-4fae-a649-6d89b0fe35be", 50 | "max_lines": 1, 51 | "songs_info": [{"end_time": self.end_time, "id": "", "start_time": self.start_time}], 52 | "words_per_line": 16 53 | } 54 | 55 | sign, device_time = self._generate_sign_parameters(url='/lv/v1/audio_subtitle/submit', pf='4', appvr='4.0.0', 56 | tdid=self.tdid) 57 | headers = self._build_headers(device_time, sign) 58 | response = requests.post(url, json=payload, headers=headers) 59 | query_id = response.json()['data']['id'] 60 | return query_id 61 | 62 | def upload(self): 63 | """Upload the file""" 64 | self._upload_sign() 65 | self._upload_auth() 66 | self._upload_file() 67 | self._upload_check() 68 | uri = self._upload_commit() 69 | return uri 70 | 71 | def query(self, query_id: str): 72 | """Query the task""" 73 | url = "https://lv-pc-api-sinfonlinec.ulikecam.com/lv/v1/audio_subtitle/query" 74 | payload = { 75 | "id": query_id, 76 | "pack_options": {"need_attribute": True} 77 | } 78 | sign, device_time = self._generate_sign_parameters(url='/lv/v1/audio_subtitle/query', pf='4', appvr='4.0.0', 79 | tdid=self.tdid) 80 | headers = self._build_headers(device_time, sign) 81 | response = requests.post(url, json=payload, headers=headers) 82 | return response.json() 83 | 84 | def _run(self, callback=None): 85 | # logging.info("正在上传文件...") 86 | if callback: 87 | callback(20, "正在上传...") 88 | self.upload() 89 | if callback: 90 | callback(50, "提交任务...") 91 | query_id = self.submit() 92 | if callback: 93 | callback(60, "获取结果...") 94 | resp_data = self.query(query_id) 95 | if callback: 96 | callback(100, "转录完成") 97 | return resp_data 98 | 99 | def _make_segments(self, resp_data: dict) -> list[ASRDataSeg]: 100 | if self.need_word_time_stamp: 101 | return [ASRDataSeg(w['text'].strip(), w['start_time'], w['end_time']) for u in 102 | resp_data['data']['utterances'] for w in u['words']] 103 | else: 104 | return [ASRDataSeg(u['text'], u['start_time'], u['end_time']) for u in resp_data['data']['utterances']] 105 | 106 | def _get_key(self): 107 | return f"{self.__class__.__name__}-{self.crc32_hex}-{self.need_word_time_stamp}" 108 | 109 | def _generate_sign_parameters(self, url: str, pf: str = '4', appvr: str = '4.0.0', tdid='') -> \ 110 | Tuple[str, str]: 111 | """Generate signature and timestamp via an HTTP request""" 112 | current_time = str(int(time.time())) 113 | data = { 114 | 'url': url, 115 | 'current_time': current_time, 116 | 'pf': pf, 117 | 'appvr': appvr, 118 | 'tdid': self.tdid 119 | } 120 | # Replace with your actual endpoint URL 121 | get_sign_url = 'https://asrtools-update.bkfeng.top/sign' 122 | try: 123 | response = requests.post(get_sign_url, json=data) 124 | response.raise_for_status() 125 | response_data = response.json() 126 | sign = response_data.get('sign') 127 | if not sign: 128 | raise ValueError("No 'sign' in response") 129 | except requests.exceptions.RequestException as e: 130 | raise SystemExit(f"HTTP Request failed: {e}") 131 | except ValueError as ve: 132 | raise SystemExit(f"Invalid response: {ve}") 133 | return sign.lower(), current_time 134 | 135 | def _build_headers(self, device_time: str, sign: str) -> Dict[str, str]: 136 | """Build headers for requests""" 137 | return { 138 | 'User-Agent': "Cronet/TTNetVersion:01594da2 2023-03-14 QuicVersion:46688bb4 2022-11-28", 139 | 'appvr': "4.0.0", 140 | 'device-time': str(device_time), 141 | 'pf': "4", 142 | 'sign': sign, 143 | 'sign-ver': "1", 144 | 'tdid': self.tdid, 145 | } 146 | 147 | def _uplosd_headers(self): 148 | headers = { 149 | 'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 Thea/1.0.1", 150 | 'Authorization': self.auth, 151 | 'Content-CRC32': self.crc32_hex, 152 | } 153 | return headers 154 | 155 | def _upload_sign(self): 156 | """Get upload sign""" 157 | url = "https://lv-pc-api-sinfonlinec.ulikecam.com/lv/v1/upload_sign" 158 | payload = json.dumps({"biz": "pc-recognition"}) 159 | sign, device_time = self._generate_sign_parameters(url='/lv/v1/upload_sign', pf='4', appvr='4.0.0', 160 | tdid=self.tdid) 161 | headers = self._build_headers(device_time, sign) 162 | response = requests.post(url, data=payload, headers=headers) 163 | response.raise_for_status() 164 | login_data = response.json() 165 | self.access_key = login_data['data']['access_key_id'] 166 | self.secret_key = login_data['data']['secret_access_key'] 167 | self.session_token = login_data['data']['session_token'] 168 | return self.access_key, self.secret_key, self.session_token 169 | 170 | def _upload_auth(self): 171 | """Get upload authorization""" 172 | if isinstance(self.audio_path, bytes): 173 | file_size = len(self.audio_path) 174 | else: 175 | file_size = os.path.getsize(self.audio_path) 176 | request_parameters = f'Action=ApplyUploadInner&FileSize={file_size}&FileType=object&IsInner=1&SpaceName=lv-mac-recognition&Version=2020-11-19&s=5y0udbjapi' 177 | 178 | t = datetime.datetime.utcnow() 179 | amz_date = t.strftime('%Y%m%dT%H%M%SZ') 180 | datestamp = t.strftime('%Y%m%d') 181 | headers = { 182 | "x-amz-date": amz_date, 183 | "x-amz-security-token": self.session_token 184 | } 185 | signature = aws_signature(self.secret_key, request_parameters, headers, region="cn", service="vod") 186 | authorization = f"AWS4-HMAC-SHA256 Credential={self.access_key}/{datestamp}/cn/vod/aws4_request, SignedHeaders=x-amz-date;x-amz-security-token, Signature={signature}" 187 | headers["authorization"] = authorization 188 | response = requests.get(f"https://vod.bytedanceapi.com/?{request_parameters}", headers=headers) 189 | store_infos = response.json() 190 | 191 | self.store_uri = store_infos['Result']['UploadAddress']['StoreInfos'][0]['StoreUri'] 192 | self.auth = store_infos['Result']['UploadAddress']['StoreInfos'][0]['Auth'] 193 | self.upload_id = store_infos['Result']['UploadAddress']['StoreInfos'][0]['UploadID'] 194 | self.session_key = store_infos['Result']['UploadAddress']['SessionKey'] 195 | self.upload_hosts = store_infos['Result']['UploadAddress']['UploadHosts'][0] 196 | self.store_uri = store_infos['Result']['UploadAddress']['StoreInfos'][0]['StoreUri'] 197 | return store_infos 198 | 199 | def _upload_file(self): 200 | """Upload the file""" 201 | url = f"https://{self.upload_hosts}/{self.store_uri}?partNumber=1&uploadID={self.upload_id}" 202 | headers = self._uplosd_headers() 203 | response = requests.put(url, data=self.file_binary, headers=headers) 204 | resp_data = response.json() 205 | assert resp_data['success'] == 0, f"File upload failed: {response.text}" 206 | return resp_data 207 | 208 | def _upload_check(self): 209 | """Check upload result""" 210 | url = f"https://{self.upload_hosts}/{self.store_uri}?uploadID={self.upload_id}" 211 | payload = f"1:{self.crc32_hex}" 212 | headers = self._uplosd_headers() 213 | response = requests.post(url, data=payload, headers=headers) 214 | resp_data = response.json() 215 | return resp_data 216 | 217 | def _upload_commit(self): 218 | """Commit the uploaded file""" 219 | url = f"https://{self.upload_hosts}/{self.store_uri}?uploadID={self.upload_id}&partNumber=1&x-amz-security-token={self.session_token}" 220 | headers = self._uplosd_headers() 221 | response = requests.put(url, data=self.file_binary, headers=headers) 222 | return self.store_uri 223 | 224 | 225 | def sign(key: bytes, msg: str) -> bytes: 226 | """使用HMAC-SHA256生成签名""" 227 | return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() 228 | 229 | 230 | def get_signature_key(secret_key: str, date_stamp: str, region_name: str, service_name: str) -> bytes: 231 | """生成用于AWS签名的密钥""" 232 | k_date = sign(('AWS4' + secret_key).encode('utf-8'), date_stamp) 233 | k_region = sign(k_date, region_name) 234 | k_service = sign(k_region, service_name) 235 | k_signing = sign(k_service, 'aws4_request') 236 | return k_signing 237 | 238 | 239 | def aws_signature(secret_key: str, request_parameters: str, headers: Dict[str, str], 240 | method: str = "GET", payload: str = '', region: str = "cn", service: str = "vod") -> str: 241 | """生成AWS签名""" 242 | canonical_uri = '/' 243 | canonical_querystring = request_parameters 244 | canonical_headers = '\n'.join([f"{key}:{value}" for key, value in headers.items()]) + '\n' 245 | signed_headers = ';'.join(headers.keys()) 246 | payload_hash = hashlib.sha256(payload.encode('utf-8')).hexdigest() 247 | canonical_request = f"{method}\n{canonical_uri}\n{canonical_querystring}\n{canonical_headers}\n{signed_headers}\n{payload_hash}" 248 | 249 | amzdate = headers["x-amz-date"] 250 | datestamp = amzdate.split('T')[0] 251 | 252 | algorithm = 'AWS4-HMAC-SHA256' 253 | credential_scope = f"{datestamp}/{region}/{service}/aws4_request" 254 | string_to_sign = f"{algorithm}\n{amzdate}\n{credential_scope}\n{hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()}" 255 | 256 | signing_key = get_signature_key(secret_key, datestamp, region, service) 257 | signature = hmac.new(signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest() 258 | return signature 259 | -------------------------------------------------------------------------------- /bk_asr/KuaiShouASR.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | from .ASRData import ASRDataSeg 4 | from .BaseASR import BaseASR 5 | 6 | 7 | class KuaiShouASR(BaseASR): 8 | def __init__(self, audio_path: [str, bytes], use_cache: bool = False): 9 | super().__init__(audio_path, use_cache) 10 | 11 | def _run(self) -> dict: 12 | return self._submit() 13 | 14 | def _make_segments(self, resp_data: dict) -> list[ASRDataSeg]: 15 | return [ASRDataSeg(u['text'], u['start_time'], u['end_time']) for u in resp_data['data']['text']] 16 | 17 | def _submit(self) -> dict: 18 | payload = { 19 | "typeId": "1" 20 | } 21 | files = [('file', ('test.mp3', self.file_binary, 'audio/mpeg'))] 22 | result = requests.post("https://ai.kuaishou.com/api/effects/subtitle_generate", data=payload, files=files) 23 | return result.json() 24 | -------------------------------------------------------------------------------- /bk_asr/WhisperASR.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from openai import OpenAI 4 | 5 | from .ASRData import ASRDataSeg 6 | from .BaseASR import BaseASR 7 | 8 | 9 | 10 | class WhisperASR(BaseASR): 11 | def __init__(self, audio_path: [str, bytes], model: str = MODEL, use_cache: bool = False): 12 | super().__init__(audio_path, use_cache) 13 | self.base_url = os.getenv('OPENAI_BASE_URL') 14 | self.api_key = os.getenv('OPENAI_API_KEY') 15 | if not self.base_url or not self.api_key: 16 | raise ValueError("环境变量 OPENAI_BASE_URL 和 OPENAI_API_KEY 必须设置") 17 | self.model = model 18 | self.client = OpenAI(base_url=self.base_url, api_key=self.api_key) 19 | 20 | def _run(self) -> dict: 21 | return self._submit() 22 | 23 | def _make_segments(self, resp_data: dict) -> list[ASRDataSeg]: 24 | return [ASRDataSeg(u['text'], u['start'], u['end']) for u in resp_data['segments']] 25 | 26 | def _get_key(self) -> str: 27 | return f"{self.__class__.__name__}-{self.model}-{self.crc32_hex}-{self.model}" 28 | 29 | def _submit(self) -> dict: 30 | completion = self.client.audio.transcriptions.create( 31 | model=self.model, 32 | temperature=0, 33 | response_format="verbose_json", 34 | file=("test.mp3", self.file_binary, "audio/mp3"), 35 | prompt="", 36 | language="zh" 37 | ) 38 | return completion.to_dict() 39 | 40 | 41 | -------------------------------------------------------------------------------- /bk_asr/__init__.py: -------------------------------------------------------------------------------- 1 | from .BcutASR import BcutASR 2 | from .JianYingASR import JianYingASR 3 | from .KuaiShouASR import KuaiShouASR 4 | # from .WhisperASR import WhisperASR 5 | 6 | __all__ = ["BcutASR", "JianYingASR", "KuaiShouASR"] 7 | 8 | 9 | def transcribe(audio_file, platform): 10 | assert platform in __all__ 11 | asr = globals()[platform](audio_file) 12 | return asr.run() 13 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | from bk_asr import BcutASR, JianYingASR, KuaiShouASR 2 | 3 | 4 | if __name__ == '__main__': 5 | audio_file = "resources/test.mp3" 6 | asr = JianYingASR(audio_file) 7 | result = asr.run() 8 | result.to_srt() 9 | print(result.to_srt()) -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WEIFENG2333/AsrTools/ef53930df9f4dc934a239cd6a7c317e46a0c0d9e/requirements.txt -------------------------------------------------------------------------------- /resources/main_window-1.1.0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WEIFENG2333/AsrTools/ef53930df9f4dc934a239cd6a7c317e46a0c0d9e/resources/main_window-1.1.0.png -------------------------------------------------------------------------------- /resources/test.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WEIFENG2333/AsrTools/ef53930df9f4dc934a239cd6a7c317e46a0c0d9e/resources/test.mp3 -------------------------------------------------------------------------------- /resources/test.srt: -------------------------------------------------------------------------------- 1 | 1 2 | 00:00:00,240 --> 00:00:01,880 3 | 根据视频的字幕 4 | 5 | 2 6 | 00:00:02,080 --> 00:00:04,200 7 | 详细总结视频的内容 8 | 9 | 3 10 | 00:00:04,320 --> 00:00:07,080 11 | 包括视频可能的详细类型 12 | 13 | 4 14 | 00:00:07,080 --> 00:00:10,840 15 | mysical教程英文电视剧电影片段 16 | 17 | 5 18 | 00:00:10,880 --> 00:00:14,320 19 | 日本动漫关于某某的视频会议 20 | 21 | 6 22 | 00:00:14,440 --> 00:00:17,200 23 | 关于某某的中文演讲等等 24 | --------------------------------------------------------------------------------