├── .gitignore ├── LICENSE ├── README.md ├── app.py ├── requirements.txt ├── transcribe.py └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .nox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | .hypothesis/ 49 | .pytest_cache/ 50 | cover/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | db.sqlite3 60 | db.sqlite3-journal 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | docs/_build/doctrees/ 72 | docs/_build/html/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # Celery stuff 88 | celerybeat-schedule 89 | celerybeat.pid 90 | 91 | # SageMath parsed files 92 | *.sage.py 93 | 94 | # Environments 95 | .env 96 | .venv 97 | env/ 98 | venv/ 99 | ENV/ 100 | env.bak/ 101 | venv.bak/ 102 | 103 | # Spyder project settings 104 | .spyderproject 105 | .spyproject 106 | 107 | # Rope project settings 108 | .ropeproject 109 | 110 | # mkdocs documentation 111 | /site 112 | 113 | # mypy 114 | .mypy_cache/ 115 | .dmypy.json 116 | dmypy.json 117 | 118 | # Pyre type checker 119 | .pyre/ 120 | 121 | # pyright type checker 122 | .pyright/ 123 | 124 | # End of https://www.toptal.com/developers/gitignore/api/python 125 | 126 | .idea -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. Copyright and Similar Rights means copyright and/or similar rights 88 | closely related to copyright including, without limitation, 89 | performance, broadcast, sound recording, and Sui Generis Database 90 | Rights, without regard to how the rights are labeled or 91 | categorized. For purposes of this Public License, the rights 92 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 93 | Rights. 94 | d. Effective Technological Measures means those measures that, in the 95 | absence of proper authority, may not be circumvented under laws 96 | fulfilling obligations under Article 11 of the WIPO Copyright 97 | Treaty adopted on December 20, 1996, and/or similar international 98 | agreements. 99 | 100 | e. Exceptions and Limitations means fair use, fair dealing, and/or 101 | any other exception or limitation to Copyright and Similar Rights 102 | that applies to Your use of the Licensed Material. 103 | 104 | f. Licensed Material means the artistic or literary work, database, 105 | or other material to which the Licensor applied this Public 106 | License. 107 | 108 | g. Licensed Rights means the rights granted to You subject to the 109 | terms and conditions of this Public License, which are limited to 110 | all Copyright and Similar Rights that apply to Your use of the 111 | Licensed Material and that the Licensor has authority to license. 112 | 113 | h. Licensor means the individual(s) or entity(ies) granting rights 114 | under this Public License. 115 | 116 | i. NonCommercial means not primarily intended for or directed towards 117 | commercial advantage or monetary compensation. For purposes of 118 | this Public License, the exchange of the Licensed Material for 119 | other material subject to Copyright and Similar Rights by digital 120 | file-sharing or similar means is NonCommercial provided there is 121 | no payment of monetary compensation in connection with the 122 | exchange. 123 | 124 | j. Share means to provide material to the public by any means or 125 | process that requires permission under the Licensed Rights, such 126 | as reproduction, public display, public performance, distribution, 127 | dissemination, communication, or importation, and to make material 128 | available to the public including in ways that members of the 129 | public may access the material from a place and at a time 130 | individually chosen by them. 131 | 132 | k. Sui Generis Database Rights means rights other than copyright 133 | resulting from Directive 96/9/EC of the European Parliament and of 134 | the Council of 11 March 1996 on the legal protection of databases, 135 | as amended and/or succeeded, as well as other essentially 136 | equivalent rights anywhere in the world. 137 | 138 | l. You means the individual or entity exercising the Licensed Rights 139 | under this Public License. Your has a corresponding meaning. 140 | 141 | 142 | Section 2 -- Scope. 143 | 144 | a. License grant. 145 | 146 | 1. Subject to the terms and conditions of this Public License, 147 | the Licensor hereby grants You a worldwide, royalty-free, 148 | non-sublicensable, non-exclusive, irrevocable license to 149 | exercise the Licensed Rights in the Licensed Material to: 150 | 151 | a. reproduce and Share the Licensed Material, in whole or 152 | in part, for NonCommercial purposes only; and 153 | 154 | b. produce, reproduce, and Share Adapted Material for 155 | NonCommercial purposes only. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. No downstream restrictions. You may not offer or impose 186 | any additional or different terms or conditions on, or 187 | apply any Effective Technological Measures to, the 188 | Licensed Material if doing so restricts exercise of the 189 | Licensed Rights by any recipient of the Licensed 190 | Material. 191 | 192 | 6. No endorsement. Nothing in this Public License constitutes or 193 | may be construed as permission to assert or imply that You 194 | are, or that Your use of the Licensed Material is, connected 195 | with, or sponsored, endorsed, or granted official status by, 196 | the Licensor or others designated to receive attribution as 197 | provided in Section 3(a)(1)(A)(i). 198 | 199 | b. Other rights. 200 | 201 | 1. Moral rights, such as the right of integrity, are not 202 | licensed under this Public License, nor are publicity, 203 | privacy, and/or other similar personality rights; however, to 204 | the extent possible, the Licensor waives and/or agrees not to 205 | assert any such rights held by the Licensor to the limited 206 | extent necessary to allow You to exercise the Licensed 207 | Rights, but not otherwise. 208 | 209 | 2. Patent and trademark rights are not licensed under this 210 | Public License. 211 | 212 | 3. To the extent possible, the Licensor waives any right to 213 | collect royalties from You for the exercise of the Licensed 214 | Rights, whether directly or through a collecting society 215 | under any voluntary or waivable statutory or compulsory 216 | licensing scheme. In all other cases the Licensor expressly 217 | reserves any right to collect such royalties, including when 218 | the Licensed Material is used other than for NonCommercial 219 | purposes. 220 | 221 | 222 | Section 3 -- License Conditions. 223 | 224 | Your exercise of the Licensed Rights is expressly made subject to the 225 | following conditions. 226 | 227 | a. Attribution. 228 | 229 | 1. If You Share the Licensed Material (including in modified 230 | form), You must: 231 | 232 | a. retain the following if it is supplied by the Licensor 233 | with the Licensed Material: 234 | 235 | i. identification of the creator(s) of the Licensed 236 | Material and any others designated to receive 237 | attribution, in any reasonable manner requested by 238 | the Licensor (including by pseudonym if 239 | designated); 240 | 241 | ii. a copyright notice; 242 | 243 | iii. a notice that refers to this Public License; 244 | 245 | iv. a notice that refers to the disclaimer of 246 | warranties; 247 | 248 | v. a URI or hyperlink to the Licensed Material to the 249 | extent reasonably practicable; 250 | 251 | b. indicate if You modified the Licensed Material and 252 | retain an indication of any previous modifications; and 253 | 254 | c. indicate the Licensed Material is licensed under this 255 | Public License, and include the text of, or the URI or 256 | hyperlink to, this Public License. 257 | 258 | 2. You may satisfy the conditions in Section 3(a)(1) in any 259 | reasonable manner based on the medium, means, and context in 260 | which You Share the Licensed Material. For example, it may be 261 | reasonable to satisfy the conditions by providing a URI or 262 | hyperlink to a resource that includes the required 263 | information. 264 | 265 | 3. If requested by the Licensor, You must remove any of the 266 | information required by Section 3(a)(1)(A) to the extent 267 | reasonably practicable. 268 | 269 | 4. If You Share Adapted Material You produce, the Adapter's 270 | License You apply must not prevent recipients of the Adapted 271 | Material from complying with this Public License. 272 | 273 | 274 | Section 4 -- Sui Generis Database Rights. 275 | 276 | Where the Licensed Rights include Sui Generis Database Rights that 277 | apply to Your use of the Licensed Material: 278 | 279 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 280 | to extract, reuse, reproduce, and Share all or a substantial 281 | portion of the contents of the database for NonCommercial purposes 282 | only; 283 | 284 | b. if You include all or a substantial portion of the database 285 | contents in a database in which You have Sui Generis Database 286 | Rights, then the database in which You have Sui Generis Database 287 | Rights (but not its individual contents) is Adapted Material; and 288 | 289 | c. You must comply with the conditions in Section 3(a) if You Share 290 | all or a substantial portion of the contents of the database. 291 | 292 | For the avoidance of doubt, this Section 4 supplements and does not 293 | replace Your obligations under this Public License where the Licensed 294 | Rights include other Copyright and Similar Rights. 295 | 296 | 297 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 298 | 299 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 300 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 301 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 302 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 303 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 304 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 305 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 306 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 307 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 308 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 309 | 310 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 311 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 312 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 313 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 314 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 315 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 316 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 317 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 318 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 319 | 320 | c. The disclaimer of warranties and limitation of liability provided 321 | above shall be interpreted in a manner that, to the extent 322 | possible, most closely approximates an absolute disclaimer and 323 | waiver of all liability. 324 | 325 | 326 | Section 6 -- Term and Termination. 327 | 328 | a. This Public License applies for the term of the Copyright and 329 | Similar Rights licensed here. However, if You fail to comply with 330 | this Public License, then Your rights under this Public License 331 | terminate automatically. 332 | 333 | b. Where Your right to use the Licensed Material has terminated under 334 | Section 6(a), it reinstates: 335 | 336 | 1. automatically as of the date the violation is cured, provided 337 | it is cured within 30 days of Your discovery of the 338 | violation; or 339 | 340 | 2. upon express reinstatement by the Licensor. 341 | 342 | For the avoidance of doubt, this Section 6(b) does not affect any 343 | right the Licensor may have to seek remedies for Your violations 344 | of this Public License. 345 | 346 | c. For the avoidance of doubt, the Licensor may also offer the 347 | Licensed Material under separate terms or conditions or stop 348 | distributing the Licensed Material at any time; however, doing so 349 | will not terminate this Public License. 350 | 351 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 352 | License. 353 | 354 | 355 | Section 7 -- Other Terms and Conditions. 356 | 357 | a. The Licensor shall not be bound by any additional or different 358 | terms or conditions communicated by You unless expressly agreed. 359 | 360 | b. Any arrangements, understandings, or agreements regarding the 361 | Licensed Material not stated herein are separate from and 362 | independent of the terms and conditions of this Public License. 363 | 364 | 365 | Section 8 -- Interpretation. 366 | 367 | a. For the avoidance of doubt, this Public License does not, and 368 | shall not be interpreted to, reduce, limit, restrict, or impose 369 | conditions on any use of the Licensed Material that could lawfully 370 | be made without permission under this Public License. 371 | 372 | b. To the extent possible, if any provision of this Public License is 373 | deemed unenforceable, it shall be automatically reformed to the 374 | minimum extent necessary to make it enforceable. If the provision 375 | cannot be reformed, it shall be severed from this Public License 376 | without affecting the enforceability of the remaining terms and 377 | conditions. 378 | 379 | c. No term or condition of this Public License will be waived and no 380 | failure to comply consented to unless expressly agreed to by the 381 | Licensor. 382 | 383 | d. Nothing in this Public License constitutes or may be interpreted 384 | as a limitation upon, or waiver of, any privileges and immunities 385 | that apply to the Licensor or You, including from the legal 386 | processes of any jurisdiction or authority. 387 | 388 | ======================================================================= 389 | 390 | Creative Commons is not a party to its public 391 | licenses. Notwithstanding, Creative Commons may elect to apply one of 392 | its public licenses to material it publishes and in those instances 393 | will be considered the “Licensor.” The text of the Creative Commons 394 | public licenses is dedicated to the public domain under the CC0 Public 395 | Domain Dedication. Except for the limited purpose of indicating that 396 | material is shared under a Creative Commons public license or as 397 | otherwise permitted by the Creative Commons policies published at 398 | creativecommons.org/policies, Creative Commons does not authorize the 399 | use of the trademark "Creative Commons" or any other trademark or logo 400 | of Creative Commons without its prior written consent including, 401 | without limitation, in connection with any unauthorized modifications 402 | to any of its public licenses or any other arrangements, 403 | understandings, or agreements concerning use of licensed material. For 404 | the avoidance of doubt, this paragraph does not form part of the 405 | public licenses. 406 | 407 | Creative Commons may be contacted at creativecommons.org. 408 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CrisperWhisper 2 | 3 | **CrisperWhisper** is an advanced variant of OpenAI's Whisper, designed for fast, precise, and verbatim speech recognition with accurate (**crisp**) word-level timestamps. Unlike the original Whisper, which tends to omit disfluencies and follows more of a intended transcription style, CrisperWhisper aims to transcribe every spoken word exactly as it is, including fillers, pauses, stutters and false starts. 4 | 5 | ## Key Features 6 | 7 | - 🎯 **Accurate Word-Level Timestamps**: Provides precise timestamps, even around disfluencies and pauses, by utilizing an adjusted tokenizer and a custom attention loss during training. 8 | - 📝 **Verbatim Transcription**: Transcribes every spoken word exactly as it is, including and differentiating fillers like "um" and "uh". 9 | - 🔍 **Filler Detection**: Detects and accurately transcribes fillers. 10 | - 🛡️ **Hallucination Mitigation**: Minimizes transcription hallucinations to enhance accuracy. 11 | 12 | ## Table of Contents 13 | 14 | - [Key Features](#key-features) 15 | - [Highlights](#highlights) 16 | - [Performance Overview](#1-performance-overview) 17 | - [Qualitative Performance Overview](#11-qualitative-performance-overview) 18 | - [Quantitative Performance Overview](#12-quantitative-performance-overview) 19 | - [Transcription Performance](#transcription-performance) 20 | - [Segmentation Performance](#segmentation-performance) 21 | - [Setup](#2-setup-⚙️) 22 | - [Prerequisites](#21-prerequisites) 23 | - [Environment Setup](#22-environment-setup) 24 | - [Usage](#3-usage) 25 | - [with transformers](#31-usage-with-🤗-transformers) 26 | - [with faster whisper](#32-usage-with-faster-whisper) 27 | - [Running the Streamlit App](#4-running-the-streamlit-app) 28 | - [Prerequisites](#41-prerequisites) 29 | - [Steps to Run the Streamlit App](#42-steps-to-run-the-streamlit-app) 30 | - [Features of the App](#43-features-of-the-app) 31 | - [How](#5-how) 32 | - [License](#license) 33 | 34 | 35 | ## Highlights 36 | 37 | - 🏆 **1st place** on the [OpenASR Leaderboard](https://huggingface.co/spaces/hf-audio/open_asr_leaderboard) in verbatim datasets (TED, AMI) and overall. 38 | - 🎓 **Accepted at INTERSPEECH 2024**. 39 | - 📄 **Paper Drop**: Check out our [paper](https://arxiv.org/abs/2408.16589) for details and reasoning behind our tokenizer adjustment. 40 | - ✨ **New Feature**: Not mentioned in the paper is a added AttentionLoss to further improve timestamp accuracy. By specifically adding a loss to train the attention scores used for the DTW alignment using timestamped data we significantly boosted the alignment performance. 41 | 42 | 43 | 44 | ## 1. Performance Overview 45 | 46 | ### 1.1 Qualitative Performance Overview 47 | 48 | 49 | | Audio | Whisper Large V3 | Crisper Whisper | 50 | |-------|------------------------|------------------------| 51 | | [Demo de 1](https://github.com/user-attachments/assets/c8608ca8-5e02-4c4a-afd3-8f7c5bff75d5) | Er war kein Genie, aber doch ein fähiger Ingenieur. | Es ist zwar kein. Er ist zwar kein Genie, aber doch ein fähiger Ingenieur.| 52 | | [Demo de 2](https://github.com/user-attachments/assets/c68414b1-0f84-441c-b39b-29069487edb6) | Leider müssen wir in diesen schweren Zeiten auch unserem Tagesgeschäft nachgehen. Der hier vorgelegte Kulturhaushalt der Ampelregierung strebt an, den Erfolgskurs der Union zumindest fiskalisch fortzuführen. | Leider [UH] müssen wir in diesen [UH] schweren Zeiten auch [UH] unserem [UH] Tagesgeschäft nachgehen. Der hier [UH] vorgelegte [UH] Kulturhaushalt der [UH] Ampelregierung strebt an, den [UH] Erfolgskurs der Union [UH] zumindest [UH] fiskalisch fortzuführen. Es. | 53 | | [Demo de 3](https://github.com/user-attachments/assets/0c1ed60c-2829-47e4-b7ba-eb584b0a5e9a) | die über alle FRA-Fraktionen hinweg gut im Blick behalten sollten, auch weil sie teilweise sehr teeteuer sind. Aber nicht nur, weil sie teeteuer sind. Wir steigen mit diesem Endentwurf ein in die sogenannten Pandemie-Bereitschaftsverträge.| Die über alle Fr Fraktionen hinweg gut im [UH] Blick behalten sollten, auch weil sie teil teilweise sehr te teuer sind. Aber nicht nur, weil sie te teuer sind. Wir [UH] steigen mit diesem Ent Entwurf ein in die sogenannten Pand Pandemiebereitschaftsverträge. | 54 | | [Demo en 1](https://github.com/user-attachments/assets/cde5d69c-657f-4ae4-b4ae-b958ea2eacc5) | alternative is you can get like, you have those Dr. Bronner's| Alternative is you can get like [UH] you have those, you know, those doctor Brahmer's. | 55 | | [Demo en 2](https://github.com/user-attachments/assets/906e307d-5613-4c41-9c61-65f4beede1fd) | influence our natural surrounding? How does it influence our ecosystem? | Influence our [UM] our [UH] our natural surrounding. How does it influence our ecosystem? | 56 | | [Demo en 3](https://github.com/user-attachments/assets/6c09cd58-a574-4697-9a7e-92e416cf2522) | and always find a place on the street to park and it was easy and you weren't a long distance away from wherever it was that you were trying to go. So I remember that being a lot of fun and easy to do and there were nice places to go and good events to attend. Come downtown and you had the Warner Theater and | And always find a place on the street to park. And and it was it was easy and you weren't a long distance away from wherever it was that you were trying to go. So, I I I remember that being a lot of fun and easy to do and there were nice places to go and, [UM] i good events to attend. Come downtown and you had the Warner Theater and, [UM] | 57 | | [Demo en 4](https://github.com/user-attachments/assets/7df19486-5e4e-4443-8528-09b07dddf61a) | you know, more masculine, who were rough, and that definitely wasn't me. Then, you know, I was very smart because my father made sure I was smart, you know. So, you know, I hung around those people, you know. And then you had the ones that were just out doing things that they shouldn't have been doing also. So, yeah, I was in the little geek squad. You were in the little geek squad. Yeah. | you know, more masculine, who were rough, and that definitely wasn't me. Then, you know, I was very smart because my father made sure I was smart. You know, so, [UM] you know, I I hung around those people, you know. And then you had the ones that were just just out doing things that they shouldn't have been doing also. So yeah, I was the l I was in the little geek squad. Do you | 58 | 59 | ### 1.2 Quantitative Performance Overview 60 | 61 | #### Transcription Performance 62 | 63 | CrisperWhisper significantly outperforms Whisper Large v3, especially on datasets that have a more verbatim transcription style in the ground truth, such as AMI and TED-LIUM. 64 | 65 | | Dataset | CrisperWhisper | Whisper Large v3 | 66 | |----------------------|:--------------:|:----------------:| 67 | | [AMI](https://huggingface.co/datasets/edinburghcstr/ami) | **8.72** | 16.01 | 68 | | [Earnings22](https://huggingface.co/datasets/revdotcom/earnings22) | 12.37 | **11.3** | 69 | | [GigaSpeech](https://huggingface.co/datasets/speechcolab/gigaspeech) | 10.27 | **10.02** | 70 | | [LibriSpeech clean](https://huggingface.co/datasets/openslr/librispeech_asr) | **1.74** | 2.03 | 71 | | [LibriSpeech other](https://huggingface.co/datasets/openslr/librispeech_asr) | 3.97 | **3.91** | 72 | | [SPGISpeech](https://huggingface.co/datasets/kensho/spgispeech) | **2.71** | 2.95 | 73 | | [TED-LIUM](https://huggingface.co/datasets/LIUM/tedlium) | **3.35** | 3.9 | 74 | | [VoxPopuli](https://huggingface.co/datasets/facebook/voxpopuli) | **8.61** | 9.52 | 75 | | [CommonVoice](https://huggingface.co/datasets/mozilla-foundation/common_voice_9_0) | **8.19** | 9.67 | 76 | | **Average WER** | **6.66** | 7.7 | 77 | 78 | #### Segmentation Performance 79 | 80 | CrisperWhisper demonstrates superior performance segmentation performance. This performance gap is especially pronounced around disfluencies and pauses. 81 | The following table uses the metrics as defined in the paper. For this table we used a collar of 50ms. Heads for each Model were selected using the method described in the [How](#5-how) section and the result attaining the highest F1 Score was choosen for each model using varying number of heads. 82 | 83 | | Dataset | Metric | CrisperWhisper | Whisper Large v2 | Whisper Large v3 | 84 | |---------|--------|------------------|------------------|------------------| 85 | | [AMI IHM](https://groups.inf.ed.ac.uk/ami/corpus/) | F1 Score | **0.79** | 0.63 | 0.66 | 86 | | | Avg IOU | **0.67** | 0.54 | 0.53 | 87 | | [Common Voice](https://commonvoice.mozilla.org/en/datasets) | F1 Score | **0.80** | 0.42 | 0.48 | 88 | | | Avg IOU | **0.70** | 0.32 | 0.43 | 89 | | [TIMIT](https://catalog.ldc.upenn.edu/LDC93S1) | F1 Score | **0.69** | 0.40 | 0.54 | 90 | | | Avg IOU | **0.56** | 0.32 | 0.43 | 91 | 92 | More plots and ablations can be found in the `run_experiments/plots` folder. 93 | 94 | ## 2. Setup ⚙️ 95 | 96 | ### 2.1 Prerequisites 97 | 98 | - **Python**: 3.10 99 | - **PyTorch**: 2.0 100 | - **NVIDIA Libraries**: cuBLAS 11.x and cuDNN 8.x (for GPU execution) 101 | 102 | ### 2.2 Environment Setup 103 | 104 | 1. **Clone the Repository**: 105 | ```bash 106 | git clone https://github.com/nyrahealth/CrisperWhisper.git 107 | cd CrisperWhisper 108 | ``` 109 | 110 | 2. **Create Python Environment**: 111 | ```bash 112 | conda create --name crisperWhisper python=3.10 113 | conda activate crisperWhisper 114 | ``` 115 | 116 | 117 | 3. **Install Dependencies**: 118 | ```bash 119 | pip install -r requirements.txt 120 | ``` 121 | 122 | 4. **Additional Installations**: 123 | Follow OpenAI's instructions to install additional dependencies like `ffmpeg` and `rust`: [Whisper Setup](https://github.com/openai/whisper#setup). 124 | 125 | ## 3. Usage 126 | 127 | Here's how to use CrisperWhisper in your Python scripts: 128 | First install our custom transformers fork for the most accurate timestamps: 129 | ``` 130 | pip install git+https://github.com/nyrahealth/transformers.git@crisper_whisper 131 | ``` 132 | 133 | ### 3.1 Usage with 🤗 transformers 134 | First make sure that you have a huggingface account and accept the licensing of the [model](https://huggingface.co/nyrahealth/CrisperWhisper). Grab your huggingface access token and login so you are certainly able to download the model. 135 | 136 | ```bash 137 | huggingface-cli login 138 | ``` 139 | 140 | ```python 141 | import os 142 | import sys 143 | import torch 144 | 145 | from datasets import load_dataset 146 | from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline 147 | from utils import adjust_pauses_for_hf_pipeline_output 148 | 149 | 150 | 151 | device = "cuda:0" if torch.cuda.is_available() else "cpu" 152 | torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32 153 | 154 | model_id = "nyrahealth/CrisperWhisper" 155 | 156 | model = AutoModelForSpeechSeq2Seq.from_pretrained( 157 | model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True 158 | ) 159 | model.to(device) 160 | 161 | processor = AutoProcessor.from_pretrained(model_id) 162 | 163 | pipe = pipeline( 164 | "automatic-speech-recognition", 165 | model=model, 166 | tokenizer=processor.tokenizer, 167 | feature_extractor=processor.feature_extractor, 168 | chunk_length_s=30, 169 | batch_size=16, 170 | return_timestamps='word', 171 | torch_dtype=torch_dtype, 172 | device=device, 173 | ) 174 | 175 | dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation") 176 | sample = dataset[0]["audio"] 177 | hf_pipeline_output = pipe(sample) 178 | crisper_whisper_result = adjust_pauses_for_hf_pipeline_output(hf_pipeline_output) 179 | print(crisper_whisper_result) 180 | ``` 181 | ### 3.2 Usage with faster whisper 182 | 183 | We also provide a converted model to be compatible with [faster whisper](https://github.com/SYSTRAN/faster-whisper). However, due to the different implementation of the timestamp calculation in faster whisper or more precisely [CTranslate2](https://github.com/OpenNMT/CTranslate2/) the timestamp accuracy can not be guaranteed. 184 | 185 | First make sure that you have a huggingface account and accept the licensing of the [model](https://huggingface.co/nyrahealth/faster_CrisperWhisper). Grab your huggingface access token and login so you are certainly able to download the model. 186 | ```bash 187 | huggingface-cli login 188 | ``` 189 | 190 | ```python 191 | from faster_whisper import WhisperModel 192 | from datasets import load_dataset 193 | faster_whisper_model = 'nyrahealth/faster_CrisperWhisper' 194 | 195 | # Initialize the Whisper model 196 | 197 | device = "cuda:0" if torch.cuda.is_available() else "cpu" 198 | torch_dtype = "float16" if torch.cuda.is_available() else "float32" 199 | model = WhisperModel(faster_whisper_model, device=device, compute_type="float32") 200 | dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation") 201 | sample = dataset[0]["audio"] 202 | 203 | segments, info = model.transcribe(sample['array'], beam_size=1, language='en', word_timestamps = True, without_timestamps= True) 204 | 205 | for segment in segments: 206 | print(segment) 207 | ``` 208 | 209 | ### 3.3 Commandline usage 210 | 211 | First make sure that you have a huggingface account and accept the licensing of the model. Grab your huggingface access token and login so you are certainly able to download the model. 212 | ```bash 213 | huggingface-cli login 214 | ``` 215 | afterwards: 216 | 217 | To transcribe an audio file, use the following command: 218 | 219 | ```bash 220 | python transcribe.py --f 221 | ``` 222 | 223 | ## 4. Running the Streamlit App 224 | 225 | To use the CrisperWhisper model with a user-friendly interface, you can run the provided Streamlit app. This app allows you to record or upload audio files for transcription and view the results with accurate word-level timestamps. 226 | 227 | ### 4.1 Prerequisites 228 | 229 | Make sure you have followed the [Setup ⚙️](#setup) instructions above and have the `crisperWhisper` environment activated. 230 | 231 | ### 4.2 Steps to Run the Streamlit App 232 | 233 | 1. **Activate the Conda Environment** 234 | 235 | Ensure you are in the `crisperWhisper` environment: 236 | ```sh 237 | conda activate crisperWhisper 238 | ``` 239 | 240 | 2. **Navigate to the App Directory** 241 | 242 | Change directory to where the `app.py` script is located: 243 | 244 | 245 | 3. **Run the Streamlit App** 246 | 247 | Use the following command to run the app. Make sure to replace `/path/to/your/model` with the actual path to your CrisperWhisper model directory: 248 | ```sh 249 | streamlit run app.py -- --model_id /path/to/your/model 250 | ``` 251 | 252 | For example: 253 | ```sh 254 | streamlit run app.py -- --model_id nyrahealth/CrisperWhisper 255 | ``` 256 | 257 | 4. **Access the App** 258 | 259 | After running the command, the Streamlit server will start, and you can access the app in your web browser at: 260 | ``` 261 | http://localhost:8501 262 | ``` 263 | 264 | ### 4.3 Features of the App 265 | 266 | - **Record Audio**: Record audio directly using your microphone. 267 | - **Upload Audio**: Upload audio files in formats like WAV, MP3, or OGG. 268 | - **Transcription**: Get accurate verbatim transcriptions including fillers 269 | - **Video Generation**: View the transcription with timestamps alongside a video with a black background. 270 | 271 | ## 5. How? 272 | 273 | 274 | We employ the popular Dynamic Time Warping (DTW) on the Whisper cross-attention scores, as detailed in our [paper](https://arxiv.org/abs/2408.16589) to derive word-level timestamps. By leveraging our retokenization process, this method allows us to consistently detect pauses. Given that the accuracy of the timestamps heavily depends on the DTW cost matrix and, consequently, on the quality of the cross-attentions, we developed a specialized loss function for the selected alignment heads to enhance precision. 275 | 276 | Although this loss function was not included in the original [paper](https://arxiv.org/abs/2408.16589) due to time constraints preventing the completion of experiments and training before the submission deadline, it has been used to train our publicly available models. 277 | Key Features of this loss are as follows: 278 | 279 | 1. **Data Preparation** 280 | - We used datasets with word-level timestamp annotations, such as [AMI IHM](https://groups.inf.ed.ac.uk/ami/corpus/) and [TIMIT](https://catalog.ldc.upenn.edu/LDC93S1) , but required additional timestamped data. 281 | - To address this, we validated the alignment accuracy of several forced alignment tools using a small hand-labeled dataset. 282 | - Based on this validation, we chose the [PyTorch CTC aligner](https://pytorch.org/audio/main/tutorials/ctc_forced_alignment_api_tutorial.html) to generate more time-aligned data from the CommonVoice dataset. 283 | - Because the [PyTorch CTC aligner](https://pytorch.org/audio/main/tutorials/ctc_forced_alignment_api_tutorial.html) tends to overestimate pause durations, we applied the same pause-splitting method detailed in our [paper](...) to correct these errors. The effectiveness of this correction was confirmed using our hand-labeled dataset. 284 | 285 | 2. **Token-Word Alignment** 286 | - Due to retokenization as detailed in our [paper](https://arxiv.org/abs/2408.16589), each token is either part of a word or a pause/space, but never both 287 | - Therefore each token can be cleanly aligned to a word OR a space/pause 288 | 289 | 3. **Ground Truth Cross-Attention** 290 | - We define the cross-attention ground truth for tokens as the L2-normalized vector, where: 291 | - A value of 1 indicates that the word is active according to the word-level ground truth timestamp. 292 | - A value of 0 indicates that no attention should be paid. 293 | - To account for small inaccuracies in the ground truth timestamps, we apply a linear interpolation of 4 steps (8 milliseconds) on both sides of the ground truth vector, transitioning smoothly from 0 to 1. 294 | 295 | 4. **Loss Calculation** 296 | - The loss function is defined as `1 - cosine similarity` between the predicted cross-attention vector (when predicting a token) and the ground truth cross-attention vector. 297 | - This loss is averaged across all predicted tokens and alignment heads. 298 | 299 | 5 **Alignment Head selection** 300 | - To choose the heads for alignment we evaluated the alignment performance of each individual decoder attention head on the timestamped timit dataset. 301 | - We choose the 15 best performing heads and finetune them using our attention loss. 302 | 303 | 5. **Training Details** 304 | - Since most of our samples during training were shorter than 30 seconds we shift the audio sample and corresponding timestamp ground truth around with a 50% probability to mitigate the cross attentions ,,overfitting" to early positions of the encoder output. 305 | - If we have more than 40ms of silence (before or after shifting) we prepend the ground truth transcript ( and corresponding cross attention ground truth) with a space so the model has to accurately predict the starting time of the first word. 306 | - We use [WavLM](https://arxiv.org/abs/2110.13900) augmentations during Training adding random speech samples or noise to the audio wave to generally increase robustness of the transcription and stability of the alignment heads. 307 | - We clip ,,predicted" values in the cross attention vectors 4 seconds before and 4 seconds after the groundtruth word they belong to to 0. This is to decrease the dimensionality of the cross attention vector and therefore emphasize the attention where it counts in the loss and ultimately for the alignment. 308 | - With a probability of 1% we use samples containing exclusively noise where the model has to return a empty prediction to improve hallucination. 309 | - The Model is trained in three stages, in the first stage we use around 10000 hours of audio to adjust Whisper to the new tokenizer. In the second stage we exclusively use high quality datasets that are transcribed in a verbatim fashion. Finally we continue training on this verbatim mixture and add the attention loss for another 6000 steps. 310 | 311 | 312 | ## License 313 | 314 | ```markdown 315 | Shield: [![CC BY-NC 4.0][cc-by-nc-shield]][cc-by-nc] 316 | 317 | This work is licensed under a 318 | [Creative Commons Attribution-NonCommercial 4.0 International License][cc-by-nc]. 319 | 320 | [![CC BY-NC 4.0][cc-by-nc-image]][cc-by-nc] 321 | 322 | [cc-by-nc]: https://creativecommons.org/licenses/by-nc/4.0/ 323 | [cc-by-nc-image]: https://licensebuttons.net/l/by-nc/4.0/88x31.png 324 | [cc-by-nc-shield]: https://img.shields.io/badge/License-CC%20BY--NC%204.0-lightgrey.svg 325 | ``` 326 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import io 3 | from typing import Any, Dict, List, Tuple, Union 4 | 5 | import moviepy as mp 6 | import numpy as np 7 | import streamlit as st 8 | import torch 9 | import torchaudio 10 | import torchaudio.transforms as T 11 | from scipy.io import wavfile 12 | from streamlit_mic_recorder import mic_recorder 13 | from transformers import ( 14 | AutomaticSpeechRecognitionPipeline, 15 | AutoModelForSpeechSeq2Seq, 16 | AutoProcessor, 17 | pipeline, 18 | ) 19 | 20 | 21 | def parse_arguments() -> argparse.Namespace: 22 | """Parse command-line arguments.""" 23 | parser = argparse.ArgumentParser( 24 | description="Streamlit app for speech transcription." 25 | ) 26 | parser.add_argument( 27 | "--model_id", type=str, required=True, help="Path to the model directory" 28 | ) 29 | return parser.parse_args() 30 | 31 | 32 | # Load model and processor from the specified path 33 | @st.cache_resource # type: ignore 34 | def load_model_and_processor( 35 | model_id: str, 36 | ) -> Tuple[AutoModelForSpeechSeq2Seq, AutoProcessor]: 37 | model = AutoModelForSpeechSeq2Seq.from_pretrained( 38 | model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True 39 | ) 40 | model.to(device) 41 | model.generation_config.median_filter_width = 3 42 | processor = AutoProcessor.from_pretrained(model_id) 43 | return model, processor 44 | 45 | 46 | # Setup the pipeline 47 | @st.cache_resource # type: ignore 48 | def setup_pipeline( 49 | _model: AutoModelForSpeechSeq2Seq, _processor: AutoProcessor 50 | ) -> AutomaticSpeechRecognitionPipeline: 51 | return pipeline( 52 | "automatic-speech-recognition", 53 | model=_model, 54 | tokenizer=_processor.tokenizer, 55 | feature_extractor=_processor.feature_extractor, 56 | chunk_length_s=30, 57 | batch_size=1, 58 | return_timestamps=True, 59 | torch_dtype=torch_dtype, 60 | device=device, 61 | ) 62 | 63 | 64 | def wav_to_black_mp4(wav_path: str, output_path: str, fps: int = 25) -> None: 65 | """Convert WAV file to a black-screen MP4 with the same audio.""" 66 | waveform, sample_rate = torchaudio.load(wav_path) 67 | duration: float = waveform.shape[1] / sample_rate 68 | audio = mp.AudioFileClip(wav_path) 69 | black_clip = mp.ColorClip((256, 250), color=(0, 0, 0), duration=duration) 70 | final_clip = black_clip.with_audio(audio) 71 | final_clip.write_videofile(output_path, fps=fps) 72 | 73 | 74 | def timestamps_to_vtt(timestamps: List[Dict[str, Union[str, Any]]]) -> str: 75 | """Convert timestamps to VTT format.""" 76 | vtt_content: str = "WEBVTT\n\n" 77 | for word in timestamps: 78 | start_time, end_time = word["timestamp"] 79 | start_time_str = f"{int(start_time // 3600)}:{int(start_time // 60 % 60):02d}:{start_time % 60:06.3f}" 80 | end_time_str = f"{int(end_time // 3600)}:{int(end_time // 60 % 60):02d}:{end_time % 60:06.3f}" 81 | vtt_content += f"{start_time_str} --> {end_time_str}\n{word['text']}\n\n" 82 | return vtt_content 83 | 84 | 85 | def process_audio_bytes(audio_bytes: bytes) -> torch.Tensor: 86 | """Process audio bytes to the required format.""" 87 | audio_stream = io.BytesIO(audio_bytes) 88 | sr, y = wavfile.read(audio_stream) 89 | y = y.astype(np.float32) 90 | y_mean = np.mean(y) 91 | y_std = np.std(y) 92 | y_normalized = (y - y_mean) / y_std 93 | transform = T.Resample(sr, 16000) 94 | waveform = transform(torch.unsqueeze(torch.tensor(y_normalized / 8), 0)) 95 | torchaudio.save("sample.wav", waveform, sample_rate=16000) 96 | return waveform 97 | 98 | 99 | def transcribe(audio_bytes: bytes) -> Dict[str, Any]: 100 | """Transcribe the given audio bytes.""" 101 | waveform = process_audio_bytes(audio_bytes) 102 | transcription = pipe(waveform[0, :].numpy(), return_timestamps="word") 103 | return transcription 104 | 105 | 106 | args = parse_arguments() 107 | model_id = args.model_id 108 | 109 | # Set up device and data type for processing 110 | device: str = "cuda:0" if torch.cuda.is_available() else "cpu" 111 | torch_dtype: torch.dtype = torch.float16 if torch.cuda.is_available() else torch.float32 112 | model, processor = load_model_and_processor(model_id) 113 | pipe = setup_pipeline(model, processor) 114 | 115 | # Streamlit app interface 116 | st.title("CrisperWhisper++ 🦻") 117 | st.subheader("Caution when using. Make sure you can handle the crispness. ⚠️") 118 | st.write("🎙️ Record an audio to transcribe or 📁 upload an audio file.") 119 | 120 | # Audio recorder component 121 | audio = mic_recorder( 122 | start_prompt="Start recording", 123 | stop_prompt="Stop recording", 124 | just_once=False, 125 | use_container_width=False, 126 | format="wav", 127 | callback=None, 128 | args=(), 129 | kwargs={}, 130 | key=None, 131 | ) 132 | 133 | audio_bytes: Union[bytes, None] = audio["bytes"] if audio else None 134 | 135 | # Audio file upload handling 136 | audio_file = st.file_uploader("Or upload an audio file", type=["wav", "mp3", "ogg"]) 137 | 138 | if audio_file is not None: 139 | audio_bytes = audio_file.getvalue() 140 | 141 | if audio_bytes: 142 | try: 143 | transcription = transcribe(audio_bytes) 144 | vtt = timestamps_to_vtt(transcription["chunks"]) 145 | 146 | with open("subtitles.vtt", "w") as file: 147 | file.write(vtt) 148 | 149 | wav_to_black_mp4("sample.wav", "video.mp4") 150 | 151 | st.video("video.mp4", subtitles="subtitles.vtt") 152 | st.subheader("Transcription:") 153 | st.markdown( 154 | f""" 155 |
156 |

