├── .gitignore ├── LICENSE ├── README.md ├── pipeline.md ├── run.sh ├── run_pipeline.sh └── scripts ├── extract_and_normalize_transcript.py ├── filter_by_cer.py ├── parse_options.sh ├── process_test_dev.py └── split_test_dev.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 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Libriheavy: a 50,000 hours ASR corpus with punctuation casing and context 2 | 3 | This is the official repository of the Libriheavy dataset. Libriheavy is a labeled version of [Librilight](https://arxiv.org/pdf/1912.07875.pdf). Please refer to our paper: *Libriheavy: a 50,000 hours ASR corpus with punctuation casing and context* for more details. [Preprint available on arxiv](https://arxiv.org/abs/2309.08105). 4 | 5 | **Updates:** 6 | 7 | * we release a version with longer duraitons (from 20 - 100 seconds), see https://huggingface.co/datasets/pkufool/libriheavy_long for details. 8 | 9 | 10 | ## How to download the dataset 11 | 12 | The audio files of Libriheavy is the same as those in Librilight, the audio files is available [here](https://github.com/facebookresearch/libri-light/tree/main/data_preparation), you can download it by: 13 | 14 | ``` 15 | bash run.sh --stage -1 --stop-stage -1 16 | ``` 17 | 18 | The manifests of Libriheavy is hosted in [huggingface](https://huggingface.co/datasets/pkufool/libriheavy) and [modelscope](https://www.modelscope.cn/datasets/pkufool/Libriheavy/summary)(for users in the Chinese mainland). You can download the manifests via: 19 | 20 | from huggingface: 21 | 22 | ``` 23 | bash run.sh --stage 1 --stop-stage 1 24 | ``` 25 | 26 | or from modelscope: 27 | ``` 28 | bash run.sh --stage 0 --stop-stage 0 29 | ``` 30 | 31 | The manifest downloaded above looks like follows, we have two version of `texts` and `pre_texts`, the first item is the transcript from original book (with casing and punctuation), the second item is the decoding result from a asr model. The second item was used to align the transcript in the original book, we decide to keep it. 32 | 33 | ```json 34 | { 35 | "id": "small/100/sea_fairies_0812_librivox_64kb_mp3/01_baum_sea_fairies_64kb_0", 36 | "start": 243.919, 37 | "duration": 7.36, 38 | "channel": 0, 39 | "supervisions": [ 40 | { 41 | "id": "small/100/sea_fairies_0812_librivox_64kb_mp3/01_baum_sea_fairies_64kb_0", 42 | "recording_id": "small/100/sea_fairies_0812_librivox_64kb_mp3/01_baum_sea_fairies_64kb", 43 | "start": 0, 44 | "duration": 7.36, 45 | "channel": 0, 46 | "language": "English", 47 | "speaker": "100", 48 | "custom": { 49 | "texts": [ 50 | "The little girl was thoughtful for a moment. \"But why do folks dive in the water when the mermaids smile an' wink?\" she asked.", 51 | "THE LITTLE GIRL WAS THOUGHTFUL FOR A MOMENT BUT WHY DO FOLKS DIVE IN THE WATER WHEN THE MERMAIDS SMILE AND WINK SHE ASKED" 52 | ], 53 | "pre_texts": [ 54 | "...us mortal folk,\" replied Cap'n Bill. \"But if anyone happens to see 'em, what then, Cap'n?\" \"Then,\" he answered, slowly wagging his head, \"the mermais give 'em a smile an' a wink, an' they dive into the water an' gets drownded.\" \"S'pose they knew how to swim, Cap'n Bill?\" \"That don't make any diff'rence, Trot. The mermaids live deep down, an' the poor mortals never come up again.", 55 | "...US MORTAL FOLK REPLIED CAP'N BILL BUT IF ANYONE HAPPENS TO SEE EM WHAT THEN CAP'N THEN HE ANSWERED SLOWLY WAGGING HIS HEAD THE MERMAIDS GIVE EM A SMILE AND A WINK AND THEY DIVES INTO THE WATER AND GETS DROWNDED S'POSE THEY KNOW HOW TO SWIM CAP'N BILL THAT DON'T MAKE ANY DIFFERENCE TROT THE MERMAIDS LIVE DEEP DOWN AND THE POOR MORTALS NEVER COME UP AGAIN" 56 | ], 57 | "begin_byte": 4993, 58 | "end_byte": 5120 59 | } 60 | } 61 | ], 62 | "recording": { 63 | "id": "small/100/sea_fairies_0812_librivox_64kb_mp3/01_baum_sea_fairies_64kb", 64 | "sources": [ 65 | { 66 | "type": "file", 67 | "channels": [ 68 | 0 69 | ], 70 | "source": "download/librilight/small/100/sea_fairies_0812_librivox_64kb_mp3/01_baum_sea_fairies_64kb.flac" 71 | } 72 | ], 73 | "sampling_rate": 16000, 74 | "num_samples": 9567080, 75 | "duration": 597.942, 76 | "channel_ids": [ 77 | 0 78 | ] 79 | }, 80 | "custom": { 81 | "text_path": "download/librilight_text/output_text_small_cleaned/Sea Fairies/text.txt" 82 | }, 83 | "type": "MonoCut" 84 | } 85 | ``` 86 | 87 | This is the full version of Libriheavy which can be use for various speech tasks. 88 | You can further extract the manifests for pure ASR training purpose by: 89 | 90 | ``` 91 | bash run.sh --stage 2 --stop-stage 2 92 | ``` 93 | 94 | Now, you have k2 format (lhotse cuts) and kaldi format corpus for both normalized version (upper case without punctuation) and full formated version (casing with punctuation): 95 | 96 | ``` 97 | ├── cases_and_punc 98 | │   ├── kaldi 99 | │   │   ├── large 100 | │   │   │   ├── segments 101 | │   │   │   ├── text 102 | │   │   │   └── wav.scp 103 | ...... 104 | │   │   ├── test_clean 105 | │   │   │   ├── segments 106 | │   │   │   ├── text 107 | │   │   │   └── wav.scp 108 | │   └── lhotse 109 | │   ├── libriheavy_cuts_dev.jsonl.gz 110 | │   ├── libriheavy_cuts_large.jsonl.gz 111 | │   ├── libriheavy_cuts_medium.jsonl.gz 112 | │   ├── libriheavy_cuts_small.jsonl.gz 113 | │   ├── libriheavy_cuts_test_clean.jsonl.gz 114 | │   ├── libriheavy_cuts_test_clean_large.jsonl.gz 115 | │   ├── libriheavy_cuts_test_other.jsonl.gz 116 | │   └── libriheavy_cuts_test_other_large.jsonl.gz 117 | └── upper_no_punc 118 | ├── kaldi 119 | │   ├── large 120 | │   │   ├── segments 121 | │   │   ├── text 122 | │   │   └── wav.scp 123 | ...... 124 | │   ├── test_other 125 | │   │   ├── segments 126 | │   │   ├── text 127 | │   │   └── wav.scp 128 | └── lhotse 129 | ├── libriheavy_cuts_dev.jsonl.gz 130 | ├── libriheavy_cuts_large.jsonl.gz 131 | ├── libriheavy_cuts_medium.jsonl.gz 132 | ├── libriheavy_cuts_small.jsonl.gz 133 | ├── libriheavy_cuts_test_clean.jsonl.gz 134 | ├── libriheavy_cuts_test_clean_large.jsonl.gz 135 | ├── libriheavy_cuts_test_other.jsonl.gz 136 | └── libriheavy_cuts_test_other_large.jsonl.gz 137 | ``` 138 | 139 | > For how to use the `pre_texts`, we have a paper: *PromptASR for contextualized ASR with controllable style* [Preprint available on arxiv](https://arxiv.org/abs/2309.07414) 140 | 141 | **Note** The directory of audio files is hard-coded to `download/librilight` in the manifests. 142 | 143 | 144 | ## Leaderboard 145 | 146 | **Note:** large subset=large + medium + small; medium subset = medium + small (i.e. large subset includes the large, medium, small manifests above, medium subset includes the medium and small manifests above). 147 | 148 | ### Models trained on normalized text 149 | 150 | > Note: The models trained with Wenet might not be tuned well. 151 | 152 | #### large subset 153 | 154 | | contributor | toolkit | LibriSpeech WER (clean & other) | Libriheavy WER (clean & other) | recipe | model | 155 | |-------------|---------|---------------------------------|--------------------------------|--------|-------| 156 | | baseline | Wenet | 2.02 & 5.22 | 2.74 & 6.68 | [CTC + Attention]() | [model]() | 157 | | baseline | icefall | 1.62 & 3.36 | 2.20 & 5.57 | [Transducer](https://github.com/k2-fsa/icefall/tree/master/egs/libriheavy/ASR/zipformer) | [model](https://www.modelscope.cn/models/pkufool/icefall-asr-zipformer-libriheavy-20230926/summary) | 158 | 159 | 160 | #### medium subset 161 | 162 | | contributor | toolkit | LibriSpeech WER (clean & other) | Libriheavy WER (clean & other) | recipe | model | 163 | |-------------|---------|---------------------------------|--------------------------------|--------|-------| 164 | | baseline | Wenet | 3.15 & 7.88 | 3.80 & 8.80 | [CTC + Attention]() | [model]() | 165 | | baseline | icefall | 2.35 & 4.82 | 2.90 & 6.57 | [Transducer](https://github.com/k2-fsa/icefall/tree/master/egs/libriheavy/ASR/zipformer) | [model](https://www.modelscope.cn/models/pkufool/icefall-asr-zipformer-libriheavy-20230926/summary) | 166 | 167 | 168 | #### small subset 169 | 170 | | contributor | toolkit | LibriSpeech WER (clean & other) | Libriheavy WER (clean & other) | recipe | model | 171 | |-------------|---------|---------------------------------|--------------------------------|--------|-------| 172 | | baseline | Wenet | 5.76 & 15.60 | 6.94 & 15.17 | [CTC + Attention]() | [model]() | 173 | | baseline | icefall | 4.05 & 9.89 | 4.68 & 10.01 | [Transducer](https://github.com/k2-fsa/icefall/tree/master/egs/libriheavy/ASR/zipformer) | [model](https://www.modelscope.cn/models/pkufool/icefall-asr-zipformer-libriheavy-20230926/summary) | 174 | 175 | 176 | ### Models trained on text with casing and punctuation 177 | 178 | #### large subset 179 | 180 | | contributor | toolkit | Libriheavy normalized WER (clean & other) | Libriheavy WER (clean & other) | recipe | model | 181 | |-------------|---------|-------------------------------------------|--------------------------------|--------|-------| 182 | | baseline | icefall | 2.28 & 5.68 | 7.76 & 11.32 | [Transducer](https://github.com/k2-fsa/icefall/tree/master/egs/libriheavy/ASR/zipformer) | [model](https://www.modelscope.cn/models/pkufool/icefall-asr-zipformer-libriheavy-punc-20230830/summary) | 183 | 184 | #### medium subset 185 | 186 | | contributor | toolkit | Libriheavy normalized WER (clean & other) | Libriheavy WER (clean & other) | recipe | model | 187 | |-------------|---------|-------------------------------------------|--------------------------------|--------|-------| 188 | | baseline | icefall | 3.05 & 6.78 | 9.84 & 13.39 | [Transducer](https://github.com/k2-fsa/icefall/tree/master/egs/libriheavy/ASR/zipformer) | [model](https://www.modelscope.cn/models/pkufool/icefall-asr-zipformer-libriheavy-punc-20230830/summary) | 189 | 190 | #### small subset 191 | 192 | | contributor | toolkit | Libriheavy normalized WER (clean & other) | Libriheavy WER (clean & other) | recipe | model | 193 | |-------------|---------|-------------------------------------------|--------------------------------|--------|-------| 194 | | baseline | icefall | 5.16 & 11.12 | 13.04 & 19.54 | [Transducer](https://github.com/k2-fsa/icefall/tree/master/egs/libriheavy/ASR/zipformer) | [model](https://www.modelscope.cn/models/pkufool/icefall-asr-zipformer-libriheavy-punc-20230830/summary) | 195 | 196 | 197 | ## Statistics 198 | 199 | You can find the detail description of the corpus in [Librilight paper](https://arxiv.org/pdf/1912.07875.pdf), here are some statistics of Libriheavy. 200 | The last 7 columns are the distribution of durations (in seconds). 201 | 202 | | subset | #hours | #books | per-spk hrs | total spks | mean | std | min | 25% | 50% | 75% | 99% | 203 | |-----------------|---------|----------|-------------|------------|------|-----|-----|------|------|------|------| 204 | | small | 509 | 173 | 1.22 | 417 | 14.9 | 6.5 | 2.0 | 10 | 14.4 | 18.6 | 30.8 | 205 | | medium | 5042 | 960 | 3.29 | 1531 | 14.8 | 6.4 | 2.0 | 9.9 | 14.3 | 18.5 | 30.8 | 206 | | large | 50794 | 8592 | 7.54 | 6736 | 14.8 | 6.4 | 2.0 | 9.8 | 14.2 | 18.4 | 30.7 | 207 | | dev | 22.3 | 180 | 0.16 | 141 | 15.0 | 6.5 | 2.1 | 10.1 | 14.5 | 18.6 | 30.8 | 208 | | test-clean | 10.5 | 87 | 0.15 | 70 | 14.7 | 6.5 | 2.3 | 9.6 | 14.2 | 18.5 | 30.8 | 209 | | test-other | 11.5 | 112 | 0.16 | 72 | 14.6 | 6.4 | 2.2 | 9.7 | 14.0 | 18.2 | 30.6 | 210 | | test-clean-large| 107.5 | 95 | 1.49 | 72 | 14.8 | 6.4 | 2.0 | 9.9 | 14.3 | 18.4 | 30.8 | 211 | | test-other-large| 100.3 | 136 | 1.37 | 73 | 14.6 | 6.5 | 2.0 | 9.7 | 14.0 | 18.4 | 30.8 | 212 | 213 | ## Creation pipeline 214 | 215 | You can find the documentation of creation pipeline [here](./pipeline.md). 216 | 217 | 218 | ## Citation 219 | 220 | ``` 221 | @misc{kang2023libriheavy, 222 | title={Libriheavy: a 50,000 hours ASR corpus with punctuation casing and context}, 223 | author={Wei Kang and Xiaoyu Yang and Zengwei Yao and Fangjun Kuang and Yifan Yang and Liyong Guo and Long Lin and Daniel Povey}, 224 | year={2023}, 225 | eprint={2309.08105}, 226 | archivePrefix={arXiv}, 227 | primaryClass={eess.AS} 228 | } 229 | ``` 230 | -------------------------------------------------------------------------------- /pipeline.md: -------------------------------------------------------------------------------- 1 | # Creation pipeline 2 | 3 | This is the documentation of creating Libriheavy asr corpus (i.e. splitting the training, dev and test sets). If you want 4 | to know how we align Librilight to be Libriheavy, please see [text search libriheavy recipe](https://github.com/k2-fsa/text_search/tree/master/examples/libriheavy) for details. 5 | 6 | **Note:** We can not guarantee that the pipeline will produce the same manifests as ours, because we select test and dev sets randomly from a "pool", read our [paper](https://arxiv.org/pdf/2309.08105.pdf) for more details. 7 | 8 | 9 | ## Download raw manifests aligned by [text search](https://github.com/k2-fsa/text_search/tree/master/examples/libriheavy) 10 | 11 | from huggingface: 12 | 13 | ``` 14 | bash run_pipeline.sh --stage 1 --stop-stage 1 15 | ``` 16 | 17 | or from modelscope 18 | 19 | ``` 20 | bash run_pipeline.sh --stage 0 --stop-stage 0 21 | ``` 22 | 23 | ## Filter out the segments with higher CER (Optional) 24 | 25 | We allow some errors when aligning the audios to avoid dropping out too much data, you can filter out those segments with higher CER if you like. 26 | 27 | ``` 28 | bash run_pipeline.sh --stage 2 --stop-stage 2 29 | ``` 30 | 31 | You can specify the `threshold`, see `scripts/filter_by_cer.py` for details. 32 | 33 | ## Get speakers and books for dev and test sets and excluding them from training sets 34 | 35 | ``` 36 | bash run_pipeline.sh --stage 3 --stop-stage 3 37 | ``` 38 | 39 | ## Split dev and test sets 40 | 41 | ``` 42 | bash run_pipeline.sh --stage 4 --stop-stage 4 43 | ``` 44 | 45 | Congratulations, you have gotten the Libriheavy corpus, see [README](./README.md) for how to use it. 46 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -eou pipefail 4 | 5 | stage=1 6 | stop_stage=2 7 | 8 | . ./scripts/parse_options.sh || exit 1 9 | 10 | log() { 11 | local fname=${BASH_SOURCE[1]##*/} 12 | echo -e "$(date '+%Y-%m-%d %H:%M:%S') (${fname}:${BASH_LINENO[0]}:${FUNCNAME[1]}) $*" 13 | } 14 | 15 | if [ $stage -le -1 ] && [ $stop_stage -ge -1 ]; then 16 | log "Stage -1: Downloading audio file." 17 | mkdir -p download/librilight 18 | for subset in small medium large; do 19 | log "Downloading ${subset} subset." 20 | if [ ! -d download/librilight/${subset} ]; then 21 | wget -P download/librilight -c https://dl.fbaipublicfiles.com/librilight/data/${subset}.tar 22 | tar xf download/librilight/${subset}.tar -C download/librilight 23 | else 24 | log "Skipping download, ${subset} subset exists." 25 | fi 26 | done 27 | fi 28 | 29 | 30 | if [ $stage -le 0 ] && [ $stop_stage -ge 0 ]; then 31 | log "Stage 0: Downloading manifests from modelscope." 32 | if [ ! -e libriheavy_cuts_small.jsonl.gz ]; then 33 | GIT_LFS_SKIP_SMUDGE=1 git clone https://www.modelscope.cn/datasets/pkufool/Libriheavy.git 34 | cd Libriheavy 35 | git lfs pull --exclude "raw/*" 36 | mv *.jsonl.gz ../ 37 | cd .. 38 | rm -rf Libriheavy 39 | fi 40 | fi 41 | 42 | 43 | if [ $stage -le 1 ] && [ $stop_stage -ge 1 ]; then 44 | log "Stage 1: Downloading manifests from huggingface." 45 | for subset in small medium large dev test_clean test_other test_clean_large test_other_large; do 46 | if [ ! -e libriheavy_cuts_${subset}.jsonl.gz ]; then 47 | log "Downloading ${subset} subset." 48 | wget -c https://huggingface.co/datasets/pkufool/libriheavy/resolve/main/libriheavy_cuts_${subset}.jsonl.gz 49 | else 50 | log "Skipping download, ${subset} subset exists." 51 | fi 52 | done 53 | fi 54 | 55 | 56 | if [ $stage -le 2 ] && [ $stop_stage -ge 2 ]; then 57 | for subset in small medium large test_clean test_other dev test_clean_large test_other_large; do 58 | log "Stage 2: Extracting subset ${subset}" 59 | python ./scripts/extract_and_normalize_transcript.py \ 60 | --manifest libriheavy_cuts_${subset}.jsonl.gz \ 61 | --subset ${subset} \ 62 | --output-dir . 63 | done 64 | fi 65 | -------------------------------------------------------------------------------- /run_pipeline.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -eou pipefail 4 | 5 | stage=1 6 | stop_stage=5 7 | 8 | . ./scripts/parse_options.sh || exit 1 9 | 10 | log() { 11 | local fname=${BASH_SOURCE[1]##*/} 12 | echo -e "$(date '+%Y-%m-%d %H:%M:%S') (${fname}:${BASH_LINENO[0]}:${FUNCNAME[1]}) $*" 13 | } 14 | 15 | 16 | if [ $stage -le 0 ] && [ $stop_stage -ge 0 ]; then 17 | log "Stage 0: Downloading raw manifests from modelscope." 18 | if [ ! -e raw/libriheavy_cuts_small.jsonl.gz ]; then 19 | GIT_LFS_SKIP_SMUDGE=1 git clone https://www.modelscope.cn/datasets/pkufool/Libriheavy.git 20 | cd Libriheavy 21 | git lfs pull --include "raw/*.jsonl.gz" 22 | mv raw ../ 23 | cd .. 24 | rm -rf Libriheavy 25 | fi 26 | fi 27 | 28 | 29 | if [ $stage -le 1 ] && [ $stop_stage -ge 1 ]; then 30 | log "Stage 1: Downloading raw manifest aligned by text_search project." 31 | mkdir -p raw 32 | for subset in small medium large; do 33 | if [ ! -e raw/libriheavy_cuts_${subset}.jsonl.gz ]; then 34 | log "Downloading ${subset} subset." 35 | wget -P raw -c https://huggingface.co/datasets/pkufool/libriheavy/resolve/main/raw/libriheavy_cuts_${subset}.jsonl.gz 36 | else 37 | log "Skipping download, ${subset} subset exists." 38 | fi 39 | done 40 | fi 41 | 42 | 43 | if [ $stage -le 2 ] && [ $stop_stage -ge 2 ]; then 44 | log "Stage 2: Filtering cuts with high cer." 45 | for subset in small medium large; do 46 | if [ ! -e raw/.${subset}_filter.done ]; then 47 | log "Filtering ${subset} subset." 48 | # might be symbolic link 49 | rm raw/libriheavy_cuts_${subset}_filter.jsonl.gz 50 | python ./scripts/filter_by_wers.py --manifest raw/libriheavy_cuts_${subset}.jsonl.gz 51 | touch raw/.${subset}_filter.done 52 | fi 53 | done 54 | else 55 | for subset in small medium large; do 56 | if [ ! -e raw/.${subset}_filter.done ]; then 57 | rm raw/libriheavy_cuts_${subset}_filter.jsonl.gz 58 | ln -s raw/libriheavy_cuts_${subset}.jsonl.gz raw/libriheavy_cuts_${subset}_filter.jsonl.gz 59 | fi 60 | done 61 | fi 62 | 63 | 64 | if [ $stage -le 3 ] && [ $stop_stage -ge 3 ]; then 65 | log "Stage 3: Excluding test and dev cuts from training set." 66 | python ./scripts/split_test_dev.py --output-dir . \ 67 | raw/libriheavy_cuts_small.jsonl.gz \ 68 | raw/libriheavy_cuts_medium.jsonl.gz \ 69 | raw/libriheavy_cuts_large.jsonl.gz 70 | fi 71 | 72 | 73 | if [ $stage -le 4 ] && [ $stop_stage -ge 4 ]; then 74 | log "Stage 4: Splitting test and dev sets." 75 | python ./scripts/process_test_dev.py --raw libriheavy_cuts_test_raw.jsonl.gz \ 76 | --output-dir . 77 | fi 78 | -------------------------------------------------------------------------------- /scripts/extract_and_normalize_transcript.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import gzip 3 | import json 4 | import logging 5 | import math 6 | from pathlib import Path 7 | 8 | 9 | def get_args(): 10 | parser = argparse.ArgumentParser() 11 | parser.add_argument( 12 | "--manifest", 13 | type=Path, 14 | help="""The manifest to extract the wav.scp, text and segments, MUST be 15 | a jsonl.gz file. 16 | """, 17 | ) 18 | parser.add_argument( 19 | "--subset", 20 | type=str, 21 | help="The subset of the corpus, could be small, medium or large.", 22 | ) 23 | parser.add_argument( 24 | "--output-dir", 25 | type=Path, 26 | help="""The dir that the wav.scp, text and segments to write to. 27 | """, 28 | ) 29 | return parser.parse_args() 30 | 31 | 32 | def normalize_text(s: str) -> str: 33 | s = s.replace("‘", "'") 34 | s = s.replace("’", "'") 35 | tokens = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'") 36 | s_list = [x.upper() if x in tokens else " " for x in s] 37 | s = " ".join("".join(s_list).split()).strip() 38 | return s 39 | 40 | 41 | def clean_text(s: str) -> str: 42 | table = str.maketrans("’‘,。;?!():-《》、“”【】", "'',.;?!(): <>/\"\"[]") 43 | s = s.translate(table) 44 | return s.strip() 45 | 46 | 47 | def write_kaldi(ifile: Path, subset: str, output_dir: Path): 48 | no_punc_dir = output_dir / "upper_no_punc" / "kaldi" / subset 49 | punc_dir = output_dir / "cases_and_punc" / "kaldi" / subset 50 | no_punc_dir.mkdir(parents=True, exist_ok=True) 51 | punc_dir.mkdir(parents=True, exist_ok=True) 52 | 53 | wav_scp = {} 54 | texts = {} 55 | punc_texts = {} 56 | segments = {} 57 | with gzip.open(ifile, "r") as f: 58 | for line in f: 59 | cut = json.loads(line) 60 | seg_id = cut["id"] 61 | start = math.floor(1000 * cut["start"]) / 1000 62 | duration = math.floor(1000 * cut["duration"]) / 1000 63 | wav_id = cut["recording"]["id"] 64 | wav = cut["recording"]["sources"][0]["source"] 65 | text = cut["supervisions"][0]["custom"]["texts"][0] 66 | no_punc_text = normalize_text(text) 67 | punc_text = clean_text(text) 68 | wav_scp[wav_id] = wav 69 | texts[seg_id] = no_punc_text 70 | punc_texts[seg_id] = punc_text 71 | segments[seg_id] = (wav_id, start, start + duration) 72 | 73 | with open(punc_dir / "wav.scp", "w", encoding="utf8") as f1, open( 74 | no_punc_dir / "wav.scp", "w", encoding="utf8" 75 | ) as f2: 76 | for k, v in wav_scp.items(): 77 | f1.write(f"{k} {v}\n") 78 | f2.write(f"{k} {v}\n") 79 | with open(punc_dir / "segments", "w", encoding="utf8") as f1, open( 80 | no_punc_dir / "segments", "w", encoding="utf8" 81 | ) as f2: 82 | for k, v in segments.items(): 83 | f1.write(f"{k} {v[0]} {v[1]} {v[2]}\n") 84 | f2.write(f"{k} {v[0]} {v[1]} {v[2]}\n") 85 | with open(punc_dir / "text", "w", encoding="utf8") as f: 86 | for k, v in punc_texts.items(): 87 | f.write(f"{k} {v}\n") 88 | with open(no_punc_dir / "text", "w", encoding="utf8") as f: 89 | for k, v in texts.items(): 90 | f.write(f"{k} {v}\n") 91 | 92 | 93 | def write_lhotse(ifile: Path, output_dir: Path): 94 | no_punc_dir = output_dir / "upper_no_punc" / "lhotse" 95 | punc_dir = output_dir / "cases_and_punc" / "lhotse" 96 | no_punc_dir.mkdir(parents=True, exist_ok=True) 97 | punc_dir.mkdir(parents=True, exist_ok=True) 98 | 99 | with gzip.open(no_punc_dir / ifile.name, "w") as f1, gzip.open( 100 | punc_dir / ifile.name, "w" 101 | ) as f2, gzip.open(ifile, "r") as fin: 102 | for line in fin: 103 | cut = json.loads(line) 104 | text = cut["supervisions"][0]["custom"]["texts"][0] 105 | del cut["supervisions"][0]["custom"] 106 | del cut["custom"] 107 | no_punc_text = normalize_text(text) 108 | punc_text = clean_text(text) 109 | cut["supervisions"][0]["text"] = no_punc_text 110 | f1.write((json.dumps(cut) + "\n").encode()) 111 | cut["supervisions"][0]["text"] = punc_text 112 | f2.write((json.dumps(cut) + "\n").encode()) 113 | 114 | 115 | def main(): 116 | args = get_args() 117 | ifile = args.manifest 118 | assert ifile.is_file(), f"File not exists : {ifile}" 119 | assert str(ifile).endswith("jsonl.gz"), f"Expect a jsonl gz file, given : {ifile}" 120 | output_dir = args.output_dir 121 | output_dir.mkdir(parents=True, exist_ok=True) 122 | write_kaldi(ifile, subset=args.subset, output_dir=output_dir) 123 | write_lhotse(ifile, output_dir=output_dir) 124 | 125 | 126 | if __name__ == "__main__": 127 | formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s" 128 | logging.basicConfig(format=formatter, level=logging.INFO) 129 | main() 130 | -------------------------------------------------------------------------------- /scripts/filter_by_cer.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import editdistance 3 | import gzip 4 | import json 5 | import logging 6 | import math 7 | import random 8 | from pathlib import Path 9 | from typing import Dict, List, Tuple 10 | 11 | 12 | def get_args(): 13 | parser = argparse.ArgumentParser() 14 | parser.add_argument( 15 | "--manifest", 16 | type=Path, 17 | help="""The manifest to be filtered. 18 | """, 19 | ) 20 | parser.add_argument( 21 | "--output-dir", 22 | type=Path, 23 | help="""The dir to write the result. 24 | """, 25 | ) 26 | 27 | parser.add_argument( 28 | "--cer-threthod", 29 | type=float, 30 | default=0.05, 31 | help="""Through the cuts that have cer greater than this value""", 32 | ) 33 | 34 | return parser.parse_args() 35 | 36 | 37 | def normalize(s: str) -> str: 38 | s = s.replace("‘", "'") 39 | s = s.replace("’", "'") 40 | tokens = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'") 41 | s_list = [x.upper() if x in tokens else " " for x in s] 42 | s = " ".join("".join(s_list).split()).strip() 43 | return s 44 | 45 | 46 | def filter( 47 | manifest, 48 | cer_threthod: float, 49 | output_dir: Path, 50 | ): 51 | name = manifest.name.replace(".jsonl.gz", "") + "_filter.jsonl.gz" 52 | of = gzip.open(output_dir / name, "w") 53 | with gzip.open(manifest, "r") as fin: 54 | for line in fin: 55 | cut = json.loads(line) 56 | texts = cut["supervisions"][0]["custom"]["texts"] 57 | ref = normalize(texts[0]).strip() 58 | hyp = texts[1].strip() 59 | distance = editdistance.eval(ref, hyp) 60 | cer = distance / len(ref) 61 | if cer <= cer_threthod: 62 | of.write(line) 63 | of.close() 64 | 65 | 66 | def main(): 67 | args = get_args() 68 | manifest = args.manifest 69 | assert manifest.is_file(), f"File not exists : {manifest}" 70 | assert str(manifest).endswith( 71 | "jsonl.gz" 72 | ), "The manifest is expected to be a jsonl.gz file, given : {manifest}" 73 | 74 | args.output_dir.mkdir(parents=True, exist_ok=True) 75 | 76 | filter(manifest, cer_threthod=args.cer_threthod, output_dir=args.output_dir) 77 | 78 | 79 | if __name__ == "__main__": 80 | formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s" 81 | logging.basicConfig(format=formatter, level=logging.INFO) 82 | main() 83 | -------------------------------------------------------------------------------- /scripts/parse_options.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Copyright 2023 Xiaomi Corp. (Author: Wei Kang) 3 | 4 | # copied and modified from https://github.com/kaldi-asr/kaldi/blob/master/egs/wsj/s5/utils/parse_options.sh 5 | while true; do 6 | [ -z "${1:-}" ] && break; # break if there are no arguments 7 | case "$1" in 8 | --*) name=`echo "$1" | sed s/^--// | sed s/-/_/g`; 9 | eval '[ -z "${'$name'+xxx}" ]' &&\ 10 | echo "$0: invalid option $1" 1>&2 && exit 1; 11 | 12 | oldval="`eval echo \\$$name`"; 13 | if [ "$oldval" == "true" ] || [ "$oldval" == "false" ]; then 14 | was_bool=true; 15 | else 16 | was_bool=false; 17 | fi 18 | eval $name=\"$2\"; 19 | if $was_bool && [[ "$2" != "true" && "$2" != "false" ]]; then 20 | echo "$0: expected \"true\" or \"false\": $1 $2" 1>&2 21 | exit 1; 22 | fi 23 | shift 2; 24 | ;; 25 | *) break; 26 | esac 27 | done 28 | 29 | true; 30 | -------------------------------------------------------------------------------- /scripts/process_test_dev.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import editdistance 3 | import gzip 4 | import json 5 | import logging 6 | import math 7 | import random 8 | from pathlib import Path 9 | from typing import Dict, List, Tuple 10 | 11 | 12 | def get_args(): 13 | parser = argparse.ArgumentParser() 14 | parser.add_argument( 15 | "--raw", 16 | type=Path, 17 | help="""The raw test dev subset split from the whole set. 18 | """, 19 | ) 20 | parser.add_argument( 21 | "--output-dir", 22 | type=Path, 23 | help="""The dir to write the result. 24 | """, 25 | ) 26 | 27 | parser.add_argument( 28 | "--cer-threthod", 29 | type=float, 30 | default=0.10, 31 | help="""Through the cuts that have cer greater than this value""", 32 | ) 33 | parser.add_argument( 34 | "--hours", 35 | type=float, 36 | default=10, 37 | help="""The number of hours for eash subset (test-clean, test-other).""", 38 | ) 39 | 40 | return parser.parse_args() 41 | 42 | 43 | def normalize(s: str) -> str: 44 | s = s.replace("‘", "'") 45 | s = s.replace("’", "'") 46 | tokens = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'") 47 | s_list = [x.upper() if x in tokens else " " for x in s] 48 | s = " ".join("".join(s_list).split()).strip() 49 | return s 50 | 51 | 52 | def get_speaker_wers(raw_manifest: str) -> Dict[str, float]: 53 | speaker_wers = {} 54 | with gzip.open(raw_manifest, "r") as fin: 55 | for line in fin: 56 | cut = json.loads(line) 57 | speaker = cut["id"].split("/")[1] 58 | texts = cut["supervisions"][0]["custom"]["texts"] 59 | ref = normalize(texts[0]).split() 60 | hyp = texts[1].split() 61 | distance = editdistance.eval(ref, hyp) 62 | if speaker in speaker_wers: 63 | speaker_wers[speaker]["errs"] += distance 64 | speaker_wers[speaker]["len"] += len(ref) 65 | else: 66 | speaker_wers[speaker] = {} 67 | speaker_wers[speaker]["errs"] = distance 68 | speaker_wers[speaker]["len"] = len(ref) 69 | speaker_wers = {k: v["errs"] / v["len"] for k, v in speaker_wers.items()} 70 | return speaker_wers 71 | 72 | 73 | def split_subset( 74 | raw_manifest, 75 | cer_threthod: float, 76 | hours: int, 77 | speaker_wers: List[Tuple[str, float]], 78 | output_dir: Path, 79 | ): 80 | speaker_wers = sorted(speaker_wers.items(), key=lambda x: x[1]) 81 | clean_speakers = set([x[0] for x in speaker_wers[0 : len(speaker_wers) // 2]]) 82 | other_speakers = set([x[0] for x in speaker_wers[len(speaker_wers) // 2 :]]) 83 | clean_hours = 0 84 | other_hours = 0 85 | with gzip.open(raw_manifest, "r") as fin: 86 | for line in fin: 87 | cut = json.loads(line) 88 | speaker = cut["id"].split("/")[1] 89 | texts = cut["supervisions"][0]["custom"]["texts"] 90 | duration = math.floor(1000 * cut["duration"]) / 1000 91 | ref = normalize(texts[0]).strip() 92 | hyp = texts[1].strip() 93 | distance = editdistance.eval(ref, hyp) 94 | cer = distance / len(ref) 95 | ref = ref.split() 96 | hyp = hyp.split() 97 | distance = editdistance.eval(ref, hyp) 98 | wer = distance / len(ref) 99 | if cer >= cer_threthod: 100 | continue 101 | else: 102 | if speaker in clean_speakers: 103 | clean_hours += duration 104 | else: 105 | assert speaker in other_speakers, speaker 106 | other_hours += duration 107 | 108 | clean_hours = math.floor(clean_hours / 3600 * 1000) / 1000 109 | other_hours = math.floor(other_hours / 3600 * 1000) / 1000 110 | 111 | logging.info(f"clean hours : {clean_hours}, other hours : {other_hours}") 112 | clean_prob = hours * 2 / clean_hours 113 | other_prob = hours * 2 / other_hours 114 | 115 | clean_of = gzip.open(output_dir / "libriheavy_cuts_test_clean.jsonl.gz", "w") 116 | clean_large_of = gzip.open(output_dir / "libriheavy_cuts_test_clean_large.jsonl.gz", "w") 117 | other_of = gzip.open(output_dir / "libriheavy_cuts_test_other.jsonl.gz", "w") 118 | other_large_of = gzip.open(output_dir / "libriheavy_cuts_test_other_large.jsonl.gz", "w") 119 | dev_of = gzip.open(output_dir / "libriheavy_cuts_dev.jsonl.gz", "w") 120 | 121 | with gzip.open(raw_manifest, "r") as fin: 122 | for line in fin: 123 | cut = json.loads(line) 124 | speaker = cut["id"].split("/")[1] 125 | prob = random.random() 126 | if speaker in clean_speakers: 127 | if prob <= clean_prob: 128 | if random.random() >= 0.5: 129 | dev_of.write(line) 130 | else: 131 | clean_of.write(line) 132 | else: 133 | clean_large_of.write(line) 134 | else: 135 | assert speaker in other_speakers, speaker 136 | if prob <= other_prob: 137 | if random.random() >= 0.5: 138 | dev_of.write(line) 139 | else: 140 | other_of.write(line) 141 | else: 142 | other_large_of.write(line) 143 | clean_of.close() 144 | clean_large_of.close() 145 | other_of.close() 146 | other_large_of.close() 147 | dev_of.close() 148 | 149 | 150 | def main(): 151 | args = get_args() 152 | raw_manifest = args.raw 153 | assert raw_manifest.is_file(), f"File not exists : {raw_manifest}" 154 | assert str(raw_manifest).endswith( 155 | "jsonl.gz" 156 | ), "The raw manifest is expected to be a jsonl.gz file." 157 | 158 | args.output_dir.mkdir(parents=True, exist_ok=True) 159 | 160 | speaker_wers = get_speaker_wers(raw_manifest) 161 | split_subset( 162 | raw_manifest, 163 | cer_threthod=args.cer_threthod, 164 | hours=args.hours, 165 | speaker_wers=speaker_wers, 166 | output_dir=args.output_dir, 167 | ) 168 | 169 | 170 | if __name__ == "__main__": 171 | formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s" 172 | logging.basicConfig(format=formatter, level=logging.INFO) 173 | main() 174 | -------------------------------------------------------------------------------- /scripts/split_test_dev.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import editdistance 3 | import gzip 4 | import json 5 | import logging 6 | import math 7 | import random 8 | import re 9 | import sys 10 | from pathlib import Path 11 | from typing import Dict, List, Tuple 12 | 13 | 14 | def get_args(): 15 | parser = argparse.ArgumentParser() 16 | 17 | parser.add_argument( 18 | "--output-dir", 19 | type=Path, 20 | help="""The dir to write the result. 21 | """, 22 | ) 23 | 24 | parser.add_argument( 25 | "manifests", 26 | type=Path, 27 | nargs="+", 28 | help="The manifests to be processed, normally the subsets of a corpus.", 29 | ) 30 | 31 | return parser.parse_args() 32 | 33 | 34 | def get_book_speaker_duration(manifests: List[Path], output_dir: Path): 35 | book_duration = {} 36 | speaker_duration = {} 37 | book_speaker_duration = {} 38 | for file in manifests: 39 | logging.info(f"Processing {file}.") 40 | with gzip.open(file, "r") as fin: 41 | for line in fin: 42 | line = json.loads(line) 43 | speaker = line["id"].split("/")[1] 44 | book = line["custom"]["text_path"].split("/")[-2] 45 | duration = line["duration"] 46 | 47 | if speaker in speaker_duration: 48 | speaker_duration[speaker] += duration 49 | else: 50 | speaker_duration[speaker] = duration 51 | 52 | if book in book_duration: 53 | book_duration[book] += duration 54 | else: 55 | book_duration[book] = duration 56 | 57 | key = str((speaker, book)) 58 | if key in book_speaker_duration: 59 | book_speaker_duration[key] += duration 60 | else: 61 | book_speaker_duration[key] = duration 62 | in_dir = manifests[0].parent 63 | with open(in_dir / "speaker.dur", "w") as f: 64 | json.dump(speaker_duration, f, indent=4) 65 | with open(in_dir / "book.dur", "w") as f: 66 | json.dump(book_duration, f, indent=4) 67 | with open(in_dir / "book_speaker.dur", "w") as f: 68 | json.dump(book_speaker_duration, f, indent=4) 69 | 70 | 71 | def select_books_speakers(manifests: List[Path], output_dir: Path): 72 | in_dir = manifests[0].parent 73 | if ( 74 | not (in_dir / "speaker.dur").exists() 75 | or not (in_dir / "book.dur").exists() 76 | or not (in_dir / "book_speaker.dur").exists() 77 | ): 78 | logging.info(f"Calculating book & speaker duration, it will take around 10 minutes.") 79 | get_book_speaker_duration(manifests, output_dir) 80 | else: 81 | logging.info(f"Loading existing speaker.dur, boo.dur, book_speaker.dur.") 82 | 83 | with open(in_dir / "speaker.dur", "r") as f: 84 | speaker_duration = json.load(f) 85 | with open(in_dir / "book.dur", "r") as f: 86 | book_duration = json.load(f) 87 | with open(in_dir / "book_speaker.dur", "r") as f: 88 | book_speaker_duration = json.load(f) 89 | 90 | selected_books = set() 91 | selected_speakers = set() 92 | selected_duration = 0.0 93 | for sb, d in book_speaker_duration.items(): 94 | sb = eval(sb) 95 | s_duration = speaker_duration[sb[0]] 96 | b_duration = book_duration[sb[1]] 97 | s_rate = d / s_duration 98 | b_rate = d / b_duration 99 | if ( 100 | s_duration < 3600 * 6 101 | and b_duration < 3600 * 6 102 | and b_rate >= 0.5 103 | and s_rate >= 0.5 104 | ): 105 | selected_speakers.add(sb[0]) 106 | selected_books.add(sb[1]) 107 | selected_duration += d 108 | logging.info( 109 | f"Selected {len(selected_books)} books, {len(selected_speakers)} speakers." 110 | ) 111 | logging.info(f"Selected duration : {selected_duration / 3600:.2f} hours.") 112 | with open(output_dir / "selected_books.txt", "w") as f: 113 | for x in selected_books: 114 | f.write(x + "\n") 115 | with open(output_dir / "selected_speakers.txt", "w") as f: 116 | for x in selected_speakers: 117 | f.write(x + "\n") 118 | 119 | 120 | def split_test_set(manifests: List[Path], output_dir: Path): 121 | if ( 122 | not (output_dir / "selected_speakers.txt").exists() 123 | or not (output_dir / "selected_books.txt").exists() 124 | ): 125 | select_books_speakers(manifests, output_dir) 126 | else: 127 | logging.info(f"Loading existing selected_speakers.txt selected_books.txt.") 128 | selected_speakers = set() 129 | with open(output_dir / "selected_speakers.txt", "r") as f: 130 | for line in f: 131 | selected_speakers.add(line.strip()) 132 | selected_books = set() 133 | with open(output_dir / "selected_books.txt", "r") as f: 134 | for line in f: 135 | selected_books.add(line.strip()) 136 | 137 | with gzip.open(output_dir / "libriheavy_cuts_test_raw.jsonl.gz", "w") as tf: 138 | for m in manifests: 139 | logging.info(f"Splitting {m}.") 140 | with gzip.open(output_dir / m.name, "w") as f, gzip.open(m, "r") as fin: 141 | for lines in fin: 142 | line = json.loads(lines) 143 | speaker = line["id"].split("/")[1] 144 | book = line["custom"]["text_path"].split("/")[-2] 145 | if book in selected_books or speaker in selected_speakers: 146 | tf.write(lines) 147 | else: 148 | f.write(lines) 149 | 150 | def main(): 151 | args = get_args() 152 | manifests = args.manifests 153 | in_dir = manifests[0].parent 154 | 155 | for m in manifests: 156 | assert ( 157 | m.parent == in_dir 158 | ), f"Input manifests MUST be in the same directory, given : {(m.parent, in_dir)}." 159 | assert str(m).endswith( 160 | "jsonl.gz" 161 | ), "The raw manifest is expected to be a jsonl.gz file." 162 | assert ( 163 | args.output_dir != in_dir 164 | ), f"Manifests directory MUST not be the same as the output_dir, given : {(args.output_dir, in_dir)}." 165 | 166 | args.output_dir.mkdir(parents=True, exist_ok=True) 167 | split_test_set(args.manifests, args.output_dir) 168 | 169 | 170 | if __name__ == "__main__": 171 | formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s" 172 | logging.basicConfig(format=formatter, level=logging.INFO) 173 | main() 174 | --------------------------------------------------------------------------------