{transcription['text']}

157 |
158 | """, 159 | unsafe_allow_html=True, 160 | ) 161 | except Exception as e: 162 | st.error(f"An error occurred during transcription: {e}") 163 | 164 | # Footer 165 | st.markdown( 166 | """ 167 |
168 | 171 | """, 172 | unsafe_allow_html=True, 173 | ) 174 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch 2 | torchaudio 3 | git+https://github.com/nyrahealth/transformers.git@crisper_whisper 4 | accelerate 5 | scipy 6 | streamlit 7 | moviepy 8 | streamlit_mic_recorder 9 | librosa 10 | -------------------------------------------------------------------------------- /transcribe.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import sys 4 | import torch 5 | from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline 6 | 7 | 8 | def transcribe_audio(file_path): 9 | device = "cuda:0" if torch.cuda.is_available() else "cpu" 10 | torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32 11 | 12 | model_id = "nyrahealth/CrisperWhisper" # You can change this to a different model if needed 13 | 14 | model = AutoModelForSpeechSeq2Seq.from_pretrained( 15 | model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True 16 | ) 17 | model.to(device) 18 | 19 | processor = AutoProcessor.from_pretrained(model_id) 20 | 21 | pipe = pipeline( 22 | "automatic-speech-recognition", 23 | model=model, 24 | tokenizer=processor.tokenizer, 25 | feature_extractor=processor.feature_extractor, 26 | chunk_length_s=30, 27 | batch_size=16, 28 | return_timestamps="word", 29 | torch_dtype=torch_dtype, 30 | device=device, 31 | ) 32 | 33 | result = pipe(file_path) 34 | return result 35 | 36 | 37 | def main(): 38 | parser = argparse.ArgumentParser(description="Transcribe an audio file.") 39 | parser.add_argument("--f", type=str, required=True, help="Path to the audio file") 40 | args = parser.parse_args() 41 | 42 | if not os.path.exists(args.f): 43 | print(f"Error: The file '{args.f}' does not exist.") 44 | sys.exit(1) 45 | 46 | try: 47 | transcription = transcribe_audio(args.f) 48 | print("Transcription:") 49 | print(transcription["text"]) 50 | except Exception as e: 51 | print(f"An error occurred while transcribing the audio: {str(e)}") 52 | sys.exit(1) 53 | 54 | 55 | if __name__ == "__main__": 56 | main() 57 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | def adjust_pauses_for_hf_pipeline_output(pipeline_output, split_threshold=0.12): 2 | """ 3 | Adjust pause timings by distributing pauses up to the threshold evenly between adjacent words. 4 | """ 5 | 6 | adjusted_chunks = pipeline_output["chunks"].copy() 7 | 8 | for i in range(len(adjusted_chunks) - 1): 9 | current_chunk = adjusted_chunks[i] 10 | next_chunk = adjusted_chunks[i + 1] 11 | 12 | current_start, current_end = current_chunk["timestamp"] 13 | next_start, next_end = next_chunk["timestamp"] 14 | pause_duration = next_start - current_end 15 | 16 | if pause_duration > 0: 17 | if pause_duration > split_threshold: 18 | distribute = split_threshold / 2 19 | else: 20 | distribute = pause_duration / 2 21 | 22 | # Adjust current chunk end time 23 | adjusted_chunks[i]["timestamp"] = (current_start, current_end + distribute) 24 | 25 | # Adjust next chunk start time 26 | adjusted_chunks[i + 1]["timestamp"] = (next_start - distribute, next_end) 27 | pipeline_output["chunks"] = adjusted_chunks 28 | 29 | return pipeline_output 30 | --------------------------------------------------------------------------------