tiny-voca-arabic-code-switching: two-voice model, code, samples, card
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+8
- LICENSEAdded+202
- README.mdAdded+95
- code/dizione/LICENSEAdded+202
- code/dizione/__init__.pyAdded+71
- code/dizione/__main__.pyAdded+41
- code/dizione/align.pyAdded+156
- code/dizione/convert.pyAdded+414
- code/dizione/data/abbreviations.txtAdded+103
- code/dizione/data/chat.txtAdded+111
- code/dizione/data/endings.txtAdded+130
- code/dizione/data/exceptions.txtAdded+250
- code/dizione/data/function_words.txtAdded+189
- code/dizione/data/homograph_fixes.txtAdded+57
- code/dizione/data/homograph_rules.txtAdded+39
- code/dizione/data/letters.txtAdded+27
- code/dizione/data/phrases.txtAdded+63
- code/dizione/data/units.txtAdded+76
- code/dizione/engine.pyAdded+277
- code/dizione/g2p.pyAdded+95
- code/dizione/homographs.pyAdded+198
- code/dizione/morphology.pyAdded+217
- code/dizione/normalize.pyAdded+1423
- code/dizione/sentence.pyAdded+115
- code/dizione/symbols.pyAdded+68
- code/dizione/tables.pyAdded+103
- code/tiny_voca/__init__.pyAdded+10
- code/tiny_voca/arabic_frontend.pyAdded+337
- code/tiny_voca/config.pyAdded+118
- code/tiny_voca/infer.pyAdded+219
- code/tiny_voca/model.pyAdded+447
- code/tiny_voca/numbers.pyAdded+75
- code/tiny_voca/text.pyAdded+317
- config.jsonAdded+38
- model.safetensorsAdded+3
- phonemizer/LICENSE.cmudictAdded+33
- phonemizer/LICENSE.homograph-dataAdded+202
- phonemizer/align.jsonAdded+2070
- phonemizer/g2p.jsonAdded+83
- phonemizer/g2p.npzAdded+3
- phonemizer/homographs.jsonAdded+1
- phonemizer/lexicon.jsonAdded+7
- phonemizer/lexicon.tsvAdded
- phonemizer/sources.jsonAdded+1
- samples/arcs_female_1.wavAdded+3
- samples/arcs_female_2.wavAdded+3
- samples/arcs_female_3.wavAdded+3
- samples/arcs_female_4.wavAdded+3
- samples/arcs_male_1.wavAdded+3
- samples/arcs_male_2.wavAdded+3
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363738394041424332 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textsamples/arcs_female_1.wav filter=lfs diff=lfs merge=lfs -textsamples/arcs_female_2.wav filter=lfs diff=lfs merge=lfs -textsamples/arcs_female_3.wav filter=lfs diff=lfs merge=lfs -textsamples/arcs_female_4.wav filter=lfs diff=lfs merge=lfs -textsamples/arcs_male_1.wav filter=lfs diff=lfs merge=lfs -textsamples/arcs_male_2.wav filter=lfs diff=lfs merge=lfs -textsamples/arcs_male_3.wav filter=lfs diff=lfs merge=lfs -textsamples/arcs_male_4.wav filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495---license: apache-2.0language: - ar - enpipeline_tag: text-to-speechlibrary_name: pytorchdatasets: - oddadmix/tiny-voca-arabic-code-switching-datasettags: - arabic - code-switching - tts - tiny-voca - multi-speaker---
# tiny-voca-arabic-code-switching
A text-to-speech model for Modern Standard Arabic with English words mixed in, as people write about work, technologyand daily life ("اجتماع الـ team على Zoom"). Two voices, **male** (`arcs_male`) and **female** (`arcs_female`).It has 4.54M parameters and was trained from scratch, with no pretrained weights, on[oddadmix/tiny-voca-arabic-code-switching-dataset](https://huggingface.co/datasets/oddadmix/tiny-voca-arabic-code-switching-dataset) (133 h after alignment checks, synthetic speech;about 80% of the texts mix in English, 20% are plain MSA).It is built on the architecture and training code of [tiny-voca](https://huggingface.co/n4ze3m/tiny-voca) by Muhammed Nazeem (Apache-2.0).Demo: [tiny-voca-arabic-code-switching](https://huggingface.co/spaces/oddadmix/tiny-voca-arabic-code-switching).
## Input
- Arabic in Arabic script, English in Latin script, in the same sentence.- The Arabic article on an English word is written `الـ` with a tatweel: `الـ meeting`, `بالـ email`, `للـ team`, `والـ app`. It is pronounced the Arabic way, including assimilation before English sun sounds (`الـ team` → at-team).- Numbers are read in Arabic, except inside English names (`iPhone 15`, `GPT-4`, `5G`).
## Front end
- **Arabic runs:** vowelled by [CATT](https://github.com/abjadai/catt) (Apache-2.0, ONNX), then MSA pronunciation rules, the same as tiny-voca-arabic.- **English runs:** [dizione](https://github.com/n4ze3m/dizione) (Apache-2.0), the tiny-voca English phonemizer (CMUdict-derived lexicon, a small neural G2P for unknown words).- One 86-symbol inventory: Arabic phonemes plus English phonemes, shared IPA symbols counted once.
## Evaluation
Speech from the model was transcribed with Whisper large-v3 (Arabic) and compared with the text. The held-out texts were neverseen in training. "Recordings" means the training-voice audio of the same texts, transcribed the same way.
Whisper often writes accented English words in Arabic letters (for example لينك for link), which counts as a word error evenwhen the word was said correctly. The **phone error** column is fairer to English: the transcript and the text are both turned intophonemes, folded into accent-neutral classes, and compared.
| | voice | word error | word error, recordings | phone error | phone error, recordings | duration vs recordings | pauses vs recordings ||---|---|---|---|---|---|---|---|| test (50 per voice) | male | 9.8% | 10.7% | 0.059 | 0.069 | 1.00 | 1.18 || test (50 per voice) | female | 10.0% | 10.5% | 0.061 | 0.069 | 1.01 | 1.14 || validation (50 per voice) | male | 10.9% | 12.2% | 0.071 | 0.071 | 1.02 | 1.28 || validation (50 per voice) | female | 11.9% | 10.9% | 0.065 | 0.070 | 1.01 | 0.99 |
8 new code-switched sentences written for the evaluation, dense with English: male: word error 19.1%, phone error 0.149; female: word error 19.1%, phone error 0.143.
## Files
- `model.safetensors`: the same weights in safetensors format (metadata holds the config).- `tiny-voca-arabic-code-switching.pt`: the checkpoint (weights, config, front-end fingerprint, duration calibration phone +0.008 / pause +0.000).- `code/tiny_voca/`: inference code and the front end (`text.py`, `arabic_frontend.py`, `numbers.py`).- `code/dizione/` and `phonemizer/`: the English phonemizer and its data (CMUdict license in `phonemizer/LICENSE.cmudict`).- `samples/`: the same texts in both voices (`texts.txt`).
## Use
```bashpip install torch soundfile onnxruntime catt-tashkeel==1.0.2```
```pythonimport os, sys, soundfile as sfos.environ["DIZIONE_DATA"] = "phonemizer"sys.path.insert(0, "code")from tiny_voca.infer import load_model, speak_text
model = load_model("tiny-voca-arabic-code-switching.pt")wave, spoken = speak_text(model, "اجتماع الـ team سيكون غدا على Zoom، فلا تنس مراجعة الـ slides.", "arcs_female") # or "arcs_male"sf.write("out.wav", wave.numpy(), 24000)```
`speak_text` reads text of any length sentence by sentence and also takes `speed` (1.0 = normal), `pitch_shift` and `seed`.
## Limitations
- English is spoken with an Arabic accent, as in the training voices; long all-English sentences are outside what it was trained on.- Arabic short vowels come from the CATT diacritizer, which sometimes picks the wrong reading of an unvowelled word; adding the vowel marks yourself fixes it.- Pauses run longer than in the recordings: about 15% on average, up to 28% for the male voice on validation.- ONNX export is not available for this model yet.- All voices are synthetic.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Dizione: English text to phonemes.
A dictionary built from CMUdict, a small model for words the dictionarylacks, homograph rules, and text rules for numbers, dates, money, units andchat forms. See ``docs/design.md``.
import dizione print(dizione.phonemize("Hello, it costs $3.50."))"""
import hashlibimport jsonfrom pathlib import Path
from .symbols import Phonemized, tokenize
__version__ = "0.1.0"VERSION = 4 # token-convention version recorded by models trained on the output_BUILT = ("lexicon.tsv", "align.json", "g2p.json", "g2p.npz", "homographs.json")_default = None
def get(): """The phonemizer over the default data directory, loaded once.""" global _default if _default is None: from .engine import Phonemizer _default = Phonemizer() return _default
def reset(): """Forget the loaded phonemizer (after the data directory or the tables changed).""" global _default _default = None
def pieces(text): """``(True, mark)`` for punctuation and ``(False, words)`` for text, in order.""" return get().pieces(text)
def phonemize(text): """Text -> ``Phonemized`` (symbols, ids, stress).""" if not isinstance(text, str) or not text.strip(): raise ValueError("text must not be empty") return tokenize(pieces(text))
def identity(directory=None): """Exactly which build produces the tokens: version, built files, tables and code. Record the fingerprint next to anything derived from the output, so tokens from two builds are never mixed.""" from .engine import default_directory from .tables import DATA directory = Path(directory) if directory else default_directory() built = {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in _BUILT if (directory / name).exists()} tables = hashlib.sha256() for path in sorted(DATA.glob("*.txt")): tables.update(path.name.encode()) tables.update(path.read_bytes()) code = hashlib.sha256() for path in sorted(Path(__file__).parent.glob("*.py")): code.update(path.name.encode()) code.update(path.read_bytes()) parts = {"version": VERSION, "built": built, "tables": tables.hexdigest(), "code": code.hexdigest()} fingerprint = hashlib.sha256(json.dumps(parts, sort_keys=True).encode()).hexdigest() return {**parts, "fingerprint": fingerprint}
__all__ = ["Phonemized", "phonemize", "pieces", "identity", "get", "reset", "tokenize", "VERSION"]1234567891011121314151617181920212223242526272829303132333435363738394041"""Try the phonemizer on a sentence.
python -m dizione "Hello, it costs $3.50." python -m dizione --words "I read the book I read yesterday."
Prints the token sequence (stress marks on the phones, <sp> between words).``--words`` also shows where each word's pronunciation came from."""
import argparsefrom pathlib import Path
from .convert import to_textfrom .engine import Phonemizerfrom .sentence import groupsfrom .symbols import tokenize
def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("text", nargs="+") parser.add_argument("--data", type=Path, help="Built data directory (default: DIZIONE_DATA)") parser.add_argument("--overrides", type=Path, help="Table of your own pronunciations: word, two spaces, pronunciation") parser.add_argument("--no-phrases", action="store_true", help="Keep a word boundary inside groups such as 'of the'") parser.add_argument("--words", action="store_true", help="Show every word and the source of its pronunciation") args = parser.parse_args() phonemizer = Phonemizer(args.data, overrides=args.overrides, join_phrases=not args.no_phrases) for sentence_text in args.text: analysis = phonemizer.analyse(sentence_text) print(tokenize([(True, value) if kind == "punct" else (False, groups(value)) for kind, value in analysis])) if args.words: for kind, value in analysis: if kind == "punct": print(f" {value}") continue for unit in value: print(f" {unit.word:24s} {unit.source:10s} {to_text(unit.phones)}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""Which letters spell which phoneme.
Every phoneme of a pronunciation is given a run of zero to four letters of theword, in order, so that the runs spell the word: "thought" TH AO T becomesth|ough|t and "box" B AA K S becomes b|o|x|(nothing). The pronunciation rulesneed this to tell an unstressed vowel written "i" from one written "a".
The table of how likely each (phoneme, letters) pair is comes from CMUdictalone, by expectation-maximisation over all its entries (``train``). The sametable aligns dictionary entries when the lexicon is built and the output of theunknown-word model at run time (``Aligner.align``)."""
from collections import defaultdictimport math
MAX_RUN = 4_LENGTH_PRIOR = (0.02, 1.0, 0.3, 0.05, 0.01) # starting belief by number of letters_UNSEEN = -14.0
def base(symbol): """ARPABET symbol without its stress digit.""" return symbol.rstrip("012")
def _expected_counts(word, phones, probability): letters, count = len(word), len(phones) forward = [[0.0] * (letters + 1) for _ in range(count + 1)] forward[0][0] = 1.0 for j in range(1, count + 1): phone, previous, row = phones[j - 1], forward[j - 1], forward[j] for i in range(letters + 1): total = 0.0 for k in range(min(MAX_RUN, i) + 1): if previous[i - k]: total += previous[i - k] * probability(phone, word[i - k:i]) row[i] = total evidence = forward[count][letters] if evidence <= 0.0: return None backward = [[0.0] * (letters + 1) for _ in range(count + 1)] backward[count][letters] = 1.0 for j in range(count - 1, -1, -1): phone, following, row = phones[j], backward[j + 1], backward[j] for i in range(letters + 1): total = 0.0 for k in range(min(MAX_RUN, letters - i) + 1): if following[i + k]: total += following[i + k] * probability(phone, word[i:i + k]) row[i] = total counts = {} for j in range(count): phone = phones[j] for i in range(letters + 1): if not forward[j][i]: continue for k in range(min(MAX_RUN, letters - i) + 1): if backward[j + 1][i + k]: run = word[i:i + k] weight = forward[j][i] * probability(phone, run) * backward[j + 1][i + k] / evidence if weight > 1e-12: counts[(phone, run)] = counts.get((phone, run), 0.0) + weight return counts
def _expectation(job): entries, table = job if table is None: probability = lambda phone, run: _LENGTH_PRIOR[len(run)] else: probability = lambda phone, run: table.get((phone, run), 0.0) + 1e-9 * _LENGTH_PRIOR[len(run)] totals, failed = defaultdict(float), 0 for word, phones in entries: counts = _expected_counts(word, phones, probability) if counts is None: failed += 1 continue for key, value in counts.items(): totals[key] += value return dict(totals), failed
def train(entries, iterations=8, workers=1, log=None): """Estimate P(letters | phoneme) from ``(word, [phoneme, ...])`` pairs (phonemes without stress). Returns ``{phoneme: {letters: log probability}}``.""" entries = [(word, [base(p) for p in phones]) for word, phones in entries if phones and len(word) <= MAX_RUN * len(phones)] table = None pool = None if workers > 1: import multiprocessing pool = multiprocessing.get_context("fork").Pool(workers) try: for iteration in range(iterations): shards = [entries[i::workers] for i in range(workers)] jobs = [(shard, table) for shard in shards] results = pool.map(_expectation, jobs) if pool else [_expectation(job) for job in jobs] totals, failed = defaultdict(float), 0 for counts, misses in results: failed += misses for key, value in counts.items(): totals[key] += value mass = defaultdict(float) for (phone, _), value in totals.items(): mass[phone] += value table = {key: value / mass[key[0]] for key, value in totals.items()} if log: log(f"alignment iteration {iteration + 1}/{iterations}: {len(table)} pairs, {failed} entries without a path") finally: if pool: pool.close() nested = defaultdict(dict) for (phone, run), value in table.items(): if value >= 1e-6: nested[phone][run] = round(math.log(value), 3) return {phone: dict(sorted(runs.items())) for phone, runs in sorted(nested.items())}
class Aligner: def __init__(self, table): self.table = table
def score(self, phone, run): known = self.table.get(phone) value = known.get(run) if known else None return value if value is not None else _UNSEEN - 2.0 * abs(len(run) - 1)
def align(self, word, phones): """Split ``word`` into one run of letters per phoneme. ``phones`` may carry stress digits. Returns ``None`` when the word is too long for the pronunciation (an abbreviation such as "dept").""" phones = [base(p) for p in phones] letters, count = len(word), len(phones) if not count or letters > MAX_RUN * count: return None low = -1e18 best = [[low] * (letters + 1) for _ in range(count + 1)] step = [[0] * (letters + 1) for _ in range(count + 1)] best[0][0] = 0.0 for j in range(1, count + 1): phone, previous, row, trace = phones[j - 1], best[j - 1], best[j], step[j] for i in range(letters + 1): for k in range(min(MAX_RUN, i) + 1): if previous[i - k] > low: value = previous[i - k] + self.score(phone, word[i - k:i]) if value > row[i]: row[i], trace[i] = value, k if best[count][letters] <= low: return None runs, i = [], letters for j in range(count, 0, -1): k = step[j][i] runs.append(word[i - k:i]) i -= k return runs[::-1]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414"""One word: CMUdict pronunciation -> phones of the inventory.
CMUdict writes a broad phonemic transcription (39 phonemes, stress digits onthe vowels). The TTS model was trained on a narrower one: flaps, a glottalstop before syllabic n, r-coloured vowels as single phones, syllabic l, severalreduced vowels. This module adds what CMUdict lacks, by rule.
Many of the rules depend on how the vowel is written (the reduced vowel of"cabin" is not that of "sofa"; "more" and "for" differ), so they work on thepronunciation aligned to the spelling (``align.Aligner``). Without an alignmentthe spelling-dependent rules fall back to their default.
The result is the citation form of the word. What depends on neighbouringwords (linking r, a flap at the end of "it" before a vowel, weak forms) is in``sentence.py``."""
from .symbols import PHONE_SET, VOWEL_SETfrom .align import base
ARPA_VOWELS = frozenset("AA AE AH AO AW AY EH ER EY IH IY OW OY UH UW".split())CONSONANTS = {"B": "b", "CH": "tʃ", "D": "d", "DH": "ð", "F": "f", "G": "ɡ", "HH": "h", "JH": "dʒ", "K": "k", "L": "l", "M": "m", "N": "n", "NG": "ŋ", "P": "p", "R": "ɹ", "S": "s", "SH": "ʃ", "T": "t", "TH": "θ", "V": "v", "W": "w", "Y": "j", "Z": "z", "ZH": "ʒ"}FULL_VOWELS = {"AA": "ɑː", "AE": "æ", "AH": "ʌ", "AO": "ɔː", "AW": "aʊ", "AY": "aɪ", "EH": "ɛ", "ER": "ɜː", "EY": "eɪ", "IH": "ɪ", "IY": "iː", "OW": "oʊ", "OY": "ɔɪ", "UH": "ʊ", "UW": "uː"}ARPABET = frozenset(CONSONANTS) | frozenset(v + d for v in ARPA_VOWELS for d in "012")SIBILANTS = frozenset(("S", "Z", "SH", "ZH", "CH", "JH"))STRESS_MARKS = {1: "ˈ", 2: "ˌ"}_VOWEL_LETTERS = frozenset("aeiouy")# Words of the FORCE set written "or" before a consonant (Wells's lexical sets):# they keep the closer vowel that "more" and "four" have._FORCE_SPELLINGS = ("forc", "ford", "sword", "worn", "torn", "sworn", "borne", "shorn", "pork", "divorc")_PREFIXES = ("dis", "mis", "un", "in", "re", "non", "over", "pre")_WEAK_PREFIXES = ("be", "de", "re", "pre")_IRE_ENDINGS = ("ing", "ings", "ingly", "able", "y", "er", "ers", "est")
assert all(p in PHONE_SET for p in list(CONSONANTS.values()) + list(FULL_VOWELS.values()) + ["ə", "ɐ", "ɚ", "ᵻ", "i", "ɔ", "oː", "iə", "ɑːɹ", "ɔːɹ", "oːɹ", "ɪɹ", "ɛɹ", "ʊɹ", "aɪɚ", "aɪə", "əl", "n̩", "ɾ", "ʔ"])
def is_arpabet(symbols): return bool(symbols) and all(s in ARPABET for s in symbols)
def vowel_letters(run): return "".join(c for c in run if c in _VOWEL_LETTERS)
def to_text(phones): """``[(phone, stress), ...]`` -> ``"h ə l ˈoʊ"``.""" return " ".join(STRESS_MARKS.get(stress, "") + phone for phone, stress in phones)
def from_text(text): """``"h ə l ˈoʊ"`` -> ``((phone, stress), ...)``; raises on a symbol outside the inventory.""" phones = [] for unit in text.split(): stress = 1 if unit[0] == "ˈ" else 2 if unit[0] == "ˌ" else 0 phone = unit[1:] if stress else unit if phone not in PHONE_SET: raise ValueError(f"{phone!r} is not a phone of the inventory") if stress and phone not in VOWEL_SET: raise ValueError(f"stress mark on the consonant {phone!r}") phones.append((phone, stress)) return tuple(phones)
class _Word: """The aligned pronunciation of one word and the questions the rules ask of it."""
def __init__(self, word, arpabet, runs): self.word = word self.bases = [base(s) for s in arpabet] self.stress = [int(s[-1]) if s[-1] in "012" else None for s in arpabet] for symbol, name in zip(arpabet, self.bases): if name not in CONSONANTS and name not in ARPA_VOWELS: raise ValueError(f"{symbol!r} is not an ARPABET symbol") self.aligned = runs is not None self.runs = list(runs) if runs is not None else [""] * len(arpabet) self.starts, position = [], 0 for run in self.runs: self.starts.append(position) position += len(run) self.count = len(self.bases)
def base(self, i): return self.bases[i] if 0 <= i < self.count else None
def vowel(self, i): return 0 <= i < self.count and self.bases[i] in ARPA_VOWELS
def unstressed(self, i): return self.vowel(i) and not self.stress[i]
def letters(self, i): return vowel_letters(self.runs[i])
def before(self, i): """Spelling that precedes the letters of segment ``i``.""" return self.word[:self.starts[i]] if self.aligned else ""
def after(self, i): """Spelling that follows the letters of segment ``i``.""" return self.word[self.starts[i] + len(self.runs[i]):] if self.aligned else ""
def ends_with(self, i, *symbols): """True when exactly ``symbols`` follow segment ``i`` to the end of the word.""" return tuple(self.bases[i + 1:]) == symbols
def first_vowel(self, i): return not any(b in ARPA_VOWELS for b in self.bases[:i])
def next_vowel_stress(self, i): for j in range(i + 1, self.count): if self.bases[j] in ARPA_VOWELS: return self.stress[j] return None
def weak_prefix(self, i): """Segment ``i`` is the "e" of an unstressed be-, de-, re- or pre-.""" return self.aligned and self.first_vowel(i) and self.letters(i) == "e" and self.word.startswith(_WEAK_PREFIXES) \ and self.before(i) in ("b", "d", "r", "pr")
def _north_or_force(w, i, before_vowel): """AO + R: ``"oː"`` for the FORCE set (more, four, door, port, story), ``"ɔː"`` for NORTH (for, short, war). General American merges them; the model has both tokens, so the choice follows the spelling.""" if not w.aligned: return "ɔː" spelled = w.letters(i) if spelled in ("oa", "oo", "ou"): return "oː" if spelled != "o": return "ɔː" run = w.runs[i] tail = run[run.find("o") + 1:] + w.after(i) # the letters after the "o", normally starting with "r" rest = tail[1:] if not before_vowel: if rest.startswith("e"): # more, store, before, ignored return "oː" if w.before(i).endswith("p") and rest.startswith("t"): # port, support, important return "oː" return "oː" if any(s in w.word for s in _FORCE_SPELLINGS) else "ɔː" if rest.startswith("r"): # horror, torrent return "ɔː" if rest in ("y", "ies", "ied", "a", "as", "ah", "er", "ers") or rest.startswith(("ia", "io", "iu", "ing", "age")): return "oː" # story, flora, memorial, boring, storage return "ɔː"
def _weak_i(w, i): """A reduced vowel written "i": the barred i of "possible", "quality" and "terrify", the happy vowel of "beautiful", otherwise ɪ.""" nxt, nxt2 = w.base(i + 1), w.base(i + 2) if nxt == "F" and nxt2 == "AH" and w.base(i + 3) == "L": return "i" if (nxt == "T" and nxt2 == "IY") or (nxt == "B" and nxt2 in ("AH", "L")) or (nxt == "F" and nxt2 == "AY"): return "ᵻ" if nxt == "T" and w.ends_with(i, "T") and w.base(i - 1) in ("R", "ER") and w.word.endswith("ite"): return "ᵻ" # favorite return "ɪ"
def _weak_e(w, i): """A reduced vowel written "e" outside a weak prefix.""" nxt, prev = w.base(i + 1), w.base(i - 1) if nxt == "T" and (w.ends_with(i, "T") or w.ends_with(i, "T", "S")): return "ə" if prev == "L" else "ᵻ" if prev == "R" else "ɪ" # bracelet; secret; pocket, basket if nxt == "S" and (w.ends_with(i, "S", "T") or w.ends_with(i, "S", "T", "L", "IY")): return "ɪ" # nearest, honest, honestly if nxt == "JH": return "ɪ" # college, knowledge if nxt == "K" and w.base(i + 2) == "T": return "ɛ" # perfect, subject if nxt == "D" and w.ends_with(i, "D"): return "ɪ" # naked, wicked return "ə"
def _inflection(w, i): """The vowel of "-ed" after t/d and of "-es" after a sibilant.""" if i + 1 >= w.count or (w.aligned and "e" not in w.runs[i] + w.runs[i + 1]): return False nxt, prev = w.base(i + 1), w.base(i - 1) if nxt == "D" and prev in ("T", "D") and (w.ends_with(i, "D") or w.ends_with(i, "D", "L", "IY")): return True return nxt == "Z" and prev in SIBILANTS and w.ends_with(i, "Z")
def _first_syllable(w, i): """An unstressed first vowel right before the stressed syllable: the weak prefixes of "before", "return", "expect", "enjoy". ``None`` if no rule applies.""" if not w.aligned or not w.first_vowel(i) or not w.next_vowel_stress(i): return None word = w.word if i == 0 and word.startswith("e"): if word.startswith("ex"): return "ɛ" if word[1:2] in ("n", "m", "s") and word[2:3] and word[2] not in _VOWEL_LETTERS and word[2] != word[1]: return "ɛ" # enjoy, embrace, escape return "ɪ" # eleven, effect, enough if w.weak_prefix(i): if word.startswith("pre") or (word.startswith("be") and word[2:3] in ("c", "g")): return "ɪ" # prevent; because, began return "ᵻ" # before, return, decide if w.letters(i) == "i" and word.startswith("di") and len(word) > 3 and word[2] not in _VOWEL_LETTERS \ and word[2] != "s" and word[3] in _VOWEL_LETTERS: return "ᵻ" # divide, direct return None
def _reduced(w, i): """Quality of an unstressed AH or IH.""" name, spelled = w.bases[i], w.letters(i) nxt, prev = w.base(i + 1), w.base(i - 1) if name == "IH" and nxt == "NG": return "ɪ" if _inflection(w, i): return "ᵻ" if name == "AH": if prev == "Y" and "u" in w.runs[i - 1] + w.runs[i]: return "ʊ" # popular, document if i == 0 and w.word.startswith("a"): return "ɐ" # about, again if i == 0 and nxt == "N" and w.word.startswith("un"): return "ʌ" # until, unhappy if spelled == "a" and w.before(i) in _PREFIXES and w.runs[i].startswith("a"): return "ɐ" # disappoint, inability prefix = _first_syllable(w, i) if prefix: return prefix if spelled == "e" and nxt in ("K", "G") and w.runs[i + 1].startswith("x") and w.next_vowel_stress(i): return "ɛ" # unexpected, inexperienced if spelled in ("i", "ai", "ui", "y"): return _weak_i(w, i) if spelled == "e": return _weak_e(w, i) if spelled == "a": if nxt == "JH" or (nxt == "N" and w.base(i + 2) == "JH"): return "ɪ" # village, orange if nxt == "S" and w.ends_with(i, "S") and w.word.endswith("ace"): return "ɪ" # palace, surface if name == "IH" and not (nxt == "T" and w.ends_with(i, "T")): return "ɪ" # character; but private return "ə" if name == "AH" and nxt == "M" and w.ends_with(i, "M") and w.word.endswith("ome"): return "ʌ" # handsome, welcome return "ɪ" if name == "IH" and spelled not in ("o", "u", "ou") else "ə"
def _unstressed_iy(w, i): nxt = w.base(i + 1) if nxt is None or w.ends_with(i, "Z") or w.ends_with(i, "D"): return "i", 0 # happy, stories, married if w.vowel(i + 1): return ("i" if nxt == "IH" and w.base(i + 2) == "NG" else "ɪ"), 0 # carrying; video, earlier if w.weak_prefix(i): return ("ᵻ", 0) if w.next_vowel_stress(i) == 1 else ("iː", 2) # remind; reconsider return "ɪ", 0 # anything, happiness
def convert(word, arpabet, runs=None): """Citation form of ``word`` as ``((phone, stress), ...)``.
``arpabet`` is a CMUdict pronunciation (symbols with stress digits) and ``runs`` the letters aligned to each symbol, or ``None``. """ w = _Word(word, list(arpabet), runs) out = [] # [phone, stress] emit = lambda phone, stress=0: out.append([phone, stress or 0]) i = 0 while i < w.count: name, stress = w.bases[i], w.stress[i] or 0 nxt = w.base(i + 1) if name not in ARPA_VOWELS: if name == "Y" and nxt == "AH" and w.unstressed(i + 1) and w.base(i - 1) in ("N", "L") and w.base(i + 2) != "L" \ and (not w.aligned or "i" in w.runs[i] + w.runs[i + 1]): emit("iə") # opinion, million, brilliant i += 2 continue emit(CONSONANTS[name]) i += 1 continue before_vowel = w.vowel(i + 2) # only meaningful when the next segment is R if name == "ER": emit("ɜː" if stress else "ɚ", stress) if nxt == "R": i += 1 if w.vowel(i + 1): emit("ɹ") # around, history elif nxt == "R" and name == "AW": emit("aʊ", stress) # hour, flour emit("ɚ") if before_vowel: emit("ɹ") i += 1 elif nxt == "R" and name in ("AA", "AO", "IH", "IY", "EH", "UH", "UW", "AY"): if name == "AA": quality, single = "ɑː", "ɑːɹ" elif name == "AO": quality = _north_or_force(w, i, before_vowel) single = quality + "ɹ" elif name in ("IH", "IY"): quality = "iə" if stress and w.letters(i) in ("e", "eo") else "ɪ" # zero, period; hearing, spirit single = "ɪɹ" elif name == "EH": doubled = (w.runs[i + 1] + w.after(i + 1)).startswith("rr") or w.runs[i].endswith("r") and w.runs[i + 1].startswith("r") quality, single = ("æ" if w.letters(i) == "a" and doubled else "ɛ"), "ɛɹ" # marry; very elif name in ("UH", "UW"): quality = single = "ʊɹ" # "during" keeps the r-coloured vowel and adds ɹ else: quality, single = ("aɪɚ" if not w.aligned or w.after(i + 1) in _IRE_ENDINGS else "aɪ"), "aɪɚ" # hiring; pirate if before_vowel: emit(quality, stress) emit("ɹ") else: emit(single, stress) i += 1 elif name == "AY" and nxt == "ER" and w.unstressed(i + 1) and w.runs[i + 1] == "er" and w.runs[i] != "i": emit("aɪ", stress) # higher, buyer, flyer: a word plus "-er" elif name == "AY" and nxt == "ER" and w.unstressed(i + 1): emit("aɪɚ", stress) # fire, tired, iron i += 1 if w.vowel(i + 1): emit("ɹ") elif name == "AY" and nxt == "AH" and w.unstressed(i + 1): emit("aɪə", stress) # quiet, society i += 1 elif name == "IY" and nxt == "AH" and w.unstressed(i + 1) and not w.weak_prefix(i): after = w.base(i + 2) if stress != 1 and (after in ("L", "D", "T") or (after == "N" and w.base(i + 3) == "S")): emit("ɪ") # material, period, immediate, experience else: emit("iə", stress) # idea, various, museum i += 1 elif not stress and name == "AH" and nxt == "N" and w.base(i - 1) == "T" and w.base(i + 2) != "T" \ and len(out) >= 2 and out[-1][0] == "t" and out[-2][0] in VOWEL_SET and out[-2][1]: out[-1][0] = "ʔ" # button, certain, frightened emit("n̩") i += 1 elif not stress and name == "AH" and nxt == "W" and w.base(i + 2) == "AH" and w.unstressed(i + 2) \ and "u" in w.runs[i] + w.runs[i + 1]: emit("uː") # usual, individual: the "u" of "-ual" i += 1 elif not stress and name == "AH" and nxt == "L" and i > 0 and not (w.vowel(i + 2) and w.stress[i + 2]): if w.letters(i) == "i" and w.vowel(i + 2): emit("ɪ") # family, easily elif w.base(i - 1) == "Y" and "u" in w.runs[i - 1] + w.runs[i]: emit("ʊ") # popular, regular else: emit("əl") # little, finally i += 1 elif not stress and name in ("AH", "IH"): emit(_reduced(w, i)) elif name == "IY" and (not stress or (stress == 2 and nxt is None)): emit(*_unstressed_iy(w, i)) elif not stress and name == "AE" and i == 0 and w.word.startswith(("ad", "acc")) and nxt in ("D", "K"): emit("ɐ") # advice, accept elif not stress and name == "ER": emit("ɚ") elif name in ("AA", "AO") and w.letters(i) == "a" and w.before(i).endswith(("w", "qu")) and nxt == "N": emit("ɔ", stress) # want, quantity elif name == "AO" and w.letters(i) == "o": emit("ɔ", stress) # long, off, lost else: emit(FULL_VOWELS[name], stress) i += 1 _flap(out) for k in range(len(out) - 1): if out[k][0] == "n" and out[k + 1][0] in ("k", "ɡ"): out[k][0] = "ŋ" # income, engaged _settle_stress(out) return tuple((phone, stress) for phone, stress in out)
def _flap(out): """t between a vowel (or r) and an unstressed vowel: water, city, party.""" for k in range(1, len(out) - 1): if out[k][0] != "t": continue before, (after, stress) = out[k - 1][0], out[k + 1] if (before not in VOWEL_SET and before != "ɹ") or before in ("n̩", "əl") or after not in VOWEL_SET or after == "n̩": continue # A word-final "o" is weak whatever stress digit CMUdict gives it: potato, photo. final_o = after == "oʊ" and (k + 2 == len(out) or (k + 3 == len(out) and out[k + 2][0] == "z")) if stress and not final_o: continue if after in ("ə", "ɚ") and k + 2 < len(out) and out[k + 2][0] == "n": continue # skeleton, important, pattern out[k][0] = "ɾ"
def settle_stress(phones): """``_settle_stress`` for a finished pronunciation (compounds, prefixed words).""" out = [[phone, stress] for phone, stress in phones] _settle_stress(out) return tuple((phone, stress) for phone, stress in out)
def _settle_stress(out): """One primary stress per word, and no secondary stress on a syllable next to the primary one (weekend, notebook, important).""" vowels = [k for k, (phone, _) in enumerate(out) if phone in VOWEL_SET] primaries = [k for k in vowels if out[k][1] == 1] for k in primaries[:-1]: out[k][1] = 2 for position, k in enumerate(vowels): if out[k][1] != 2: continue neighbours = [vowels[p] for p in (position - 1, position + 1) if 0 <= p < len(vowels)] if any(out[n][1] == 1 for n in neighbours): out[k][1] = 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103# Abbreviations written with a full stop, and what to say for them.## Columns (two or more spaces): abbreviation without its stop, when it applies,# words to say. The stop is not a sentence end. "when":# always wherever it is written with the stop# small like "always", but not in capitals (CT. and FL. are states)# title before a capitalised word, with or without the stop (Mr Smith)# number only before a number (No. 5, p. 12)# Decided in the code: "St." and "Dr." are Saint or Doctor before a name and# Street or Drive after one; "est." is "established" before a year and# "estimated" otherwise; "no." is also "number" after "ref.", "serial",# "account" and the like; "max.", "min." and "est." in small letters are the# abbreviation only before a word in small letters ("max. load").
mr title mistermrs title mrsms title msprof title professorgen title generalcol title colonellt title lieutenantcapt title captainsgt title sergeantcpl title corporalrev title reverendhon title honorablegov title governorsen title senatorrep title representativepres title presidentmt title mountft title fortfr title fatherjr always juniorsr always seniorvs always versusetc always et ceterainc always incorporatedltd always limitedco always companycorp always corporationave always avenueblvd always boulevardrd always roadln always lanehwy always highwayapt always apartmentbldg always buildingdept always departmentgovt always governmentuniv always universityassn always associationbros always brothersapprox always approximatelyest always establishedmisc always miscellaneoustel always telephonemax always maximummin always minimumsq always squarepkwy always parkwayappt always appointmentqty always quantityacct always accountavg always averageincl always includingexcl always excludingattn always attentionfl small floorct small courtno number numbernos number numbersp number pagepp number pagesfig number figurevol number volumech number chaptersec number sectionref number referenceext number extensionste number suiterm number roomca number circajan always Januaryfeb always Februarymar always Marchapr always Apriljun always Junejul always Julyaug always Augustsep always Septembersept always Septemberoct always Octobernov always Novemberdec always Decembermon always Mondaytue always Tuesdaytues always Tuesdaywed always Wednesdaythu always Thursdaythur always Thursdaythurs always Thursdayfri always Friday123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111# Chat spellings and what to say for them. Edit freely.## Columns (two or more spaces): the token as typed (any letter case), then# words to say btw -> by the way# *LETTERS read letter by letter: lol -> L O L# - say nothing# A third column, "alone", keeps a spelling for replies: it is read this way# only when it is a clause by itself ("k", "k, thanks", "see you, k?"). Next# to a word or a figure it is what was typed: in "the value of k" and "8 k"# the letter K.# Emoticons such as :) and :)) and emoji are removed before this table is used;# they are never read and never make a pause.
lol *LOLlmao *LMAOrofl *ROFLomg *OMGomfg *OMGwtf *WTFwth what the heckidk I don't knowidc I don't carebtw by the wayimo in my opinionimho in my humble opiniontbh to be honestbrb be right backbbl be back laterttyl talk to you latergtg got to gog2g got to goafaik as far as I knowiirc if I recall correctlyfyi *FYIfaq *FAQdiy *DIYaka *AKAeta *ETAtba *TBAtbd *TBDrsvp *RSVPasap *ASAPsmh *SMHirl in real lifedm *DMdms *DM sthx thankstnx thanksty thank youtysm thank you so muchyw you're welcomenp no problempls pleaseplz pleaseppl peoplemsg messagemsgs messagespic picpics picsu youur yourr arek okay alonekk okayok okaynvm never mindbc becausecuz becausecoz becausetho thoughthru throughw/ withw/o withoutb4 beforegr8 greatl8r later2day today2moro tomorrow2nite tonightrn right nowjk just kiddingikr I know rightomw on my wayhbu how about youwyd what are you doingfr for realngl not gonna lieicl I can't lieistg I swear to godidek I don't even knowtbf to be fairiykyk if you know you knowwsg what's goodgng gangpov *POVfyp *FYPafk *AFKnpc *NPCgg *GGhaha ha hahahaha ha ha hahahahaha ha ha hahehe heh hehxd -xoxo -n/a not applicable
# keys of the keyboardctrl controlcmd commandesc escape123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130# Endings of web addresses and file names, and how to say them. Edit freely.## Columns (two or more spaces): the ending without its dot, then# word said as a word: example.com -> "example dot com"# letters read letter by letter: notes.txt -> "notes dot T X T"## A name with a listed ending is always read as a file or an address. An# ending that is not listed is read letter by letter as well, but only when# the name shows in another way that it is a file (an underscore or a slash),# so that a missing space, "the end.Then", is never taken for a file name.# Short common words ("it", "in", "me", "us") are left out on purpose.
# web addressescom wordorg wordnet wordgov wordinfo wordbiz wordapp worddev wordco wordedu lettersio lettersai letterssh lettersly letterstv lettersfm lettersgg lettersxyz lettersuk letterseu lettersde lettersfr letterses lettersnl lettersse lettersch lettersca lettersau lettersjp letterscn lettersru lettersbr letters
# documents and datapdf letterstxt letterscsv letterstsv lettersdoc worddocx lettersxls lettersxlsx lettersppt letterspptx lettersodt lettersrtf letterstex lettersmd lettersepub wordjson wordyaml wordyml letterstoml wordxml lettershtml lettershtm letterssql letterslog wordconf wordcfg lettersini lettersenv letterslock word
# pictures, sound, videopng lettersjpg lettersjpeg wordgif wordsvg lettersbmp letterstiff wordpsd letterswebp lettersheic lettersmp3 lettersmp4 lettersm4a letterswav wordflac wordmidi wordmpeg wordmov lettersavi lettersmkv letterswebm letters
# programs and archivesexe lettersdll lettersapk lettersdmg lettersiso letterszip wordtar wordgz letterstgz lettersrar lettersjar lettersbin wordbat wordbak letterstmp letterspy lettersjs lettersts lettersjsx letterstsx letterscss lettersrb lettersrs letterscpp lettersphp lettersjava wordswift wordkt lettersipynb letters123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250# Pronunciations that win over the dictionary. Written by hand.## Two kinds of entry: words CMUdict lacks (names, recent words) and words where# its first pronunciation is not the usual one in running speech. Either# CMUdict notation (the conversion rules then apply) or phones with stress marks.# Columns: word, pronunciation (two or more spaces between them).## This is the place to teach a new word: add a line. A name of several words# whose rhythm matters takes one pronunciation per word, separated by "|"# (see "tung tung tung sahur" below); the stress written there is kept.# CMUdict notation in short: AA father, AE cat, AH cut (AH0 the "a" of sofa),# AO law, AW cow, AY my, EH bed, ER her, EY day, IH sit, IY see, OW go, OY boy,# UH book, UW boot; after a vowel 1 = main stress, 2 = lesser stress, 0 = none;# consonants B CH D DH (this) F G HH JH (joy) K L M N NG P R S SH T TH (thin)# V W Y Z ZH (vision).
# usual pronunciation differs from CMUdict's first entryevery EH1 V R IY0because B IH0 K AH1 Zreally ɹ ˈiə l ireal ɹ ˈiː ə lthirty TH ER1 T IY0houses HH AW1 Z AH0 Zenough ɪ n ˈʌ fminutes m ˈɪ n ɪ t semail IY1 M EY2 Lemails IY1 M EY2 L Zmonday M AH1 N D EY2tuesday T UW1 Z D EY2wednesday W EH1 N Z D EY2thursday TH ER1 Z D EY2friday F R AY1 D EY2saturday S AE1 T ER0 D EY2sunday S AH1 N D EY2yesterday Y EH1 S T ER0 D EY2didn't d ˈɪ d n twasn't w ˈʌ z n̩ tcannot K AE0 N AA1 Tdifferent D IH1 F R AH0 N Tdifference D IH1 F R AH0 N Sdifferences D IH1 F R AH0 N S AH0 Zsometimes S AH1 M T AY2 M Zdowntown D AW1 N T AW2 Nputting P UH1 T IH0 NGwomen w ˈɪ m ɪ nmaybe m ˈeɪ b iːherself h ɜː s ˈɛ l fyourself j oːɹ s ˈɛ l fyours j ˈoːɹ zdirect d ᵻ ɹ ˈɛ k tdirectly d ᵻ ɹ ˈɛ k t l idirection d ᵻ ɹ ˈɛ k ʃ ə ndirections d ᵻ ɹ ˈɛ k ʃ ə n zdirector d ᵻ ɹ ˈɛ k t ɚschedule S K EH1 JH UW0 Lschedules S K EH1 JH UW0 L Zscheduled S K EH1 JH UW0 L Dconference K AA1 N F R AH0 N Sconferences K AA1 N F R AH0 N S AH0 Zpolished P AA1 L IH0 SH Tpolishing P AA1 L IH0 SH IH0 NGpolishes P AA1 L IH0 SH IH0 Zaddress AH0 D R EH1 Saddresses AH0 D R EH1 S IH0 Zgovernment G AH1 V ER0 N M AH0 N Tgovernments G AH1 V ER0 N M AH0 N T S
# recent words CMUdict lackswifi W AY1 F AY2wi W AY1covid K OW1 V IH0 Demoji IH0 M OW1 JH IY0emojis IH0 M OW1 JH IY0 Zselfie S EH1 L F IY0selfies S EH1 L F IY0 Zblog B L AO1 Gblogs B L AO1 G Zpodcast P AA1 D K AE2 S Tpodcasts P AA1 D K AE2 S T Ssmartphone S M AA1 R T F OW2 Nsmartphones S M AA1 R T F OW2 N Zbluetooth B L UW1 T UW2 THhashtag HH AE1 SH T AE2 Ghashtags HH AE1 SH T AE2 G Zlogin L AO1 G IH2 Nusername Y UW1 Z ER0 N EY2 Mmeme M IY1 Mmemes M IY1 M Zgif G IH1 Fjpeg JH EY1 P EH2 Gjson JH EY1 S AH0 Nlinux L IH1 N AH0 K Sgithub G IH1 T HH AH2 Bchatbot CH AE1 T B AA2 Tchatbots CH AE1 T B AA2 T Swebcam W EH1 B K AE2 Mtouchscreen T AH1 CH S K R IY2 Nnetflix N EH1 T F L IH0 K Sspotify S P AA1 T IH0 F AY2instagram IH1 N S T AH0 G R AE2 Mtiktok T IH1 K T AA2 Kwhatsapp W AH1 T S AE2 Pyoutube Y UW1 T UW2 Biphone AY1 F OW2 Nipad AY1 P AE2 Dandroid AE1 N D R OY2 Dgoogle G UW1 G AH0 Luber UW1 B ER0tesla T EH1 S L AH0okay OW2 K EY1
# names and rare words the dictionary lacks or has wrongemmaleigh EH1 M AH0 L IY0hermione HH ER0 M AY1 AH0 N IY0persephone P ER0 S EH1 F AH0 N IY0coeliac S IY1 L IY0 AE2 Kceliac S IY1 L IY0 AE2 Kscabies S K EY1 B IY0 Zlyssavirus L IH1 S AH0 V AY2 R AH0 Sprovirus P R OW0 V AY1 R AH0 Sbobsleigh B AA1 B S L EY2
# sounds people write: said as the sound, not letter by letter# ("sh", "shh", "hm", "hmm" and "mm" are in the dictionary; the text rules# read a hiss and a snore, "Ss!" and "Zzz": "ss" is also two letters)tsk T IH1 S Kpsst P S Tpfft P F Thmph HH AH1 M Fpsh P SHpssh P SH
# words the text rules say: units, file namesmilliamp M IH1 L IY0 AE2 M Pkilocalorie K IH1 L AH0 K AE2 L ER0 IY0kilocalories K IH1 L AH0 K AE2 L ER0 IY0 Zgigabit G IH1 G AH0 B IH2 Tgigabits G IH1 G AH0 B IH2 T Smegabits M EH1 G AH0 B IH2 T Skilobits K IH1 L AH0 B IH2 T Snginx EH1 N JH AH0 N EH2 K Sconf K AA1 N Fyaml Y AE1 M AH0 Ltoml T AA1 M AH0 Lmpeg EH1 M P EH2 Gflac F L AE1 Kepub IY1 P AH2 B
# internet slangskibidi S K IH1 B IH0 D IY0rizz R IH1 Zrizzler R IH1 Z L ER0rizzed R IH1 Z Dgyatt G Y AE1 Tgyat G Y AE1 Tfanum F AE1 N AH0 Mdelulu D IH0 L UW1 L UW0solulu S AH0 L UW1 L UW0bussin B AH1 S IH0 Nsussy S AH1 S IY0yeet Y IY1 Tsimp S IH1 M Pbruh B R AH1brainrot B R EY1 N R AA2 Tdoomscroll D UW1 M S K R OW2 Ldoomscrolling D UW1 M S K R OW2 L IH0 NGmewing M Y UW1 IH0 NGmog M AA1 Gmogging M AA1 G IH0 NGmogged M AA1 G Dlooksmaxxing L UH1 K S M AE2 K S IH0 NGlooksmaxing L UH1 K S M AE2 K S IH0 NGcrashout K R AE1 SH AW2 Tgoated G OW1 T IH0 Dunc AH1 NG Khuzz HH AH1 Zbruzz B R AH1 Zlabubu L AH0 B UW1 B UW0matcha M AA1 CH AH0clanker K L AE1 NG K ER0gurt G ER1 Tpookie P UH1 K IY0bestie B EH1 S T IY0lowkey L OW1 K IY2highkey HH AY1 K IY2finna F IH1 N AH0boutta B AW1 T AH0tryna T R AY1 N AH0imma AY1 M AH0fomo F OW1 M OW0uwu UW1 W UW0bae B EY1poggers P AA1 G ER0 Zkek K EH1 Knoob N UW1 Bstonks S T AA1 NG K Schungus CH AH1 NG G AH0 Samogus AH0 M OW1 G AH0 Sgriddy G R IH1 D IY0blud B L AH1 Dopps AA1 P Sragebait R EY1 JH B EY2 Tparasocial P EH2 R AH0 S OW1 SH AH0 Lbrr B ER1
# meme namestung T UW1 NGsahur S AA0 HH UH1 Rtung tung tung sahur T UW1 NG | T UW2 NG | T UW2 NG | S AA0 HH UH1 Rtralalero T R AA2 L AH0 L EH1 R OW0tralala T R AA2 L AH0 L AA1tralaleritos T R AA2 L AH0 L EH0 R IY1 T OW0 Sbombardiro B AA2 M B AA0 R D IY1 R OW0crocodilo K R AA2 K AH0 D IY1 L OW0cappuccina K AE2 P AH0 CH IY1 N AH0ballerino B AE2 L ER0 IY1 N OW0patapim P AA2 T AH0 P IY1 Mlirili L IH2 R IY0 L IY1larila L AA2 R IY0 L AA1chimpanzini CH IH2 M P AE0 N Z IY1 N IY0bananini B AE2 N AH0 N IY1 N IY0trippi T R IH1 P IY0troppi T R AA1 P IY0assassino AE2 S AH0 S IY1 N OW0vaca V AA1 K AH0saturno S AH0 T ER1 N OW0saturnita S AE2 T ER0 N IY1 T AH0boneca B OW0 N EH1 K AH0ambalabu AA2 M B AH0 L AH0 B UW1camelo K AH0 M EH1 L OW0bombombini B AA2 M B AA0 M B IY1 N IY0gusini G UW0 Z IY1 N IY0trulimero T R UW2 L IH0 M EH1 R OW0trulicina T R UW2 L IH0 CH IY1 N AH0glorbo G L AO1 R B OW0fruttodrillo F R UW2 T OW0 D R IH1 L OW0burbaloni B ER2 B AH0 L OW1 N IY0luliloli L UW2 L IY0 L OW1 L IY0baraboom B AA2 R AH0 B UW1 Mgirafa JH IH0 R AA1 F AH0celestre CH EH0 L EH1 S T R EY0orangutini AO0 R AE2 NG AH0 T IY1 N IY0ananasini AA2 N AH0 N AH0 S IY1 N IY0udin UW1 D IH0 Nespressona EH2 S P R EH0 S OW1 N AH0cocofanto K OW2 K OW0 F AA1 N T OW0elefanto EH2 L AH0 F AA1 N T OW0toasterino T OW2 S T ER0 IY1 N OW0garama G AH0 R AA1 M AH0madundung M AA0 D UW1 N D UW0 NG123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189# Function words: weak forms and how each word takes sentence stress.## Written by hand. The dictionary gives every word its full, stressed form;# in running speech these words are unstressed or half stressed, and a few# have a different vowel. The choices among valid weak forms (for example# "of" with ʌ, "has" with ɐ) follow the tokens the TTS model was trained on.## Columns (separated by two or more spaces): word, class, form, final form.# u never stressed# uf unstressed; stressed when it is the last word of its clause# ur unstressed; stressed when no stressed word follows in the clause# s secondary stress; primary when no stressed word follows in the clause# ss always secondary stress# si secondary when it opens the clause, otherwise unstressed; primary# when no stressed word follows# pf stressed as written; the final form when it closes the clause# The form is the medial one. The final form is used when the word is# promoted; without it the marked (or first) vowel takes the primary stress.
# articles, pronouns, determinersthe u ð əa u ɐan u ɐ ni uf aɪyou u j uːhe u h iːshe u ʃ iːit u ɪ twe u w iːthey u ð eɪme ss m ˌiːhim ss h ˌɪ mher u h ɜːus ss ˌʌ sthem ss ð ˌɛ mmy uf m aɪyour u j ʊɹhis uf h ɪ zits u ɪ t sour ss ˌaʊ ɚtheir u ð ɛɹthis uf ð ɪ sthat uf ð æ tthese uf ð iː zthose uf ð oʊ zsome ss s ˌʌ many ss ˌɛ n iwho s h ˌuːwhose s h ˌuː zwhich ss w ˌɪ tʃwhat si w ˌʌ twhere s w ˌɛɹwhen si w ˌɛ nwhy s w ˌaɪhow s h ˌaʊthere uf ð ɛɹ
# auxiliariesam u æ mis u ɪ zare u ɑːɹwas u w ʌ zwere u w ɜːbe uf b iːbeen ss b ˌɪ nbeing s b ˌiː ɪ ŋhave uf h æ vhas uf h ɐ z h ˈæ zhad uf h æ d h ˌæ dhaving ss h ˌæ v ɪ ŋwill ur w ɪ lwould uf w ʊ dshall ss ʃ ˌæ lshould s ʃ ˌʊ dcan ur k æ ncould uf k ʊ dmight s m ˌaɪ tget ur ɡ ɛ tgot ur ɡ ɑː tgetting ss ɡ ˌɛ ɾ ɪ ŋgo s ɡ ˌoʊgoes ur ɡ oʊ zgoing s ɡ ˌoʊ ɪ ŋgone ur ɡ ɔ nwent uf w ɛ n tmake ss m ˌeɪ kmakes ss m ˌeɪ k smaking ss m ˌeɪ k ɪ ŋmade s m ˌeɪ dput ss p ˌʊ tdoing ss d ˌuː ɪ ŋbecame ss b ɪ k ˌeɪ mbecome s b ɪ k ˌʌ m
# contractionsi'm u aɪ mi'll u aɪ li've u aɪ vi'd u aɪ dyou're u j ʊɹyou'll u j uː lyou've u j uː vyou'd u j uː dhe's u h iː zhe'll u h iː lhe'd u h iː dshe's u ʃ iː zshe'll u ʃ iː lshe'd u ʃ iː dit's u ɪ t sit'll ss ˌɪ ɾ əlwe're u w ɪɹwe'll u w iː lwe've u w iː vwe'd u w iː dthey're u ð eɪ ɚthey'll u ð eɪ lthey've u ð eɪ vthey'd u ð eɪ dthat's u ð æ t sthere's u ð ɛɹ zwhat's ss w ˌʌ t swho's ss h ˌuː zwhere's ss w ˌɛɹ zhow's ss h ˌaʊ zisn't s ˌɪ z ə n twon't uf w oʊ n tcouldn't s k ˌʊ d ə n tshouldn't s ʃ ˌʊ d ə n t
# prepositions, conjunctions, particlesof u ʌ vto uf t ə t uːin uf ɪ non s ˌɔ nat u æ tby uf b aɪfor u f ɔːɹfrom u f ɹ ʌ mwith u w ɪ ðas u æ zthan u ð ɐ nand uf æ n dor u ɔːɹif u ɪ fbut s b ˌʌ tso s s ˌoʊnot s n ˌɑː tup s ˌʌ pdown s d ˌaʊ nabout s ɐ b ˌaʊ tabove s ə b ˌʌ vacross ss ə k ɹ ˌɑː samong ss ɐ m ˌʌ ŋbefore s b ᵻ f ˌoːɹbehind s b ᵻ h ˌaɪ n dbelow s b ᵻ l ˌoʊbeneath ss b ᵻ n ˌiː θbeside s b ᵻ s ˌaɪ dbetween s b ᵻ t w ˌiː nbeyond ss b ᵻ j ˌɔ n dinto ss ˌɪ n t ʊonto ss ˌɑː n t ʊunto ss ˌʌ n t ʊupon ss ə p ˌɑː nover s ˌoʊ v ɚunder s ˌʌ n d ɚnear s n ˌɪɹnearly ss n ˌɪɹ l ithrough ur θ ɹ uːwithin s w ɪ ð ˌɪ nwithout s w ɪ ð ˌaʊ twhile s w ˌaɪ lthough s ð ˌoʊtogether s t ə ɡ ˌɛ ð ɚalready s ɔː l ɹ ˌɛ d iwhenever ss w ɛ n ˌɛ v ɚsir s s ˌɜː
# numbers: "one" weakens at the end of a clause; the teens are stressed on the# first syllable before another word and on "teen" at the endone pf w ˈʌ n w ˌʌ nthirteen pf θ ˈɜː t iː n θ ɜː t ˈiː nfourteen pf f ˈoːɹ t iː n f oːɹ t ˈiː nfifteen pf f ˈɪ f t iː n f ɪ f t ˈiː nsixteen pf s ˈɪ k s t iː n s ɪ k s t ˈiː nseventeen pf s ˈɛ v ə n t iː n s ɛ v ə n t ˈiː neighteen pf ˈeɪ t iː n eɪ t ˈiː nnineteen pf n ˈaɪ n t iː n n aɪ n t ˈiː n123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657# Pronunciations of homograph senses, where matching Google's sense list to# CMUdict does not give the right one. Written by hand.## The build takes every sense of the Wikipedia Homograph Data (wordids.tsv),# picks the CMUdict entry closest to the pronunciation given there, and then# applies this table. Most rows are senses CMUdict does not list separately# (it has one entry for both "implement"s), or typing slips in the source.# Columns: word, sense, pronunciation (CMUdict notation or phones).
abuses vrb AH0 B Y UW1 Z IH0 Zanalyses vrb AE1 N AH0 L AY2 Z IH0 Zaugust adj AO0 G AH1 S Taugust august AO1 G AH0 S Taugust nam AW1 G UH2 S Taxes nou-vrb AE1 K S IH0 Zblessed adj B L EH1 S IH0 Dconduct vrb K AH0 N D AH1 K Tconglomerate vrb K AH0 N G L AA1 M ER0 EY2 Tconjugate adj-nou K AA1 N JH AH0 G AH0 Tdeviate nou D IY1 V IY0 AH0 Tdiagnoses vrb D AY2 AH0 G N OW1 S IH0 Zdocument nou D AA1 K Y AH0 M AH0 N Tdocument vrb D AA1 K Y AH0 M EH2 N Telaborate adj IH0 L AE1 B ER0 AH0 Tentrance vrb IH0 N T R AE1 N Sexport vrb IH0 K S P AO1 R Texpose nou EH2 K S P OW0 Z EY1fragment vrb F R AE0 G M EH1 N Tfrequent vrb F R IY0 K W EH1 N Tgraduate adj-nou G R AE1 JH UW0 AH0 Thouse vrb HH AW1 Zimplement vrb IH1 M P L AH0 M EH2 N Tincrement vrb IH1 N K R AH0 M EH2 N Tinitiate nou IH0 N IH1 SH IY0 AH0 Tinstrument vrb IH1 N S T R AH0 M EH2 N Tintrigue nou-vrb IH0 N T R IY1 Gisolate nou AY1 S AH0 L AH0 Tjesus es HH EY0 S UW1 Sminute minute m ˈɪ n ɪ tmobile geo M OW0 B IY1 Lmobile nou-art M OW1 B IY2 Lmoderate vrb M AA1 D ER0 EY2 Tmouth vrb M AW1 DHnestle nam N EH1 S L IY0ornament vrb AO1 R N AH0 M EH2 N Tperfect adj P ER1 F EH0 K Tpasty adj P EY1 S T IY0pasty nou P AE1 S T IY0pigment vrb P IH0 G M EH1 N Tprecipitate adj-nou P R IH0 S IH1 P IH0 T AH0 Trecount vrb R IH0 K AW1 N Trefuse nou R EH1 F Y UW2 Srerelease rerelease R IY1 R IH0 L IY2 Srerelease vrb R IY2 R IH0 L IY1 Srodeo geo R OW0 D EY1 OW0row 2 R AW1supplement vrb S AH1 P L AH0 M EH2 N T123456789101112131415161718192021222324252627282930313233343536373839# Grammar and context rules for a few very common homographs. Written by hand.## They are tried before the trained classifier, in order; the first rule whose# conditions all hold decides. The training sentences come from Wikipedia,# where questions, commands and first-person speech are rare, so the cases# below ("have you read", "will you read", "take a bow") need saying outright.## Columns (two or more spaces): word, sense, conditions separated by ";".# aux: ... the nearest word to the left, skipping adverbs, "not",# pronouns and articles, is one of these# before: ... the word just before (adverbs and "not" skipped) is one of these# next: ... the word just after is one of these; </s> = end of sentence# near: ... one of these occurs within six words# first the word opens the sentence# joined: ... a hyphen joins the word to one of these before it ("well-read")
read past joined: well widely best better most least little much oft often rarely seldom never half unread past aux: have has had having haven't hasn't hadn't was were been being is are be am gotread present aux: to will would can could should shall may might must do does did don't doesn't didn't let let's please cannot can't won't wouldn't couldn't shouldn'tread present first
live vrb before: i you we they who people tolive adj next: music show shows broadcast performance performances concert concerts stream streaming coverage tv television album recording audience action event events demo feed wire ammunition
wound vrb aux: has have had having was were been got get tightlywound vrb next: up around round down through back tightlywound vrb before: he she it and then
bow nou-ship aux: take took takes taking taken to will would mustbow nou-knot near: tie tied tying ties ribbon ribbons hair arrow arrows violin cello fiddle string strings rainbow gift shoelace shoelacesbow nou-ship near: ship ships boat deck stern captain audience curtain applause stage head knee knees waist
bass corp near: fish fishing fished caught catch lake river pond sea striped largemouth smallmouth angler trout
lead nou near: pipe pipes paint pencil poisoning metal metals bullet bullets zinc copper tin mercury ore
minute adj before: is are was were so very extremely too such ; next: </s> , . ! ? and but details detail amount amounts quantities quantity particles differences changes fraction
content adj-nou-vrb before: is are was were am be been feel feels felt seem seems seemed quite so very perfectly not ; next: </s> , . ! ? with to in and123456789101112131415161718192021222324252627# Names of the letters, for initialisms and single letters.a ˈeɪb b ˈiːc s ˈiːd d ˈiːe ˈiːf ˈɛ fg dʒ ˈiːh ˈeɪ tʃi ˈaɪj dʒ ˈeɪk k ˈeɪl ˈɛ lm ˈɛ mn ˈɛ no ˈoʊp p ˈiːq k j ˈuːr ˈɑːɹs ˈɛ st t ˈiːu j ˈuːv v ˈiːw d ˈʌ b əl j uːx ˈɛ k sy w ˈaɪz z ˈiː123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# Function-word groups spoken as one unit: no word boundary inside, and often# a weaker form than the words have alone ("for the", "of a", "would have").## Written by hand. Which pairs are joined follows the tokens the TTS model was# trained on, so that the common cases look the same to it; switch the table# off (join_phrases=False) to keep a boundary token between all words.## Columns (two or more spaces): words, class, form, final form. Classes as in# function_words.txt; p = stress exactly as written. A final "the" or "to"# still takes its form before a vowel (ð ɪ, t ʊ). A form written with "|"# keeps the word boundaries and only fixes the stress of the pair.
of the u ʌ v ð əin the u ɪ n ð əon the u ɔ n ð əfor the u f ɚ ð əfrom the u f ɹ ʌ m ð əwith the u w ɪ ð ð əthat the u ð æ t ð əwas the u w ʌ z ð əof a u ə v əof an u ə v ə nfor a u f ɚ ɹ əfor an u f ɚ ɹ ə nat a u æ ɾ əwas a u w ʌ z ɐto be uf t ə b i t ə b ˈiːhad to u h æ d t əi am u aɪ ɐ mi shall ss aɪ ʃ ˌɐ lwe shall ss w iː ʃ ˌɐ lhad been u h ɐ d b ɪ nhave been u h ɐ v b ɪ nhas been p h ˈæ z b iː nwould have u w ʊ d h ɐ vcould have ss k ˌʊ d ɐ vshould have ss ʃ ˌʊ d ə vmight have ss m ˌaɪ t h ɐ vmust have p m ˈʌ s t ɐ vdid not s d ɪ d n ˌɑː tdo not s d uː n ˌɑː tdoes not s d ʌ z n ˌɑː thave not s h ɐ v n ˌɑː tthere was s ð ɛɹ w ˌʌ zthere were s ð ɛɹ w ˌɜːthere are ss ð ɛ ɹ ˌɑːɹout of ss ˌaʊ ɾ ə vat once p ɐ t w ˈʌ n sno one p n ˈoʊ w ˈʌ nthat one p ð ˈæ t w ˌʌ nthis one p ð ˈɪ s w ˌʌ nthat it ss ð ˌɐ ɾ ɪ tthat a ss ð ˌæ ɾ ənot a ss n ˌɑː ɾ ənot have ss n ˌɑː ɾ ɐ vof which p ʌ v w ˈɪ tʃin which ss ɪ n w ˌɪ tʃ
# stress of a pair, boundary keptso much p s ˈoʊ | m ˌʌ tʃso far p s ˈoʊ | f ˌɑːɹtoo much p t ˈuː | m ʌ tʃno longer p n ˌoʊ | l ˈɔ ŋ ɡ ɚ12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# Units written after a number: abbreviation, singular, plural.# Columns separated by two or more spaces. Letter case is ignored, except for# the units marked "exact" in a fourth column: those are read only in the# letter case written here ("5 m" is five meters, "5 M" and "5G" are not units).
km kilometer kilometerskg kilogram kilogramscm centimeter centimetersmm millimeter millimetersml milliliter millilitersmg milligram milligramskb kilobyte kilobytesmb megabyte megabytesgb gigabyte gigabytestb terabyte terabyteshz hertz hertzkhz kilohertz kilohertzmhz megahertz megahertzghz gigahertz gigahertzkw kilowatt kilowattskwh kilowatt hour kilowatt hourslb pound poundslbs pound poundsoz ounce ouncesft foot feetmi mile milesmin minute minutesmins minute minuteshr hour hourshrs hour hourssec second secondssecs second secondsms millisecond millisecondsmph mile per hour miles per hourkph kilometer per hour kilometers per hourkm/h kilometer per hour kilometers per hour°c degree Celsius degrees Celsius°f degree Fahrenheit degrees Fahrenheit° degree degreesm/s meter per second meters per secondyd yard yardsnm nanometer nanometersμm micrometer micrometersμg microgram microgramsmcg microgram microgramsmah milliamp hour milliamp hourshp horsepower horsepowertsp teaspoon teaspoonstbsp tablespoon tablespoonsdb decibel decibelskcal kilocalorie kilocaloriespx pixel pixelsrpm revolution per minute revolutions per minutebpm beat per minute beats per minutefps frame per second frames per secondmpg mile per gallon miles per gallonpsi pound per square inch pounds per square inchkbps kilobit per second kilobits per secondmbps megabit per second megabits per secondgbps gigabit per second gigabits per secondyr year yearsyrs year yearswk week weekswks week weeks
# one letter, or easily taken for something else: only in this letter casem meter meters exactg gram grams exactl liter liters exactL liter liters exacth hour hours exactV volt volts exactW watt watts exactMW megawatt megawatts exactp penny pence exactha hectare hectares exact123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277"""The phonemizer: text -> spoken words of phones, clause by clause.
Order of authority for one word: 1. pronunciation written inline in the text 2. the user's override list 3. the built-in exception list (``data/exceptions.txt``); a name of several words listed there or by the user is spoken with the stress written 4. function words and function-word groups (sentence level) 5. the dictionary built from CMUdict 6. regular endings, prefixes and compounds of dictionary words 7. names in "-leigh" and words in "-virus", put together from their parts 8. the unknown-word model"""
import jsonimport osfrom pathlib import Pathimport re
from . import morphology, normalize, sentence, tablesfrom .align import Alignerfrom .convert import convert, from_text, settle_stressfrom .g2p import Modelfrom .homographs import Homographsfrom .sentence import Unit
ENVIRONMENT = "DIZIONE_DATA"OVERRIDES_ENVIRONMENT = "DIZIONE_OVERRIDES"_LETTER_NAMES = None_LEIGH = re.compile(r"(?<=[a-z]{2})leigh(?=s?$)")_VIRUS = ("viruses", "virus")_HYPHEN_PREFIXES = {"re": "ɹ ˌiː", "inter": "ˌɪ n t ɚ"}
def default_directory(): """Where the built files live: ``$DIZIONE_DATA`` or ``built`` inside the package.""" return Path(os.environ.get(ENVIRONMENT) or Path(__file__).parent / "built")
class Phonemizer: def __init__(self, directory=None, overrides=None, join_phrases=True): self.directory = Path(directory) if directory else default_directory() lexicon = self.directory / "lexicon.tsv" if not lexicon.exists(): raise FileNotFoundError( f"no phonemizer data in {self.directory}: build it with scripts/build.sh" f"or point ${ENVIRONMENT} at a built directory") self.lexicon = dict(line.split("\t", 1) for line in lexicon.read_text(encoding="utf-8").splitlines() if line) self.aligner = Aligner(json.loads((self.directory / "align.json").read_text(encoding="utf-8"))) self.model = Model(self.directory) if (self.directory / "g2p.npz").exists() else None self.homographs = Homographs(self.directory / "homographs.json") if (self.directory / "homographs.json").exists() else None self.functions = tables.function_words() self.phrases = tables.phrases() if join_phrases else {} self.phrase_length = max((len(key) for key in self.phrases), default=1) self.exceptions = tables.pronunciations("exceptions.txt") self.names = tables.names("exceptions.txt") # names of several words, with their own rhythm self.name_starts = {key[0] for key in self.names} self.name_length = max((len(key) for key in self.names), default=1) self.user_names = set() self.overrides = {} override_file = os.environ.get(OVERRIDES_ENVIRONMENT) if override_file: self.add_overrides(Path(override_file)) if overrides: self.add_overrides(overrides) self.normalizer = normalize.Normalizer(self.is_word) self._cache = {}
# ---- single words -------------------------------------------------
def add_overrides(self, source): """Pronunciations that win over everything else. ``source`` is a dictionary ``{word: pronunciation}``, a path, or the text of a table; a pronunciation is CMUdict notation or phones with stress marks. A name of several words takes one pronunciation per word, separated by ``|``: ``{"tung tung tung sahur": "T UW1 NG | T UW2 NG | T UW2 NG | S AA0 HH UH1 R"}``.""" self.overrides.update(tables.pronunciations(source)) taught = tables.names(source) self.names.update(taught) self.user_names.update(taught) self.name_starts = {key[0] for key in self.names} self.name_length = max((len(key) for key in self.names), default=1) self._cache = {}
def _entry(self, word, entry): kind, value = entry if kind == "phones": return tuple(value) return convert(word, value, self.aligner.align(word, value))
def known(self, word): """Pronunciation from the override list, the exceptions or the dictionary.""" if word in self.overrides: return self._entry(word, self.overrides[word]) if word in self.exceptions: return self._entry(word, self.exceptions[word]) text = self.lexicon.get(word) return from_text(text) if text is not None else None
def ordinary(self, word): """Pronunciation of a dictionary word that may be half of a compound. CMUdict is full of surnames; a word that is also listed with a regular ending ("webs", "screens") is an ordinary one.""" if len(word) < 3 or not any(word + ending in self.lexicon for ending in ("s", "es", "ed", "ing")): return None return self.known(word)
def guess(self, word): """The unknown-word model, then the conversion rules, on one spelling.""" if self.model is None: return self.spell(word) spelling = self.model.spellable(word) symbols = self.model.predict(spelling) # The model emits each phoneme on its own, and between two possible vowels before # an r it sometimes emits neither ("okafor" -> ... F R). An r with no vowel beside # it is a syllable: write it as one. for k, symbol in enumerate(symbols): if symbol == "R" and not any(0 <= j < len(symbols) and symbols[j][-1] in "012" for j in (k - 1, k + 1)): symbols[k] = "ER0" if not any(symbol[-1] in "012" for symbol in symbols): return self.spell(word) # Every word spoken alone has a main stress, even when the model marked none. return sentence.promote(convert(spelling, symbols, self.aligner.align(spelling, symbols)))
def spell(self, letters): """Letter names, joined: the last letter carries the main stress.""" global _LETTER_NAMES if _LETTER_NAMES is None: _LETTER_NAMES = {key: from_text(value) for key, value in tables.mapping("letters.txt").items()} possessive = letters.lower().endswith("'s") names = [_LETTER_NAMES[c] for c in (letters[:-2] if possessive else letters).lower() if c in _LETTER_NAMES] out = [] for index, name in enumerate(names): out.extend((phone, 2 if stress and index < len(names) - 1 else stress) for phone, stress in name) return morphology.plural(tuple(out)) if possessive and out else tuple(out)
def is_word(self, word): """True for a spelling the tables or the dictionary know.""" return word in self.lexicon or word in self.functions or word in self.exceptions or word in self.overrides
def from_parts(self, word): """``(phones, source)`` for two kinds of new word the model reads badly, or ``None``. A name in "-leigh" is said like the same name in "-ley" (Kayleigh, Ryleigh). A word in "-virus" is its first part, from the dictionary or the model, and then "virus" (coronavirus).""" if word.endswith("'s") and len(word) > 3: found = self.from_parts(word[:-2]) return found and (morphology.plural(found[0]), found[1]) if _LEIGH.search(word): return self.word(_LEIGH.sub("ley", word)) for tail in _VIRUS: second = self.known(tail) if word.endswith(tail) and len(word) - len(tail) > 2 else None if second is not None: first, source = self.word(word[:-len(tail)]) phones = sentence.promote(settle_stress(morphology.compound(first, second))) return phones, "model" if source == "model" else "ending" return None
def word(self, word): """``(phones, source)`` for one spelling in lower case.""" if word in self._cache: return self._cache[word] phones, source = self.known(word), "dictionary" if phones is None: phones, source = morphology.derive(word, self.known, self.ordinary), "ending" if phones is not None: phones = settle_stress(phones) if phones is None: found = self.from_parts(word) if found: phones, source = found if phones is None and word.endswith("'s") and len(word) > 3: phones, source = morphology.plural(self.guess(word[:-2])), "model" if phones is None: phones, source = self.guess(word), "model" self._cache[word] = (phones, source) return phones, source
# ---- sentences ----------------------------------------------------
def _units(self, words, places=None, written=None): """Units of one clause from its ``normalize.Word`` tokens. ``written`` is the whole text as tokens and ``places`` where each word sits in it, for the homograph rules.""" units, index = [], 0 while index < len(words): token = words[index] if token.phones is not None: units.append(Unit(token.text, tuple(token.phones), "p", attach=token.attach, source="inline")) elif token.spell: units.append(Unit(token.text, self.spell(token.text), "p", attach=token.attach, source="letters")) else: size = self._name(words, index) if token.text in self.name_starts else 0 if size: # a taught name: every word as written in the table key = tuple(w.text for w in words[index:index + size]) units.extend(Unit(text, self._entry(text, entry), "p", attach=token.attach and position == 0, source="name") for position, (text, entry) in enumerate(zip(key, self.names[key]))) index += size continue size = self._phrase(words, index) if size: key = tuple(w.text for w in words[index:index + size]) kind, forms, final = self.phrases[key] if len(forms) == 1: units.append(Unit(" ".join(key), forms[0], kind, final, token.attach, "phrase")) else: # the boundaries stay, only the stress is fixed units.extend(Unit(text, form, kind, attach=token.attach and position == 0, source="phrase") for position, (text, form) in enumerate(zip(key, forms))) index += size continue if token.text in self.overrides: units.append(Unit(token.text, self.known(token.text), "c", attach=token.attach, source="override")) elif token.text in _HYPHEN_PREFIXES and index + 1 < len(words) and words[index + 1].attach \ and words[index + 1].phones is None and not words[index + 1].spell: # "re-run", "inter-city": the prefix, not the note "re" or the verb "inter" units.append(Unit(token.text, from_text(_HYPHEN_PREFIXES[token.text]), "c", attach=token.attach, source="prefix")) elif self.homographs and written and self.homographs.covers(token.text) and token.text not in self.exceptions: phones, ending = self.homographs.pronounce(token.text, written, places[index], token.attach) phones = morphology.plural(from_text(phones)) if ending else from_text(phones) units.append(Unit(token.text, phones, "c", attach=token.attach, source="homograph")) elif token.text in self.functions: kind, form, final = self.functions[token.text] units.append(Unit(token.text, form, kind, final, token.attach, "function")) else: phones, source = self.word(token.text) units.append(Unit(token.text, phones, "c", attach=token.attach, source=source)) index += 1 return units
def _name(self, words, index): for size in range(min(self.name_length, len(words) - index), 1, -1): span = words[index:index + size] key = tuple(w.text for w in span) if key in self.names and all(w.phones is None and not w.spell for w in span) and not any(w.attach for w in span[1:]) \ and (key in self.user_names or not any(w.text in self.overrides for w in span)): return size # the user's own word list wins over a built-in name return 0
def _phrase(self, words, index): for size in range(min(self.phrase_length, len(words) - index), 1, -1): span = words[index:index + size] if all(w.phones is None and not w.spell and not w.attach for w in span[1:]) and span[0].phones is None \ and not span[0].spell and tuple(w.text for w in span) in self.phrases \ and not any(w.text in self.overrides for w in span): return size return 0
def analyse(self, text): """Clauses and marks in order: ``("punct", mark)`` or ``("clause", [Unit, ...])``.""" stream = self.normalizer.tokens(text) # The text as the homograph rules see it; a word given only as phones stands as "x". written = [token.mark if isinstance(token, normalize.Punct) else (token.raw or token.text or "x") for token in stream] out, words, places = [], [], []
def flush(): if words: units = self._units(words, places, written) sentence.stress_clause(units) sentence.join_clause(units) out.append(("clause", units)) words.clear() places.clear()
for place, token in enumerate(stream): if isinstance(token, normalize.Punct): flush() out.append(("punct", token.mark)) else: words.append(token) places.append(place) flush() return out
def pieces(self, text): """The structure ``symbols.tokenize`` takes: ``(True, mark)`` for punctuation, ``(False, [[(phone, stress), ...], ...])`` for a run of words.""" return [(True, value) if kind == "punct" else (False, sentence.groups(value)) for kind, value in self.analyse(text)]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""The unknown-word model at run time: letters -> CMUdict phonemes.
Pure NumPy, one forward pass per word, no decoder loop. The network is the onetrained by ``scripts/train_g2p.py``: letter embeddings (each lettergiven ``slots`` positions), residual convolutions, a bidirectional GRU and aCTC output layer read greedily. The arithmetic below is the reference for theportable implementation."""
import jsonfrom pathlib import Pathimport unicodedata
import numpy as np
def _sigmoid(x): return 1.0 / (1.0 + np.exp(-x))
def _layer_norm(x, weight, bias): mean = x.mean(axis=-1, keepdims=True) variance = ((x - mean) ** 2).mean(axis=-1, keepdims=True) return (x - mean) / np.sqrt(variance + 1e-5) * weight + bias
def _conv(x, weight, bias): """x: (frames, channels); weight: (out, in, kernel), zero padding.""" kernel = weight.shape[2] pad = kernel // 2 padded = np.pad(x, ((pad, pad), (0, 0))) out = np.zeros((x.shape[0], weight.shape[0]), dtype=np.float32) + bias for k in range(kernel): out += padded[k:k + x.shape[0]] @ weight[:, :, k].T return out
def _gru(x, w_ih, w_hh, b_ih, b_hh, reverse): size = w_hh.shape[1] inputs = x @ w_ih.T + b_ih state = np.zeros(size, dtype=np.float32) out = np.empty((x.shape[0], size), dtype=np.float32) for t in (range(x.shape[0] - 1, -1, -1) if reverse else range(x.shape[0])): recurrent = w_hh @ state + b_hh reset = _sigmoid(inputs[t, :size] + recurrent[:size]) update = _sigmoid(inputs[t, size:2 * size] + recurrent[size:2 * size]) candidate = np.tanh(inputs[t, 2 * size:] + reset * recurrent[2 * size:]) state = (1.0 - update) * candidate + update * state out[t] = state return out
class Model: def __init__(self, directory): directory = Path(directory) self.settings = json.loads((directory / "g2p.json").read_text(encoding="utf-8")) with np.load(directory / "g2p.npz") as arrays: self.weights = {name: arrays[name] for name in arrays.files} self.letters = {letter: index + 1 for index, letter in enumerate(self.settings["letters"])} self.symbols = self.settings["symbols"] self.parameters = int(sum(value.size for value in self.weights.values()))
def spellable(self, word): """The word reduced to the letters the model knows (accents removed).""" plain = unicodedata.normalize("NFKD", word.lower()) return "".join(c for c in plain if c in self.letters).strip("'")
def log_probabilities(self, word): w, slots = self.weights, self.settings["slots"] ids = [self.letters[c] for c in word] x = (w["embed__weight"][ids][:, None, :] + w["slot"][None, :, :]).reshape(len(ids) * slots, -1) for block in range(self.settings["convs"]): normed = _layer_norm(x, w[f"norms__{block}__weight"], w[f"norms__{block}__bias"]) x = x + np.maximum(_conv(normed, w[f"convs__{block}__weight"], w[f"convs__{block}__bias"]), 0.0) for layer in range(self.settings["layers"]): both = [] for suffix, reverse in (("", False), ("_reverse", True)): both.append(_gru(x, w[f"gru__weight_ih_l{layer}{suffix}"], w[f"gru__weight_hh_l{layer}{suffix}"], w[f"gru__bias_ih_l{layer}{suffix}"], w[f"gru__bias_hh_l{layer}{suffix}"], reverse)) x = np.concatenate(both, axis=1) logits = x @ w["out__weight"].T + w["out__bias"] logits = logits - logits.max(axis=1, keepdims=True) return logits - np.log(np.exp(logits).sum(axis=1, keepdims=True))
def predict(self, word): """CMUdict symbols with stress digits for ``word`` (letters and apostrophes).""" word = self.spellable(word) if not word: return [] out, previous = [], 0 for label in self.log_probabilities(word).argmax(axis=1): if label != previous and label != 0: out.append(self.symbols[label - 1]) previous = label return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"""Words spelled alike and pronounced differently: which reading is meant.
"I read it yesterday" / "to read", "a live show" / "they live here". For eachhomograph of the Wikipedia Homograph Data a small linear classifier looks atthe neighbouring words. The weights are trained by``scripts/train_homographs.py``; this module computes the samefeatures at run time and adds up the weights. No tagger, no network.
Two kinds of model: * noun-or-verb homographs (record, present, use, ...) share one set of weights on the grammatical class of the neighbours ("to" before, an article before, ...), so a verb reading is found even for a word whose verb sense never occurs in the training sentences; each word adds its own weights and prior; * the others (bass, bow, lead, read, ...) have weights of their own."""
import jsonfrom pathlib import Pathimport re
_CLASSES = ( ("TO", "to"), ("DET", "the a an this that these those every each no some any another such what which whose"), ("POSS", "my your his her its our their"), ("SUBJ", "i you he she it we they who"), ("OBJ", "me him us them"), ("MODAL", "will would shall should can could may might must 'll 'd won't can't cannot couldn't shouldn't wouldn't let's please"), ("DO", "do does did don't doesn't didn't"), ("BE", "am is are was were be been being isn't aren't wasn't weren't i'm you're we're they're he's she's it's that's there's"), ("HAVE", "have has had having haven't hasn't hadn't i've you've we've they've"), ("NEG", "not never"), ("PREP", "of in on at by for from with into onto over under about after before between through during without within " "against among around across behind beside near upon toward towards as than like"), ("CONJ", "and or but nor so yet if because although though while when where unless until since whether"), ("ADV", "very too quite rather more most less least also just only even still always often sometimes usually again " "now then here there soon already almost"),)_TAG = {word: name for name, words in _CLASSES for word in words.split()}TOKEN = re.compile(r"[A-Za-z]+(?:'[A-Za-z]+)*|\d+(?:[.,]\d+)*|\S")SENTENCE_END = frozenset((".", "?", "!"))WINDOW = 6
def tag(token): """Coarse grammatical class of a neighbouring token, from closed lists and endings.""" if token in ("<s>", "</s>"): return token if not token[0].isalpha(): return "NUM" if token[0].isdigit() else "PUNCT" lower = token.lower() if lower in _TAG: return _TAG[lower] for ending, name in (("'s", "POS"), ("ly", "LY"), ("ing", "ING"), ("ed", "ED")): if lower.endswith(ending) and len(lower) > len(ending) + 1: return name if lower.endswith("s") and not lower.endswith("ss") and len(lower) > 3: return "S" return "CAP" if token[0].isupper() else "W"
def features(tokens, index): """Names of the features that are on for ``tokens[index]``. ``tokens`` is one sentence: words as written, punctuation marks as their own tokens.""" def at(offset): position = index + offset return tokens[position] if 0 <= position < len(tokens) else ("<s>" if offset < 0 else "</s>")
p2, p1, n1, n2 = at(-2), at(-1), at(1), at(2) tp2, tp1, tn1, tn2 = tag(p2), tag(p1), tag(n1), tag(n2) out = ["tp1=" + tp1, "tp2=" + tp2, "tn1=" + tn1, "tn2=" + tn2, "tp2p1=" + tp2 + "+" + tp1, "tp1n1=" + tp1 + "+" + tn1, "tn1n2=" + tn1 + "+" + tn2] if index == 0: out.append("first") elif tokens[index][0].isupper(): out.append("cap") out += ["p1=" + p1.lower(), "p2=" + p2.lower(), "n1=" + n1.lower(), "n2=" + n2.lower()] target = tokens[index].lower() nearby = {t.lower() for t in tokens[max(0, index - WINDOW):index + WINDOW + 1] if t[0].isalpha()} - {target} out += ["w=" + word for word in sorted(nearby)] return out
def shared(names): """The features of the noun-or-verb model that all its words share.""" return [name for name in names if name[0] == "t" or name in ("first", "cap")]
def sentence_of(tokens, index): """The sentence around ``tokens[index]`` and the index inside it.""" start = index while start > 0 and tokens[start - 1] not in SENTENCE_END: start -= 1 end = index while end < len(tokens) and tokens[end] not in SENTENCE_END: end += 1 return tokens[start:end + 1], index - start
_SKIP_FOR_BEFORE = frozenset(("ADV", "NEG", "LY"))_SKIP_FOR_AUX = _SKIP_FOR_BEFORE | frozenset(("SUBJ", "OBJ", "DET", "POSS"))
def _left(tokens, index, skip): """The nearest token to the left that is not of a skipped class, in lower case, with "'ll" and "'ve" read as "will" and "have".""" for position in range(index - 1, max(index - 6, -1), -1): token = tokens[position] if tag(token) in skip: continue lower = token.lower() return "will" if lower.endswith("'ll") else "have" if lower.endswith("'ve") else lower return "<s>"
def read_rules(source="homograph_rules.txt"): """word -> [(sense id, [(condition, words)])] from the hand-written table.""" from .tables import rows rules = {} for number, columns in rows(source): if len(columns) != 3: raise ValueError(f"homograph_rules.txt line {number}: expected word, sense, conditions") conditions = [] for part in columns[2].split(";"): name, _, words = part.strip().partition(":") if name not in ("aux", "before", "next", "near", "first", "joined") or (name == "first") == bool(words.strip()): raise ValueError(f"homograph_rules.txt line {number}: bad condition {part.strip()!r}") conditions.append((name, frozenset(words.split()))) rules.setdefault(columns[0], []).append((columns[1], conditions)) return rules
def _holds(condition, words, tokens, index, joined=False): if condition == "first": return index == 0 if condition == "joined": return joined and index > 0 and tokens[index - 1].lower() in words if condition == "aux": return _left(tokens, index, _SKIP_FOR_AUX) in words if condition == "before": return _left(tokens, index, _SKIP_FOR_BEFORE) in words if condition == "next": return (tokens[index + 1].lower() if index + 1 < len(tokens) else "</s>") in words return any(token.lower() in words for token in tokens[max(0, index - WINDOW):index + WINDOW + 1])
class Homographs: def __init__(self, path, rules=None): data = json.loads(Path(path).read_text(encoding="utf-8")) self.words = data["words"] # word -> {"senses": [{"id", "role", "phones"}], "model": ...} self.pooled = data["pooled"] # {"bias": b, "weights": {feature: w}} for the verb reading self.plural_bases = frozenset(data.get("plural_bases", ())) self.rules = read_rules() if rules is None else rules for word, word_rules in self.rules.items(): known = {sense["id"] for sense in self.words[word]["senses"]} if word in self.words else set() for sense, _ in word_rules: if sense not in known: raise ValueError(f"homograph rule for {word!r} names the unknown sense {sense!r}")
def __contains__(self, word): return word in self.words
def covers(self, word): """True for a homograph and for the regular -s form of a noun-or-verb one.""" return word in self.words or (word.endswith("s") and word[:-1] in self.plural_bases)
def pronounce(self, word, tokens, index, joined=False): """``(phones as text, needs the -s ending)`` for ``tokens[index]``. ``joined`` says a hyphen joins the word to the one before it.""" if word in self.words: return self.choose(word, tokens, index, joined)["phones"], False entry = self.words[word[:-1]] adjective = next((sense for sense in entry["senses"] if sense["role"] == "n"), None) if adjective and adjective["id"] == "adj": # "separates" can only be the verb return next(sense for sense in entry["senses"] if sense["role"] == "v")["phones"], True return self.choose(word[:-1], tokens, index, joined)["phones"], True
def scores(self, word, tokens, index): """Score of every sense of ``word`` (higher is more likely).""" entry = self.words[word] names = features(*sentence_of(tokens, index)) model = entry["model"] if model["kind"] == "noun-verb": verb = self.pooled["bias"] + sum(self.pooled["weights"].get(name, 0.0) for name in shared(names)) verb += model["bias"] + sum(model["weights"].get(name, 0.0) for name in names) return [verb if sense["role"] == "v" else -verb for sense in entry["senses"]] return [bias + sum(weights.get(name, 0.0) for name in names) for bias, weights in zip(model["bias"], model["weights"])]
def choose(self, word, tokens, index, joined=False): """The sense meant by ``tokens[index]``: ``{"id", "role", "phones"}``. Hand rules first, then the classifier.""" entry = self.words[word] sentence, position = sentence_of(tokens, index) for sense, conditions in self.rules.get(word, ()): if all(_holds(name, words, sentence, position, joined) for name, words in conditions): return next(s for s in entry["senses"] if s["id"] == sense) scores = self.scores(word, tokens, index) return entry["senses"][max(range(len(scores)), key=scores.__getitem__)]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217"""Words the dictionary lacks but can be built from words it has.
Plurals, possessives, -ed, -ing, -ly and other regular endings, a fewprefixes, compounds of two dictionary words and British spellings. The stem'spronunciation comes from the dictionary; the ending is added by rule, with theadjustments English makes at the seam (the flap of "waited", the r of"starring", the voicing of "dogs" against "cats")."""
import re
from .symbols import VOWEL_SET
_SHORT_STEM = re.compile(r"(?:^|[^aeiou])[aeiou](?:[bcdfgklmnprstvz]|th)$")_SIBILANT = frozenset(("s", "z", "ʃ", "ʒ", "tʃ", "dʒ"))_VOICELESS = frozenset(("p", "t", "k", "f", "θ", "ʔ"))_SPLIT = {"ɑːɹ": "ɑː", "ɔːɹ": "ɔː", "oːɹ": "oː", "ɪɹ": "ɪ", "ɛɹ": "ɛ"}_RHOTIC = frozenset(("ɚ", "ɜː", "aɪɚ", "ʊɹ"))_CONSONANT_LETTERS = frozenset("bcdfghjklmnpqrstvwxz")P = lambda *phones: tuple((phone, 0) for phone in phones)
# Endings that leave the stem's stress alone: spelling, phones._ENDINGS = ( ("fully", P("f", "əl", "i")), ("lessly", P("l", "ə", "s", "l", "i")), ("ness", P("n", "ə", "s")), ("less", P("l", "ə", "s")), ("ments", P("m", "ə", "n", "t", "s")), ("ment", P("m", "ə", "n", "t")), ("ful", P("f", "əl")), ("ship", (("ʃ", 0), ("ɪ", 2), ("p", 0))), ("hood", (("h", 0), ("ʊ", 2), ("d", 0))), ("like", (("l", 0), ("aɪ", 2), ("k", 0))), ("dom", P("d", "ə", "m")), ("ish", P("ɪ", "ʃ")), ("able", P("ə", "b", "əl")), ("ism", P("ɪ", "z", "ə", "m")), ("ist", P("ɪ", "s", "t")), ("wards", P("w", "ɚ", "d", "z")), ("ward", P("w", "ɚ", "d")), ("age", P("ɪ", "dʒ")), ("ers", P("ɚ", "z")), ("er", P("ɚ",)), ("est", P("ɪ", "s", "t")), ("y", P("i",)),)# Prefix spelling -> (form before a stem stressed on its first syllable, form otherwise)._PREFIXES = ( ("under", ((("ʌ", 2), ("n", 0), ("d", 0), ("ɚ", 0)),) * 2), ("over", ((("oʊ", 2), ("v", 0), ("ɚ", 0)),) * 2), ("anti", ((("æ", 2), ("n", 0), ("t", 0), ("i", 0)),) * 2), ("semi", ((("s", 0), ("ɛ", 2), ("m", 0), ("i", 0)),) * 2), ("non", ((("n", 0), ("ɑː", 2), ("n", 0)),) * 2), ("out", ((("aʊ", 2), ("t", 0)),) * 2), ("dis", (P("d", "ɪ", "s"), (("d", 0), ("ɪ", 2), ("s", 0)))), ("mis", (P("m", "ɪ", "s"), (("m", 0), ("ɪ", 2), ("s", 0)))), ("un", (P("ʌ", "n"), (("ʌ", 2), ("n", 0)))), ("in", (P("ɪ", "n"), (("ɪ", 2), ("n", 0)))), ("re", (P("ɹ", "ᵻ"), (("ɹ", 0), ("iː", 2)))), ("pre", ((("p", 0), ("ɹ", 0), ("iː", 2)),) * 2),)_BRITISH = (("isation", "ization"), ("ising", "izing"), ("ised", "ized"), ("ises", "izes"), ("ise", "ize"), ("yse", "yze"), ("our", "or"), ("ourable", "orable"), ("ours", "ors"), ("oured", "ored"), ("ouring", "oring"), ("tre", "ter"), ("tres", "ters"), ("bre", "ber"), ("ence", "ense"), ("ogue", "og"), ("mme", "m"), ("lled", "led"), ("lling", "ling"), ("ller", "ler"), ("oul", "ol"), ("ae", "e"), ("enqui", "inqui"))
def join(stem, ending): """Stem + ending, adjusted at the seam.""" stem = list(stem) if not stem or not ending: return tuple(stem) + tuple(ending) (last, stress), (first, first_stress) = stem[-1], ending[0] if first in VOWEL_SET: if last in _SPLIT: stem[-1:] = [(_SPLIT[last], stress), ("ɹ", 0)] # star + ing elif last in _RHOTIC: stem.append(("ɹ", 0)) # wander + ing, sure + er elif last == "t" and len(stem) > 1 and (stem[-2][0] in VOWEL_SET or stem[-2][0] == "ɹ") and not first_stress \ and not (first == "ə" and len(ending) > 1 and ending[1][0] == "n"): stem[-1] = ("ɾ", 0) # wait + ed elif last == "i": stem[-1] = ("ɪ", stress) if first != "ɪ" else ("i", stress) # storm·y + er; carry + ing elif last == "i" and first in ("n", "l", "f", "m"): stem[-1] = ("ɪ", stress) # happi + ness, happi + ly elif last == "n" and first in ("k", "ɡ"): stem[-1] = ("ŋ", 0) return tuple(stem) + tuple(ending)
def plural(stem): last = stem[-1][0] return join(stem, P("ᵻ", "z") if last in _SIBILANT else P("s") if last in _VOICELESS else P("z"))
def past(stem): last = stem[-1][0] if last in ("t", "d", "ɾ"): return join(stem, P("ᵻ", "d")) return join(stem, P("t") if last in _VOICELESS or last in ("s", "ʃ", "tʃ") else P("d"))
def adverb(stem): last = stem[-1][0] return join(stem, P("i") if last in ("əl", "l") else P("l", "i"))
def _stems(body): """Spellings the stem may have had before an ending starting with a vowel.""" out = [body] if len(body) > 2 and body[-1] == body[-2] and body[-1] in _CONSONANT_LETTERS: out.append(body[:-1]) # stopp-ed if body and body[-1] in _CONSONANT_LETTERS | {"u"}: # A short vowel before a single consonant would have doubled it ("hopped"), # so "hoped" and "clothed" come from "hope" and "clothe". single = _SHORT_STEM.search(body) is not None out.insert(0 if single else len(out), body + "e") # lov-ed, spong-ing if body.endswith("i") and len(body) > 2: out.append(body[:-1] + "y") # stormi-er return out
def _secondary(phones): """Demote the primary stress of the second part of a compound.""" return tuple((phone, 2 if stress == 1 else stress) for phone, stress in phones)
def compound(first, second): """Two words said as one: the second keeps only a lesser stress ("sandpiper").""" return join(first, _secondary(second))
def derive(word, lookup, part=None, depth=0): """Pronunciation of ``word`` from a shorter dictionary word, or ``None``.
``lookup(spelling)`` returns the dictionary pronunciation or ``None``; ``part(spelling)`` does the same for a word that may be half of a compound (by default any dictionary word). """ part = part or lookup
def stem(spelling): if len(spelling) < 2: return None return lookup(spelling) or (derive(spelling, lookup, part, depth + 1) if depth < 2 else None)
def first(candidates, build): for spelling in candidates: found = stem(spelling) if found: return build(found) return None
if word.endswith("'s"): return first([word[:-2]], plural) if word.endswith("s'"): return first([word[:-1]], lambda found: found) if word.endswith("ies") and len(word) > 4: found = first([word[:-3] + "y"], plural) if found: return found if word.endswith("ves") and len(word) > 4: found = first([word[:-3] + "f", word[:-3] + "fe"], lambda f: join(f[:-1] + (("v", 0),), P("z")) if f[-1][0] == "f" else None) if found: return found if word.endswith("es") and len(word) > 3: found = first([word[:-2]] if word[-3] in "sxzh" else [], plural) if found: return found if word.endswith("s") and not word.endswith(("ss", "us", "is")) and len(word) > 3: found = first([word[:-1]], plural) if found: return found if word.endswith("ied") and len(word) > 4: found = first([word[:-3] + "y"], past) if found: return found if word.endswith("ed") and len(word) > 3: found = first(_stems(word[:-2]), past) if found: return found if word.endswith("ing") and len(word) > 4: found = first(_stems(word[:-3]), lambda f: join(f, P("ɪ", "ŋ"))) if found: return found if word.endswith("ily") and len(word) > 4: found = first([word[:-3] + "y"], adverb) if found: return found if word.endswith("ly") and len(word) > 3: found = first([word[:-2], word[:-2] + "le", word[:-1] + "e"] if word.endswith("bly") or word.endswith("ply") else [word[:-2]], adverb) if found: return found for spelling, phones in _ENDINGS: if word.endswith(spelling) and len(word) - len(spelling) > 2: body = word[:-len(spelling)] if spelling == "y" and body[-1] not in _CONSONANT_LETTERS: continue # "copay" is not "copa" + y vowel_first = phones[0][0] in VOWEL_SET found = first(_stems(body) if vowel_first else [body[:-1] + "y", body] if body.endswith("i") else [body], lambda f, phones=phones: join(f, phones)) if found: return found for spelling, (plain, stressed) in _PREFIXES: if word.startswith(spelling) and len(word) - len(spelling) > 2: found = stem(word[len(spelling):]) if found: vowels = [stress for phone, stress in found if phone in VOWEL_SET] head = plain if vowels and vowels[0] == 1 else stressed return join(head, found) for old, new in _BRITISH: if old in word: found = stem(word.replace(old, new, 1)) if found: return found if depth == 0: # Two dictionary words of four letters or more: "sandpiper", "houseplant". # Shorter halves turn up by chance too often ("couplet" is not "coup" + "let"). best = None def tail(spelling): # The second half may carry a plural ending ("wagonways" = wagon + way + s). found = part(spelling) if found is None and spelling.endswith("s") and not spelling.endswith(("ss", "us", "is")) and len(spelling) > 3: single = part(spelling[:-1]) # The plural's own entry when the dictionary has one ("winds" W IH N D Z, not the verb). found = single and (lookup(spelling) or plural(single)) return found
for cut in range(4, len(word) - 3): left, right = part(word[:cut]), tail(word[cut:]) if left and right: score = min(cut, len(word) - cut) if best is None or score > best[0]: best = (score, left, right) if best: return compound(best[1], best[2]) return None1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423"""Text -> the words to say and the punctuation marks between them.
Everything that is not a plain word is turned into words here, by rule:numbers, ordinals, money, dates, times, telephone numbers, units,abbreviations, initialisms, symbols, chat spellings, version numbers, codesand reference numbers, web addresses and file names.Emoticons and emoji are dropped: they are neither read nor a pause.A pronunciation can be given inline, ``{HH AH0 L OW1}`` or ``{h ə l ˈoʊ}``,alone or right after the word it replaces. Braces that hold anything else areread as text.
The result is a list of ``Word`` and ``Punct`` tokens. Hand-written tables in``data/`` hold the abbreviations, units, chat spellings and file endings."""
import refrom typing import NamedTupleimport unicodedata
from .symbols import PUNCTUATIONfrom . import tablesfrom .convert import convert, from_text, is_arpabet
class Word(NamedTuple): text: str # letters and apostrophes, lower case attach: bool = False # continues the previous word (hyphenated compound, parts of one token) raw: str = "" # as written spell: bool = False # read letter by letter phones: tuple = None # pronunciation given inline by the user
class Punct(NamedTuple): mark: str
# Private-use characters that carry decisions through the rewriting of the text:# letters to be named sit between _SPELL and _END, and an inline pronunciation# is a single character (its number added to _INLINE_BASE) between two _INLINE._SPELL, _END, _INLINE, _INLINE_BASE = "", "", "", 0xE100_ONES = ("zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen " "seventeen eighteen nineteen").split()_TENS = "twenty thirty forty fifty sixty seventy eighty ninety".split()_SCALES = ("thousand", "million", "billion", "trillion", "quadrillion", "quintillion")_NUMBER_WORDS = frozenset(_ONES) | frozenset(_TENS) | {"hundred"}_ORDINAL = {"one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth", "nine": "ninth", "twelve": "twelfth"}_MONTHS = "January February March April May June July August September October November December".split()_MONTH_NUMBER = {name.lower()[:3]: index + 1 for index, name in enumerate(_MONTHS)}_MONTH_PATTERN = "|".join(_MONTHS) + "|Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sept|Sep|Oct|Nov|Dec"_DAY_NAMES = {"mon": "Monday", "tue": "Tuesday", "wed": "Wednesday", "thu": "Thursday", "fri": "Friday", "sat": "Saturday", "sun": "Sunday"}_DAY_PATTERN = "Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday|Thurs|Thur|Tues|Mon|Tue|Wed|Thu|Fri|Sat|Sun"_CURRENCY = {"$": ("dollar", "dollars", "cent", "cents"), "£": ("pound", "pounds", "penny", "pence"), "€": ("euro", "euros", "cent", "cents"), "¥": ("yen", "yen", "", ""), "₹": ("rupee", "rupees", "paisa", "paise")}_CURRENCY.update({"USD": _CURRENCY["$"], "EUR": _CURRENCY["€"], "GBP": _CURRENCY["£"], "JPY": _CURRENCY["¥"], "INR": _CURRENCY["₹"], "CHF": ("Swiss franc", "Swiss francs", "centime", "centimes"), "CAD": ("Canadian dollar", "Canadian dollars", "cent", "cents"), "AUD": ("Australian dollar", "Australian dollars", "cent", "cents"), "CNY": ("yuan", "yuan", "", "")})_CURRENCY_CODES = "USD|EUR|GBP|JPY|INR|CHF|CAD|AUD|CNY"_SCALE_LETTER = {"k": "thousand", "m": "million", "b": "billion", "bn": "billion", "t": "trillion"}_FRACTION = {2: ("half", "halves"), 4: ("quarter", "quarters")}_SYMBOL_WORDS = {"&": "and", "@": "at", "+": "plus", "=": "equals", "%": "percent", "×": "times", "÷": "divided by", "±": "plus or minus", "©": "copyright", "§": "section", "°": "degrees", "≥": "greater than or equal to", "≤": "less than or equal to", "≠": "not equal to", "≈": "approximately", "∞": "infinity", "√": "square root of", "π": "pi"}_COMPARISONS = {">=": "greater than or equal to", "<=": "less than or equal to", "!=": "not equal to"}# Capitals read letter by letter although they also spell a word._INITIALISMS = frozenset("US IT AI ID UN EU UK LA AD BC AM PM OS PE PA MA LED SAT RIP ER RAF SAS UPS".split())# Two capitals that are a word to say, not letters to name ("OH", "HI"); any other pair# the dictionary happens to list is named: "MS" (not "Ms"), "CT", "ET", "IB".# "pp. 12-15": the range is already words when the abbreviations are read.# Words after an amount that show it does not describe a noun: "the $500 will be returned"._NOT_A_NOUN = frozenset("will would is was are were has had have can could should may might must shall did does do " "to for in on at of from and or but nor that which who whom whose i you he she we they it me him " "them us back each a an the per now today yesterday tomorrow already more less extra plus off " "only as by with so then if when every monthly weekly yearly annually daily later instead too again " "upfront up down out over under into onto than before after since until while because just still " "also even here there this these those what where how why worth apiece total altogether " "is being been not no cash".split())_PAGE_LIKE = frozenset("p pp fig vol ch sec".split())_CAPITAL_PAIRS = frozenset("OK OH HI YO UH UM AH HA OW OX EH OI HM MM SH EX".split())# Sounds written without a vowel. "Ss" among them, or alone, is a hiss ("Sh! Ss! Tsk!")._SOUNDS = frozenset("sh shh ss zz hm hmm mm tsk psst pfft hmph psh pssh".split())# A comparison between two values is said with "is": "67 > 66" is "sixty seven# is greater than sixty six", "see if b>a" is "see if B is greater than A". A# value is a figure, a single letter or a closing bracket, with the same space# (or none) on both sides of the sign. "Is" is left out where the comparison# only describes the value: "for n > 4", "any q > 0", "an integer k ≥ 2". The# mark below is put after the first value and stays there while the figures# around it are turned into words._IS = chr(0xE006)_COMPARED = re.compile(r"(?P<gap>[ \t]?)(?P<sign>>=|<=|!=|[<>≥≤≠])(?P=gap)")_VALUE_BEFORE = re.compile(r"(?:(?<![\w.,])\d[\d.,]*%?|(?<![\w'’.-])[A-Za-z]|[)\]])$")_VALUE_AFTER = re.compile(r"(?:[-+]?[$£€¥₹]?\d[\d.,]*%?(?!\w)|\.\d|[A-Za-z](?![\w'’])|[(\[])")_CLAUSE_OPENERS = frozenset("if elif while when whenever where whether that because since as and or but so then think thinks " "thought know knows say says said suppose assume means implies hence thus therefore although though " "unless until once else also clearly obviously indeed here now again first next finally similarly " "otherwise however moreover".split())# "A", "a" and the small letters chat writes for a word ("k", "u", "r") are read# as words. Beside a sign or alone in brackets they stand for something and are# named: "a=10", "b>a", "k = k + 1", "(a)". After "=" or a spaced sign the letter# must not open a phrase ("mode = a set of notes")._SIGN = r"[<>+*/^≤≥≠≈×÷±]"_SPACED_SIGN = r" [<>+*≤≥≠≈×÷±] "_NO_PHRASE = r"(?![\w'’-]|\s+(?!(?:and|or|then|if|when|where|while|for|is|are|was|but|so|in|to)\b)[A-Za-z])"_LETTER_PLACES = tuple(re.compile(pattern) for pattern in ( r"(?<![\w'’.-])(?P<letter>[Aakur])(?=" + _IS + r"?\s?[<>!=]?=)", # a=10, a = 10, a >= b r"[<>!=]?=\s?(?P<letter>[Aakur])" + _NO_PHRASE, # x=a, c = a + b r"(?<![\w'’.-])(?P<letter>[Aakur])(?=" + _IS + r"?" + _SIGN + r"(?:[\w($]|\.\d))", # a>b, a+b, a/b, a^2 r"(?<=[\w)" + _IS + r"]" + _SIGN + r")(?<![Ww]/)(?P<letter>[Aakur])(?![\w'’-])", # b>a, 1/a; not "w/a friend" r"(?<![\w'’.-])(?P<letter>[Aakur])(?=" + _IS + r"?" + _SPACED_SIGN + r"(?:[A-Za-z]|\d[\d.,]*)(?![\w'’]))", # a > b r"(?<![\w'’.])(?:[A-Za-z]|\d[\d.,]*)" + _IS + r"?" + _SPACED_SIGN + r"(?P<letter>[Aakur])" + _NO_PHRASE, # b > a r"(?<=\()(?P<letter>[Aakur])(?=\)|, )", # (a), f(a, b) r"(?<=, )(?P<letter>[Aakur])(?=\))", # f(b, a) r"(?:(?<=\s)|^)(?P<letter>[akur])(?=\)\s)", # a) the first point))# "<b>", "</p>", "<your name>", "Vec<u64>", "map<int, int>": angle brackets that# enclose something. The "<" and ">" that are left may compare two things._ANGLES = re.compile(r"(?<![\w)" + _END + _IS + r"])<[A-Za-z0-9/!?][^<>(){}+*;|\n]*>" r"|(?<=[\w" + _END + _IS + r"])<[^<>(){}+*;|\n]{1,80}>(?![\w$])" r"|</?[A-Za-z][\w-]+/?>")_ANGLE_MARK = chr(0xE005)
def _without_angles(text): """``text`` with the angle brackets that enclose something replaced by a mark, one for one, the inner ones first.""" while "<" in text and ">" in text: marked = _ANGLES.sub(lambda match: _ANGLE_MARK + match.group(0)[1:-1] + _ANGLE_MARK, text) if marked == text: break text = marked return text
# "<" or ">" with no space on either side: "b>a", "x<5", "p<.05". It is read as a# comparison when a figure stands on one side, or a single letter or a bracket on# both. "File>Open" and "M>Train" are not comparisons._JOINED_COMPARISON = re.compile(r"(?<=[\w)" + _END + _IS + r"])[<>](?=[\w(" + _SPELL + r"]|\.\d| minus \d)")_FIGURE_BEFORE = re.compile(r"(?<![\w.,])\d[\d.,]*%?$")_FIGURE_AFTER = re.compile(r"(?:\d[\d.,]*%?(?!\w)|\.\d| minus \d)")_LETTER_BEFORE = re.compile(r"(?:(?<![\w'’.])[A-Za-z]|[)" + _END + r"])$")_LETTER_AFTER = re.compile(r"(?:[A-Za-z](?![\w'’])|[(" + _SPELL + r"])")_SENTENCE_STARTERS = frozenset("the he she it i we they this that there but and in on at a an if when what why how who my our " "you then so now after before however".split())_YEAR_CONTEXT = frozenset("in since by from until till before after during around circa of year early late mid summer winter " "spring fall autumn class".split())_CARDINAL_AFTER = frozenset("war chapter part book volume act scene section phase type class level stage title article " "appendix world".split())_LABELLED = frozenset("plan vitamin grade type option class section part team group exhibit appendix point model series " "hepatitis level".split())_ROMAN = {"II": 2, "III": 3, "IV": 4, "VI": 6, "VII": 7, "VIII": 8, "IX": 9, "XI": 11, "XII": 12, "XIII": 13, "XIV": 14, "XV": 15, "XVI": 16, "XVII": 17, "XVIII": 18, "XIX": 19, "XX": 20, "XXI": 21, "XXII": 22, "XXIII": 23, "XXIV": 24, "XXV": 25}_LEADING_APOSTROPHE = frozenset(("'em", "'tis", "'twas", "'til", "'cause", "'bout", "'round", "'n"))_EMOJI = re.compile("[\U0001F000-\U0001FAFF☀-➿\U0001F1E6-\U0001F1FF←-⇿⬀-⯿️⃣]+")_EMOTICON = re.compile( r"(?<![A-Za-z0-9])(?:[:;=]['^-]?[DPpOo3|/\\*\]\[}{><]+|[)(\]\[][-^']?[:;=]|<3+|</3|\^_?\^|-_-|[oO]_[oO]|>_<|T_T|\\o/|:'[()])(?![A-Za-z0-9])" r"|[:;]['^-]?[)(]+" r"|(?<![A-Za-z0-9)])=['^-]?[)(]+|=['^-]?[)(]+(?![A-Za-z0-9(.$-])" # "=(" is a face, but not in "y=(a+b)" r"|(?<=[A-Za-z]{2})<3+(?![.,]?\d)") # a heart joined to a word: "you<3"
# Words that say what the number after them is. A telephone number, a PIN or a# reference is read digit by digit; an amount is not._PHONE_WORDS = frozenset("call dial ring phone telephone tel mobile cell fax hotline text sms whatsapp".split())_PHONE_LINKS = frozenset("to on at or us me him her them back".split())_PIN_WORDS = frozenset("code pin extension ext passcode password zip postcode cvv cvc otp".split())_STRONG_WORDS = frozenset("number id reference ref serial account tracking booking confirmation".split())_WEAK_WORDS = frozenset("order ticket invoice case claim policy receipt transaction parcel shipment container payment " "reservation membership customer batch lot item job issue bug request".split())_LINK_WORDS = frozenset("is was are were ends ending in with starts starting begins beginning".split())_NOT_COUNTED = frozenset("is was has does goes ships arrives departs leaves shows needs blocks remains includes contains " "says reads starts ends closes opens runs takes comes this his its us as yes plus minus less".split())_NUMBERED = frozenset("ref reference serial account order invoice tracking part model phone tel fax id room flight case " "ticket policy licence license booking customer vat tax reg registration".split())_DATE_BEFORE = frozenset("on dated due until till by since from before after for shipped delivered arriving arrives arrive " "arrived expires expired ends ending starts starting begins beginning monday tuesday wednesday " "thursday friday saturday sunday mon tue tues wed thu thur thurs fri sat sun".split())_CLASSIC_FRACTIONS = frozenset((2, 3, 4, 5, 6, 8, 10, 16, 32, 64, 100))_RATIO_WORDS = frozenset("ratio ratios scale odds aspect mix split proportion".split())_DURATION_WORDS = frozenset("lasted took duration runtime recording video clip track lap pace length long".split())_CLOCK_WORDS = frozenset("window slot open opens opening hours shift session served service available booked appointment " "delivery arrive arrives arriving".split())_CAPITAL_WORDS = frozenset("IN ON AT TO OF BY OR IS AS IF NO SO WE HE MY ME DO GO UP AN AM PM BE IT US THE AND FOR BUT NOT " "ALL".split())_SHORT_WORDS = frozenset("my to in on of go up no do me we us it is at by be so or an as if he hi ok".split())_ZONES = "ET|CT|MT|PT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|GMT|UTC|BST|CET|CEST|IST|AEST|AEDT|JST"_SIZES = "XXXL|XXL|XXS|XL|XS|S|M|L"_LENGTHS = "mm|cm|km|m|ft|in|inch|inches|feet|foot|metres?|meters?|yards?|yd|px|pixels?"# Before a number these mean a version: its parts are read as whole numbers ("three point twelve")._VERSIONED = ("version|ver|release|firmware|patch|kernel|build|python|node|nodejs|ios|ipados|macos|watchos|tvos|android|" "chrome|firefox|safari|java|php|ruby|rust|swift|kotlin|golang|django|rails|react|angular|vue|docker|" "kubernetes|ubuntu|debian|fedora|windows|linux|postgres|postgresql|mysql|redis|numpy|pytorch|tensorflow|cuda|" "xcode|gcc|clang|unity|minecraft|typescript|bluetooth|usb|hdmi|opengl|vulkan|directx|" "upgrade[ds]?|update[ds]?|downgrade[ds]?")_SEPARATORS = {".": "dot", "/": "slash", "@": "at", "-": "dash", "_": "underscore", ":": "colon", "=": "equals", "&": "and", "+": "plus"}_HALF_DAY = r"(?:\s?([AaPp])\.[Mm]\.?|\s?([AaPp])[Mm]\b)"_AMOUNT = r"(?P<whole>\d{1,3}(?:,\d{3})+|\d+)(?:\.(?P<fraction>\d+))?"_MONEY = re.compile(r"(?:(?<![\w.])(?P<minus>-)\s?)?(?P<symbol>[$£€¥₹]|(?<![A-Za-z])(?:" + _CURRENCY_CODES + r")(?![A-Za-z]))\s?" r"(?P<inner>-)?" + _AMOUNT + r"(?:\s?(?P<scale>thousand|million|billion|trillion|bn|[kKmMbB])(?![A-Za-z]))?")# A currency written after the amount: "20 €", "20€", "12.50 EUR". Those who write# it there often part the thousands with spaces: "750 000 $"._SIGN_AFTER = r"[$£€¥₹](?![\w$£€¥₹])|(?:" + _CURRENCY_CODES + r")(?![A-Za-z])"_MONEY_AFTER = re.compile(r"(?:(?<![\w.])(?P<minus>-)\s?)?(?<![\w.,^])" r"(?P<whole>\d{1,3}(?:,\d{3})+|[1-9]\d{0,2}(?: \d{3})+|\d+)(?:\.(?P<fraction>\d+))?" r"\s?(?P<symbol>" + _SIGN_AFTER + r")")_RANGE_BEFORE_SIGN = re.compile(r"(?<![\w.,-])(\d[\d,]*(?:\.\d+)?)-(?=\d[\d,]*(?:\.\d+)?\s?(?:" + _SIGN_AFTER + r"))")# Figures written the continental way: a point between the thousands and a comma# before the decimals ("1.299,50"). Without the points a comma is a decimal# comma only next to a currency or a percent sign ("€12,50", "0,99 €", "3,5%")# or before a unit ("1,5 kg", see ``_decimal_comma``); "1,2 and 3" stays a list._CONTINENTAL = re.compile(r"(?<![\w.,])([1-9]\d{0,2}(?:\.\d{3})+),(\d{1,2})(?!\d|[.,]\d)")_COMMA_AFTER_SIGN = re.compile(r"((?:[$£€¥₹]|(?<![A-Za-z])(?:" + _CURRENCY_CODES + r"))\s?-?\d+),(\d{1,2})(?!\d|[.,]\d)")_COMMA_BEFORE_SIGN = re.compile(r"(?<![\w.,])(\d+),(\d{1,2})(?=\s?(?:%|" + _SIGN_AFTER + r"))")# "$x = 2$", "$3 + 5 = 8$": the sign after the last figure closes a formula, it is# not a currency written after an amount. A formula opens with a sign before a# letter, or before a figure or a space when a "=" or the like follows; "from $5# to 30$" is two prices, and the sign in "5 $, 10 $" opens nothing. The closing# sign becomes a mark no rule knows, so the rest is read as it was before._FORMULA_SIGN = chr(0xE004)_FORMULA_END = re.compile(r"(?<![\w$])(?<!\d\s)\$(?:(?=[^\s\d$.,;:!?)])[^$\n]{0,80}" r"|(?=\d)[^$\n]{0,80}[=^_\\{}+*/<>][^$\n]{0,80}" r"|(?=\s)[^$\n]{0,80}[=^_\\{}+*<>][^$\n]{0,80})\d\s?\$(?![\w$])")_VULGAR = re.compile(r"(?<![\d.,/])(?:(\d+)\s?)?([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑⅒])")_ADDRESS = re.compile( r"(?P<url>(?:https?://|www\.)[^\s<>\"']+)" r"|(?P<mail>[\w.+-]+@[\w-]+(?:\.[\w-]+)+)" r"|(?P<file>(?<![\w@./-])(?P<folder>/?(?:[\w~-]+/)+)?(?P<stem>[\w-]+(?:\.[\w-]+)*)\.(?P<ending>[A-Za-z][A-Za-z0-9]{0,9})" r"(?![\w-])(?P<path>/[^\s<>\"']*)?)")_DAY_RANGE = re.compile(r"\b(" + _DAY_PATTERN + "|" + _MONTH_PATTERN + r")\b(\.?)\s?[-–]\s?(" + _DAY_PATTERN + "|" + _MONTH_PATTERN + r")\b(\.?)")_RATIO = re.compile(r"(?<![\d:.,])(\d{1,3}):(\d{1,3}(?:,\d{3})+|\d+)(?![\d:]|[.,]\d)")_CODE = re.compile(r"(?<![\w.,/-])(#)?([A-Za-z0-9]+(?:-[A-Za-z0-9]+)+)(?![\w-]|[.,]\d)")_SLASHED = re.compile(r"(?<![\w.,/-])(\d+(?:/\d+){2,})(?![\w/]|[.,]\d)")_GROUPED = re.compile( r"(?<![\w.,:/#+-])(?P<plus>\+)?(?:(?P<lead>[A-Z]{2}) )?" r"(?P<core>[A-Z0-9]*\d[A-Z0-9]*(?: [A-Z0-9]*\d[A-Z0-9]*)+)" r"(?(lead)(?: (?P<trail>[A-Z]{2})(?![\w]))?)" r"(?![\w]|[.,:/-]\d|\s?[%°])")_GLUED = re.compile(r"(?<![\w'.])(?=[A-Za-z0-9]*[A-Za-z])(?=[A-Za-z0-9]*\d)[A-Za-z0-9]+(?![\w']|\.\d)")
# Words whose accent is the only sign of how they are read: without it "résumé" is "resume"._ACCENT_DECIDES = {"résumé": "R EH1 Z AH0 M EY2", "resumé": "R EH1 Z AH0 M EY2", "exposé": "EH2 K S P OW0 Z EY1", "rosé": "R OW0 Z EY1", "pâté": "P AA0 T EY1", "maté": "M AA1 T EY2", "saké": "S AA1 K EY2", "lamé": "L AA0 M EY1"}_ACCENTED = re.compile(r"\b(" + "|".join(_ACCENT_DECIDES) + r")(s?)\b", re.IGNORECASE)_LETTER_FORMS = {"ß": "ss", "æ": "ae", "Æ": "Ae", "œ": "oe", "Œ": "Oe", "ø": "o", "Ø": "O", "đ": "d", "ł": "l", "Ł": "L"}
def _plain_letter(char): """An accented Latin letter without its accent ("café" is in the dictionary as "cafe"). Other characters are left alone.""" if char.isascii() or not char.isalpha(): return char if char in _LETTER_FORMS: return _LETTER_FORMS[char] base = "".join(c for c in unicodedata.normalize("NFKD", char) if not unicodedata.combining(c)) return base if base.isascii() and base.isalpha() else char
# ---- numbers as words ------------------------------------------------------
def cardinal(number): """``1234`` -> ``"one thousand two hundred thirty four"``.""" if number < 0: return "minus " + cardinal(-number) if number < 20: return _ONES[number] if number < 100: tens, ones = divmod(number, 10) return _TENS[tens - 2] + (" " + _ONES[ones] if ones else "") if number < 1000: hundreds, rest = divmod(number, 100) return _ONES[hundreds] + " hundred" + (" " + cardinal(rest) if rest else "") if number >= 1000 ** (len(_SCALES) + 1): return digits(str(number)) parts = [] for power in range(len(_SCALES), 0, -1): count, number = divmod(number, 1000 ** power) if count: parts.append(cardinal(count) + " " + _SCALES[power - 1]) if number: parts.append(cardinal(number)) return " ".join(parts)
def ordinal(number): words = cardinal(number).split() last = words[-1] words[-1] = _ORDINAL.get(last) or (last[:-1] + "ieth" if last.endswith("y") else last + "th") return " ".join(words)
def digits(text, zero="zero"): return " ".join(zero if c == "0" else _ONES[int(c)] for c in text if c.isdigit())
def year(number): """The way a year is said: 1984, 1905, 1900, 2005, 2026.""" if not 1000 <= number <= 2999: return cardinal(number) high, low = divmod(number, 100) if low == 0: return cardinal(number) if high % 10 == 0 else cardinal(high) + " hundred" if high == 20 and low < 10: return "two thousand " + _ONES[low] return cardinal(high) + (" oh " + _ONES[low] if low < 10 else " " + cardinal(low))
def pairs(number): """A number read two digits at a time, the way model numbers are: 4070 "forty seventy", 9001 "ninety oh one", 720 "seven twenty".""" high, low = divmod(number, 100) if not 100 <= number <= 9999 or (low == 0 and (high < 10 or high % 10 == 0)): return cardinal(number) if low == 0: return cardinal(high) + " hundred" return cardinal(high) + (" oh " + _ONES[low] if low < 10 else " " + cardinal(low))
def number_words(text): """An unsigned number as written: ``1,234``, ``3.14``, ``007``.""" whole, _, fraction = text.replace(",", "").partition(".") if fraction: return (cardinal(int(whole)) if whole else "") + " point " + digits(fraction) if len(whole) > 1 and whole.startswith("0") or len(whole) > 18: return digits(whole) return cardinal(int(whole))
def duration(hours, minutes, seconds): """``2:03:45`` as a length of time: "two hours, three minutes and forty five seconds".""" parts = [f"{cardinal(count)} {name if count == 1 else name + 's'}" for count, name in ((hours, "hour"), (minutes, "minute"), (seconds, "second")) if count] if len(parts) < 2: return parts[0] if parts else "zero seconds" return ", ".join(parts[:-1]) + " and " + parts[-1]
def _plural_of(words): """Plural of a spelled number, for decades: "nineteen nineties".""" head, _, last = words.rpartition(" ") last = last[:-1] + "ies" if last.endswith("y") else last + "s" return (head + " " if head else "") + last
def _fraction_words(top, bottom, article=False): """"three quarters", "one half"; after a whole number "a half", "an eighth".""" one, many = _FRACTION.get(bottom, (ordinal(bottom), ordinal(bottom) + "s")) if top != 1: return f"{cardinal(top)} {many}" return (("an " if one[0] in "aeiou" else "a ") if article else "one ") + one
def _version_part(part): """One part of a version number: "4" four, "12" twelve, "03" zero three, "129" one two nine.""" return digits(part) if len(part) > 2 else number_words(part)
def _minor(part): """The part after the point of a version: "12" twelve, "04" oh four.""" return digits(part, "oh") if part.startswith("0") else cardinal(int(part))
def _short_number(text): """A number in a code that is said as a number: one or two digits, or a round one (B-12, KX-300).""" if text.startswith("0"): return False return len(text) <= 2 or set(text[1:]) == {"0"}
def _spelled(letters): return f"{_SPELL}{letters}{_END}"
def _before(text, position, count=4): """The words just before ``position`` in the same clause, in lower case.""" clause = re.split(r"[.!?;…]\s|[()\"]", text[max(0, position - 80):position])[-1] return [word.lower() for word in re.findall(r"[A-Za-z]+", clause)][-count:]
def _identifier(text, position): """What the words before a number say it is: ``"phone"``, ``"pin"``, ``"strong"`` (a number, an ID, a reference), ``"weak"`` (an order, a ticket), ``"enter"`` or ``None``.""" words = _before(text, position) if not words: return None if words[-1] in _PHONE_WORDS or (words[-1] in _PHONE_LINKS and any(word in _PHONE_WORDS for word in words[-3:-1])): return "phone" index = len(words) - 1 while index > 0 and words[index] in _LINK_WORDS: index -= 1 for kind, group in (("phone", _PHONE_WORDS), ("pin", _PIN_WORDS), ("strong", _STRONG_WORDS), ("weak", _WEAK_WORDS)): if words[index] in group: return kind return "enter" if words[-1] == "enter" else None
def _decimal_comma(text): """"1,5" before a unit is one number: a comma with one or two digits after it does not part thousands. "1,250" is left as it is.""" return text.replace(",", ".") if re.fullmatch(r"\d+,\d{1,2}", text) else text
def _address_digits(text): """Digits inside a file name or an address: 3, 2026, 0412.""" if len(text) <= 2 and not (len(text) == 2 and text[0] == "0"): return cardinal(int(text)) if len(text) == 4 and 1900 <= int(text) <= 2099: return year(int(text)) return digits(text)
# ---- rewriting -------------------------------------------------------------
class Normalizer: def __init__(self, is_word=None): self.is_word = is_word or (lambda word: True) self.abbreviations = {columns[0]: (columns[1], columns[2]) for _, columns in tables.rows("abbreviations.txt")} # A unit marked "exact" is written in one letter case only: "m" is a meter, "M" is not. self.units, self.exact_units = {}, {} for _, columns in tables.rows("units.txt"): if len(columns) > 3 and columns[3] == "exact": self.exact_units[columns[0]] = (columns[1], columns[2]) else: self.units[columns[0].lower()] = (columns[1], columns[2]) # A chat spelling marked "alone" is read that way only as a reply by itself ("k", "k, thanks"). self.chat, self.replies = {}, set() for number, columns in tables.rows("chat.txt"): if len(columns) > 2 and columns[2:] != ["alone"]: raise ValueError(f"chat.txt line {number}: after the words to say there can only be \"alone\"") self.chat[columns[0]] = columns[1] if len(columns) > 1 else "-" if len(columns) > 2: self.replies.add(columns[0]) self.endings = tables.mapping("endings.txt") names = sorted({re.escape(unit) for unit in list(self.units) + list(self.exact_units)}, key=lambda name: (-len(name), name)) self._unit_names = "|".join(names) self._unit = re.compile(r"(?<![\w.])(\d[\d,]*(?:\.\d+)?)(?:[-–](\d[\d,]*(?:\.\d+)?))?\s?(" + self._unit_names + r")(?![A-Za-z])(\.(?=\s+(?-i:[a-z])))?", re.IGNORECASE) self._area = re.compile(r"(?<![\w.])(\d[\d,]*(?:\.\d+)?)\s?(km|cm|mm|m|ft|mi|yd|in)([²³])") self._area_plain = re.compile(r"(?<![\w.])(\d[\d,]*(?:\.\d+)?)\s?(km|cm|mm|m|ft)([23])(?![\w])") self.inline = [] self.day_first = False self.dated = False
# -- pieces of the text that are not words --
def _amount(self, symbol, whole, fraction, scale, before_noun=False): one, many, cent, cents = _CURRENCY[symbol] if before_noun: # "a $5 fee": five dollar fee many, cents = one, cent if scale: scale = _SCALE_LETTER.get(scale.lower(), scale.lower()) return f"{number_words(whole + ('.' + fraction if fraction else ''))} {scale} {many}" if fraction and (len(fraction) > 2 or not cent): return f"{number_words(whole + '.' + fraction)} {many}" amount, change = int(whole), int((fraction or "0").ljust(2, "0")) parts = [] if amount or not change: parts.append(f"{cardinal(amount)} {one if amount == 1 else many}") if change and cent: parts.append(f"{cardinal(change)} {cent if change == 1 else cents}") return " and ".join(parts)
@staticmethod def _continental(match): """"1.299,50" as "1,299.50". Four groups that could be an internet address are left alone.""" groups = match.group(1).split(".") if len(groups) == 4 and all(int(group) <= 255 for group in groups): return match.group(0) return ",".join(groups) + "." + match.group(2)
@staticmethod def _before_noun(match): """True when an amount describes the noun after it: "a $5 fee", "the $3 million deal", "an $8bn contract". "the $500 will be", "a $5 or $10 fee" are not.""" before = re.search(r"(?:^|[\s(])(a|an|the|this|that|your|my|our|their|his|her|its)\s+$", match.string[:match.start()], re.IGNORECASE) after = re.match(r"\s+([a-z]+)\b(?!['’])", match.string[match.end():]) if not before or not after or after.group(1) in _NOT_A_NOUN: return False if before.group(1).lower() in ("a", "an"): return not after.group(1).endswith(("ed", "ly")) word = after.group(1) # "the $500 deposited", "your $50 remaining" are amounts return not word.endswith(("ed", "ing", "ly")) and (not word.endswith("s") or word.endswith("ss"))
def _money(self, match): found = match.groupdict() whole = found["whole"].replace(",", "").replace(" ", "") words = self._amount(found["symbol"], whole, found["fraction"], found.get("scale"), self._before_noun(match)) return (" minus " if found.get("minus") or found.get("inner") else " ") + words + " "
@staticmethod def _half_day(match, dotted, plain): """" A M" or " P M" as letters. A full stop that closes "p.m." is kept as a sentence end only when a new sentence follows.""" if not (dotted or plain): return "" following = match.string[match.end():].lstrip() first = re.match(r"[A-Za-z']+", following) closes = bool(dotted) and match.group(0).endswith(".") and ( not following or (following[0].isupper() and first is not None and first.group(0).lower() in _SENTENCE_STARTERS)) return f"{_SPELL}{(dotted or plain).upper()}M{_END}{' .' if closes else ''} "
def _time(self, match): hour, minute, second = int(match.group(1)), int(match.group(2)), match.group(3) half = match.group(4) or match.group(5) before = _before(match.string, match.start(), 3) if second is not None and not half and not (before and before[-1] == "at"): return f" {duration(hour, minute, int(second))} " # 2:03:45 is a length of time if hour > 24 and second is None and not half: after = re.match(r"\s*([A-Za-z]+)", match.string[match.end():]) if set(before) & _DURATION_WORDS or (after and after.group(1).lower() in _DURATION_WORDS): return f" {duration(0, hour, minute)} " # 48:12 long return f" {cardinal(hour)} {'oh ' if minute < 10 else ''}{cardinal(minute)} " if hour > 24: return match.group(0) words = cardinal(hour) if minute == 0: if half: pass elif hour == 0: words = "midnight" elif hour > 12: words += " hundred" # 20:00 else: words += " o'clock" else: words += (" oh " if minute < 10 else " ") + cardinal(minute) if second: words += " and " + cardinal(int(second)) + (" second" if int(second) == 1 else " seconds") return f" {words} " + self._half_day(match, match.group(4), match.group(5))
def _dot_time(self, match): """"6.30" as a time of day where the words around say so: "at 7.15", "6.30 in the morning", "until 10.45 tonight". "at 6.25 percent", "at 7.15 each" stay figures.""" hour, minute = int(match.group(1)), int(match.group(2)) following = match.string[match.end():] if not 1 <= hour <= 23: return match.group(0) if re.match(r"\s?(?:in the (?:morning|afternoon|evening)|at night|tonight|this (?:morning|afternoon|evening)|o'clock)\b", following, re.IGNORECASE): return f"{hour}:{match.group(2)}" before = _before(match.string, match.start(), 1) if before and before[-1] in ("at", "until", "till") and minute % 5 == 0 \ and re.match(r"\s*(?:$|[.,;:!?)—]|(?:and|or|to|on|in|the|we|i|you|he|she|they|it|tomorrow|today|tonight|sharp|every|when)\b)", following, re.IGNORECASE): return f"{hour}:{match.group(2)}" return match.group(0)
@staticmethod def _short_years(match): """"1939-45" is nineteen thirty nine to forty five; "1984-12" (lower) is no range of years.""" first, last = int(match.group(1)), int(match.group(2)) if last <= first % 100: return f" {number_words(match.group(1))} to {number_words(match.group(2))} " return f" {year(first)} to {'oh ' + _ONES[last] if last < 10 else cardinal(last)} "
def _dot_times(self, match): """"9.30 to 11.30" where the words before say it is a time of day.""" following = match.string[match.end():] if int(match.group(1)) > 23 or int(match.group(4)) > 23 or not set(_before(match.string, match.start())) & _CLOCK_WORDS \ or re.match(r"\s?(?:%|percent|million|billion|" + self._unit_names + r")(?![A-Za-z])", following, re.IGNORECASE): return match.group(0) return f"{match.group(1)}:{match.group(2)}{match.group(3)}{match.group(4)}:{match.group(5)}"
def _ratio(self, match): """16:9, 3:1, 1:25,000. Two digits after the colon are a time unless the words say "ratio".""" first, second = match.group(1), match.group(2) if len(first) <= 2 and len(second) == 2 and second[0] in "012345": after = re.match(r"\s*([A-Za-z]+)", match.string[match.end():]) if not (set(_before(match.string, match.start(), 3)) & _RATIO_WORDS or (after and after.group(1).lower() in _RATIO_WORDS)): return match.group(0) return f" {number_words(first)} to {number_words(second)} "
def _date(self, month, day, year_text=None, the=False, plain=False): if not 1 <= month <= 12 or not 1 <= day <= 31: return None if plain: # "March 20" as written: "March twenty" ("March 20th" and "March 20, 2026" read the ordinal) words = f"{_MONTHS[month - 1]} {cardinal(day)}" else: words = f"the {ordinal(day)} of {_MONTHS[month - 1]}" if the else f"{_MONTHS[month - 1]} {ordinal(day)}" if year_text: words += " " + (year(int(year_text)) if len(year_text) == 4 else ("oh " if int(year_text) < 10 else "") + cardinal(int(year_text))) return f" {words} "
def _slash_date(self, match): first, second = int(match.group(1)), int(match.group(2)) if first > 12 >= second or (self.day_first and second <= 12): first, second = second, first # day first return self._date(first, second, match.group(3)) or match.group(0)
def _dot_date(self, match): """15.11.2026: dates written with full stops put the day first.""" day, month = int(match.group(1)), int(match.group(2)) if month > 12 >= day: day, month = month, day return self._date(month, day, match.group(3)) or match.group(0)
def _day_month(self, match): """"22 February", "5 Jan. 2026". The stop after a short month name is dropped; any other one ends the sentence.""" month = match.group(2) spoken = self._date(_MONTH_NUMBER[month.lower()[:3]], int(match.group(1)), match.group(4), the=True) if spoken is None: return match.group(0) return spoken + (". " if match.group(3) and month in _MONTHS else "")
def _days_of_month(self, match): """"3-17 November" and "November 3-17".""" month_first = match.group(1)[0].isalpha() month, first, second = (match.group(1), match.group(2), match.group(3)) if month_first else \ (match.group(3), match.group(1), match.group(2)) first, second = int(first), int(second) if not (1 <= first <= 31 and 1 <= second <= 31): return match.group(0) name = _MONTHS[_MONTH_NUMBER[month.lower()[:3]] - 1] words = f"{name} {ordinal(first)} to {ordinal(second)}" if month_first else \ f"the {ordinal(first)} to the {ordinal(second)} of {name}" return f" {words}{' ' + year(int(match.group(4))) if match.group(4) else ''} "
def _day_range(self, match): """"Mon.-Fri.", "Jan-Mar": from one day or month to another.""" names = [] for name in (match.group(1), match.group(3)): key = name.lower() names.append(self.abbreviations[key][1] if key in self.abbreviations else _DAY_NAMES.get(key, name)) following = match.string[match.end():].lstrip() first = re.match(r"[A-Za-z']+", following) ends = bool(match.group(4)) and (not following or (following[0].isupper() and first is not None and first.group(0).lower() in _SENTENCE_STARTERS)) return f"{names[0]} to {names[1]}{' .' if ends else ''}"
def _short_date(self, match): """"14/03", "12/10" as a day of the year, or ``None`` when it is a fraction.""" first_text, second_text = match.group(1), match.group(2) if len(first_text) > 2 or len(second_text) > 2: return None first, second = int(first_text), int(second_text) before = _before(match.string, match.start()) if 1 <= first <= 12 and 20 <= second <= 49 and "card" in before: return f" {_MONTHS[first - 1]} {year(2000 + second)} " # a card that expires 08/27 last = before[-1] if before else "" classic = first < second and second in _CLASSIC_FRACTIONS # 1/2, 3/4, 7/10 zero = len(first_text) == 2 and first_text[0] == "0" or len(second_text) == 2 and second_text[0] == "0" if not (zero or (12 < first <= 31 and second <= 12 and (first, second) != (24, 7)) or (last in _DATE_BEFORE and (not classic or last == "on")) or (self.dated and not classic and first != second)): return None if first > 12 or (self.day_first and second <= 12): first, second = second, first # day first return self._date(first, second)
def _fraction(self, match): spoken = self._short_date(match) if spoken: return spoken top, bottom = int(match.group(1)), int(match.group(2)) if (top, bottom) == (24, 7) or top == bottom: return f" {cardinal(top)} {cardinal(bottom)} " # twenty four seven, fifty fifty if not 0 < top < 100 or not 1 < bottom <= 100: return f" {cardinal(top)} over {cardinal(bottom)} " return f" {_fraction_words(top, bottom)} "
def _mixed_fraction(self, match): """"2 1/2": two and a half.""" top, bottom = int(match.group(2)), int(match.group(3)) if not 0 < top < bottom: return match.group(0) return f" {number_words(match.group(1))} and {_fraction_words(top, bottom, article=True)} "
def _vulgar(self, match): """"½" and "1½". Runs before the text is normalised, which would turn "1½" into "11/2".""" top, bottom = (int(part) for part in unicodedata.normalize("NFKC", match.group(2)).split("⁄")) if match.group(1) is None: return f" {top}/{bottom} " return f" {cardinal(int(match.group(1)))} and {_fraction_words(top, bottom, article=True)} "
def _phone(self, match): groups = [g for g in match.groups() if g] return " " + ", ".join("eight hundred" if g == "800" else digits(g, "oh") for g in groups) + " "
def _measure(self, match): unit = match.group(3) names = self.exact_units.get(unit) or self.units.get(unit.lower()) if names is None or (len(unit) == 1 and match.string[match.end(3):match.end(3) + 1] in ("-", "'", "/")): return match.group(0) one, many = names value, upper = _decimal_comma(match.group(1)), match.group(2) and _decimal_comma(match.group(2)) if upper: return f" {number_words(value)} to {number_words(upper)} {many} " return f" {number_words(value)} {one if value in ('1', '1.0') else many} "
def _square(self, match): """"120 m²", "3 m3": square and cubic measures.""" unit = match.group(2) one, many = {"in": ("inch", "inches")}.get(unit) or self.exact_units.get(unit) or self.units[unit] kind = "square" if match.group(3) in "²2" else "cubic" value = _decimal_comma(match.group(1)) return f" {number_words(value)} {kind} {one if value in ('1', '1.0') else many} "
def _counted(self, text, end): """True when a plural noun follows a number: it is then an amount, not a reference.""" after = re.match(r"\s*([A-Za-z]+)", text[end:]) if not after: return False word = after.group(1).lower() if word in ("people", "men", "women", "children", "feet", "miles"): return True return len(word) > 3 and word.endswith("s") and not word.endswith("ss") and word not in _NOT_COUNTED \ and self.is_word(word[:-1])
def _number(self, match, text): value = match.group(0) plain = value.replace(",", "") if "." not in plain and "," not in value and not plain.startswith("0") and len(plain) > 2: kind = _identifier(text, match.start()) limit = {"phone": 3, "pin": 3, "strong": 4, "enter": 4, "weak": 5}.get(kind, 7) if len(plain) >= limit and not (kind is None and plain.endswith("000")) \ and not (kind == "enter" and len(plain) == 4 and 1900 <= int(plain) <= 2099) \ and not (kind in (None, "phone", "weak") and self._counted(text, match.end())): return f" {digits(plain, 'oh' if kind == 'phone' else 'zero')} " # a reference, not an amount if "." not in plain and "," not in value and len(plain) == 4 and not plain.startswith("0"): number = int(plain) before = re.findall(r"[A-Za-z]+", text[:match.start()][-24:]) after = re.match(r"\s*([A-Za-z]+)", text[match.end():]) counted = bool(after) and re.search(r"(?:[^s]s|people|men|women|children|feet|miles)$", after.group(1).lower()) is not None dated = bool(before) and (before[-1].lower() in _YEAR_CONTEXT or before[-1].lower()[:3] in _MONTH_NUMBER) model = re.search(r"(?<![A-Za-z])([A-Z]{2,5}) $", text[:match.start()]) if model and model.group(1) not in _CAPITAL_WORDS and not counted: return f" {pairs(number)} " # RTX 4070, ISO 9001 if 1100 <= number <= 1999 or (2000 <= number <= 2099 and (dated or not counted)) \ or (1000 < number < 1100 and dated and not counted): # "in 1066" return f" {year(number)} " return f" {number_words(value)} "
# -- codes and reference numbers --
def _reads_as_word(self, letters): """Letters inside a code that are a word to say, not letters to name: SAVE-20.""" lower = letters.lower() if len(lower) < 3 or not self.is_word(lower): return False return len(lower) > 3 or any(self.is_word(lower + ending) for ending in ("s", "es", "ed", "ing"))
@staticmethod def _alnum(group, zero="zero"): """A group that mixes letters and digits: the letters are named, the digits read one by one.""" return " ".join(digits(run, zero) if run.isdigit() else _spelled(run) for run in re.findall(r"[A-Za-z]+|\d+", group))
@staticmethod def _digit_groups(groups, zero="zero"): """Groups of digits with a short break between them. Small numbers stay numbers: 9-1-1.""" if all(_short_number(group) and len(group) <= 2 for group in groups): return " , ".join(cardinal(int(group)) for group in groups) return " , ".join(digits(group, zero) for group in groups)
def _code_words(self, groups, match): token = "-".join(groups) if not any(char.isdigit() for char in token): return None # well-known, Wi-Fi kinds = ["d" if g.isdigit() else "m" if any(c.isdigit() for c in g) else "u" if g.isupper() else "l" for g in groups] if all(kind == "d" for kind in kinds): if len(groups) == 2: years = all(len(g) == 4 and 1000 <= int(g) <= 2100 for g in groups) if not (match.group(1) or any(len(g) > 1 and g[0] == "0" for g in groups) or (min(len(g) for g in groups) >= 4 and not years) or _identifier(match.string, match.start()) in ("strong", "pin")): return None # 10-15 and 2019-2021 are ranges return self._digit_groups(groups) if len(groups) == 2 and kinds[1] == "d" and kinds[0] in "ul": letters, number = groups if (kinds[0] == "l" and len(letters) > 1) or self._reads_as_word(letters): return None # pre-2020, COVID-19, SAVE-20 if _short_number(number): return f"{_spelled(letters)} {cardinal(int(number))}" # B-12, KX-300 return f"{_spelled(letters)} , {digits(number)}" if len(groups) == 2 and kinds[0] == "d" and (kinds[1] == "l" or len(groups[1]) == 1 or re.fullmatch(r"\d+[A-Za-z]+", groups[1])): return None # 5-year, 3-D, 5-10MB if any((kind == "l" and len(g) > 2) or (kind == "m" and re.fullmatch(r"\d+(?:s|st|nd|rd|th)", g)) for kind, g in zip(kinds, groups)): return None # 20-year-old, F-16s if not any(char.isupper() for char in token) and ("l" in kinds or any(kind == "m" for kind in kinds)): return None # 3-in-1, 50s-60s parts = [] for kind, group in zip(kinds, groups): if kind == "d": parts.append(digits(group)) elif kind == "m": parts.append(self._alnum(group)) elif len(group) > 3 and self.is_word(group.lower()): parts.append(group) else: parts.append(_spelled(group) if len(group) <= 5 else group) return " , ".join(parts)
def _code(self, match): """Codes written with hyphens: AB-4471-Z, 91-220-0017, #A7-4419.""" words = self._code_words(match.group(2).split("-"), match) if words is None: return match.group(0) return (" number " if match.group(1) else " ") + words + " "
def _grouped(self, match): """Digits written in groups with spaces: a telephone number, a card or tracking number, or a large number with spaces between the thousands.""" text, plus, lead, trail = match.string, match.group("plus"), match.group("lead"), match.group("trail") core = match.group("core").split(" ") head = tail = "" if lead in _CAPITAL_WORDS: # "IN 2019 150 ..." in capitals head, tail, lead, trail = lead + " ", (" " + trail if trail else ""), None, None kind = _identifier(text, match.start()) pure = all(part.isdigit() for part in core) if pure and not plus and not lead: following = text[match.end():] amount = self._counted(text, match.end()) or re.match(r"\s?(?:" + self._unit_names + r")(?![A-Za-z])", following, re.IGNORECASE) is not None if kind is None and core[0][0] != "0" and len(core[0]) <= 3 and all(len(part) == 3 for part in core[1:]) \ and (core[-1] == "000" or (amount and len(core) > 2)): return head + ",".join(core) + tail # 1 000 000: the number rules read it if not (kind or (len(core[0]) > 1 and core[0][0] == "0") or (len(core) > 2 and any(len(part) > 2 for part in core))): return match.group(0) elif not pure and not lead and not plus and kind is None: return match.group(0) zero = "oh" if plus or kind == "phone" or (pure and core[0][0] == "0" and sum(len(part) for part in core) >= 10) else "zero" if pure: spoken = self._digit_groups(core, zero) else: spoken = " , ".join(digits(part, zero) if part.isdigit() else self._alnum(part, zero) for part in core) if lead: spoken = f"{_spelled(lead)} , {spoken}" if trail: spoken = f"{spoken} , {_spelled(trail)}" return head + (" plus " if plus else " ") + spoken + " " + tail
def _glued(self, match): """Letters and digits written together: B12, 14C, X7K, PS5. A single letter is always named; it is never the article "a".""" out = [] for run in re.findall(r"[A-Za-z]+|\d+", match.group(0)): if run.isdigit(): out.append(cardinal(int(run)) if _short_number(run) else digits(run)) elif len(run) == 1 or ((run.isupper() or len(run) <= 3) and not self._reads_as_word(run)): out.append(_spelled(run)) else: out.append(run) return " " + " ".join(out) + " "
# -- web addresses and file names --
def _address_part(self, part): """One run of letters inside an address: a word, or letters to name.""" lower = part.lower() if len(part) > 1 and self.is_word(lower) and (len(part) > 2 or lower in _SHORT_WORDS): return part return _spelled(part) if len(part) <= 3 else part
def _spoken_address(self, core): pieces = re.findall(r"[A-Za-z]+|\d+|.", core) mail, host = "@" in core, False out = [] for index, piece in enumerate(pieces): following = pieces[index + 1] if index + 1 < len(pieces) else "" if piece == "@": host = True if piece.isdigit(): out.append(_address_digits(piece)) elif not piece.isalpha(): out.append(_SEPARATORS.get(piece, "")) elif index and pieces[index - 1] == "." and (host or not mail) and ( following in ("", "/", ":", "?", "#") or (len(piece) <= 3 and (piece.lower() in self.endings or not self.is_word(piece.lower())))): # the ending of a file name or an address: a word if the table says so, otherwise letters out.append(piece.lower() if self.endings.get(piece.lower()) == "word" else _spelled(piece)) else: letters = "" for part in re.findall(r"[A-Z]?[a-z]+|[A-Z]+(?![a-z])", piece): spoken = self._address_part(part) if spoken.startswith(_SPELL): letters += part continue if letters: out.append(_spelled(letters)) letters = "" out.append(spoken) if letters: out.append(_spelled(letters)) return " ".join(item for item in out if item)
def _address(self, match): """Web and mail addresses, file names and paths: the dots, slashes, underscores and @ are spoken. The ending is a word when ``data/endings.txt`` says so ("dot com") and letters otherwise ("dot P D F").""" whole = match.group(0) text = whole.rstrip(".,;:!?)") # punctuation of the sentence, not of the address tail = whole[len(text):] if match.group("file"): ending = match.group("ending") known = ending.lower() in self.endings marked = bool(match.group("folder") or match.group("path")) or "_" in match.group("stem") if not (known or (marked and len(ending) <= 5 and (ending.islower() or ending.isupper()) and not self.is_word(ending.lower()))): return whole # "the end.Then": a missing space, not a file core = re.sub(r"^(?:https?://)?(?:www\.)?", "", text).rstrip("/") return f" {self._spoken_address(core)} {tail}"
def _chat_form(self, match): """Chat spellings that contain a digit or a slash: gr8, b4, 2day.""" said = self.chat.get(match.group(0).lower()) if said is None: return match.group(0) if said == "-": return " " return " " + " ".join(f"{_SPELL}{part[1:]}{_END}" if part.startswith("*") else part for part in said.split()) + " "
def _inline(self, match): """``{...}``: a pronunciation written by the user. Braces that hold anything else are no error: they stay and are read like brackets ("{name}", "{1, 2, 3}", "\\frac{1}{2}"). So are single letters, which are phones only by chance ("x_{i}", "{n}").""" symbols = match.group(2).split() if not symbols or all(len(symbol) == 1 and symbol.isascii() for symbol in symbols): return match.group(0) try: phones = convert("", symbols) if is_arpabet(symbols) else from_text(" ".join(symbols)) except ValueError: return match.group(0) self.inline.append((match.group(1) or "", phones)) return f" {_INLINE}{chr(_INLINE_BASE + len(self.inline) - 1)}{_INLINE} "
def _dotted(self, match, text): """``U.S.``, ``e.g.``, ``p.m.``: letters with full stops.""" letters = match.group(0).replace(".", "") key = letters.lower() following = text[match.end():].lstrip() if key == "eg": words = "for example" elif key == "ie": words = "that is" else: words = f"{_SPELL}{letters.upper()}{_END}" first = re.match(r"[A-Za-z']+", following) ends_sentence = not following or (following[0].isupper() and first and first.group(0).lower() in _SENTENCE_STARTERS) return f" {words}{' .' if ends_sentence and match.group(0).endswith('.') else ''} "
def _initial(self, match, text): """"George W. Bush", "J. R. R. Tolkien": the initial of a name is named and its full stop is no sentence end. "an A. Then", "Plan B. The" keep the stop.""" before = re.search(r"(?:([A-Za-z]+)|([A-Z])\.)\s+$", text[:match.start()]) after = re.match(r"\s+(?:([A-Z])\.(?=\s)|([A-Z][a-z'’]+|[A-Z]{2,})\b)", text[match.end():]) if not after: return match.group(0) if after.group(2): word = after.group(2).lower().rstrip("'’s") if after.group(2).lower().endswith(("'s", "’s")) else after.group(2).lower() if word in _SENTENCE_STARTERS | _CLAUSE_OPENERS: return match.group(0) if self.is_word(word + "ing") or (word.endswith("e") and self.is_word(word[:-1] + "ing")): return match.group(0) # a verb opens a new sentence: "Meet the Zephyr X. Schedule a drive" if before is None: if text[:match.start()].strip() and not re.search(r"[.!?;:\"'(]\s*$", text[:match.start()]): return match.group(0) # after a small word or a figure: "an A. Then" if not after.group(1): return match.group(0) # "A. Smith" alone at the start is too uncertain elif before.group(1) and not after.group(1): # "by T. R. Hale": a run of initials needs no name before word = before.group(1) if not word[0].isupper() or word.lower() in _LABELLED or word.lower() in _CARDINAL_AFTER: return match.group(0) return f" {_SPELL}{match.group(1)}{_END} "
def _abbreviation(self, match, text): token, stop = match.group(1), match.group(2) key = token.lower() following = text[match.end():] next_word = re.match(r"\s*([A-Za-z]+|\d)", following) capital_next = bool(next_word) and next_word.group(1)[0].isupper() capital_before = re.search(r"[A-Z][a-z]+\s+$", text[:match.start()]) is not None if key in ("st", "dr") and token[0].isupper(): if capital_next and (stop or key == "dr" or not capital_before): return (" saint " if key == "st" else " doctor ") # "St. Mary's", "St Heliers"; "Main St" stays if capital_before and stop: return (" street" if key == "st" else " drive") + (" ." if not following.strip() else " ") return match.group(0) if key not in self.abbreviations: return match.group(0) when, words = self.abbreviations[key] number_next = bool(next_word) and (next_word.group(1).isdigit() or (key in _PAGE_LIKE and next_word.group(1).lower() in _NUMBER_WORDS)) if when == "title": if not (token[0].isupper() and (capital_next or stop)): return match.group(0) elif when == "number": previous = re.search(r"([A-Za-z]+)\.?\s+$", text[:match.start()]) if not (stop and (number_next or (key == "no" and previous and previous.group(1).lower() in _NUMBERED))): return match.group(0) elif not stop or (when == "small" and token.isupper()): return match.group(0) elif key in ("mar", "sun", "sat", "jan", "dec", "max", "min", "est", "no") and not token[0].isupper() and not number_next: # also words; "max. load" and "est. time" are the abbreviation, "he sat." is not if not (key in ("max", "min", "est") and next_word and next_word.group(1)[0].islower()): return match.group(0) if key == "est" and not number_next: words = "estimated" # "Est. arrival"; "est. 1885" is "established" ends_sentence = when != "title" and (not following.strip() or (capital_next and next_word.group(1).lower() in _SENTENCE_STARTERS)) return f" {words}{' .' if ends_sentence else ''} "
def rewrite(self, text): """The text with every non-word written out, markers included.""" text = _VULGAR.sub(self._vulgar, text) # before "1½" becomes "11/2" and "m²" becomes "m2" text = self._area.sub(self._square, text) text = text.replace("²", " squared ").replace("³", " cubed ") text = unicodedata.normalize("NFKC", text).replace("⁄", "/").replace("−", " minus ") if not text.isascii(): text = _ACCENTED.sub(lambda m: "{" + _ACCENT_DECIDES[m.group(1).lower()] + (" Z" if m.group(2) else "") + "}", text) text = "".join(_plain_letter(char) for char in text) text = re.sub(r"(?<=\d)–(?=\d)", "-", text) # 10–15 is a range, not a pause text = _DAY_RANGE.sub(self._day_range, text) for old, new in (("‘", "'"), ("’", "'"), ("‚", "'"), ("‛", "'"), ("`", "'"), ("´", "'"), ("“", '"'), ("”", '"'), ("„", '"'), ("‟", '"'), ("«", '"'), ("»", '"'), ("–", "—"), ("―", "—"), ("[", "("), ("]", ")")): text = text.replace(old, new) self.inline = [] text = re.sub(r"([A-Za-z']+)?\{([^{}]*)\}", self._inline, text) text = text.replace("{", "(").replace("}", ")") text = _ADDRESS.sub(self._address, text) text = text.replace("→", " to ") text = _EMOJI.sub(" ", text) text = _EMOTICON.sub(" ", text) text = re.sub(r"\.{3,}", "…", text) text = re.sub(r"(?<=\d)\s-\s(?=\d[\d.,]*\s?=)", " minus ", text) text = re.sub(r"(?<![\d.,/-])(\d[\d.,]*)-(?=\d[\d.,]*=)", r"\1 minus ", text) # 10-3=7, not the date 2024-11-15= text = re.sub(r"-{2,}|\s-\s", "—", text) text = re.sub(r"\bw/o\b", " without ", text, flags=re.IGNORECASE) text = re.sub(r"\bw/(?=\s|$)", " with ", text, flags=re.IGNORECASE) text = re.sub(r"\bn/a\b", " not applicable ", text, flags=re.IGNORECASE) text = text.replace("'n'", " 'n ") if re.search(r"[<>≥≤≠]|!=", text): text = self._mark_comparisons(text) if re.search(r"\d", text): # most text has no digit and skips these passes text = self._figures(text) return self._signs(text)
def _figures(self, text): """The passes that need a digit: money, times, dates, telephone numbers, versions, codes, units, fractions, ranges.""" text = _FORMULA_END.sub(lambda match: match.group(0)[:-1] + _FORMULA_SIGN, text) # a height: 6'2", 5' 11'', 5ft 6in text = re.sub(r"(?<![\w.'])([1-9])\s?(?:'|′)\s?(\d|1[01])\s?(?:\"|''|″|′′)", lambda m: f" {cardinal(int(m.group(1)))} foot {cardinal(int(m.group(2)))} ", text) text = re.sub(r"(?<![\w.])([1-9])\s?ft\.?\s?(\d|1[01])\s?in\b\.?", lambda m: f" {cardinal(int(m.group(1)))} feet {cardinal(int(m.group(2)))} inches ", text) # continental figures become American ones, so every rule below sees one notation text = _CONTINENTAL.sub(self._continental, text) text = _COMMA_AFTER_SIGN.sub(r"\1.\2", text) text = _COMMA_BEFORE_SIGN.sub(r"\1.\2", text) text = _MONEY.sub(self._money, text) text = _RANGE_BEFORE_SIGN.sub(r"\1 to ", text) # 5-10 € text = _MONEY_AFTER.sub(self._money, text) text = re.sub(r"(?<![\w.])(\d[\d,]*(?:\.\d+)?)\s?¢", lambda m: f" {number_words(m.group(1))} {'cent' if m.group(1) == '1' else 'cents'} ", text)
# times of day, lengths of time, ratios clock = r"\d{1,2}:[0-5]\d(?:\s?[AaPp]\.?[Mm]\.?)?|\b\d{1,2}\s?[AaPp]\.?[Mm]\.?" text = re.sub(r"(" + clock + r")\s(" + _ZONES + r")\b", lambda m: f"{m.group(1)} {_spelled(m.group(2))}", text) text = re.sub(r"(?<![\d.,:])(\d{1,2})\.([0-5]\d)(?=\s?[AaPp]\.?[Mm]\b)", r"\1:\2", text) # 7.30 pm text = re.sub(r"(?<![\d.,:])(\d{1,2})\.([0-5]\d)(?!\d|\.\d)", self._dot_time, text) # at 6.30, 6.30 in the morning text = re.sub(r"(?<![\d.,:])(\d{1,2})\.(00|15|30|45)(\s?(?:to|until|till|and|[-—])\s?)(\d{1,2})\.(00|15|30|45)(?!\d|\.\d)", self._dot_times, text) text = re.sub(r"(" + clock + r")\s?[-—]\s?(?=\d{1,2}(?::[0-5]\d|\s?[AaPp]\.?[Mm]\b))", r"\1 to ", text) text = re.sub(r"(?<![\w.,:-])(\d{1,2})\s?[-—]\s?(?=\d{1,2}(?::[0-5]\d)?\s?[AaPp]\.?[Mm]\b)", r"\1 to ", text) # 3-4pm text = _RATIO.sub(self._ratio, text) text = re.sub(r"(?<![\d:])(\d{1,2}):([0-5]\d)(?::([0-5]\d))?" + _HALF_DAY + r"?(?![\d:])", self._time, text) text = re.sub(r"(?<![\d.:,])(\d{1,2})" + _HALF_DAY + r"(?![A-Za-z])", lambda m: f" {cardinal(int(m.group(1)))} " + self._half_day(m, m.group(2), m.group(3)), text)
# dates seen = [(int(a), int(b)) for a, b in re.findall(r"(?<![\d/.])(\d{1,2})/(\d{1,2})(?:/(?:\d{4}|\d{2}))?(?![\d/])", text)] seen = [pair for pair in seen if pair != (24, 7)] self.day_first = any(a > 12 >= b for a, b in seen) and not any(b > 12 >= a for a, b in seen) self.dated = re.search(r"(?<![\d/])\d{1,2}/\d{1,2}/(?:\d{4}|\d{2})(?![\d/])", text) is not None text = re.sub(r"(?<![\d-])(\d{4})-(\d{1,2})-(\d{1,2})(?![\d-])", lambda m: self._date(int(m.group(2)), int(m.group(3)), m.group(1)) or m.group(0), text) text = re.sub(r"(?<![\d/])(\d{4})/(\d{1,2})/(\d{1,2})(?![\d/])", lambda m: self._date(int(m.group(2)), int(m.group(3)), m.group(1)) or m.group(0), text) text = re.sub(r"(?<![\d.])(\d{1,2})\.(\d{1,2})\.(\d{4})(?!\d|\.\d)", self._dot_date, text) text = re.sub(r"(?<![\d/])(\d{1,2})/(\d{1,2})/(\d{4}|\d{2})(?![\d/])", self._slash_date, text) text = re.sub(r"\b(" + _MONTH_PATTERN + r")\.?\s+(\d{1,2})(?:st|nd|rd|th)?\s?[-—]\s?(\d{1,2})(?:st|nd|rd|th)?(?:,?\s+(\d{4}))?(?![\d:])", self._days_of_month, text) text = re.sub(r"(?<![\d.,/:-])(\d{1,2})(?:st|nd|rd|th)?\s?[-—]\s?(\d{1,2})(?:st|nd|rd|th)?\s+(" + _MONTH_PATTERN + r")\b(?:,?\s+(\d{4}))?", self._days_of_month, text) text = re.sub(r"\b(" + _MONTH_PATTERN + r")\.?\s+(\d{1,2})(st|nd|rd|th)?(?:,?\s+(\d{4}))?(?![\d:])", lambda m: self._date(_MONTH_NUMBER[m.group(1).lower()[:3]], int(m.group(2)), m.group(4), plain=not (m.group(3) or m.group(4))) or m.group(0), text) # with a year: "January twelfth, nineteen eighty five" text = re.sub(r"(?<![\d.,/:-])(\d{1,2})(?:st|nd|rd|th)?\s+(" + _MONTH_PATTERN + r")\b(\.(?=\s+[a-z\d]))?(?:,?\s+(\d{4}))?", self._day_month, text)
# telephone numbers, versions, codes text = re.sub(r"(?<![\d-])(?:\+?(1)[-.\s])?\(?(\d{3})\)?[-.\s](\d{3})[-.\s](\d{4})(?![\d-])", self._phone, text) text = re.sub(r"(?<![\w.,-])(\d{3})-(\d{4})(?![\w-])", self._phone, text) text = re.sub(r"(?<![\w.])([vV])?(\d+(?:\.\d+){2,})(?:-(\d+)(?![\w-]|\.\d))?(?![\w])", lambda m: " " + (_spelled(m.group(1)) + " " if m.group(1) else "") + " point ".join(_version_part(part) for part in m.group(2).split(".")) + (" dash " + number_words(m.group(3)) if m.group(3) else "") + " ", text) text = re.sub(r"(?<![\w.])([vV])(\d+)\.(\d{2,3})(?!\d|\.\d|\w)", lambda m: f" {_spelled(m.group(1))} {cardinal(int(m.group(2)))} point {_minor(m.group(3))} ", text) text = re.sub(r"\b(" + _VERSIONED + r")(\.?\s(?:(?:from|to)\s)?)(\d+)\.(\d{2,3})(?:(\s(?:to|or|and)\s)(\d+)\.(\d{2,3}))?(?!\d|\.\d|\s?%|\s(?:percent|million|billion)\b)", lambda m: f"{m.group(1)}{m.group(2)}{cardinal(int(m.group(3)))} point {_minor(m.group(4))}" + (f"{m.group(5)}{cardinal(int(m.group(6)))} point {_minor(m.group(7))}" if m.group(5) else "") + " ", text, flags=re.IGNORECASE) text = _CODE.sub(self._code, text) text = _SLASHED.sub(lambda m: " " + self._digit_groups(m.group(1).split("/")) + " ", text) text = _GROUPED.sub(self._grouped, text)
text = re.sub(r"(?<![\w.])-(?=\d)", " minus ", text) text = re.sub(r"(?:(?<=\d)\s?[xX×]|×)\s?(?=\d[\d.,]*\s?(?:" + _LENGTHS + r")\b)", " by ", text) # 3 × 4 metres text = re.sub(r"(?<=\d)\s[xX×]\s(?=\d)", " times ", text) text = re.sub(r"(?<![\w.,])(\d{1,4})[xX×](\d{1,4})(?![\w.,]|\.\d)", lambda m: f" {pairs(int(m.group(1)))} by {pairs(int(m.group(2)))} ", text) # 4x4, 1920x1080 text = re.sub(r"(?<![\w/'])[A-Za-z0-9/]*[0-9/][A-Za-z0-9/]*(?![\w/'])", self._chat_form, text) text = re.sub(r"(?<![\w.])'?(\d{2}|\d{4})'?s\b", lambda m: " " + _plural_of(year(int(m.group(1))) if len(m.group(1)) == 4 else cardinal(int(m.group(1)))) + " ", text) text = re.sub(r"(?<![\w.])(\d+)(?:st|nd|rd|th)\b", lambda m: f" {ordinal(int(m.group(1)))} ", text) text = re.sub(r"(?<![\w.])(144|240|360|480|540|576|720|900|1080|1440|2160|4320)([pi])\b", lambda m: f" {pairs(int(m.group(1)))} {_spelled(m.group(2))} ", text) # 1080p text = re.sub(r"(?<![\w.,-])(\d+(?:\.\d+)?)[-–](?=\d+(?:\.\d+)?\s?%)", r"\1 to ", text) # 10-20% text = re.sub(r"(\d[\d,]*(?:\.\d+)?)\s?%", lambda m: f" {number_words(m.group(1))} percent ", text) text = self._area_plain.sub(self._square, text) text = self._unit.sub(self._measure, text) text = re.sub(r"(?<![\d/.,-])(\d+) (\d)/(2|3|4|5|6|8|10|16)(?![\d/]|\.\d)", self._mixed_fraction, text) text = re.sub(r"(?<![\d/.])(\d+)/(\d+)(?![\d/]|\.\d)", self._fraction, text) text = re.sub(r"(?<![\w.,-])(\d{4})[-–](\d{4})(?![\w.,-])", lambda m: f" {year(int(m.group(1)))} to {year(int(m.group(2)))} ", text) text = re.sub(r"(?<![\w.,-])(1[1-9]\d\d|20\d\d)[-–](\d\d)(?![\w-]|[.,]\d)", self._short_years, text) # 1939-45, 2010-11 text = re.sub(r"(?<![\w.,-])(\d+(?:\.\d+)?)[-–](\d+(?:\.\d+)?)(?![\w-]|[.,]\d)", lambda m: f" {number_words(m.group(1))}{'' if m.group(1) == m.group(2) else ' to'} {number_words(m.group(2))} ", text) text = re.sub(r"(?<![\w.])(\d+)x\b", lambda m: f" {number_words(m.group(1))} times ", text) text = re.sub(r"(?<=\d)\^(?=\d)", " to the power of ", text) return text
@staticmethod def _named_letters(text): """Mark the letters that stand for something, to be named: "a=10", "b>a", "(k)".""" if not any(sign in text for sign in "=<>+*/^()≤≥≠≈×÷±"): return text plain = _without_angles(text) places = {match.start("letter") for pattern in _LETTER_PLACES for match in pattern.finditer(plain)} if not places: return text return "".join(f"{_SPELL}{char.upper()}{_END}" if index in places else char for index, char in enumerate(text))
@staticmethod def _mark_comparisons(text): """Put the mark for "is" after the first value of each comparison between two values: "67 > 66", "b>a", "f(x) >= 0". Not where a word that opens no clause stands before that value: "for n > 4", "any q > 0".""" plain = _without_angles(text)
def mark(match): before, after = plain[:match.start()], plain[match.end():] value = _VALUE_BEFORE.search(before) if plain[match.start("sign")] != match.group("sign")[0] or value is None or not _VALUE_AFTER.match(after): return match.group(0) start = value.start() if value.group(0) in ")]": # "f(x) > 0", "a[i] < b": the whole of it is the value depth = 0 while start >= 0: depth += (before[start] in ")]") - (before[start] in "([") if depth == 0: break start -= 1 while start > 0 and (before[start - 1].isalnum() or before[start - 1] in "_."): start -= 1 word = re.search(r"[A-Za-z']+$", before[:max(start, 0)].rstrip()) if word and word.group(0).lower() not in _CLAUSE_OPENERS: return match.group(0) return _IS + match.group(0)
return _COMPARED.sub(mark, text)
@staticmethod def _compared(match, words): """``words`` for a comparison sign, after "is" where the mark for it stands before the sign.""" marked = match.group(0).startswith(_IS) or match.string[:match.start()].rstrip(" ").endswith(_IS) return f" {'is ' if marked else ''}{words} "
def _joined_comparisons(self, text): """"b>a", "x<5", "p<.05": the words for "<" and ">" written with no spaces.""" plain = _without_angles(text)
def read(match): before, after = text[:match.start()].rstrip(_IS), text[match.end():] if plain[match.start()] != match.group(0): # the bracket of a tag return match.group(0) if not (_FIGURE_BEFORE.search(before) or _FIGURE_AFTER.match(after) or (_LETTER_BEFORE.search(before) and _LETTER_AFTER.match(after))): return match.group(0) return self._compared(match, "less than" if match.group(0) == "<" else "greater than")
return _JOINED_COMPARISON.sub(read, text)
def _signs(self, text): """The passes that follow: signs, abbreviations, and the numbers that are left.""" text = self._named_letters(text) if "<" in text or ">" in text: text = self._joined_comparisons(text) text = re.sub(r"(?<![\w-])(" + _SIZES + r")-(" + _SIZES + r")(?![\w-])", lambda m: f" {_spelled(m.group(1))} to {_spelled(m.group(2))} ", text) text = re.sub(r"#(?=\d)", " number ", text) text = re.sub(r"#(?=[A-Z]{1,4}-?\d)", " number ", text) # Order #A7 text = re.sub(r"#(?=[A-Za-z])", " hashtag ", text) text = re.sub(r"~(?=\s?\d)", " about ", text) text = re.sub(r"(?<=[\w\s" + _END + _IS + r"])(>=|<=|!=)(?=[\w\s" + _SPELL + r"])", lambda m: self._compared(m, _COMPARISONS[m.group(1)]), text) text = re.sub(r"(?<=\d) Ti\b", f" {_spelled('TI')}", text) # RTX 4070 Ti text = re.sub(r"\b([Rr])ef\.\s?[Nn]o\.(?=\s)", r"\1eference number", text) text = re.sub(r"(?<![\w.])c\.\s?(?=(?:1[0-9]|20)\d\d\b|\d{3}\b)", " circa ", text) # c. 1500 if "." in text: text = re.sub(r"(?<![\w.'])([A-Z])\.(?=\s+[A-Z])", lambda m: self._initial(m, text), text) text = re.sub(r"\b(he|she|him|her|his|hers)/(he|she|him|her|his|hers)\b", r"\1 or \2", text, flags=re.IGNORECASE) text = re.sub(r"\b((?:[A-Za-z]\.){2,})", lambda m: self._dotted(m, text), text) if "." in text else text text = re.sub(r"\b([A-Za-z]{1,6})\b(\.?)(?![A-Za-z'’])", lambda m: self._abbreviation(m, text), text) if re.search(r"\d", text): text = _GLUED.sub(self._glued, text) text = re.sub(r"(?<![\w.])\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|(?<![\w.])\.\d+", lambda m: self._number(m, text), text) text = re.sub(r"(?<=[A-Za-z])/(?=[A-Za-z])", " ", text) text = re.sub(r"(?<=\d)" + _IS + r"?\s?[<>]\s?(?=\d)|(?<=\s)[<>](?=\s)", lambda m: self._compared(m, "less than" if "<" in m.group(0) else "greater than"), text) text = re.sub("[" + re.escape("".join(_SYMBOL_WORDS)) + "]", lambda m: self._compared(m, _SYMBOL_WORDS[m.group(0)]) if m.group(0) in "≥≤≠" else f" {_SYMBOL_WORDS[m.group(0)]} ", text) return text.replace(_IS, "")
# -- words --
@staticmethod def _unstretched(word): """Spellings a word stretched for emphasis may stand for. A letter typed three times or more is cut to one or to two: at the end of a word one is the usual spelling ("sooo", "heyyy") unless the letter is one that doubles there ("alll", "offf"); inside a word two ("goood", "cooool"). "mmm" is tried with two first: it is the hum "mm", not the letter M.""" if not re.search(r"(.)\1\1", word): return [] def cut(double_inside, double_final): def replace(match): final = match.end() == len(word) return match.group(1) * (2 if (double_final if final else double_inside) else 1) return re.sub(r"(.)\1{2,}", replace, word) liked = bool(re.search(r"([lfsz])\1\1+$", word)) or set(word) == {"m"} or re.sub(r"(.)\1{2,}$", r"\1", word) == "to" ordered = [cut(True, liked), cut(True, not liked), cut(False, liked), cut(False, not liked)] return list(dict.fromkeys(ordered))
@staticmethod def _chat_words(chat, raw): """Tokens for one row of the chat table: words, letters to name, or nothing.""" if chat == "-": return [] return [Word(part[1:].lower(), raw=raw, spell=True) if part.startswith("*") else Word(part.lower(), raw=part) for part in chat.split()]
@staticmethod def _reply(out, place): """True when the word at ``place`` is a clause by itself and can be a reply: "k", "k, thanks", "see you there, k?". Between two commas, or with a single letter next to it across a comma, it is one of a list: "i, j, k".""" marks = [] for step in (-1, 1): index = place + step while 0 <= index < len(out) and isinstance(out[index], Punct) and out[index].mark in "\"'()": index += step # quotation marks and brackets part nothing if not 0 <= index < len(out): marks.append("") # the text starts or ends here elif isinstance(out[index], Word): return False # a word in the same clause: "the value of k" else: marks.append(out[index].mark) beyond = out[index + step] if 0 <= index + step < len(out) else None if out[index].mark == "," and isinstance(beyond, Word) and len(beyond.text) == 1 and beyond.text != "i": return False return marks != [",", ","]
def _word_tokens(self, raw, all_caps, previous, following=True, fresh=False): """Tokens for one run of letters and apostrophes as written. ``previous`` is the word before it, ``following`` whether a word follows directly, ``fresh`` whether a new sentence starts here.""" lower = raw.lower() chat = self.chat.get(lower) name = raw[:1].isupper() and raw[1:].islower() and not fresh # "thank you, Ty", "Dr. Ehud Ur" if chat is not None and (len(raw) > 1 or raw.islower()) and lower not in self.replies and not name: return self._chat_words(chat, raw) roman, owner = (raw[:-2], "'s") if raw.endswith("'s") else (raw, "") if roman in _ROMAN and previous and previous[0].isupper(): number = _ROMAN[roman] words = cardinal(number) if previous.lower() in _CARDINAL_AFTER else "the " + ordinal(number) return [Word(word, raw=raw) for word in (words + owner).split()] # "Elizabeth II's" if raw == "I" and previous and previous[0].isupper() and previous.lower() in _CARDINAL_AFTER - {"world"}: return [Word("one", raw=raw)] # "World War I", "Type I" letters = raw.replace("'", "") possessive = lower.endswith("'s") stem = raw[:-2] if possessive else raw if len(stem) == 1 and stem.isalpha(): # "A" is the article unless it labels something: "Plan A.", "vitamin A" label = stem == "A" and previous and (not following or (not fresh and previous.lower() in _LABELLED)) if stem in ("a", "A", "I", "i") and not possessive and not label: return [Word(stem.lower(), raw=raw)] return [Word(lower, raw=raw, spell=True)] if len(stem) > 2 and stem[0] in "SsZz" and len(set(lower)) == 1 and (all_caps or not stem.isupper()): return [Word(lower, raw=raw, phones=((lower[0], 0),))] # "Sss", "Zzzz": a hiss, a snore if stem.isupper() and stem.isalpha() and 2 <= len(stem) <= 5 and (not all_caps or not self.is_word(stem.lower())): if stem in _INITIALISMS or not self.is_word(stem.lower()) \ or (len(stem) == 2 and stem not in _CAPITAL_WORDS and stem not in _CAPITAL_PAIRS): return [Word(lower, raw=raw, spell=True)] if not letters.isalpha(): return [] # iOS, macOS, eSIM: small letters, then capitals that are named. The dictionary's "ios" is another word. capitals = re.fullmatch(r"[a-z]+(?:[A-Z][a-z]+)*[A-Z]{2,}(?:'s)?", raw) is not None if capitals or not self.is_word(lower): for candidate in ([] if capitals else self._unstretched(lower)): # "soooo" -> "so", "goooood" -> "good" if self.is_word(candidate): return [Word(candidate, raw=raw)] parts = re.findall(r"[A-Z]?[a-z']+|[A-Z]+(?![a-z])", raw) if len(parts) > 1 and "".join(parts) == raw: # iPhone, YouTube, JavaScript out = [] for part in parts: named = part in _INITIALISMS if capitals and part.isupper() else False spelled = len(part) == 1 or named or (part.isupper() and not self.is_word(part.lower())) if capitals and out and out[-1].spell and (spelled or part == "'s"): out[-1] = out[-1]._replace(text=out[-1].text + part.lower(), raw=out[-1].raw + part) # i + OS else: out.append(Word(part.lower(), attach=bool(out), raw=part, spell=spelled)) return out return [Word(lower, raw=raw)]
def tokens(self, text): text = self.rewrite(text) runs = re.findall(r"[A-Za-z]{2,}", text) all_caps = len(runs) >= 3 and sum(run.isupper() for run in runs) >= 0.6 * len(runs) out = [] pattern = re.compile( _SPELL + r"([A-Za-z ]+)" + _END + r"|" + _INLINE + r"(.)" + _INLINE + r"|('?[A-Za-z]+(?:'[A-Za-z]+)*)|(\d+)|(-)|(\S)") attach = False previous = "" fresh = True # a sentence starts here: "a plan. A dog" is the article short = [] # where "Ss" or "Zz" stands apart: perhaps a hiss, a snore replies = [] # where a chat spelling stands that is read only as a reply for match in pattern.finditer(text): spelled, inline, word, number, hyphen, other = match.groups() before = text[match.start() - 1] if match.start() else " " if hyphen: attach = bool(out) and isinstance(out[-1], Word) and not before.isspace() \ and match.end() < len(text) and text[match.end()].isalnum() continue new = [] if spelled is not None: new = [Word(spelled.replace(" ", "").lower(), raw=spelled, spell=True)] elif inline is not None: written, phones = self.inline[ord(inline) - _INLINE_BASE] new = [Word(written.lower(), raw=written, phones=phones)] elif word is not None: if word.startswith("'") and word.lower() not in _LEADING_APOSTROPHE: out.append(Punct("'")) word = word[1:] elif word.startswith("'") and not self.is_word(word.lower()): word = word[1:] new = self._word_tokens(word, all_caps, previous, re.match(r"\s*[A-Za-z]", text[match.end():]) is not None, fresh) previous = word if word in ("Ss", "ss", "Zz", "zz") and len(new) == 1 and (before.isspace() or before in "\"'(") \ and re.match(r"[.!?…,;:—\"')]*(?:\s|$)", text[match.end():]): short.append(len(out)) # a reply stands free: not "(k)", "/k/", "[:k]", and not before a colon or a mid-text "!" ("k: king", "k! = mk") if word.lower() in self.replies and (len(word) > 1 or word.islower()) and len(new) == 1 \ and (before.isspace() or before in "\"'") \ and re.match(r"(?:[.?…,;—]*[\"']?(?:\s|$)|!+[\"']?\s*$)", text[match.end():]): replies.append(len(out)) elif number is not None: new = [Word(part, raw=number) for part in number_words(number).split()] elif other in PUNCTUATION: if not (other == "'" and before.isalnum() and match.end() < len(text) and text[match.end()].isalnum()): out.append(Punct(other)) if other in ".!?;…": fresh = True attach = False continue if new and attach: new[0] = new[0]._replace(attach=True) out.extend(new) attach = False fresh = fresh and not new # "Ss!" and "Sh, ss, tsk" are a hiss. Beside an ordinary word the two letters # stay letters, as in "the ss", "mm:ss" and a variable named ss. Quotation # marks and brackets do not part them from that word: "written as 'ss'". for place in short: first, last = place, place + 1 while first and (isinstance(out[first - 1], Word) or out[first - 1].mark in "\"'()"): first -= 1 while last < len(out) and (isinstance(out[last], Word) or out[last].mark in "\"'()"): last += 1 if all(token.text in _SOUNDS or (token.phones is not None and len(set(token.text)) == 1) for token in out[first:last] if isinstance(token, Word)): out[place] = out[place]._replace(phones=((out[place].text[0], 0),)) # "k" is "okay" as a reply by itself; beside a word or a figure it is the letter. for place in reversed(replies): if self._reply(out, place): raw = out[place].raw out[place:place + 1] = self._chat_words(self.chat[raw.lower()], raw) return out
_DEFAULT = None
def tokens(text, is_word=None): """Words and punctuation marks of ``text``. ``is_word(spelling)`` tells whether the dictionary knows a spelling (used for capitals and chat forms).""" global _DEFAULT if is_word is None: if _DEFAULT is None: _DEFAULT = Normalizer() return _DEFAULT.tokens(text) return Normalizer(is_word).tokens(text)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115"""Sentence rules: what a word's pronunciation owes to its neighbours.
Works on one clause (the words between two punctuation marks):
* sentence stress: function words lose their stress, or keep half of it, unless they close the clause (``function_words.txt`` says which);* "the" and "to" before a vowel;* linking r: "for" + "all", "after" + "it";* the flap at the end of "it" and "at" before a vowel."""
from dataclasses import dataclass
from .symbols import VOWEL_SET
_SPLIT = {"ɑːɹ": "ɑː", "ɔːɹ": "ɔː", "oːɹ": "oː", "ɪɹ": "ɪ", "ɛɹ": "ɛ", "ʊɹ": "ʊ"}_RHOTIC = frozenset(("ɚ", "ɜː", "aɪɚ"))# A slight break precedes these, so nothing links or flaps into them._NO_LINK_BEFORE = frozenset(("and", "or", "if"))_FLAP_BEFORE_VOWEL = frozenset(("it", "at"))
@dataclassclass Unit: word: str # spelling in lower case; several words for a phrase phones: tuple # ((phone, stress), ...) kind: str = "c" # stress class of function_words.txt; "c" = stress as given final: tuple = None # form to use when the word is promoted attach: bool = False # no word boundary before this unit (hyphenated compound) source: str = "" # where the pronunciation came from (for reports)
@property def last_word(self): return self.word.rsplit(" ", 1)[-1]
@property def first_word(self): return self.word.split(" ", 1)[0]
def unstress(phones): return tuple((phone, 0) for phone, _ in phones)
def promote(phones): """Give the word a primary stress: on its marked vowel, else on the first vowel.""" marks = [stress for _, stress in phones] if 1 in marks: return tuple(phones) if 2 in marks: target = len(marks) - 1 - marks[::-1].index(2) else: target = next((i for i, (phone, _) in enumerate(phones) if phone in VOWEL_SET), None) return tuple((phone, 1 if i == target else stress) for i, (phone, stress) in enumerate(phones))
def stress_clause(units): """Resolve the stress class of every unit of a clause, right to left.""" primary_follows = False for index in range(len(units) - 1, -1, -1): unit = units[index] promoted = lambda: unit.final if unit.final is not None else promote(unit.phones) if unit.kind == "u": phones = unstress(unit.phones) elif unit.kind == "uf": phones = promoted() if index == len(units) - 1 else unstress(unit.phones) elif unit.kind == "ur": phones = unstress(unit.phones) if primary_follows else promoted() elif unit.kind == "s": phones = unit.phones if primary_follows else promoted() elif unit.kind == "si": phones = promoted() if not primary_follows else unit.phones if index == 0 else unstress(unit.phones) elif unit.kind == "pf": phones = promoted() if index == len(units) - 1 else unit.phones else: # "c", "p", "ss": as written phones = unit.phones unit.phones = tuple(phones) marks = {stress for _, stress in unit.phones} primary_follows = primary_follows or 1 in marks if units and not any(stress for unit in units for _, stress in unit.phones): for unit in reversed(units): # a clause is never without any stress if any(phone in VOWEL_SET for phone, _ in unit.phones): unit.phones = promote(unit.phones) break
def join_clause(units): """Adjust the end of each word to the beginning of the next.""" for unit, following in zip(units, units[1:]): if not unit.phones or not following.phones or following.phones[0][0] not in VOWEL_SET: continue last, stress = unit.phones[-1] if unit.last_word == "the" and last == "ə": unit.phones = unit.phones[:-1] + (("ɪ", stress),) elif unit.last_word == "to" and last == "ə": unit.phones = unit.phones[:-1] + (("ʊ", stress),) elif following.first_word in _NO_LINK_BEFORE: continue elif last in _SPLIT: unit.phones = unit.phones[:-1] + ((_SPLIT[last], stress), ("ɹ", 0)) elif last in _RHOTIC: unit.phones = unit.phones + (("ɹ", 0),) elif last == "t" and unit.word in _FLAP_BEFORE_VOWEL and len(unit.phones) > 1 and unit.phones[-2][0] in VOWEL_SET: unit.phones = unit.phones[:-1] + (("ɾ", 0),)
def groups(units): """Units of a clause as spoken words: an attached unit continues the one before.""" out = [] for unit in units: if unit.attach and out: out[-1] = out[-1] + list(unit.phones) else: out.append(list(unit.phones)) return [group for group in out if group]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""The phone inventory and the token sequence built from it.
59 phones of American English, 12 punctuation marks and 5 special tokens. Lexical stress is a parallel feature (0 none, 1 primary,2 secondary), not a symbol. The order is append-only: models trained on theseids depend on it."""
from dataclasses import dataclass
PAD, BOS, EOS, SP, UNK = "<pad>", "<bos>", "<eos>", "<sp>", "<unk>"SPECIALS = (PAD, BOS, EOS, SP, UNK)PUNCTUATION = (",", ".", "?", "!", ";", ":", '"', "'", "(", ")", "—", "…")CONSONANTS = ("p", "b", "t", "d", "k", "ɡ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h", "m", "n", "ŋ", "l", "ɹ", "j", "w", "tʃ", "dʒ", "ɾ", "ʔ")VOWELS = ("ə", "ɐ", "ɚ", "ᵻ", "ɪ", "i", "iː", "ɛ", "æ", "ʌ", "ɑː", "ɔ", "ɔː", "ʊ", "uː", "ɜː", "eɪ", "aɪ", "ɔɪ", "oʊ", "aʊ", "iə", "oː", "ɑːɹ", "ɔːɹ", "oːɹ", "ɪɹ", "ɛɹ", "ʊɹ", "aɪɚ", "aɪə", "əl", "n̩")PHONES = CONSONANTS + VOWELSSYMBOLS = SPECIALS + PUNCTUATION + PHONESSYMBOL_TO_ID = {symbol: index for index, symbol in enumerate(SYMBOLS)}PHONE_SET = frozenset(PHONES)VOWEL_SET = frozenset(VOWELS)STRESS_MARKS = {1: "ˈ", 2: "ˌ"}
@dataclass(frozen=True)class Phonemized: symbols: tuple ids: tuple stress: tuple unknown: tuple # phones outside the inventory (never produced by the built-in rules)
def __len__(self): return len(self.ids)
def __str__(self): return " ".join(STRESS_MARKS.get(level, "") + symbol for symbol, level in zip(self.symbols, self.stress))
def tokenize(pieces): """Build the token sequence from ``(is_punctuation, value)`` pieces, where a text piece's value is a list of words and a word is a list of ``(phone, stress)``. Words are separated by ``<sp>``; repeated punctuation is collapsed.""" symbols, stress, unknown = [BOS], [0], [] for punctuation, value in pieces: if punctuation: if symbols[-1] != value: symbols.append(value) stress.append(0) continue for word in value: if symbols[-1] in PHONE_SET or symbols[-1] == UNK: symbols.append(SP) stress.append(0) for phone, level in word: if phone in PHONE_SET: symbols.append(phone) stress.append(level) else: unknown.append(phone) symbols.append(UNK) stress.append(0) symbols.append(EOS) stress.append(0) if not any(s in PHONE_SET or s == UNK for s in symbols): raise ValueError("the text has nothing to pronounce") return Phonemized(tuple(symbols), tuple(SYMBOL_TO_ID[s] for s in symbols), tuple(stress), tuple(unknown))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""Hand-written tables that ship with the source (``data/*.txt``).
Plain text, one entry per line, columns separated by tabs or by two or morespaces, ``#`` starts a comment line. Pronunciations are either phones of theTTS inventory with stress marks (``h ə l ˈoʊ``) or CMUdict notation(``HH AH0 L OW1``); the reader tells them apart."""
from pathlib import Pathimport re
from .convert import from_text, is_arpabet
DATA = Path(__file__).parent / "data"_COLUMNS = re.compile(r"\t+| {2,}")STRESS_CLASSES = frozenset(("u", "uf", "ur", "s", "ss", "si", "pf", "p"))
def rows(source): """Rows of a table given as a file name in ``data/``, a path or a text.""" if isinstance(source, Path): text = source.read_text(encoding="utf-8") elif "\n" in source or " " in source or "\t" in source: text = source else: text = (DATA / source).read_text(encoding="utf-8") for number, line in enumerate(text.splitlines(), 1): line = line.strip() if line and not line.startswith("#"): yield number, [column.strip() for column in _COLUMNS.split(line)]
def function_words(): """word -> (class, form, final form or None).""" table = {} for number, columns in rows("function_words.txt"): if len(columns) not in (3, 4) or columns[1] not in STRESS_CLASSES: raise ValueError(f"function_words.txt line {number}: expected word, class, form[, final form]") table[columns[0]] = (columns[1], from_text(columns[2]), from_text(columns[3]) if len(columns) == 4 else None) return table
def phrases(): """(word, word, ...) -> (class, forms, final form or None). ``forms`` has one entry per spoken word of the group: a single one when the words are joined, several when the form is written with ``|`` and the boundaries stay.""" table = {} for number, columns in rows("phrases.txt"): if len(columns) not in (3, 4) or columns[1] not in STRESS_CLASSES: raise ValueError(f"phrases.txt line {number}: expected words, class, form[, final form]") forms = tuple(from_text(part) for part in columns[2].split("|")) if len(forms) > 1 and (columns[1] != "p" or len(forms) != len(columns[0].split())): raise ValueError(f"phrases.txt line {number}: a form with boundaries needs class p and one part per word") table[tuple(columns[0].split())] = (columns[1], forms, from_text(columns[3]) if len(columns) == 4 else None) return table
def _entries(source): if isinstance(source, dict): return [(word, [word, pronunciation]) for word, pronunciation in source.items()] return list(rows(source))
def _pronunciation(text): symbols = text.split() return ("arpabet", symbols) if is_arpabet(symbols) else ("phones", from_text(text))
def pronunciations(source): """word -> ("arpabet", [symbols]) or ("phones", ((phone, stress), ...)).
Used for the built-in exception list and for user override files. Rows whose first column has several words are names: see ``names``.""" table = {} for where, columns in _entries(source): if len(columns) != 2: raise ValueError(f"{where}: expected a word and its pronunciation, separated by a tab or two spaces") if len(columns[0].split()) == 1: table[columns[0].lower()] = _pronunciation(columns[1]) return table
def names(source): """(word, word, ...) -> one pronunciation per word, for a name of several words whose rhythm matters: ``tung tung tung sahur`` with ``T UW1 NG | T UW2 NG | T UW2 NG | S AA0 HH UH1 R``. The pronunciations are separated by ``|``; the stress written is the stress spoken.""" table = {} for where, columns in _entries(source): words = columns[0].lower().split() if len(columns) != 2 or len(words) < 2: continue parts = [part.strip() for part in columns[1].split("|")] if len(parts) != len(words): raise ValueError(f"{where}: {columns[0]!r} has {len(words)} words and {len(parts)} pronunciations; " "write one per word, separated by |") table[tuple(words)] = tuple(_pronunciation(part) for part in parts) return table
def mapping(name): """Two-column table as a dictionary (second column may be empty).""" return {columns[0]: (columns[1] if len(columns) > 1 else "") for _, columns in rows(name)}12345678910"""tiny-voca: a small two-voice TTS trained from scratch.
The speech model loads no pretrained weights. A pretrained phoneme recogniseris used only by the annotation step, and an ASR model only by evaluation."""
from .config import Configfrom .model import TinyVoca
__all__ = ["Config", "TinyVoca"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337"""MSA front end: undiacritized text -> phonemes + stress, for an Arabic tiny-voca.
text --(split at punctuation)--> phrases --CATT diacritizer--> fully vowelled phrases --rules--> phonemes
Rules (MSA, connected speech): * definite article: sun letters assimilate the l (al+shams -> aʃʃams), moon letters keep it * hamzat al-wasl: pronounced (ʔa / ʔi) only at the start of a phrase, elided inside it; a preceding long vowel is shortened (fiː + l -> fil), a preceding sukun gets a helping vowel (min + al -> mina l) * shadda -> doubled consonant; tanween -> vowel + n; long vowels from ا و ي ى and dagger alif * ta marbuta: t + case vowel inside a phrase, dropped at a pause (pausal -a) * pausal forms (before punctuation / at the end): final short vowel and -un/-in dropped, -an -> aː * emphasis: a / aː next to an emphatic (sˤ dˤ tˤ ðˤ), q, or after x ɣ r -> back ɑ / ɑː; dark l in الله * word stress by syllable weight: superheavy final > heavy penult > antepenultInside a phrase the case ending is marked optional (Phone.optional): the voice sometimes drops it, andthe aligner keeps it only when the audio has it."""from dataclasses import dataclass, fieldimport reimport unicodedata
FATHA, DAMMA, KASRA, SUKUN, SHADDA = "َ", "ُ", "ِ", "ْ", "ّ"FATHATAN, DAMMATAN, KASRATAN, DAGGER = "ً", "ٌ", "ٍ", "ٰ"MARKS = {FATHA, DAMMA, KASRA, SUKUN, SHADDA, FATHATAN, DAMMATAN, KASRATAN, DAGGER}SHORT = {FATHA: "a", DAMMA: "u", KASRA: "i"}TANWEEN = {FATHATAN: "a", DAMMATAN: "u", KASRATAN: "i"}
CONS = {"ء": "ʔ", "أ": "ʔ", "إ": "ʔ", "ؤ": "ʔ", "ئ": "ʔ", "ب": "b", "ت": "t", "ث": "θ", "ج": "dʒ", "ح": "ħ", "خ": "x", "د": "d", "ذ": "ð", "ر": "r", "ز": "z", "س": "s", "ش": "ʃ", "ص": "sˤ", "ض": "dˤ", "ط": "tˤ", "ظ": "ðˤ", "ع": "ʕ", "غ": "ɣ", "ف": "f", "ق": "q", "ك": "k", "ل": "l", "م": "m", "ن": "n", "ه": "h", "و": "w", "ي": "j", "ة": "t"}SUN = set("تثدذرزسشصضطظلن")EMPHATIC = {"sˤ", "dˤ", "tˤ", "ðˤ", "q", "lˤ"}BACKING_BEFORE = {"x", "ɣ", "r"} # back a/aː when they precede the vowelCONSONANTS = sorted(set(CONS.values()) | {"lˤ"})VOWELS = ["a", "i", "u", "aː", "iː", "uː", "ɑ", "ɑː"]LONG = {"aː", "iː", "uː", "ɑː"}VOICELESS = {"ʔ", "t", "θ", "ħ", "x", "s", "ʃ", "sˤ", "tˤ", "f", "q", "k", "h"}PAUSE_PUNCT = "،,.؟?!:;؛…"
# Words whose spelling hides a long vowel (written without the dagger alif) or is irregular.LEXICON = { "هذا": "haːðaː", "هذه": "haːðihi", "هذان": "haːðaːni", "هذين": "haːðajni", "هؤلاء": "haːʔulaːʔi", "ذلك": "ðaːlika", "ذلكم": "ðaːlikum", "تلك": "tilka", "لكن": "laːkin", "لكنه": "laːkinnahu", "لكنها": "laːkinnahaː", "لكنني": "laːkinnaniː", "لكني": "laːkinniː", "أولئك": "ʔulaːʔika", "هكذا": "haːkaðaː", "الله": "ʔallˤaːh", "والله": "wallˤaːhi", "بالله": "billaːhi", "لله": "lillaːhi", "الرحمن": "ʔarraħmaːn", "إله": "ʔilaːh", "طه": "tˤaːhaː", "داود": "daːwuːd", "عمرو": "ʕamr", "مئة": "miʔa", "مائة": "miʔa",}
@dataclassclass Phone: p: str word: int # word index in the utterance (-1 = boundary/punctuation token) stress: int = 0 optional: bool = False # case ending inside a phrase: the aligner may drop it
@dataclassclass Result: phrases: list # diacritized phrases phones: list = field(default_factory=list)
def symbols(self): return [x.p for x in self.phones]
_diacritizer = None
def diacritize(phrases, batch_size=32): global _diacritizer if _diacritizer is None: from catt_tashkeel import CATTEncoderDecoder _diacritizer = CATTEncoderDecoder() todo = [p for p in phrases if p.strip()] out = iter(_diacritizer.do_tashkeel_batch(todo, batch_size=batch_size, verbose=False)) if todo else iter([]) return [next(out) if p.strip() else "" for p in phrases]
def normalize(text): text = unicodedata.normalize("NFC", text).replace("ـ", "") # tatweel text = re.sub(r"[\"'«»“”()\[\]{}<>*_~`]", " ", text) text = re.sub(r"\s*-\s*", " ", text) return re.sub(r"\s+", " ", text).strip()
def split_phrases(text): """[(phrase, punct)] split at pause punctuation; punct is the closing mark or '' at the end.""" parts = re.split(f"([{re.escape(PAUSE_PUNCT)}]+)", normalize(text)) out = [] for i in range(0, len(parts), 2): ph = parts[i].strip(); pu = parts[i + 1][0] if i + 1 < len(parts) else "" if ph: out.append((ph, pu)) elif pu and out: out[-1] = (out[-1][0], out[-1][1] or pu) return out
def letters(word): """[(letter, set_of_marks)] with marks attached to the preceding letter.""" out = [] for ch in word: if ch in MARKS and out: out[-1][1].add(ch) elif "ء" <= ch <= "ي" or ch == "ٱ": out.append([ch, set()]) return out
def strip_marks(s): return "".join(c for c in s if c not in MARKS)
def word_phones(word, first_in_phrase, last_in_phrase): """Phones of one diacritized word -> (list of (phone, optional), starts_with_wasl).""" bare = strip_marks(word) if bare in LEXICON: seq = re.findall(r"dʒ|sˤ|dˤ|tˤ|ðˤ|lˤ|[a-zʔʕħθðʃɣχ]ː?", LEXICON[bare]) if bare.startswith("ال") and not first_in_phrase: seq = seq[2:] if last_in_phrase is False and LEXICON[bare][-1] in "aiu" and len(seq) > 1: return [(s, i == len(seq) - 1) for i, s in enumerate(seq)], bare.startswith("ال") return [(s, False) for s in seq], bare.startswith("ال") L = letters(word) if not L: return [], False out = [] wasl = False i = 0 # proclitics before a definite article: و ف ب ك ل + ال / لل pro = [] while i < len(L) - 2 and L[i][0] in "وفبك" and L[i + 1][0] == "ا" and L[i + 2][0] == "ل" and i == 0: pro.append(L[i]); i += 1; break if i == 0 and len(L) > 2 and L[0][0] == "ل" and L[1][0] == "ل" and not (L[0][1] & {SUKUN}): # لل = li + l(article) out += [("l", False), ("i", False)]; i = 1 art_l = True else: art_l = False for c, m in pro: out += [(CONS[c], False), (SHORT.get(next(iter(m & set(SHORT)), FATHA if c != "ب" else KASRA), "a"), False)] # article if not art_l and i < len(L) - 1 and L[i][0] in "اٱ" and L[i + 1][0] == "ل": nxt = L[i + 2][0] if i + 2 < len(L) else "" if not pro: wasl = True if first_in_phrase: out += [("ʔ", False), ("a", False)] i += 1 # skip the alif if nxt in SUN: i += 1 # silent l; the sun letter carries shadda if L[i][0] != "ل" and SHADDA not in L[i][1]: L[i][1].add(SHADDA) else: out.append(("l", False)); i += 1 elif art_l: i = 1 nxt = L[2][0] if len(L) > 2 else "" if nxt in SUN and nxt != "ل": i = 2 if SHADDA not in L[2][1]: L[2][1].add(SHADDA) else: out.append(("l", False)); i = 2 elif i == 0 and L[0][0] in "اٱ": # other hamzat al-wasl (verbs, ism, ibn ...) wasl = True v = SHORT.get(next(iter(L[0][1] & set(SHORT)), KASRA), "i") if first_in_phrase: out += [("ʔ", False), (v, False)] i = 1 n = len(L) while i < n: c, m = L[i] last = i == n - 1 nxt = L[i + 1] if i + 1 < n else None prev_v = out[-1][0] if out else "" if c == "ا": if prev_v in ("a", "ɑ"): out[-1] = ("aː", False) elif i == n - 1 and len(L) > 1 and L[i - 1][0] == "و": pass # silent alif after plural waw (كتبوا) elif FATHATAN in L[i - 1][1] if i else False: pass else: out.append(("aː", False)) i += 1; continue if c == "آ": out += [("ʔ", False), ("aː", False)]; i += 1; continue if c == "ى": if prev_v in ("a", "ɑ") or not prev_v: if out: out[-1] = ("aː", False) else: out.append(("aː", False)) elif prev_v == "i": out[-1] = ("iː", False) else: out.append(("aː", False)) i += 1; continue if c in "وي" and not (m & (set(SHORT) | set(TANWEEN) | {SHADDA})): longv = {"و": ("u", "uː"), "ي": ("i", "iː")}[c] if prev_v == longv[0]: out[-1] = (longv[1], False); i += 1; continue if prev_v in ("a", "ɑ") and SUKUN in m: out.append((CONS[c], False)); i += 1; continue # diphthong aw / aj if not prev_v or prev_v in VOWELS: if SUKUN not in m and not m and prev_v not in VOWELS: out.append((longv[1], False)); i += 1; continue if c == "ة": if last_in_phrase: i += 1; continue # pausal: ...a(h) cons = "t" else: cons = CONS.get(c) if cons is None: i += 1; continue out.append((cons, False)) if c in "أإ" and not (m & (set(SHORT) | set(TANWEEN) | {SUKUN})) and nxt is not None and nxt[0] not in "اوي": m = m | {KASRA if c == "إ" else FATHA} if SHADDA in m: out.append((cons, False)) if DAGGER in m: out.append(("aː", False)) tv = next(iter(m & set(TANWEEN)), None) sv = next(iter(m & set(SHORT)), None) if tv: v = TANWEEN[tv] if last_in_phrase: if v == "a" and c != "ة": out.append(("aː", False)) else: out += [(v, True), ("n", True)] elif sv: v = SHORT[sv] if last and last_in_phrase: pass # pausal: final short vowel dropped else: out.append((v, last)) i += 1 return out, wasl
def emphasis(seq): """Back a/aː near emphatics. seq: list of phone strings (one word, or the whole phrase).""" out = list(seq) for k, p in enumerate(out): if p not in ("a", "aː"): continue prev = out[k - 1] if k else ""; nxt = out[k + 1] if k + 1 < len(out) else "" nxt2 = out[k + 2] if k + 2 < len(out) else "" if prev in EMPHATIC or prev in BACKING_BEFORE or nxt in EMPHATIC or (nxt not in VOWELS and nxt2 in EMPHATIC and False): out[k] = "ɑ" if p == "a" else "ɑː" return out
def syllable_stress(phones): """Index (into phones) of the stressed vowel of one word, by MSA syllable weight.""" vidx = [k for k, p in enumerate(phones) if p in VOWELS] if not vidx: return None syl = [] # (vowel index, weight) weight: 1 light, 2 heavy, 3 superheavy for j, k in enumerate(vidx): end = vidx[j + 1] - 1 if j + 1 < len(vidx) else len(phones) # next onset consonant belongs to next syllable coda = (vidx[j + 1] - k - 2) if j + 1 < len(vidx) else (len(phones) - k - 1) coda = max(coda, 0) w = (2 if phones[k] in LONG else 1) + min(coda, 2) - (0 if phones[k] in LONG or coda else 0) w = 1 if (phones[k] not in LONG and coda == 0) else (2 if (phones[k] in LONG) + coda == 1 else 3) syl.append((k, w)) if len(syl) == 1: return syl[0][0] if syl[-1][1] == 3: return syl[-1][0] if syl[-2][1] >= 2 or len(syl) == 2: return syl[-2][0] return syl[-3][0]
def phonemize(text, diacritized=None): """text -> Result. Tokens: '^' start, '$' end, ' ' word boundary, punctuation marks, phones.""" parts = split_phrases(text) dia = diacritized if diacritized is not None else diacritize([p for p, _ in parts]) res = Result(phrases=dia) res.phones.append(Phone("^", -1)) wi = 0 for (phrase, punct), dphrase in zip(parts, dia): words = dphrase.split() pw = [] for j, w in enumerate(words): seq, wasl = word_phones(w, j == 0, j == len(words) - 1) pw.append([seq, wasl]) # elision across words: wasl after a long vowel shortens it; after a consonant add a helping vowel for j in range(1, len(pw)): if pw[j][1] and pw[j - 1][0]: prev = pw[j - 1][0] last = prev[-1][0] if last in LONG: prev[-1] = ({"aː": "a", "iː": "i", "uː": "u", "ɑː": "ɑ"}[last], False) elif last not in VOWELS: helper = "u" if strip_marks(words[j - 1]) in ("هم", "أنتم", "لكم", "عليهم", "بكم", "منهم") else \ ("a" if strip_marks(words[j - 1]) == "من" else "i") prev.append((helper, False)) elif prev[-1][1]: prev[-1] = (last, False) # the case vowel carries the liaison: no longer optional for j in range(1, len(pw)): if strip_marks(words[j]) == "الله" and pw[j - 1][0] and pw[j - 1][0][-1][0] == "i": pw[j][0] = [("l" if p == "lˤ" else p, o) for p, o in pw[j][0]] for j, (seq, _) in enumerate(pw): if not seq: continue ps = emphasis([p for p, _ in seq]) st = syllable_stress(ps) if j: res.phones.append(Phone(" ", -1)) for k, (p, (_, opt)) in enumerate(zip(ps, seq)): res.phones.append(Phone(p, wi, 1 if k == st else 0, opt)) wi += 1 res.phones.append(Phone(punct if punct else " ", -1) if punct else Phone(" ", -1)) if res.phones[-1].p == " ": res.phones.pop() res.phones.append(Phone("$", -1)) return res
def show(res): s = [] for x in res.phones: if x.word < 0: s.append({"^": "", "$": "", " ": " "}.get(x.p, f" {x.p} ")) else: s.append(("ˈ" if x.stress else "") + x.p + ("?" if x.optional else "")) return "".join(s).strip()
if __name__ == "__main__": import sys for line in sys.argv[1:] or ["نعم، يمكن أن تقدم لهم قطع صغيرة من الحلويات.", "ابدأ بخطوة صغيرة، مثل ترتيب جدولك في الأسبوع القادم."]: r = phonemize(line) print(line); print(" ", " | ".join(r.phrases)); print(" ", show(r))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118from dataclasses import asdict, dataclassimport hashlibimport json
CHECKPOINT_FORMAT = 4 # 2-3: byte tokens + learned aligner (rejected explicitly).ANNOTATION_VERSION = 3# Architecture switches added after the released models (2026-11-29). They default# off, and a switch that is off is left out of to_dict (and so of the fingerprint# and of saved checkpoints): older configurations load and compare as before.ARCH_FLAGS = ("critic_log", "critic_highband", "voicing_gate", "pulsed_noise")
def _digest(value): return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
@dataclass(frozen=True)class Config: # Acoustic features (unchanged since feature schema 2; existing files are reused). sample_rate: int = 24000 hop: int = 256 n_fft: int = 1024 n_mels: int = 80 f0_min: float = 50.0 f0_max: float = 600.0 speakers: tuple[str, ...] = ("a000",) # Phoneme tokens from tiny_voca.text.SYMBOLS (Arabic front end ar-1). vocab_size: int = 86 # Arabic + English inventory (text.py) # Text encoder and frame-level transformer. channels: int = 192 heads: int = 4 feedforward: int = 640 kernel: int = 7 encoder_layers: int = 4 prosody_layers: int = 2 acoustic_layers: int = 5 dropout: float = 0.1 predictor_channels: int = 128 # Source-filter waveform head: harmonic branch and noise branch STFT sizes, # causal/anticausal complex-cepstrum orders. synth_fft: int = 512 synth_hop: int = 128 noise_fft: int = 256 noise_hop: int = 64 cep_causal: int = 80 cep_anti: int = 16 noise_cep: int = 32 harmonic_limit: float = 0.47 max_tokens: int = 512 max_frames: int = 3000 mel_mean: float = -5.0 mel_scale: float = 5.0 energy_mean: float = -4.0 energy_scale: float = 2.0 pitch_reference_hz: float = 200.0 # Training only: spectrogram critics see |X|^0.3 instead of |X|; one more critic sees 4-12 kHz. critic_log: bool = False critic_highband: bool = False # Pulse train scaled by eps + (1 - eps) * voicing (recorded voicing in training, sigmoid of the prediction at inference). voicing_gate: bool = False # Noise modulated with the glottal phase in voiced frames; one more noise-head output per frame (the depth). pulsed_noise: bool = False
def __post_init__(self): from .text import SYMBOLS if self.vocab_size != len(SYMBOLS): raise ValueError(f"vocab_size must equal the phoneme inventory size {len(SYMBOLS)}") if self.channels % self.heads or (self.channels // self.heads) % 2: raise ValueError("channels must be divisible by heads with an even head width") if not self.speakers or len(set(self.speakers)) != len(self.speakers): raise ValueError("speaker names must be unique and nonempty") for fft, hop in ((self.synth_fft, self.synth_hop), (self.noise_fft, self.noise_hop)): if fft != 4 * hop or self.hop % hop: raise ValueError("synthesis windows need 4x overlap and a hop dividing the acoustic hop") if self.cep_causal + self.cep_anti >= self.synth_fft // 2 or self.noise_cep >= self.noise_fft // 2: raise ValueError("cepstrum orders must be well below half the synthesis FFT size") if min(self.encoder_layers, self.prosody_layers, self.acoustic_layers, self.kernel) < 1 or not self.kernel % 2: raise ValueError("layer counts must be positive and the kernel odd") if min(self.mel_scale, self.energy_scale) <= 0 or not 0 < self.harmonic_limit < 0.5: raise ValueError("invalid normalization scale or harmonic limit")
def to_dict(self): value = asdict(self) for key in ARCH_FLAGS: if not value[key]: del value[key] return value
@classmethod def from_dict(cls, value): return cls(**{**value, "speakers": tuple(value["speakers"])})
@property def fingerprint(self): return _digest(self.to_dict())
@property def acoustic_config(self): """Settings that determine stored wave/mel/prosody tensors. Tokens and durations are versioned separately by the annotation layer.""" fields = ("sample_rate", "hop", "n_fft", "n_mels", "f0_min", "f0_max") return {**{key: getattr(self, key) for key in fields}, "feature_version": 2, "pitch_reference_hz": 200, "log_floor": 1e-5}
@property def acoustic_fingerprint(self): return _digest(self.acoustic_config)
@property def legacy_feature_fingerprint(self): """Fingerprint written by the byte-token preparation (front end 2).
Feature files carrying it hold compatible acoustics and STALE tokens; only the annotation step may read them, and it ignores their tokens. """ fields = ("sample_rate", "hop", "n_fft", "n_mels", "f0_min", "f0_max", "speakers") return _digest({**{key: getattr(self, key) for key in fields}, "vocab_size": 259, "feature_version": 2, "frontend_version": 2, "pitch_reference_hz": 200, "log_floor": 1e-5})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219import argparseimport osfrom pathlib import Pathimport reimport torchfrom .config import CHECKPOINT_FORMAT, Configfrom .model import TinyVoca, UtteranceTooLongfrom .text import (FRONTEND_VARIABLE, FRONTENDS, NothingToPronounce, frontend_fingerprint, passage_addressee, phonemize, sentence_addressee, set_frontend)
# The loudest sample of the audio that ``speak_text`` and the command return.PEAK = 0.99# Said when no sentence of a text could be read. The browser demo says the same.ENGLISH_ONLY = "only symbols, emoji or characters this voice cannot read were found"_SPACE = re.compile("[\\s" + chr(0xFEFF) + "]+") # JavaScript's \s, which the demo uses, takes U+FEFF too_SENTENCE_END = re.compile(r"""(?:(?<=[.!?؟…])|(?<=[.!?؟…]["')\]»]))\s+(?=\S)""")_NOT_AN_END = re.compile(r"(?:\b(?:mr|mrs|ms|dr|prof|sr|jr|st|vs|etc|no|inc|ltd|co|e\.g|i\.e|a\.m|p\.m)|\b[A-Z])\.$", re.IGNORECASE | re.ASCII)# Arabic abbreviations end in a dot after one letter: د. أحمد, أ. سارة, م. علي, ج.م., أ.د., ص.ب._NOT_AN_END_ARABIC = re.compile(r"(?:^|[\s(])(?:[\u0621-\u064A]\.)+$")_CLAUSE_END = re.compile(r"(?<=[,;:—،؛])\s+")_TEXT_END = re.compile("[\\s" + chr(0xFEFF) + "]+$")_CLOSING = "\"'”’)]»" # these may stand after the last mark: She said "go!"
def load_model(path, device="cpu", check_frontend=True): """``check_frontend=False`` lets a checkpoint speak tokens of the other front end (same inventory, slightly different conventions): for listening tests of the new phonemizer before the model is retrained on it.""" state = torch.load(path, map_location="cpu", weights_only=True) if state.get("format_version") != CHECKPOINT_FORMAT: raise ValueError("unsupported checkpoint format: byte-token checkpoints (format 2-3) cannot be used with this code") if check_frontend and state["frontend"]["fingerprint"] != frontend_fingerprint(): raise ValueError("checkpoint was trained with a different phoneme inventory/front end") model = TinyVoca(Config.from_dict(state["config"])) model.load_state_dict(state["model"], strict=True) calibration = state.get("duration_calibration") if calibration: model.duration_log_offset = (float(calibration["phone"]), float(calibration["pause"])) return model.to(device).eval()
def match_frontend(path): """Select the front end the checkpoint was trained with.""" wanted = torch.load(path, map_location="cpu", weights_only=True)["frontend"]["fingerprint"] for name in FRONTENDS: set_frontend(name) try: if frontend_fingerprint() == wanted: return name except ImportError: continue set_frontend(FRONTENDS[0]) return None
def sentences(text): """The sentences of ``text``, without a break after a title or an initial or inside a number. The browser demo splits the same way (``web/public/worker.js``); keep the two alike.""" parts, current = [], "" for piece in _SENTENCE_END.split(_SPACE.sub(" ", text).strip()): current = f"{current} {piece}" if current else piece if not _NOT_AN_END.search(current) and not _NOT_AN_END_ARABIC.search(current): parts.append(current) current = "" if current: parts.append(current) return [part for part in parts if any(char.isalnum() for char in part)]
def finished(text): """``text`` with a full stop added when it ends without a mark. Before a final mark the voice lengthens the last syllable and lets the sound fall; without one the audio breaks off. A face or another sign after the last word is no mark ("see you :)"), a comma or a colon is one. The browser demo does the same (``web/public/worker.js``); keep the two alike.""" body = _TEXT_END.sub("", text) if not body: return text last = _SPACE.split(body)[-1] if any(char.isalnum() for char in last): marked = last.rstrip(_CLOSING)[-1:] in tuple(".!?…,;:") else: marked = any(char in ".!?…" for char in last) or last in (",", ";", ":") return text if marked else body + "."
def shorter(text): """``text`` in smaller pieces: cut after commas and the like if it has any, else in two between words. ``[]`` for a single word.""" pieces = _CLAUSE_END.split(text) if len(pieces) > 1: return pieces words = text.split(" ") if len(words) < 2: return [] half = (len(words) + 1) // 2 return [" ".join(words[:half]), " ".join(words[half:])]
def limit_peak(wave, peak=PEAK): """``wave`` scaled down as a whole when its loudest sample is above ``peak``; quieter audio is returned as it is. The model sometimes peaks above 1.0, and that clips when the audio is saved as 16-bit samples.""" loudest = float(wave.abs().max()) if wave.numel() else 0.0 return wave * (peak / loudest) if loudest > peak else wave
def _voice(model, phones, voice, speed, pitch_shift, seed, pitch_range): """Phonemes -> (float waveform tensor, details): one call of the model.""" device = next(model.parameters()).device tokens = torch.tensor([phones.ids], device=device) stress = torch.tensor([phones.stress], device=device) speaker = torch.tensor([model.config.speakers.index(voice)], device=device) audio, lengths, details = model.synthesize(tokens, stress, torch.tensor([len(phones)], device=device), speaker, speed, pitch_shift, seed, pitch_range) if not torch.isfinite(audio).all(): raise RuntimeError("model produced non-finite audio") return audio[0, :int(lengths[0])].cpu(), details
def speak(model, text, voice, speed=1.0, pitch_shift=0.0, seed=0, pitch_range=1.0): """One utterance: text -> (float waveform tensor, phonemized text, details). Same front end as training. The audio is the model's output as it is and can peak above 1.0 (see ``limit_peak``). ``speak_text`` reads text of any length.""" phones = phonemize(text) if len(phones) > model.config.max_tokens: raise ValueError("text is too long for one utterance; speak_text splits it into sentences") wave, details = _voice(model, phones, voice, speed, pitch_shift, seed, pitch_range) return wave, phones, details
def speak_text(model, text, voice, speed=1.0, pitch_shift=0.0, seed=0, pitch_range=1.0, peak=PEAK): """Text of any length -> (float waveform tensor, phonemized utterances).
The text is read sentence by sentence and the audio is joined; the addressee gender the passage cues is carried to every sentence without a cue of its own. A text that ends without a mark gets a full stop (``finished``). A sentence too long for one call of the model (``max_tokens`` phonemes or ``max_frames`` frames) is cut after commas, then between words. A sentence with nothing to pronounce (another script, a face, signs only) is skipped; when no sentence could be read, ``NothingToPronounce`` says so. The audio is scaled down as a whole when it peaks above ``peak``, so that it can be saved as 16-bit samples without clipping; ``peak=None`` returns the model's output as it is.""" limit = model.config.max_tokens - 12 waves, spoken = [], [] # the addressee of the whole passage, for a sentence with no cue of its own ("يا مريم، تعالي. عايز أقولك حاجة.") addressee = passage_addressee(text)
def read(piece): try: phones = phonemize(piece, addressee=addressee if sentence_addressee(piece) is None else None) except NothingToPronounce: return if len(phones) <= limit: try: wave, _ = _voice(model, phones, voice, speed, pitch_shift, seed + len(waves), pitch_range) except UtteranceTooLong: pass else: waves.append(wave) spoken.append(phones) return pieces = shorter(piece) if not pieces: raise ValueError(f"one word is too long to speak: {piece[:40]!r}") for part in pieces: read(part)
for sentence in sentences(finished(text)): read(sentence) if not waves: raise NothingToPronounce(f"nothing in the text could be read: {ENGLISH_ONLY}") wave = torch.cat(waves) return (wave if peak is None else limit_peak(wave, peak)), spoken
def main(): parser = argparse.ArgumentParser(description="Generate speech from a trained tiny-voca inference checkpoint") parser.add_argument("--checkpoint", type=Path, required=True) source = parser.add_mutually_exclusive_group(required=True) source.add_argument("--text", help="Text of any length; it is read sentence by sentence") source.add_argument("--text-file", type=Path, help="Read the text from a file (UTF-8)") parser.add_argument("--voice", choices=Config().speakers, default=Config().speakers[0]) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--speed", type=float, default=1) parser.add_argument("--pitch-shift", type=float, default=0, help="Added to log F0 (0.058 is about one semitone)") parser.add_argument("--pitch-range", type=float, default=1, help="Scale pitch movement around the utterance mean (1 = as predicted)") parser.add_argument("--device", default="cpu") parser.add_argument("--frontend", choices=FRONTENDS, help="Phonemizer (default: TINY_VOCA_FRONTEND, else the one the checkpoint was trained with)") parser.add_argument("--allow-frontend-mismatch", action="store_true", help="Speak although the checkpoint was trained on the other front end's tokens") args = parser.parse_args() import soundfile as sf if args.frontend: set_frontend(args.frontend) elif FRONTEND_VARIABLE not in os.environ: match_frontend(args.checkpoint) model = load_model(args.checkpoint, args.device, check_frontend=not args.allow_frontend_mismatch) text = args.text if args.text is not None else args.text_file.read_text(encoding="utf-8") try: raw, spoken = speak_text(model, text, args.voice, args.speed, args.pitch_shift, pitch_range=args.pitch_range, peak=None) except NothingToPronounce: parser.exit(1, f"{ENGLISH_ONLY}. Nothing in the text could be read, so no file was written.\n") wave = limit_peak(raw) args.output.parent.mkdir(parents=True, exist_ok=True) # Float samples, never above PEAK: a later conversion to 16-bit does not clip. sf.write(args.output, wave.numpy(), model.config.sample_rate, subtype="FLOAT") for phones in spoken: print(" ".join(phones.symbols)) loudest = float(raw.abs().max()) scaled = f", scaled down to {PEAK}" if wave is not raw else "" print(f"Saved {len(wave)/model.config.sample_rate:.2f}s in {len(spoken)} utterance{'s' if len(spoken) != 1 else ''}; peak={loudest:.4f}{scaled}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447"""tiny-voca v2: feed-forward transformer with a pitch-driven source-filter head.
All weights start random. Tensor conventions: hidden [B,T,C], frame features[B,T], waveform [B,S]. Acoustic frame i is centred on sample ``i * hop``.
phoneme + stress + voice -> transformer encoder -> duration predictor -> repeat tokens by duration (supervised durations while training) -> frame transformer A -> pitch / voicing / energy -> frame transformer B -> filter parameters -> harmonic pulse train (from pitch) and noise, each shaped by its time-varying filter in the STFT domain -> 24 kHz waveform
The waveform head has no neural upsampling network. The oscillator supplies theperiodicity that a tiny decoder cannot render reliably on its own; the networkonly has to predict slowly varying spectral envelopes (complex cepstra), whichis what keeps the voice from sounding buzzy or unstable at this size."""
import mathimport torchfrom torch import nnfrom torch.nn import functional as Ffrom .config import Configfrom .text import PHONE_IDS, SYMBOL_TO_ID, VOWELS
# Config.voicing_gate: the pulse train keeps this share where the frame is unvoiced.VOICING_FLOOR = 0.1# Frame tracks that scale the sources (voicing gate, noise pulse depth) change# over a moving average of this many samples (4 ms at 24 kHz) instead of a step.TRACK_SMOOTHING = 97# Config.pulsed_noise: noise *= 1 + depth * (exp(KAPPA * (cos(theta) - 1)) - mean) in# voiced frames, depth = PULSE_DEPTH * sigmoid(noise-head output). The mean of the# bump over a cycle is exp(-KAPPA) * I0(KAPPA), so the noise power stays near one# for small depths; PULSE_DEPTH < 1 / mean keeps the factor positive.PULSE_KAPPA = 4.0PULSE_MEAN = math.exp(-PULSE_KAPPA) * sum((PULSE_KAPPA / 2) ** (2 * k) / math.factorial(k) ** 2 for k in range(30))PULSE_DEPTH = 4.0PULSE_DEPTH_BIAS = -5.0 # depth starts at PULSE_DEPTH * sigmoid(-5) = 0.027
class UtteranceTooLong(ValueError): """The utterance needs more frames than ``max_frames``: split the input."""
def length_mask(lengths, size=None): size = int(lengths.max()) if size is None else size return torch.arange(size, device=lengths.device)[None, :] < lengths[:, None]
def rotary_table(size, width, device): inverse = 1.0 / (10000 ** (torch.arange(0, width, 2, device=device, dtype=torch.float32) / width)) angle = torch.arange(size, device=device, dtype=torch.float32)[:, None] * inverse[None] return angle.cos(), angle.sin()
def rotate(x, table): cos, sin = table[0].to(x.dtype), table[1].to(x.dtype) a, b = x[..., 0::2], x[..., 1::2] return torch.stack((a * cos - b * sin, a * sin + b * cos), dim=-1).flatten(-2)
class Attention(nn.Module): """Self-attention with rotary (relative) positions: no absolute position table, so utterances longer than those seen in training stay in range."""
def __init__(self, channels, heads, dropout): super().__init__() self.heads, self.dropout = heads, dropout self.qkv = nn.Linear(channels, 3 * channels) self.out = nn.Linear(channels, channels)
def forward(self, x, mask, table): b, t, c = x.shape q, k, v = self.qkv(x).view(b, t, 3, self.heads, c // self.heads).permute(2, 0, 3, 1, 4) y = F.scaled_dot_product_attention(rotate(q, table), rotate(k, table), v, attn_mask=mask[:, None, None, :], dropout_p=self.dropout if self.training else 0.0) return self.out(y.transpose(1, 2).reshape(b, t, c))
class Block(nn.Module): def __init__(self, c): super().__init__() self.norm1 = nn.LayerNorm(c.channels) self.attention = Attention(c.channels, c.heads, c.dropout) self.norm2 = nn.LayerNorm(c.channels) self.depthwise = nn.Conv1d(c.channels, c.channels, c.kernel, padding=c.kernel // 2, groups=c.channels) self.expand = nn.Linear(c.channels, c.feedforward) self.project = nn.Linear(c.feedforward, c.channels) self.dropout = nn.Dropout(c.dropout)
def forward(self, x, mask, table): keep = mask[..., None] x = (x + self.dropout(self.attention(self.norm1(x), mask, table))) * keep # Mask before the convolution so padded positions cannot leak back in. y = self.depthwise((self.norm2(x) * keep).transpose(1, 2)).transpose(1, 2) y = self.project(self.dropout(F.gelu(self.expand(y)))) return (x + self.dropout(y)) * keep
class Stack(nn.Module): def __init__(self, c, layers): super().__init__() self.blocks = nn.ModuleList(Block(c) for _ in range(layers)) self.norm = nn.LayerNorm(c.channels) self.width = c.channels // c.heads
def forward(self, x, mask): table = rotary_table(x.shape[1], self.width, x.device) for block in self.blocks: x = block(x, mask, table) return self.norm(x) * mask[..., None]
class Predictor(nn.Module): def __init__(self, c, outputs): super().__init__() p = c.predictor_channels self.conv1 = nn.Conv1d(c.channels, p, 3, padding=1) self.conv2 = nn.Conv1d(p, p, 3, padding=1) self.norm1, self.norm2 = nn.LayerNorm(p), nn.LayerNorm(p) self.drop = nn.Dropout(c.dropout) self.out = nn.Linear(p, outputs)
def forward(self, x, mask): x = self.conv1((x * mask[..., None]).transpose(1, 2)).transpose(1, 2) x = self.drop(self.norm1(F.gelu(x))) * mask[..., None] x = self.conv2(x.transpose(1, 2)).transpose(1, 2) x = self.drop(self.norm2(F.gelu(x))) return self.out(x) * mask[..., None]
def pulse_train(f0, sample_rate, hop, limit=0.47, phase=None, return_phase=False): """Band-limited pulse train [B, T*hop] with unit power for f0 [B, T] in Hz (and, with ``return_phase``, its phase in [0, 2 pi), 0 at the pulse peak).
Frame values sit at samples i*hop and are interpolated in the log domain. The sum of all harmonics below ``limit * sample_rate`` has the closed form sin((K+1/2)x) / (2 sin(x/2)) - 1/2; the top harmonic fades in and out so the signal stays continuous while the pitch glides. Float64 keeps the phase exact. """ frames = f0.shape[1] knots = torch.log(f0.double().clamp_min(1.0)) knots = torch.cat((knots, knots[:, -1:]), dim=1) position = torch.arange(frames * hop, device=f0.device, dtype=torch.float64) / hop low = position.floor().long() weight = position - low frequency = torch.exp(knots[:, low] * (1 - weight) + knots[:, low + 1] * weight) theta = 2 * math.pi * torch.cumsum(frequency / sample_rate, dim=1) if phase is not None: theta = theta + phase.double()[:, None] theta = torch.remainder(theta, 2 * math.pi) harmonics = (limit * sample_rate / frequency).clamp_min(1.0) whole = torch.floor(harmonics) denominator = 2 * torch.sin(theta / 2) tiny = denominator.abs() < 1e-7 core = torch.where(tiny, whole, torch.sin((whole + 0.5) * theta) / torch.where(tiny, torch.ones_like(denominator), denominator) - 0.5) wave = core + (harmonics - whole) * torch.cos((whole + 1) * theta) wave = (wave * torch.sqrt(2.0 / harmonics)).float() return (wave, theta.float()) if return_phase else wave
def sample_track(values, hop, width=TRACK_SMOOTHING): """Frame values [B, T] (frame i centred on sample i*hop) as samples [B, T*hop]: the nearest frame's value, then a moving average over ``width`` samples, so a change ramps over a few milliseconds. The ends repeat the edge values.""" frames = values.shape[1] index = torch.div(torch.arange(frames * hop, device=values.device) + hop // 2, hop, rounding_mode="floor").clamp(max=frames - 1) track = values.index_select(1, index)[:, None] return F.avg_pool1d(F.pad(track, (width // 2, width // 2), mode="replicate"), width, stride=1)[:, 0]
def pulse_bump(theta): """The zero-mean glottal-cycle shape that modulates the noise.""" return torch.exp(PULSE_KAPPA * (torch.cos(theta) - 1)) - PULSE_MEAN
def filtered(source, response, fft, hop, window): """Time-varying filtering: response [B, frames, bins] multiplies the STFT.""" spectrum = torch.stft(source, fft, hop, window=window, center=True, pad_mode="constant", return_complex=True) if spectrum.shape[-1] != response.shape[1]: raise ValueError("filter frames do not match the source") return torch.istft(spectrum * response.transpose(1, 2), fft, hop, window=window, center=True, length=source.shape[-1])
def cepstrum_response(causal, anticausal, fft): """Complex frequency response exp(FFT(cepstrum)). Causal coefficients give a minimum-phase filter; anticausal ones add a maximum-phase part (glottal pulse).""" buffer = causal.new_zeros(*causal.shape[:-1], fft) buffer[..., :causal.shape[-1]] = causal if anticausal is not None: buffer[..., fft - anticausal.shape[-1]:] = anticausal.flip(-1) spectrum = torch.fft.rfft(buffer, dim=-1) return torch.polar(torch.exp(spectrum.real.clamp(-14, 6)), spectrum.imag)
class SourceFilter(nn.Module): """Harmonic-plus-noise synthesis controlled per frame by two linear heads."""
def __init__(self, c): super().__init__() self.config = c self.harmonic_steps, self.noise_steps = c.hop // c.synth_hop, c.hop // c.noise_hop self.harmonic = nn.Linear(c.channels, c.cep_causal + c.cep_anti + self.harmonic_steps) # With pulsed_noise the noise head has one more output: the pulse depth. self.noise = nn.Linear(c.channels, c.noise_cep + self.noise_steps + int(c.pulsed_noise)) for head, level in ((self.harmonic, -1.5), (self.noise, -2.5)): # start quiet and spectrally flat nn.init.zeros_(head.weight) nn.init.zeros_(head.bias) head.bias.data[0] = level if c.pulsed_noise: self.noise.bias.data[-1] = PULSE_DEPTH_BIAS # no pulsing at the start
def lifter(size, first): scale = 1.0 / (1.0 + torch.arange(first, first + size, dtype=torch.float32) / 4) if first == 0: scale[0] = 2.0 # coefficient 0 is the log gain and needs range return scale self.register_buffer("causal_lifter", lifter(c.cep_causal, 0), persistent=False) self.register_buffer("anti_lifter", lifter(c.cep_anti, 1), persistent=False) self.register_buffer("noise_lifter", lifter(c.noise_cep, 0), persistent=False) self.register_buffer("synth_window", torch.hann_window(c.synth_fft), persistent=False) self.register_buffer("noise_window", torch.hann_window(c.noise_fft), persistent=False)
@staticmethod def _take(values, index): return values.gather(1, index[..., None].expand(-1, -1, values.shape[-1]))
def _subframes(self, frames, lengths, steps): """Sub-frame j uses frame j // steps; indices past an utterance's end repeat its last sub-frame so padding never changes real audio. Two extra sub-frames cover the half window of zeros appended to the source.""" sub = torch.arange(steps * frames + 3, device=lengths.device)[None].expand(len(lengths), -1) return torch.minimum(sub, (steps * lengths - 1).clamp_min(0)[:, None])
@staticmethod def _shape(source, response, fft, hop, window): # Half a window of trailing zeros: the frames around an utterance's end are # then the same whether it stands alone or is padded inside a batch. return filtered(F.pad(source, (0, fft // 2)), response, fft, hop, window)[:, :source.shape[-1]]
def forward(self, hidden, f0, lengths, noise=None, phase=None, voicing=None): """``voicing`` [B, T] in [0, 1] (needed by ``voicing_gate`` and ``pulsed_noise``): the recorded voiced flag in training, the predicted probability at inference.""" c = self.config frames = hidden.shape[1] samples = frames * c.hop with torch.autocast(device_type=hidden.device.type, enabled=False): hidden = hidden.float() audible = length_mask(lengths * c.hop, samples) last = (lengths - 1).clamp_min(0)[:, None] # Harmonic branch: envelope interpolated between frames, one gain per sub-frame. h = self.harmonic(hidden) split = c.cep_causal + c.cep_anti sub = self._subframes(frames, lengths, self.harmonic_steps) here, following = sub // self.harmonic_steps, torch.minimum((sub + 1) // self.harmonic_steps, last) causal = 0.5 * (self._take(h[..., :c.cep_causal], here) + self._take(h[..., :c.cep_causal], following)) * self.causal_lifter anti = 0.5 * (self._take(h[..., c.cep_causal:split], here) + self._take(h[..., c.cep_causal:split], following)) * self.anti_lifter causal = torch.cat((causal[..., :1] + h[..., split:].flatten(1).gather(1, sub)[..., None], causal[..., 1:]), dim=-1) harmonic_response = cepstrum_response(causal, anti, c.synth_fft) # Noise branch: one envelope per frame, four gains per frame for sharp consonants. n = self.noise(hidden) sub = self._subframes(frames, lengths, self.noise_steps) shape = self._take(n[..., :c.noise_cep], sub // self.noise_steps) * self.noise_lifter gains = n[..., c.noise_cep:c.noise_cep + self.noise_steps] shape = torch.cat((shape[..., :1] + gains.flatten(1).gather(1, sub)[..., None], shape[..., 1:]), dim=-1) noise_response = cepstrum_response(shape, None, c.noise_fft) # Hold the last real pitch value through padding: the pitch glide inside an # utterance's final frame must not depend on what the batch was padded with. hold = torch.minimum(torch.arange(frames, device=f0.device)[None], last) f0 = f0.float().gather(1, hold) if not (c.voicing_gate or c.pulsed_noise): pulses = pulse_train(f0, c.sample_rate, c.hop, c.harmonic_limit, phase) * audible else: if voicing is None or voicing.shape != (hidden.shape[0], frames): raise ValueError("voicing_gate and pulsed_noise need the frame voicing [B, T]") voiced = sample_track(voicing.float().gather(1, hold), c.hop) pulses, theta = pulse_train(f0, c.sample_rate, c.hop, c.harmonic_limit, phase, return_phase=True) pulses = pulses * audible if c.voicing_gate: pulses = pulses * (VOICING_FLOOR + (1 - VOICING_FLOOR) * voiced) if noise is None: noise = torch.randn(hidden.shape[0], samples, device=hidden.device) if c.pulsed_noise: depth = sample_track(PULSE_DEPTH * torch.sigmoid(n[..., -1].gather(1, hold)), c.hop) noise = noise * (1 + voiced * depth * pulse_bump(theta)) wave = (self._shape(pulses, harmonic_response, c.synth_fft, c.synth_hop, self.synth_window) + self._shape(noise * audible, noise_response, c.noise_fft, c.noise_hop, self.noise_window)) return wave * audible
class TinyVoca(nn.Module): def __init__(self, config=Config()): super().__init__() self.config = c = config self.tokens = nn.Embedding(c.vocab_size, c.channels, padding_idx=0) self.stress = nn.Embedding(3, c.channels) self.voices = nn.Embedding(len(c.speakers), c.channels) self.encoder = Stack(c, c.encoder_layers) # Outputs per token: log(1 + frames) and, for pause-capable tokens, a # "has frames at all" logit. A pause is absent more often than present, so # one regression would average both cases into a pause that is too short. self.duration = Predictor(c, 2) self.frame_voices = nn.Embedding(len(c.speakers), c.channels) self.frame_position = nn.Linear(3, c.channels) self.prosody_stack = Stack(c, c.prosody_layers) # Outputs: continuous log(F0/reference), voiced logit, normalized log RMS energy. self.prosody_head = nn.Linear(c.channels, 3) self.prosody_projection = nn.Linear(3, c.channels) self.acoustic_stack = Stack(c, c.acoustic_layers) self.vocoder = SourceFilter(c) phones = torch.zeros(c.vocab_size, dtype=torch.bool) phones[sorted(PHONE_IDS)] = True self.register_buffer("phone_tokens", phones, persistent=False) # Inference-time duration calibration (log(1+frames) offsets for phones and # pause-capable tokens). The duration head is trained with MSE in the log # domain, which predicts the median length; the mean is longer by about # var/2, so plain predictions run fast. Set from the checkpoint's # "duration_calibration" entry by load_model; (0, 0) leaves them untouched. self.duration_log_offset = (0.0, 0.0) vowels = torch.zeros(c.vocab_size, dtype=torch.bool) vowels[[SYMBOL_TO_ID[v] for v in VOWELS]] = True self.register_buffer("vowel_tokens", vowels, persistent=False)
def encode(self, tokens, stress, lengths, speakers): if tokens.ndim != 2 or stress.shape != tokens.shape or lengths.shape != (tokens.shape[0],) or speakers.shape != lengths.shape: raise ValueError("expected tokens[B,N], stress[B,N], lengths[B], speakers[B]") if tokens.shape[1] > self.config.max_tokens or bool((lengths < 1).any()) or bool((lengths > tokens.shape[1]).any()): raise ValueError("invalid token length") mask = length_mask(lengths, tokens.shape[1]) x = (self.tokens(tokens) + self.stress(stress) + self.voices(speakers)[:, None]) * mask[..., None] return self.encoder(x, mask), mask
def expand(self, hidden, durations, token_mask, speakers): """Repeat token states by integer durations (zero is allowed for pause tokens) and add each frame's position inside its token.""" if durations.shape != token_mask.shape or bool((durations < 0).any()) or bool((durations[~token_mask] != 0).any()): raise ValueError("invalid durations") lengths = durations.sum(1) if bool((lengths < 1).any()): raise ValueError("utterance has no frames") if bool((lengths > self.config.max_frames).any()): raise UtteranceTooLong("utterance exceeds max_frames; split the input") size = int(lengths.max()) ends = durations.cumsum(1) frame = torch.arange(size, device=hidden.device)[None].expand(hidden.shape[0], size).contiguous() index = torch.searchsorted(ends, frame, right=True).clamp(max=durations.shape[1] - 1) owned = durations.gather(1, index).clamp_min(1) offset = frame - (ends.gather(1, index) - durations.gather(1, index)) relative = (offset.to(hidden.dtype) + 0.5) / owned features = torch.stack((relative, 1 - relative, torch.log1p(owned.to(hidden.dtype)) / 4), dim=-1) mask = frame < lengths[:, None] expanded = hidden.gather(1, index[..., None].expand(-1, -1, hidden.shape[-1])) expanded = expanded + self.frame_position(features) + self.frame_voices(speakers)[:, None] return expanded * mask[..., None], mask, lengths
def predict_prosody(self, frames, frame_mask): hidden = self.prosody_stack(frames, frame_mask) return hidden, self.prosody_head(hidden) * frame_mask[..., None]
@staticmethod def hard_prosody(prediction): """What the decoder is conditioned on when it is not teacher-forced.""" return torch.stack((prediction[..., 0].clamp(-2.0, 1.5), (prediction[..., 1] > 0).to(prediction.dtype), prediction[..., 2].clamp(-4.5, 3.0)), dim=-1)
def decode(self, prosody_hidden, condition, frame_mask): return self.acoustic_stack((prosody_hidden + self.prosody_projection(condition)) * frame_mask[..., None], frame_mask)
def frequency(self, log_f0): c = self.config return (c.pitch_reference_hz * torch.exp(log_f0.float())).clamp(c.f0_min, c.f0_max)
def duration_offset(self, tokens, dtype=torch.float32): phone, pause = self.duration_log_offset return torch.where(self.phone_tokens[tokens], torch.tensor(phone, dtype=dtype), torch.tensor(pause, dtype=dtype))
def predict_durations(self, hidden, mask, tokens, speed=1.0): output = self.duration(hidden, mask).float() log_frames = output[..., 0] + self.duration_offset(tokens, output.dtype) frames = torch.round(torch.expm1(log_frames.clamp(0, math.log1p(400))) / speed).long().clamp_min(1) # Every phoneme is audible for at least one frame. A pause-capable token # (edge, punctuation, word boundary) lasts its predicted length when the # presence logit says there is a pause, and vanishes otherwise. present = self.phone_tokens[tokens] | (output[..., 1] > 0) return torch.where(present, frames, torch.zeros_like(frames)) * mask
@staticmethod def widen_pitch(prosody, frame_mask, pitch_range): """Scale the predicted pitch movement around each utterance's voiced mean. Regression predicts a flatter contour than the recordings; values above 1 restore range (1.0 leaves the prediction untouched).""" if pitch_range == 1.0: return prosody voiced = ((prosody[..., 1] > 0) & frame_mask).to(prosody.dtype) mean = (prosody[..., 0] * voiced).sum(1, keepdim=True) / voiced.sum(1, keepdim=True).clamp_min(1) pitch = mean + (prosody[..., 0] - mean) * pitch_range return torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1) * frame_mask[..., None]
@staticmethod def pitch_wobble(shape, semitones, seed, device): """Small random pitch movement for the oscillator only (log-F0 units). Recorded pitch has cycle-to-cycle irregularity that a predicted contour lacks; two thirds of the wobble is slow drift, one third frame-level.""" generator = torch.Generator().manual_seed(seed + 7919) fast = torch.randn(shape, generator=generator) slow = F.avg_pool1d(torch.randn(shape[0], 1, shape[1] + 16, generator=generator), 17, stride=1)[:, 0] slow = slow / slow.std().clamp_min(1e-6) return ((2 * slow + fast) / 5 ** 0.5 * semitones * math.log(2) / 12).to(device)
@torch.inference_mode() def synthesize(self, tokens, stress, lengths, speakers, speed=1.0, pitch_shift=0.0, seed=0, pitch_range=1.0, pitch_jitter=0.0, voiced_vowels=True): """Free-running synthesis: predicted durations, pitch, voicing and energy.""" if not math.isfinite(speed) or not 0.25 <= speed <= 4 or not math.isfinite(pitch_shift) or not 0 <= pitch_range <= 3: raise ValueError("speed must be between 0.25 and 4, pitch_shift finite and pitch_range between 0 and 3") hidden, mask = self.encode(tokens, stress, lengths, speakers) durations = self.predict_durations(hidden, mask, tokens, speed) frames, frame_mask, frame_lengths = self.expand(hidden, durations, mask, speakers) prosody_hidden, prosody = self.predict_prosody(frames, frame_mask) if voiced_vowels: # The pitch tracker missed creaky vowels in the recordings, and the # voicing predictor learned to drop whole vowels (heard as a whispered # word). A vowel is voiced by definition, so its frames are kept voiced. ends = durations.cumsum(1) frame = torch.arange(frames.shape[1], device=tokens.device)[None].expand(len(lengths), -1).contiguous() owner = torch.searchsorted(ends, frame, right=True).clamp(max=tokens.shape[1] - 1) vowel = self.vowel_tokens[tokens].gather(1, owner) & frame_mask prosody = torch.cat((prosody[..., :1], torch.where(vowel, prosody[..., 1].clamp_min(2.0), prosody[..., 1])[..., None], prosody[..., 2:]), dim=-1) voicing = None if self.config.voicing_gate or self.config.pulsed_noise: voicing = torch.sigmoid(prosody[..., 1].float()) if voiced_vowels: voicing = torch.where(vowel, torch.ones_like(voicing), voicing) prosody = self.widen_pitch(prosody, frame_mask, pitch_range) acoustic = self.decode(prosody_hidden, self.hard_prosody(prosody), frame_mask) # One noise stream per row, drawn at the row's own length, so batching or # padding never changes a row's audio. noise = nn.utils.rnn.pad_sequence([torch.randn(int(n) * self.config.hop, generator=torch.Generator().manual_seed(seed + row)) for row, n in enumerate(frame_lengths)], batch_first=True) pitch = prosody[..., 0] + pitch_shift if pitch_jitter > 0: pitch = pitch + self.pitch_wobble(pitch.shape, pitch_jitter, seed, pitch.device) wave = self.vocoder(acoustic, self.frequency(pitch), frame_lengths, noise=noise.to(hidden.device), voicing=voicing) return wave, frame_lengths * self.config.hop, {"durations": durations, "prosody": prosody, "frame_mask": frame_mask}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475"""Read digits as Modern Standard Arabic words before diacritization.
Cardinals use the masculine nominative form without gender agreement with the counted noun, which ishow numbers are most often read aloud. Handles Western and Arabic-Indic digits, thousands separators,decimals (فاصلة), percent (في المائة) and a leading minus (سالب)."""import re
ONES = ["صفر", "واحد", "اثنان", "ثلاثة", "أربعة", "خمسة", "ستة", "سبعة", "ثمانية", "تسعة"]TEENS = ["عشرة", "أحد عشر", "اثنا عشر", "ثلاثة عشر", "أربعة عشر", "خمسة عشر", "ستة عشر", "سبعة عشر", "ثمانية عشر", "تسعة عشر"]TENS = ["", "", "عشرون", "ثلاثون", "أربعون", "خمسون", "ستون", "سبعون", "ثمانون", "تسعون"]HUNDREDS = ["", "مائة", "مئتان", "ثلاثمائة", "أربعمائة", "خمسمائة", "ستمائة", "سبعمائة", "ثمانمائة", "تسعمائة"]# (value, singular, dual, plural for 3-10)SCALES = [(10 ** 9, "مليار", "ملياران", "مليارات"), (10 ** 6, "مليون", "مليونان", "ملايين"), (1000, "ألف", "ألفان", "آلاف")]INDIC = str.maketrans("٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹", "01234567890123456789")
def _below_1000(n): parts = [] h, rest = divmod(n, 100) if h: parts.append(HUNDREDS[h]) if rest: if rest < 10: parts.append(ONES[rest]) elif rest < 20: parts.append(TEENS[rest - 10]) else: t, o = divmod(rest, 10) parts.append(f"{ONES[o]} و{TENS[t]}" if o else TENS[t]) return " و".join(parts)
def number_words(n): if n == 0: return ONES[0] if n >= 10 ** 12: return " ".join(ONES[int(d)] for d in str(n)) parts = [] for value, one, two, few in SCALES: k, n = divmod(n, value) if not k: continue if k == 1: parts.append(one) elif k == 2: parts.append(two) elif k <= 10: parts.append(f"{_below_1000(k)} {few}") else: parts.append(f"{_below_1000(k)} {one}") if n: parts.append(_below_1000(n)) return " و".join(parts)
_NUMBER = re.compile(r"(-?)(\d{1,3}(?:[,٬]\d{3})+|\d+)(?:[.٫](\d+))?(\s*[%٪])?")
def _read(m): sign, whole, frac, pct = m.groups() out = number_words(int(re.sub(r"[,٬]", "", whole))) if frac: out += " فاصلة " + (number_words(int(frac)) if not frac.startswith("0") else " ".join(ONES[int(d)] for d in frac)) if sign: out = "سالب " + out if pct: out += " في المائة" return f" {out} "
def expand_numbers(text): return re.sub(r"[ \t]+", " ", _NUMBER.sub(_read, text.translate(INDIC))).strip()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317"""Arabic (MSA) + English code-switching front end: text -> phoneme tokens with a stress feature.
Same interface as the MSA, Egyptian, Persian and Urdu front ends, so the model, annotation and training code are unchanged.
text -> digits outside English names read as Arabic words (numbers.expand_numbers) -> phrases (split at pause punctuation, kept as tokens) -> runs of Arabic words and runs of Latin-script words Arabic runs: CATT diacritizer -> MSA rules (arabic_frontend), exactly as tiny-voca-arabic English runs: dizione (CMUdict + a small G2P model + rules; Apache-2.0), the front end of tiny-voca / tiny-voca-english "الـ" written before an English word (الـ meeting, بالـ email, للـ team) is the Arabic article: l, assimilated to a following coronal like before an Arabic sun letter (الـ team = at-team); inside a phrase its vowel is optional.
* A token is one phoneme. Arabic and English phonemes written the same in IPA (b t d k s z f m n l h w j ʃ θ ð ...) are one token; the rest are separate (English ɹ p v ɡ ŋ tʃ, its vowels and diphthongs; Arabic ħ ʕ q x ɣ, emphatics ...).* Stress is a parallel feature: Arabic 0/1 from syllable weight, English 0/1/2 from the lexicon.* Punctuation, word boundaries and the utterance edges are tokens that may last zero frames.* ``Phonemized.optional`` marks Arabic case endings inside a phrase and the article's vowel; the aligner keeps them only when the recording has them, inference always says them."""
from dataclasses import dataclass, fieldimport hashlibimport jsonimport osimport reimport unicodedata
from . import arabic_frontend as affrom .numbers import expand_numbers
FRONTEND_VERSION = "arcs-1"FRONTENDS = ("arcs",)FRONTEND_VARIABLE = "TINY_VOCA_FRONTEND"_frontend = "arcs"
PAD, BOS, EOS, SP, UNK = "<pad>", "<bos>", "<eos>", "<sp>", "<unk>"SPECIALS = (PAD, BOS, EOS, SP, UNK)PUNCTUATION = (",", ".", "?", "!", ";", ":", "…")_PUNCT_MAP = {"،": ",", ",": ",", ".": ".", "؟": "?", "?": "?", "!": "!", "؛": ";", ";": ";", ":": ":", "…": "…"}PAUSE_PUNCT = "،,.؟?!:;؛…"AR_CONSONANTS = tuple(af.CONSONANTS)AR_VOWELS = tuple(af.VOWELS)EN_CONSONANTS = ("p", "b", "t", "d", "k", "ɡ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h", "m", "n", "ŋ", "l", "ɹ", "j", "w", "tʃ", "dʒ", "ɾ", "ʔ")EN_VOWELS = ("ə", "ɐ", "ɚ", "ᵻ", "ɪ", "i", "iː", "ɛ", "æ", "ʌ", "ɑː", "ɔ", "ɔː", "ʊ", "uː", "ɜː", "eɪ", "aɪ", "ɔɪ", "oʊ", "aʊ", "iə", "oː", "ɑːɹ", "ɔːɹ", "oːɹ", "ɪɹ", "ɛɹ", "ʊɹ", "aɪɚ", "aɪə", "əl", "n̩")_uniq = lambda seq: tuple(dict.fromkeys(seq))CONSONANTS = _uniq(AR_CONSONANTS + EN_CONSONANTS)VOWELS = _uniq(p for p in AR_VOWELS + EN_VOWELS if p not in CONSONANTS)PHONES = CONSONANTS + VOWELS# Append-only: changing the order or removing a symbol invalidates checkpoints.SYMBOLS = SPECIALS + PUNCTUATION + PHONESSYMBOL_TO_ID = {symbol: index for index, symbol in enumerate(SYMBOLS)}PHONE_SET = frozenset(PHONES)PHONE_IDS = frozenset(SYMBOL_TO_ID[p] for p in PHONES) | {SYMBOL_TO_ID[UNK]}VOICELESS = frozenset(af.VOICELESS) | frozenset(("p", "t", "k", "f", "θ", "s", "ʃ", "h", "tʃ"))VOWEL_SET = frozenset(VOWELS)SUN_EN = frozenset(("t", "d", "s", "z", "n", "l", "ɹ", "ʃ", "θ", "ð")) # English onsets the Arabic article assimilates to
class NothingToPronounce(ValueError): """The text has nothing to say."""
@dataclass(frozen=True)class Phonemized: symbols: tuple ids: tuple stress: tuple unknown: tuple optional: tuple = field(default=()) diacritized: tuple = field(default=()) # diacritized Arabic runs and the English runs, for inspection
def __len__(self): return len(self.ids)
def frontend(): return _frontend
def set_frontend(name): if name not in FRONTENDS: raise ValueError(f"front end must be one of {FRONTENDS}, not {name!r}")
def _dizione(): import dizione return dizione
def frontend_identity(): return {"frontend_version": FRONTEND_VERSION, "phonemizer": "tiny_voca.arabic_frontend + dizione", "diacritizer": "catt-tashkeel ed_model v2", "symbols": list(SYMBOLS)}
def frontend_runtime(): h = hashlib.sha256() for name in ("text.py", "arabic_frontend.py", "numbers.py"): h.update(open(os.path.join(os.path.dirname(__file__), name), "rb").read()) try: dz = _dizione().identity() except Exception as e: dz = f"unavailable: {e!r}" return {"phonemizer": h.hexdigest(), "dizione": dz}
def frontend_fingerprint(): return hashlib.sha256(json.dumps(frontend_identity(), sort_keys=True, ensure_ascii=False).encode()).hexdigest()
def sentence_addressee(text): return None
def passage_addressee(text): return None
_cache = None
def _diacritized(phrases): global _cache if _cache is None: _cache = {} path = os.environ.get("TINY_VOCA_DIACRITIZED") if path and os.path.exists(path): with open(path, encoding="utf-8") as f: for line in f: r = json.loads(line); _cache[r["p"]] = r["d"] missing = [p for p in dict.fromkeys(phrases) if p not in _cache] if missing: for p, d in zip(missing, af.diacritize(missing)): _cache[p] = d return [_cache[p] for p in phrases]
_AR_LETTER = re.compile(r"[ء-يٱ]")# the Arabic article written for an English word: (و|ف)? (ب|ك)? ال + tatweel, or (و|ف)? لل + tatweel_ARTICLE = re.compile(r"^(?P<pre>[وف]?[بك]?)(?P<al>ال|لل)ـ$")_LATIN_TOKEN = re.compile(r"^[A-Za-z0-9']+$")
def normalize(text): text = unicodedata.normalize("NFC", text).replace("’", "'").replace("‘", "'") text = re.sub(r"ـ(?!\s*[A-Za-z0-9])", "", text) # tatweel, except the article before Latin text = re.sub(r"(?<=[A-Za-z0-9])\+\+", " plus plus", text) text = re.sub(r"(?<=[A-Za-z0-9])\s*\+\s*(?=[A-Za-z0-9])", " plus ", text) text = re.sub(r"(?<=[A-Za-z])\s*&\s*(?=[A-Za-z])", " and ", text).replace("&", " و ") # digits inside an English name (iPhone 15, GPT-4, Windows 11, 5G) stay for the English reader; the rest become Arabic words protected = {} def keep(m): key = f"{chr(0xE100 + len(protected))}"; protected[key] = m.group(0); return key text = re.sub(r"[A-Za-z][A-Za-z'.]*(?:[ \-]?[0-9]+(?:\.[0-9]+)?)+[A-Za-z]*|[0-9]+[A-Za-z]+", keep, text) text = expand_numbers(text) for k, v in protected.items(): text = text.replace(k, v) text = re.sub(r"[\"«»“”()\[\]{}<>*_~`|/\\]", " ", text) text = re.sub(r"(?<=[A-Za-z0-9])-(?=[A-Za-z0-9])", " ", text) # check-in, USB-C, GPT-4 text = re.sub(r"\s*-\s*", " ", text) text = re.sub(r"(?<=[A-Za-z])\.(?=[A-Za-z])", " dot ", text) # Node.js, Booking.com text = re.sub(r"(?<=[0-9])\.(?=[0-9])", " point ", text) text = re.sub(r"ـ\s*", "ـ ", text) return re.sub(r"\s+", " ", text).strip()
def split_phrases(text): """[(phrase, punct)] split at pause punctuation; punct is the closing mark or '' at the end.""" parts = re.split(f"([{re.escape(PAUSE_PUNCT)}]+)", normalize(text)) out = [] for i in range(0, len(parts), 2): ph = parts[i].strip(); pu = parts[i + 1][0] if i + 1 < len(parts) else "" if ph and (_AR_LETTER.search(ph) or re.search(r"[A-Za-z0-9]", ph)): out.append((ph, pu)) elif pu and out: out[-1] = (out[-1][0], out[-1][1] or pu) return out
def runs(phrase): """[(kind, text, article)]: kind 'ar' or 'en'; article = (prefix, al) of an English run written with الـ, else None.""" out = [] for w in phrase.split(): m = _ARTICLE.match(w) if m: out.append(["art", (m.group("pre"), m.group("al")), None]); continue if _LATIN_TOKEN.match(w): kind = "en" elif _AR_LETTER.search(w): kind = "ar" else: continue if out and out[-1][0] == kind: out[-1][1] += " " + w else: article = out.pop()[1] if out and out[-1][0] == "art" else None if article and kind != "en": # الـ before an Arabic word: just Arabic pre, al = article; w = pre + al + w; article = None out.append([kind, w, article]) return [(k, t, a) for k, t, a in out if k != "art"]
_CONJ = {"و": ["w", "a"], "ف": ["f", "a"]}_PREFIX = {"و": ["w", "a"], "ف": ["f", "a"], "ب": ["b", "i"], "ك": ["k", "a"]}
def _article(pre, al, first_phone, phrase_initial): """Phones and optional flags of the article before an English word.""" ph, opt = [], [] for ch in pre: ph += _PREFIX[ch]; opt += [0, 0] if al == "لل": # للـ = li + l ph += ["l", "i"]; opt += [0, 0] elif not pre: ph, opt = (["ʔ", "a"], [1, 0]) if phrase_initial else (["a"], [1]) ph.append(first_phone if first_phone in SUN_EN else "l"); opt.append(0) return ph, opt
def _english(run): """dizione on one English run -> list of words, each [(phone, stress)].""" words = [] for is_punct, value in _dizione().pieces(run): if not is_punct: words += value return words
def _arabic(run, diacritized): """MSA rules on one Arabic run -> list of words, each [(phone, stress, optional)].""" res = af.phonemize(run, [diacritized]) words, cur = [], [] for x in res.phones: if x.p in ("^", "$") or x.word < 0: if cur: words.append(cur); cur = [] continue cur.append((x.p, x.stress, int(x.optional))) if cur: words.append(cur) return words
def prefetch(texts): """Diacritize every Arabic run of ``texts`` in one batch.""" todo = [] for t in texts: try: todo += [r for p, _ in split_phrases(t) for k, r, _ in runs(p) if k == "ar"] except Exception: continue if todo: _diacritized(list(dict.fromkeys(todo)))
def phonemize(text, addressee=None): """``addressee`` is accepted for interface parity and ignored.""" if not isinstance(text, str) or not text.strip(): raise ValueError("text must not be empty") parts = split_phrases(text) if not parts: raise NothingToPronounce("the text has nothing to pronounce") phrase_runs = [runs(p) for p, _ in parts] ar = [t for rs in phrase_runs for k, t, _ in rs if k == "ar"] dia = dict(zip(ar, _diacritized(ar))) if ar else {} symbols, stress, optional, shown, unknown = [BOS], [0], [0], [], []
def add(sym, st=0, op=0): symbols.append(sym); stress.append(st); optional.append(op)
for (phrase, punct), rs in zip(parts, phrase_runs): first = True for kind, run, article in rs: if kind == "ar": words = _arabic(run, dia[run]); shown.append(dia[run]) first_word = run.split()[0] if words and first_word in _CONJ: # و / ف standing before an English word: wa / fa words[0] = [(p, 0, 0) for p in _CONJ[first_word]] elif words and not first and first_word[:1] == "ا" and len(words[0]) > 1 and words[0][0][0] == "ʔ": words[0][0] = (words[0][0][0], words[0][0][1], 1) # hamzat al-wasl inside a phrase: optional words[0][1] = (words[0][1][0], words[0][1][1], 1) else: words = [[(p, s, 0) for p, s in w] for w in _english(run)]; shown.append(run) if words and words[0] and article: ph, op = _article(*article, words[0][0][0], first) words[0] = [(p, 0, o) for p, o in zip(ph, op)] + words[0] for w in words: if not w: continue if symbols[-1] not in (BOS,) + PUNCTUATION: add(SP) for p, st, op in w: if p in PHONE_SET: add(p, st, op) else: unknown.append(p); add(UNK) first = False if punct and symbols[-1] not in (BOS,) + PUNCTUATION: add(_PUNCT_MAP.get(punct, ",")) add(EOS) if not any(s in PHONE_SET for s in symbols): raise NothingToPronounce("the text has nothing to pronounce") return Phonemized(tuple(symbols), tuple(SYMBOL_TO_ID[s] for s in symbols), tuple(stress), tuple(unknown), tuple(optional), tuple(shown))
def drop(ph, remove): """Copy of ``ph`` without the token positions in ``remove`` (dropped optional tokens).""" remove = set(remove) keep = [i for i in range(len(ph.symbols)) if i not in remove] pick = lambda seq: tuple(seq[i] for i in keep) if seq else seq return Phonemized(pick(ph.symbols), pick(ph.ids), pick(ph.stress), ph.unknown, pick(ph.optional), ph.diacritized)
def is_phone(token_ids): return [int(i) in PHONE_IDS for i in token_ids]1234567891011121314151617181920212223242526272829303132333435363738{ "sample_rate": 24000, "hop": 256, "n_fft": 1024, "n_mels": 80, "f0_min": 50.0, "f0_max": 600.0, "speakers": [ "arcs_male", "arcs_female" ], "vocab_size": 86, "channels": 192, "heads": 4, "feedforward": 640, "kernel": 7, "encoder_layers": 4, "prosody_layers": 2, "acoustic_layers": 5, "dropout": 0.1, "predictor_channels": 128, "synth_fft": 512, "synth_hop": 128, "noise_fft": 256, "noise_hop": 64, "cep_causal": 80, "cep_anti": 16, "noise_cep": 32, "harmonic_limit": 0.47, "max_tokens": 512, "max_frames": 3000, "mel_mean": -5.0, "mel_scale": 5.0, "energy_mean": -4.0, "energy_scale": 2.0, "pitch_reference_hz": 200.0, "voicing_gate": true}123version https://git-lfs.github.com/spec/v1oid sha256:4b821572590b11aceafd5acc2113499e1527cffbdb22eb0ec7cbe9abf1461834size 18177516123456789101112131415161718192021222324252627282930313233Copyright (C) 1993-2015 Carnegie Mellon University. All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditionsare met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. The contents of this file are deemed to be source code.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
This work was supported in part by funding from the Defense AdvancedResearch Projects Agency, the Office of Naval Research and the NationalScience Foundation of the United States of America, and by membercompanies of the Carnegie Mellon Sphinx Speech Consortium. We acknowledgethe contributions of many volunteers to the expansion and improvement ofthis dictionary.
THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' ANDANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITYNOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOTLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANYTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070{"AA": {"": -5.789,"'a": -10.021,"'e": -10.133,"a": -0.59,"a'": -10.096,"a'a": -10.365,"aa": -4.888,"aad": -12.13,"aah": -9.714,"aar": -12.325,"ac": -9.944,"ach": -8.057,"agh": -9.71,"aghe": -10.135,"ah": -4.597,"ahe": -9.803,"ahh": -10.123,"al": -6.168,"an": -8.515,"ar": -6.248,"as": -8.752,"at": -9.291,"au": -5.282,"augh": -8.517,"aul": -11.453,"aw": -6.77,"awe": -8.73,"az": -11.889,"co": -11.124,"com": -9.523,"e": -6.187,"ha": -6.246,"hat": -10.186,"he": -8.736,"ho": -5.952,"i": -8.92,"il": -13.088,"ko": -11.238,"o": -0.916,"ob": -10.114,"oba": -10.135,"oc": -10.462,"och": -10.124,"od": -9.788,"oes": -12.562,"oh": -6.087,"ohn": -9.266,"oi": -11.832,"oire": -12.067,"ois": -7.261,"ol": -8.724,"om": -11.711,"on": -8.563,"op": -12.035,"os": -11.248,"ot": -7.123,"otts": -8.989,"ou": -8.417,"ouce": -10.123,"oug": -10.47,"ough": -8.484,"ow": -7.415,"ra": -11.577,"rois": -9.306,"s": -11.783,"u": -9.967,"ul": -9.123,"ur": -10.154,"yach": -12.271,"yah": -10.65},"AE": {"": -5.694,"a": -0.014,"a'a": -10.277,"ac": -8.868,"ad": -8.295,"ae": -8.032,"aed": -10.155,"ag": -8.359,"ah": -6.847,"aha": -8.902,"ahan": -10.09,"aho": -9.342,"ai": -12.59,"ak": -9.315,"al": -6.347,"am": -12.153,"an": -5.961,"ap": -12.473,"ar": -8.439,"as": -8.213,"aste": -10.009,"at": -8.4,"au": -8.609,"c": -9.884,"ca": -9.971,"caha": -12.257,"e": -9.457,"eah": -10.605,"ha": -7.425,"hat": -12.657,"i": -6.637,"ian": -11.215,"o": -8.386,"ra": -9.242,"saec": -10.035,"ui": -11.499,"yeah": -12.037,"zcza": -11.383},"AH": {"": -2.8,"'": -8.756,"'e": -10.924,"'l": -9.218,"a": -1.023,"a'": -10.339,"a's": -11.164,"aa": -12.622,"ac": -8.976,"ae": -13.044,"agh": -10.749,"ah": -6.167,"ai": -7.62,"al": -10.02,"an": -9.33,"anc": -11.212,"as": -11.05,"au": -9.444,"b": -9.342,"c": -5.138,"ce": -12.549,"ci": -12.324,"cil": -9.955,"co": -11.649,"d": -7.991,"dagh": -11.195,"de": -13.747,"dhi": -10.872,"e": -1.873,"e'l": -12.187,"ea": -11.224,"eau": -9.896,"eh": -9.472,"eha": -11.787,"eig": -8.851,"eigh": -9.555,"el": -11.178,"en": -12.371,"enk": -12.787,"eog": -12.938,"er": -9.282,"erun": -10.495,"es": -8.031,"g": -13.259,"h": -11.374,"ha": -6.566,"hae": -12.658,"hah": -11.486,"haha": -11.702,"he": -8.74,"hel": -11.992,"hi": -9.333,"ho": -9.107,"hol": -11.156,"i": -2.632,"i'": -11.164,"ia": -8.945,"ie": -9.651,"ien": -12.235,"io": -11.288,"ist": -12.595,"ist'": -11.518,"iu": -11.502,"j": -12.497,"kah": -10.332,"kah'": -13.536,"ko": -11.156,"l": -10.036,"lah": -9.585,"lar": -10.151,"le": -10.303,"loh": -12.56,"mul": -11.165,"nah": -11.808,"nais": -11.321,"ne": -11.423,"nel": -9.946,"nes": -12.664,"nois": -11.053,"o": -1.723,"o'": -10.828,"oeu": -12.801,"oh": -9.396,"oi": -12.631,"ois": -11.759,"ol": -9.214,"om": -13.173,"on": -9.359,"oo": -7.719,"os": -10.703,"ou": -4.749,"ough": -9.373,"pen": -10.084,"r": -10.804,"ra": -13.364,"ragh": -10.107,"rah": -10.571,"re": -11.9,"ri": -12.412,"rod": -11.164,"s": -12.56,"t": -6.265,"ta": -8.787,"te": -6.886,"ti": -10.581,"u": -1.92,"ub": -8.798,"ud": -10.365,"ug": -10.836,"ugh": -9.373,"uh": -7.8,"uhh": -11.164,"ui": -9.169,"ul": -9.804,"um": -11.224,"un": -9.143,"ur": -10.162,"ut": -10.7,"utts": -11.745,"y": -6.245,"yah": -11.345,"ym": -11.25,"ze": -11.927},"AO": {"": -8.202,"'al": -9.62,"'o": -13.145,"a": -2.275,"aa": -13.253,"agh": -8.647,"ah": -8.324,"al": -3.397,"ao": -11.066,"ar": -7.563,"au": -2.378,"aud": -9.34,"augh": -4.078,"auh": -9.34,"aul": -7.89,"aw": -3.126,"awe": -6.554,"che": -8.923,"e": -7.651,"ear": -10.414,"eou": -10.454,"hen": -9.34,"ho": -6.863,"hof": -12.882,"hors": -12.726,"ia": -9.288,"iac": -9.348,"ie": -9.341,"o": -0.431,"oa": -4.186,"oe": -7.332,"oeh": -6.703,"oer": -9.743,"of": -11.177,"oh": -5.996,"ohe": -9.877,"oo": -6.102,"or": -4.89,"ore": -10.532,"os": -12.722,"ou": -4.105,"ough": -5.845,"our": -11.543,"owa": -8.638,"ro": -9.317,"u": -6.307,"ua": -8.61,"ue": -8.727,"uo": -6.505,"ur": -6.667,"wo": -7.199,"y'al": -11.054},"AW": {"": -8.108,"a": -7.798,"aeu": -6.926,"aeus": -8.456,"ao": -3.681,"aou": -7.576,"au": -1.721,"aud": -8.116,"aue": -5.599,"augh": -5.408,"auh": -7.487,"aul": -8.116,"aus": -11.293,"auw": -8.116,"aw": -5.551,"b": -7.436,"cou": -7.81,"do": -9.314,"eau": -13.305,"eo": -8.312,"h": -7.931,"haue": -8.143,"ho": -10.662,"hou": -4.996,"how": -7.47,"lb": -11.795,"o": -4.494,"oce": -8.121,"oid": -8.116,"ou": -0.76,"oub": -5.408,"ough": -3.832,"ouh": -13.651,"ouw": -7.018,"ow": -1.367,"ow'": -8.034,"owe": -4.819,"rao": -10.638,"saue": -8.978,"u": -8.116,"uo": -8.116},"AY": {"": -7.788,"a": -6.06,"ae": -6.632,"ah": -7.96,"ai": -3.924,"aie": -8.388,"aii": -13.082,"ais": -7.728,"aj": -5.675,"ajch": -9.338,"aji": -8.671,"ay": -4.791,"aye": -8.573,"ayi": -8.668,"ayy": -7.702,"ci": -8.986,"cie": -8.711,"cien": -9.349,"e": -9.484,"ei": -2.105,"eie": -10.043,"eigh": -7.985,"eije": -9.338,"eill": -9.518,"eis": -9.417,"eiz": -13.769,"eu": -9.338,"ey": -5.62,"eye": -4.938,"hai": -7.344,"hei": -7.029,"heid": -10.941,"hi": -6.232,"hite": -9.336,"hy": -7.142,"hy'": -8.4,"hyay": -11.066,"hys": -9.184,"i": -0.481,"i'": -8.157,"ia": -6.487,"ic": -7.66,"ice": -9.135,"ie": -4.859,"ig": -5.312,"igh": -3.176,"io": -7.733,"ioc": -12.439,"is": -6.351,"iy": -10.205,"kai": -13.684,"lles": -9.338,"nih": -8.031,"nihi": -12.821,"oy": -9.384,"raj": -11.82,"sig": -7.538,"ui": -8.494,"uy": -5.381,"y": -1.981,"ya": -9.592,"ye": -5.847,"yi": -9.818,"ys": -11.561},"B": {"": -7.203,"'b": -8.74,"b": -0.038,"b'": -11.137,"ba": -7.984,"bb": -3.763,"bbe": -6.485,"be": -4.844,"bea": -9.855,"bh": -8.25,"bi": -10.114,"bles": -9.965,"bo": -9.001,"boe": -12.248,"bou": -10.606,"bu": -6.21,"bus": -8.512,"by": -9.872,"bys": -9.338,"ckb": -12.369,"eb": -12.596,"ebu": -8.713,"lleb": -9.965,"pb": -10.214,"pbo": -9.314,"pboa": -12.468,"w": -8.808},"CH": {"": -8.497,"ach": -8.144,"ache": -12.914,"at": -7.102,"atch": -11.953,"atu": -10.486,"c": -2.48,"cc": -3.603,"cch": -7.592,"cci": -5.578,"ce": -7.391,"ch": -0.607,"che": -4.147,"chi": -5.846,"chu": -8.489,"ci": -3.993,"ciej": -7.806,"ctuo": -12.988,"cz": -3.302,"dch": -13.749,"ghte": -8.384,"h": -5.173,"hch": -7.589,"ic": -8.937,"itu": -12.057,"jcz": -8.491,"och": -11.538,"q": -8.499,"s": -7.526,"sc": -8.567,"sch": -7.129,"sche": -8.274,"sci": -8.443,"sh": -8.495,"si": -6.302,"su": -9.535,"t": -2.43,"ta": -8.581,"tar": -8.501,"tch": -2.281,"tche": -7.784,"te": -6.639,"teo": -8.094,"teu": -13.361,"th": -7.903,"ti": -4.301,"tio": -10.432,"ts": -8.496,"tsch": -4.19,"tsh": -5.452,"tt": -10.024,"tto": -8.507,"ttsh": -8.565,"tu": -3.701,"tual": -8.703,"tur": -8.496,"tzsc": -12.139,"wch": -8.484,"x": -12.821,"xi": -8.512},"D": {"": -7.901,"'d": -10.618,"ad": -7.314,"bed": -11.123,"d": -0.098,"d'": -6.85,"da": -9.252,"dd": -3.973,"dde": -8.124,"ddh": -9.208,"de": -3.703,"den": -10.38,"dh": -7.902,"dhah": -11.099,"do": -12.665,"ds": -10.379,"dt": -8.966,"e'd": -10.079,"ed": -3.093,"edde": -10.692,"hde": -9.785,"id": -10.355,"made": -11.546,"ned": -9.239,"od": -8.494,"rd": -10.216,"red": -9.382,"rt": -10.449,"t": -7.604,"ted": -13.166,"tt": -10.426,"w": -8.17},"DH": {"ath": -2.372,"athe": -5.219,"eth": -13.567,"hyth": -13.26,"ith": -13.272,"th": -0.215,"the": -2.374,"uth": -6.358},"EH": {"": -4.391,"'e": -9.45,"'eg": -10.608,"a": -2.984,"aa": -11.487,"ae": -5.301,"aed": -11.032,"aeh": -9.664,"ah": -9.997,"aha": -10.242,"ahe": -11.158,"ai": -4.219,"aig": -11.024,"ar": -5.069,"ay": -8.745,"aye": -8.614,"chet": -13.16,"cze": -10.344,"e": -0.139,"e'e": -11.012,"ea": -3.924,"ead": -9.813,"eb": -7.598,"ed": -8.128,"ede": -10.229,"eg": -9.105,"eh": -4.872,"ehe": -12.141,"ei": -7.333,"eice": -10.32,"el": -7.79,"em": -10.08,"en": -6.833,"eo": -7.327,"er": -6.212,"es": -7.738,"et": -8.04,"ette": -10.212,"etzs": -10.216,"ey": -7.77,"ha": -10.234,"he": -8.053,"hei": -8.264,"het": -10.791,"i": -8.373,"ia": -8.862,"ie": -7.038,"l": -9.095,"nai": -13.699,"nec": -9.564,"o": -9.435,"oe": -8.985,"quar": -10.282,"quet": -10.835,"re": -11.667,"rei": -8.761,"res": -9.724,"rhe": -12.616,"s": -10.1,"se": -13.221,"ses": -7.662,"u": -5.97,"uei": -10.036,"uet": -13.107,"yet": -10.556,"ze": -11.008},"ER": {"": -7.685,"'oe": -9.582,"'re": -8.482,"a": -7.545,"aer": -9.032,"ahr": -8.887,"air": -8.222,"ar": -2.873,"are": -8.653,"arr": -6.019,"arrh": -8.918,"ary": -10.304,"aur": -8.112,"awr": -10.273,"cear": -12.938,"char": -8.766,"curr": -10.222,"dre": -10.214,"e": -9.467,"e're": -9.232,"ea": -10.615,"ear": -5.206,"ehr": -8.887,"ei": -10.289,"eir": -10.126,"er": -0.377,"era": -11.437,"ere": -8.004,"ern": -8.098,"err": -5.556,"erre": -7.971,"erts": -10.266,"eu": -10.909,"eur": -7.728,"eure": -10.072,"har": -8.289,"hear": -10.267,"her": -6.574,"heur": -10.271,"hir": -10.025,"hirr": -11.121,"i": -9.755,"ir": -3.608,"ire": -8.139,"irk": -10.017,"irr": -7.587,"irre": -9.642,"irrh": -10.311,"kard": -10.682,"lar": -12.356,"lard": -12.064,"me": -9.902,"mer": -13.084,"nair": -10.55,"o": -7.794,"oa": -10.298,"oe": -9.174,"oeur": -9.583,"olo": -9.174,"or": -2.376,"ore": -7.71,"orr": -6.182,"orrh": -9.096,"ou": -10.348,"our": -5.222,"pir": -10.273,"poor": -9.673,"r": -5.058,"re": -4.254,"rer": -11.191,"ri": -10.086,"ro": -6.929,"rre": -9.711,"rro": -10.788,"sair": -11.274,"seur": -13.813,"sour": -9.618,"tar": -11.155,"te": -10.366,"ter": -6.261,"tere": -12.442,"terr": -8.628,"u": -8.887,"uerr": -8.627,"uert": -10.275,"uhr": -8.481,"ur": -2.613,"ura": -10.085,"urch": -10.271,"ure": -5.727,"urr": -5.147,"urra": -9.239,"urre": -7.918,"urrh": -10.273,"vor": -13.477,"vre": -10.273,"wer": -8.64,"were": -9.723,"yer": -10.775,"yr": -6.687,"yrrh": -9.58},"EY": {"": -5.121,"'est": -9.513,"'eta": -8.847,"a": -0.454,"ace": -10.331,"ae": -5.224,"aeb": -9.513,"aeh": -9.637,"aey": -9.709,"ah": -10.597,"ai": -2.185,"aig": -7.426,"aigh": -6.75,"ais": -6.076,"ait": -8.385,"ame": -9.527,"aste": -9.511,"ate": -8.825,"au": -9.921,"ay": -2.279,"ay'": -12.632,"ay'l": -9.01,"aye": -5.993,"ayh": -9.056,"ayw": -11.2,"che": -9.504,"e": -2.53,"ea": -8.924,"eh": -6.752,"ei": -4.54,"eic": -11.403,"eig": -7.058,"eigh": -4.915,"eil": -9.287,"ej": -6.414,"ema": -9.966,"er": -6.734,"es": -6.847,"et": -5.336,"et'": -10.34,"ete": -13.299,"ey": -3.989,"ey'": -8.862,"ey'l": -9.94,"eye": -11.716,"eyh": -8.897,"eyi": -8.868,"ez": -9.502,"fete": -10.15,"gae": -12.86,"ha": -10.046,"i": -8.788,"ia": -9.514,"iai": -10.895,"ie": -8.783,"iej": -9.511,"ier": -12.138,"kei": -8.685,"kei'": -11.562,"leis": -9.513,"let": -13.113,"lete": -10.253,"nais": -11.046,"net": -13.673,"oeh": -8.822,"or": -9.513,"quet": -9.519,"ra": -9.325,"raig": -8.254,"re": -8.477,"rel": -7.639,"rey": -11.161,"rzej": -9.748,"sei": -8.975,"seig": -12.747,"sez": -8.826,"sier": -8.919,"ue": -12.311,"uen": -10.995,"ues": -8.853,"y": -9.461,"ye": -9.527,"zej": -9.51},"F": {"": -8.967,"'f": -9.455,"affe": -11.056,"df": -10.879,"ef": -8.437,"efe": -9.491,"eff": -8.702,"enf": -10.012,"euf": -8.995,"f": -0.287,"f'": -9.722,"fe": -4.552,"ff": -2.226,"ff'": -11.114,"ffe": -5.22,"ffe'": -10.154,"fi": -9.375,"fle": -12.22,"ft": -6.98,"fte": -9.706,"fth": -10.661,"ful": -7.434,"gf": -10.234,"gh": -10.68,"h": -8.912,"hf": -13.182,"hfi": -9.824,"if": -12.103,"lf": -8.941,"lf'": -9.181,"lph": -9.513,"off": -8.775,"oph": -8.902,"ough": -9.491,"p": -8.833,"pf": -5.457,"pfe": -11.001,"ph": -2.413,"pha": -12.767,"phe": -8.198,"pho": -7.376,"pph": -8.845,"ufe": -10.272,"uff": -8.851,"uffe": -9.818,"ugh": -5.318,"ugh'": -9.31,"v": -6.004,"v'": -8.12,"w": -3.982,"wful": -9.543,"zow": -9.553},"G": {"": -7.176,"'g": -9.426,"c": -9.139,"eg": -7.958,"egge": -9.151,"egu": -7.878,"erg": -10.828,"g": -0.115,"ga": -7.304,"ge": -6.222,"gg": -3.138,"gge": -5.645,"gh": -4.364,"ghe": -8.313,"gi": -8.2,"go": -9.747,"gu": -3.724,"gue": -5.103,"k": -8.418,"nga": -9.517,"ngh": -9.517,"qu": -9.517,"tg": -7.56,"u": -11.451,"ug": -8.343,"ugh": -7.775,"x": -4.449,"xh": -7.196},"HH": {"": -3.239,"'he": -9.135,"arh": -9.252,"ch": -5.099,"ech": -11.321,"eh": -11.937,"ehr": -9.214,"g": -8.03,"gh": -6.917,"h": -0.07,"ha": -7.699,"ha'": -9.711,"he": -4.612,"hmm": -9.135,"hu": -7.35,"hy": -8.324,"ich": -9.063,"j": -5.629,"ja": -7.757,"jill": -12.291,"kh": -7.457,"ogh": -9.193,"ugh": -11.611,"wh": -5.398,"who'": -8.904,"x": -9.198,"zhe": -10.358},"IH": {"": -6.722,"'": -4.994,"a": -4.662,"aa": -9.762,"ae": -10.627,"ay": -10.828,"ba": -13.464,"cen": -10.821,"cha": -11.313,"chu": -10.938,"cis": -9.473,"cze": -10.876,"da": -12.627,"e": -1.691,"ea": -5.441,"ear": -9.475,"ee": -10.437,"eh": -10.262,"em": -10.121,"eo": -10.369,"es": -9.353,"et": -10.239,"ez": -10.848,"he": -13.48,"hi": -8.814,"hy": -9.482,"i": -0.273,"ic": -13.748,"ich": -12.911,"ick": -11.168,"id": -10.479,"ie": -7.544,"ier": -8.754,"ih": -10.096,"il": -9.759,"im": -9.968,"imp": -10.9,"in": -7.952,"is": -8.753,"ist": -9.883,"it": -10.892,"ith": -12.658,"its": -10.23,"itzs": -10.818,"iw": -10.82,"kne": -11.043,"nes": -13.777,"net": -10.899,"o": -6.369,"oo": -10.145,"ou": -8.357,"pea": -10.277,"que": -13.772,"r": -10.816,"ret": -10.162,"rha": -9.933,"ri": -13.263,"ria": -12.489,"rie": -10.545,"s": -13.495,"s'": -11.06,"sa": -12.344,"se": -13.046,"ta": -8.688,"te": -9.573,"ti": -11.719,"u": -5.936,"ui": -8.449,"ur": -10.826,"y": -3.694,"yc": -12.814,"yh": -12.981,"yhr": -10.823,"yle": -10.819,"yn": -9.046,"yz": -10.953,"ze": -10.272,"zy": -9.152},"IY": {"": -4.113,"'": -8.741,"a": -7.927,"ae": -6.418,"aeh": -10.54,"ay": -6.628,"ay'": -12.776,"chi": -6.769,"ci": -12.599,"die": -12.258,"dy": -12.37,"dye": -10.721,"e": -1.735,"e'": -9.091,"e'l": -10.555,"ea": -2.905,"eah": -11.982,"eay": -12.992,"ee": -2.846,"eeh": -7.937,"eh": -8.422,"ei": -6.552,"eigh": -8.261,"eip": -9.42,"eo": -7.862,"es": -10.165,"ese": -10.558,"ey": -3.112,"he": -9.345,"hee": -8.9,"hi": -8.004,"hy": -9.702,"i": -1.063,"ia": -9.02,"ie": -2.579,"ieh": -7.905,"iehe": -11.758,"ies": -9.844,"iets": -10.431,"ietz": -10.484,"ig": -11.757,"ih": -10.379,"ii": -7.986,"ij": -9.433,"il": -10.121,"ill": -8.147,"ille": -9.358,"ine": -10.458,"is": -7.988,"it": -9.426,"ix": -9.735,"iy": -7.362,"iyy": -10.465,"leah": -10.459,"lee": -9.78,"lely": -9.968,"ley": -13.361,"ly": -8.624,"nee": -9.882,"ney": -10.487,"nie": -11.829,"oe": -8.586,"oey": -10.893,"ohy": -12.776,"oye": -12.343,"ray": -11.044,"ree": -9.651,"rhoe": -10.473,"ri": -8.651,"rie": -10.817,"rij": -10.559,"ry": -7.131,"se": -10.345,"sis": -12.868,"sye": -12.454,"ti": -11.197,"ty": -12.848,"uig": -11.756,"uil": -13.81,"uill": -9.967,"uis": -13.34,"vie": -11.585,"y": -1.536,"y'": -9.232,"ye": -8.037,"yee": -10.502,"yi": -8.93,"yz": -11.404,"zy": -12.327,"zys": -11.285,"zysz": -11.014},"JH": {"": -8.747,"ag": -7.641,"age": -6.581,"c": -8.755,"d": -3.915,"dg": -3.531,"dge": -3.17,"di": -6.681,"dj": -4.68,"djo": -10.174,"drz": -8.564,"du": -7.104,"dz": -5.375,"dzh": -7.382,"dzi": -7.775,"edrz": -8.756,"etj": -8.946,"g": -0.937,"ga": -8.962,"ge": -2.052,"gg": -4.902,"ggi": -7.792,"gi": -3.542,"gio": -6.929,"gj": -7.655,"j": -1.124,"ja": -8.702,"jdz": -8.062,"je": -6.157,"jh": -10.271,"ji": -7.647,"jj": -8.755,"jo": -8.91,"ju": -7.715,"kj": -8.752,"nd": -10.311,"qi": -8.755,"tj": -8.029,"ug": -7.436,"uge": -8.04,"zh": -9.501,"zha": -9.398},"K": {"": -7.81,"'c": -9.445,"'ca": -10.729,"'k": -10.584,"ac": -9.353,"acke": -12.651,"acq": -10.923,"ak": -11.032,"aq": -12.399,"auc": -13.591,"c": -0.756,"ca": -10.285,"cal": -5.761,"cc": -4.713,"ccah": -13.243,"cch": -7.795,"cco": -10.525,"ch": -3.098,"cha": -8.274,"chc": -12.739,"che": -7.826,"cho": -9.115,"ci": -13.755,"ck": -2.469,"ck'": -9.15,"cke": -6.484,"co": -8.545,"cq": -8.585,"cq'": -10.93,"cqu": -8.834,"cque": -8.333,"ct": -7.492,"cu": -11.358,"ech": -10.772,"eck": -9.684,"ecke": -10.894,"ek": -11.928,"g": -8.406,"gh": -9.461,"hlke": -9.563,"iqu": -12.272,"iqui": -10.884,"jk": -12.256,"k": -1.264,"ka": -11.926,"kc": -10.671,"ke": -3.892,"ke'": -11.057,"kh": -6.189,"ki": -10.94,"kk": -6.773,"kka": -10.604,"kke": -8.843,"ko": -12.424,"ks'": -11.487,"l'aq": -12.14,"lk": -7.313,"lk'": -10.632,"q": -3.673,"qu": -5.828,"qua": -9.397,"que": -6.017,"que'": -11.912,"ques": -9.513,"quez": -10.662,"quh": -11.577,"tk": -8.717,"uc": -12.679,"ugh": -8.855,"ulk": -11.114,"x": -3.11,"xt": -13.813,"ykj": -10.102},"L": {"": -7.81,"'ll": -8.603,"al": -8.158,"all": -6.944,"chl": -13.385,"dle": -13.499,"ehl": -12.078,"ehle": -10.985,"el": -7.5,"ell": -13.679,"hl": -6.774,"hle": -12.95,"il": -9.145,"ill": -12.32,"l": -0.232,"l'": -8.763,"la": -9.491,"lah": -11.355,"ld": -9.813,"le": -2.683,"leic": -13.43,"les": -10.787,"li": -8.982,"ll": -2.08,"ll'": -11.055,"lla": -10.525,"lle": -4.682,"lles": -10.81,"lo": -8.341,"lt": -10.097,"ol": -11.527,"pler": -11.125,"relo": -11.58,"sle": -12.23,"tl": -12.147,"tle": -12.425,"u": -10.813,"ul": -13.129,"yl": -11.638,"yle": -11.087},"M": {"": -9.188,"'am": -12.417,"am": -8.38,"ehme": -10.9,"em": -10.834,"eme": -9.833,"ghm": -10.291,"ham": -9.93,"hm": -7.216,"hme": -13.725,"lm": -8.05,"lme": -10.862,"m": -0.066,"m'": -13.798,"ma": -9.515,"ma'": -12.329,"mb": -5.325,"mbe": -7.622,"mbh": -10.292,"me": -3.972,"mh": -10.257,"mi": -8.933,"mm": -3.365,"mme": -6.481,"mn": -7.433,"mne": -9.196,"mo": -12.508,"mp": -7.01,"n": -10.308,"ncm": -13.363,"nd": -9.194,"nm": -11.706,"thm": -9.467,"um": -10.81,"ymp": -13.427},"N": {"": -8.01,"an": -9.005,"anh": -10.51,"dn'": -11.01,"dne": -13.789,"ehne": -11.268,"eign": -12.643,"en": -8.798,"en'": -10.298,"enw": -10.283,"g": -11.006,"ghan": -13.742,"gn": -6.662,"gne": -8.322,"hn": -7.561,"hne": -10.193,"hon": -13.582,"ign": -13.623,"in": -6.737,"ine": -9.057,"int": -10.864,"k'n'": -11.087,"kn": -5.617,"kna": -12.59,"kne": -10.062,"mn": -9.62,"n": -0.089,"n'": -6.773,"n't": -8.928,"na": -9.656,"ncai": -13.675,"nd": -6.557,"ne": -3.322,"ne'": -11.714,"nes": -10.975,"ng": -10.114,"nh": -8.52,"ni": -10.82,"nn": -3.505,"nne": -6.017,"nnes": -10.971,"ns": -10.268,"nt": -5.311,"on": -7.654,"pne": -9.061,"sne": -9.738,"ten": -11.103,"un": -9.669,"urne": -11.076},"NG": {"en": -12.919,"gni": -9.199,"hn": -7.381,"ing": -11.591,"inge": -12.328,"n": -1.452,"nc": -7.5,"nd": -7.813,"ng": -0.274,"nge": -7.216,"ngg": -8.871,"ngh": -7.342,"ngu": -7.897,"ngue": -6.903,"ni": -9.416,"nk": -7.667,"ong": -11.401},"OW": {"": -9.833,"'": -9.871,"a": -9.859,"aoh": -8.482,"au": -5.249,"aud": -7.686,"ault": -6.147,"aux": -7.86,"co": -9.291,"eau": -4.599,"eaux": -6.1,"eou": -9.932,"eux": -7.412,"ew": -8.199,"ewe": -10.164,"faut": -9.168,"gh": -9.86,"hco": -11.229,"ho": -6.163,"hoa": -8.781,"hom": -13.208,"io": -9.662,"know": -9.862,"leux": -10.728,"llo": -11.912,"low": -10.276,"lowe": -11.561,"lowk": -10.772,"neau": -11.512,"o": -0.172,"o'": -4.976,"oa": -3.67,"oah": -8.621,"oc": -9.613,"ock": -9.956,"od": -9.856,"oe": -3.681,"oeh": -6.045,"oet": -10.452,"oett": -10.035,"oew": -8.095,"oewe": -9.726,"og": -9.083,"ogh": -8.069,"oh": -4.567,"ohe": -9.826,"ohh": -9.861,"ok": -9.852,"ol": -6.615,"ome": -13.085,"one": -10.805,"oooh": -11.13,"os": -8.865,"ot": -6.605,"othe": -9.798,"ou": -5.73,"ough": -5.872,"ow": -3.033,"owe": -6.253,"ro": -11.181,"row": -6.177,"rowe": -13.788,"saud": -9.673,"zo": -10.463},"OY": {"ai": -7.153,"awy": -6.054,"cheu": -7.219,"eu": -2.721,"eus": -13.683,"euts": -4.961,"joll": -7.154,"noy": -11.149,"noye": -10.5,"o": -6.458,"oi": -0.802,"oie": -6.041,"oig": -5.638,"oigh": -7.217,"ois": -6.135,"ois'": -10.962,"oix": -5.777,"oix'": -10.363,"oj": -4.018,"ouy": -6.055,"oy": -0.858,"oye": -4.297,"poi": -7.868,"rhoi": -6.885,"uoy": -7.293,"uy": -7.153},"P": {"": -9.112,"b": -9.889,"bpo": -8.508,"epf": -9.196,"eppe": -12.301,"l": -9.208,"op": -8.053,"ough": -9.197,"p": -0.089,"pa": -8.634,"pe": -4.047,"pea": -13.527,"pew": -9.141,"po": -8.771,"pp": -2.747,"ppe": -6.198,"ppo": -9.715,"pr": -8.865,"pt": -9.326,"rp": -8.671,"upe": -10.137},"R": {"": -7.779,"'r": -10.192,"'re": -10.105,"ar": -6.528,"ars'": -11.531,"aur": -11.162,"care": -10.736,"er": -4.962,"ere": -8.741,"err": -8.845,"ewr": -13.656,"her": -10.555,"hr": -6.838,"hre": -9.985,"ir": -7.836,"ire": -8.99,"or": -6.646,"orrh": -10.737,"r": -0.073,"ra": -8.929,"rc": -11.952,"rd": -10.382,"re": -3.612,"re'": -10.146,"rea": -12.002,"reig": -8.872,"rh": -8.105,"rhe": -10.39,"ri": -7.651,"ro": -9.029,"rp": -9.095,"rps": -9.637,"rr": -3.735,"rre": -7.487,"rrh": -10.308,"rs": -10.762,"rt": -9.64,"ru": -11.442,"ry": -10.709,"rz": -10.325,"ur": -10.63,"urth": -10.815,"wr": -5.363,"y're": -10.738,"yre": -9.515},"S": {"": -3.293,"'": -10.119,"'s": -3.924,"c": -2.624,"c'": -11.089,"cais": -10.883,"ce": -3.758,"ces": -9.321,"ci": -9.698,"cy": -10.087,"cz": -10.734,"e": -9.183,"e's": -6.944,"es": -7.168,"es'": -9.544,"es's": -10.642,"ess": -9.529,"f": -10.831,"h": -9.609,"is": -12.162,"ise": -9.59,"ish": -13.577,"iss": -9.849,"isse": -10.16,"k's": -11.381,"mps": -13.43,"nsie": -10.146,"ous": -9.759,"p's": -10.859,"ps": -6.787,"pse": -8.916,"psy": -10.672,"s": -0.316,"s'": -5.385,"s's": -10.304,"sa": -13.365,"sai": -10.81,"sc": -5.272,"sce": -8.913,"sch": -11.398,"scz": -12.631,"se": -4.347,"sk": -9.856,"ss": -2.706,"ss'": -8.354,"sse": -6.564,"st": -6.385,"st's": -10.049,"ste": -8.538,"stes": -13.494,"sts": -6.533,"sw": -10.151,"sz": -8.081,"t": -9.839,"t's": -8.496,"tc": -10.361,"te's": -10.744,"ths": -9.864,"ts": -6.855,"ts'": -9.207,"tsa": -11.748,"tsch": -10.865,"tz": -9.422,"us": -10.143,"x": -8.726,"z": -4.071,"z'": -9.428,"ze": -9.214,"zh": -9.895,"zs": -9.383,"zsch": -10.817},"SH": {"": -6.185,"'she": -9.286,"c": -5.244,"ce": -6.222,"ceo": -7.304,"ch": -3.326,"cha": -7.999,"che": -5.503,"cher": -10.12,"ches": -8.997,"chet": -8.929,"chi": -7.697,"chs": -9.073,"chsi": -9.077,"ci": -3.519,"cia": -13.093,"cial": -8.52,"cio": -5.526,"ciou": -8.654,"cti": -12.089,"echs": -8.383,"esch": -12.79,"hs": -7.946,"hsi": -8.008,"i": -7.33,"ic": -9.074,"io": -7.414,"is": -8.382,"ish": -8.721,"oise": -8.382,"pshi": -8.479,"pti": -7.562,"s": -4.614,"sc": -7.024,"sch": -1.973,"scha": -7.5,"sche": -6.113,"schu": -9.129,"sci": -6.633,"scio": -6.937,"se": -7.41,"seo": -11.087,"sh": -0.902,"sh'": -9.073,"shch": -7.741,"she": -5.98,"shh": -8.92,"shi": -5.904,"shio": -8.14,"si": -5.006,"sj": -7.13,"ss": -5.014,"ss'": -9.072,"ssh": -8.082,"ssi": -3.962,"ssio": -8.042,"ssu": -10.705,"sz": -4.364,"szcz": -6.773,"t": -6.195,"te": -9.076,"ti": -1.271,"tie": -12.081,"tio": -4.605,"tsh": -8.771,"tte": -9.076,"tti": -10.181,"tu": -6.955,"useo": -9.639,"x": -7.569,"xi": -8.082,"xio": -9.226,"zi": -9.075,"zs": -9.075,"zsch": -9.077,"zysz": -9.345},"T": {"": -6.049,"'t": -9.131,"ate": -13.73,"bt": -13.296,"bt'": -12.36,"c": -8.343,"ct": -9.281,"d": -7.865,"date": -10.128,"dt": -5.63,"dt'": -10.038,"ed": -3.963,"edt": -12.626,"et": -10.966,"eth": -10.867,"ght": -9.351,"gt": -11.277,"it": -9.083,"it'": -11.556,"ked": -9.427,"l": -11.348,"ped": -8.066,"pt": -8.156,"sed": -8.475,"t": -0.16,"t'": -9.743,"ta": -8.699,"tau": -8.793,"te": -2.915,"te'": -13.545,"tes": -10.751,"tes'": -11.147,"th": -9.063,"to": -12.674,"tt": -2.89,"tte": -4.864,"tte'": -12.295,"tz": -8.971,"ught": -12.814,"z": -6.076,"ze": -13.071,"zz": -7.558},"TH": {"'ath": -6.27,"ath": -7.396,"ath'": -8.17,"athe": -9.974,"c": -7.975,"ethe": -9.046,"fth": -7.975,"h": -12.211,"hoff": -7.975,"hth": -12.883,"htha": -6.591,"oth": -7.568,"t": -7.272,"th": -0.025,"th'": -9.199,"tha": -12.891,"the": -4.861,"tho": -7.289,"ths": -13.585,"tth": -5.315,"uth": -5.445,"uth'": -9.849},"UH": {"": -6.394,"a": -7.288,"a'": -8.618,"bou": -13.249,"e": -7.066,"eu": -4.87,"eux": -7.651,"f": -9.385,"hu": -9.892,"iu": -13.724,"o": -3.402,"oo": -0.928,"orce": -7.053,"ou": -3.052,"ou'": -7.305,"oul": -5.262,"our": -7.988,"seux": -7.852,"sou": -6.372,"u": -0.826,"ue": -3.352,"ueb": -8.667,"ueh": -5.358,"uen": -12.268,"uer": -11.624,"uh": -4.5,"ui": -6.293,"uic": -9.829,"uit": -8.04,"ul": -5.964,"un": -6.619,"uo": -5.134,"ur": -6.031,"you'": -8.739},"UW": {"": -5.914,"au": -9.326,"aue": -9.032,"e": -12.777,"eau": -7.965,"eaux": -9.194,"eeuw": -8.064,"esui": -8.633,"eu": -5.488,"euw": -9.135,"eux": -7.808,"ew": -2.756,"ewa": -12.885,"ewe": -5.838,"ghue": -7.872,"gu": -8.795,"heau": -9.195,"heu": -7.627,"hew": -9.291,"hoo": -9.663,"hou": -8.202,"hu": -6.443,"hue": -8.476,"huet": -12.262,"hugh": -6.288,"hut": -9.204,"huu": -9.24,"huy": -8.518,"ie": -8.538,"ieu": -6.769,"iew": -6.769,"ioux": -8.504,"jew": -9.337,"keow": -9.28,"loue": -9.921,"ngu": -9.745,"nguy": -10.159,"noud": -9.837,"nual": -8.672,"o": -4.111,"o'": -9.69,"o'l": -10.377,"oe": -5.863,"oeu": -8.505,"ois": -9.147,"oo": -2.044,"ooh": -7.533,"oohe": -8.851,"oooh": -8.503,"oose": -8.446,"orce": -9.194,"ou": -2.875,"ou'": -8.389,"ou'l": -10.019,"ouc": -13.019,"oue": -7.934,"ough": -7.115,"ouh": -9.396,"ouil": -9.205,"ouis": -11.69,"oup": -7.808,"oups": -9.191,"ous": -7.457,"ouw": -8.502,"ouwe": -9.194,"oux": -6.149,"ouy": -11.717,"ow": -8.473,"ruz": -13.368,"sou": -9.735,"sui": -13.123,"u": -0.445,"ua": -8.152,"ual": -13.539,"uc": -8.856,"ue": -3.31,"ueh": -6.467,"uehr": -9.136,"uet": -12.251,"uewe": -9.194,"ug": -12.754,"ugh": -6.125,"ughe": -9.022,"uh": -5.371,"uhe": -9.192,"ui": -4.411,"uiel": -9.194,"uit": -11.662,"un": -9.174,"uo": -7.615,"uoh": -9.291,"uos": -9.747,"uoy": -9.791,"us": -8.925,"ut": -7.743,"ute": -8.655,"uu": -7.537,"uw": -7.429,"uwe": -9.192,"uy": -9.685,"w": -6.639,"who'": -9.081,"wo": -7.402,"you'": -10.134,"yu": -11.438,"zew": -9.485},"V": {"": -8.179,"'ve": -7.165,"amh": -9.279,"av": -11.046,"avo": -9.425,"bh": -11.703,"e've": -9.537,"ev": -10.982,"eve": -8.992,"ew": -6.374,"f": -8.643,"iew": -11.211,"jv": -9.278,"lve": -9.906,"obh": -9.371,"of": -9.173,"ph": -7.487,"sve": -10.106,"tive": -9.276,"uvre": -8.18,"v": -0.153,"va": -8.252,"ve": -2.117,"ves": -9.276,"vi": -7.017,"vo": -11.084,"vv": -7.338,"vve": -9.746,"vvi": -13.309,"w": -4.22,"wi": -8.097,"zv": -12.88},"W": {"": -4.462,"'hu": -8.4,"e": -9.414,"ew": -8.021,"ewi": -9.09,"ho": -10.164,"hu": -7.41,"i": -9.053,"in": -9.092,"jo": -7.298,"ju": -7.123,"o": -6.558,"oi": -5.905,"oir": -11.506,"ois": -6.24,"oix": -8.397,"on": -9.094,"ou": -5.93,"qu": -4.905,"rois": -9.395,"tuo": -9.358,"u": -1.813,"v": -8.397,"w": -0.332,"wa": -10.734,"wai": -8.387,"we": -5.431,"we'": -9.041,"wey": -8.396,"wh": -2.489,"whe": -13.399,"wi": -12.339,"wieh": -9.408},"Y": {"": -0.559,"c": -5.869,"e": -3.545,"ea": -6.705,"h": -5.421,"hy": -7.663,"hya": -8.861,"i": -2.144,"ie": -7.528,"ille": -8.555,"io": -10.449,"j": -2.873,"ja": -7.779,"je": -8.575,"jj": -7.862,"jo": -8.551,"ju": -7.859,"l": -9.011,"li": -5.553,"ll": -7.81,"m": -6.2,"r": -8.962,"sie": -11.19,"u": -6.628,"ue": -8.505,"y": -1.604,"y'": -11.299,"y'k": -8.569,"ye": -5.653,"yo": -6.502},"Z": {"": -5.095,"'s": -1.664,"ahs": -10.194,"as": -11.428,"aso": -11.964,"cs": -10.24,"cz": -8.516,"ds": -9.591,"ds'": -11.965,"e's": -5.098,"es": -2.764,"es'": -6.27,"ese": -13.558,"eys": -12.141,"ez": -10.676,"h": -7.557,"h's": -9.077,"ires": -10.524,"is": -9.246,"ise": -8.711,"lles": -12.078,"n's": -11.46,"ns": -12.949,"oohs": -10.564,"os": -13.797,"ps'": -10.306,"r's": -12.647,"s": -0.633,"s'": -3.975,"s's": -8.22,"sa": -9.875,"se": -3.997,"si": -9.191,"so": -13.282,"sp": -9.944,"ss": -8.082,"sso": -12.36,"sth": -10.604,"sz": -8.863,"szcz": -10.526,"t's": -11.082,"thes": -9.58,"ts": -9.925,"use": -8.88,"x": -6.154,"xh": -10.271,"z": -2.045,"z'": -10.235,"za": -10.181,"ze": -3.848,"zh": -7.678,"zi": -13.426,"zo": -11.271,"zy": -9.137,"zz": -4.734,"zze": -9.73},"ZH": {"": -4.756,"as": -3.641,"asu": -3.788,"g": -2.042,"ge": -2.792,"ges": -5.635,"gues": -13.793,"isu": -6.134,"iz": -7.38,"izu": -5.778,"j": -2.279,"jar": -10.2,"je": -4.634,"jo": -5.549,"s": -2.515,"sh": -4.989,"shi": -8.268,"si": -0.856,"sio": -5.057,"ssi": -9.52,"su": -3.643,"ti": -5.635,"uygu": -13.649,"x": -5.538,"xi": -4.539,"xia": -10.53,"yesi": -10.211,"z": -4.407,"zc": -6.328,"zh": -3.53,"zho": -5.866,"zi": -4.72,"zs": -5.229,"zsch": -6.328,"zu": -8.57}}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283{ "letters": "abcdefghijklmnopqrstuvwxyz'", "symbols": [ "AA0", "AA1", "AA2", "AE0", "AE1", "AE2", "AH0", "AH1", "AH2", "AO0", "AO1", "AO2", "AW0", "AW1", "AW2", "AY0", "AY1", "AY2", "B", "CH", "D", "DH", "EH0", "EH1", "EH2", "ER0", "ER1", "ER2", "EY0", "EY1", "EY2", "F", "G", "HH", "IH0", "IH1", "IH2", "IY0", "IY1", "IY2", "JH", "K", "L", "M", "N", "NG", "OW0", "OW1", "OW2", "OY0", "OY1", "OY2", "P", "R", "S", "SH", "T", "TH", "UH0", "UH1", "UH2", "UW0", "UW1", "UW2", "V", "W", "Y", "Z", "ZH" ], "width": 64, "hidden": 127, "convs": 0, "kernel": 3, "layers": 2, "slots": 2, "parameters": 458682, "test_word_error": 0.3239775461106656, "test_phoneme_error": 0.07940553088413403}123version https://git-lfs.github.com/spec/v1oid sha256:eb3fd519ff00e72d850928d2fccb968adc36134bca2f3bda09de7e794c2ed01bsize 18401041{"plural_bases": ["abstract", "addict", "advocate", "affiliate", "aggregate", "alternate", "animate", "appropriate", "approximate", "articulate", "associate", "attribute", "blessed", "buffet", "combine", "compact", "compound", "conduct", "conflict", "conglomerate", "conjugate", "conscript", "console", "consort", "construct", "consummate", "contest", "contract", "contrast", "converse", "convert", "convict", "coordinate", "decrease", "defect", "degenerate", "delegate", "deliberate", "desert", "deviate", "discard", "discharge", "discount", "document", "duplicate", "elaborate", "entrance", "escort", "estimate", "expatriate", "exploit", "export", "expose", "extract", "fragment", "frequent", "graduate", "impact", "implant", "implement", "import", "incense", "incline", "increase", "increment", "initiate", "insert", "instrument", "insult", "interchange", "intimate", "invert", "invite", "laminate", "learned", "moderate", "moped", "object", "ornament", "overthrow", "perfect", "perfume", "permit", "pervert", "pigment", "postulate", "precipitate", "predicate", "present", "produce", "project", "protest", "rebel", "record", "recount", "refund", "refuse", "reject", "resume", "retard", "separate", "subject", "subordinate", "supplement", "suspect", "syndicate", "tear", "transplant", "transport", "upset"], "pooled": {"bias": -2.0459, "weights": {"cap": -2.3791, "first": -0.0013, "tn1=ADV": 0.0326, "tn1=BE": -1.9895, "tn1=CAP": 0.829, "tn1=CONJ": -0.3262, "tn1=DET": 2.2059, "tn1=ED": -0.5811, "tn1=HAVE": -0.5379, "tn1=LY": 1.5112, "tn1=OBJ": 7.4895, "tn1=POS": 2.2855, "tn1=POSS": 5.0781, "tn1=PREP": -0.9661, "tn1=PUNCT": -0.699, "tn1=S": -0.5612, "tn1=SUBJ": 1.5861, "tn1=TO": -0.518, "tn1=W": -0.2529, "tn1n2=CAP+CAP": -1.067, "tn1n2=CAP+PREP": 0.2951, "tn1n2=CAP+PUNCT": -0.0392, "tn1n2=CAP+TO": 0.244, "tn1n2=CAP+W": -0.6209, "tn1n2=CONJ+W": -0.8776, "tn1n2=DET+S": 0.4925, "tn1n2=DET+SUBJ": -0.3513, "tn1n2=DET+W": 1.5442, "tn1n2=ED+PREP": -0.3539, "tn1n2=ING+PUNCT": -0.4339, "tn1n2=LY+PREP": 0.4924, "tn1n2=PREP+DET": 0.3162, "tn1n2=PREP+S": -0.7325, "tn1n2=PUNCT+CAP": 0.0839, "tn1n2=PUNCT+CONJ": -0.1019, "tn1n2=PUNCT+ED": 0.0468, "tn1n2=PUNCT+PREP": -0.1972, "tn1n2=PUNCT+W": -0.2283, "tn1n2=S+DET": -0.2897, "tn1n2=S+PUNCT": -0.1665, "tn1n2=S+TO": 0.4195, "tn1n2=S+W": -0.2766, "tn1n2=SUBJ+PUNCT": 0.2412, "tn1n2=TO+DET": -0.7581, "tn1n2=W+DET": 0.843, "tn1n2=W+PUNCT": -0.2504, "tn1n2=W+S": 0.6466, "tn1n2=W+TO": -0.0649, "tn1n2=W+W": 0.6605, "tn2=ADV": 0.2338, "tn2=BE": -1.5298, "tn2=ED": -0.537, "tn2=HAVE": -0.6655, "tn2=LY": -0.1787, "tn2=MODAL": -1.4938, "tn2=POS": 0.5558, "tn2=PUNCT": -0.4414, "tn2=S": 0.2707, "tn2=SUBJ": -0.5764, "tn2=TO": 0.4385, "tn2=W": 0.2501, "tp1=<s>": -0.5995, "tp1=ADV": 0.5648, "tp1=BE": -1.5174, "tp1=CONJ": 0.5358, "tp1=DET": -3.0969, "tp1=DO": 1.2311, "tp1=ED": -1.2476, "tp1=HAVE": -0.8374, "tp1=ING": -2.0053, "tp1=LY": 1.1058, "tp1=MODAL": 6.171, "tp1=NEG": 0.7247, "tp1=NUM": -0.7705, "tp1=POS": -1.4653, "tp1=POSS": -3.4859, "tp1=PREP": -2.7183, "tp1=S": 1.4298, "tp1=SUBJ": 4.7497, "tp1=TO": 4.4197, "tp1=W": -1.6407, "tp1n1=<s>+CAP": -0.5351, "tp1n1=<s>+PUNCT": 0.0968, "tp1n1=ADV+PREP": 0.4385, "tp1n1=CAP+CAP": 0.1395, "tp1n1=CAP+PUNCT": -0.3045, "tp1n1=CONJ+CAP": 0.2994, "tp1n1=CONJ+PREP": -0.0389, "tp1n1=CONJ+S": 0.0089, "tp1n1=CONJ+SUBJ": 0.0221, "tp1n1=CONJ+W": -0.2556, "tp1n1=DET+CONJ": -0.9335, "tp1n1=DET+DET": 0.4123, "tp1n1=DET+PREP": -0.3091, "tp1n1=DET+S": 0.722, "tp1n1=LY+PREP": 1.0064, "tp1n1=LY+PUNCT": -0.6799, "tp1n1=PUNCT+PREP": -0.0484, "tp1n1=PUNCT+PUNCT": 0.0138, "tp1n1=PUNCT+S": -0.3554, "tp1n1=PUNCT+W": -0.828, "tp1n1=S+PREP": 0.0226, "tp1n1=S+PUNCT": -0.8279, "tp1n1=S+S": 0.278, "tp1n1=TO+CONJ": 0.6379, "tp1n1=TO+PREP": 0.3896, "tp1n1=W+CONJ": 0.1217, "tp1n1=W+DET": -0.2229, "tp1n1=W+PREP": -0.172, "tp1n1=W+PUNCT": -1.2626, "tp1n1=W+TO": 0.0798, "tp2=<s>": -0.4257, "tp2=ADV": 0.4309, "tp2=BE": -0.5828, "tp2=CAP": 0.1227, "tp2=CONJ": 0.3637, "tp2=DET": -1.5678, "tp2=DO": 0.9146, "tp2=ED": -0.3802, "tp2=HAVE": -0.3374, "tp2=ING": -0.4404, "tp2=MODAL": 2.9652, "tp2=NUM": -0.994, "tp2=PREP": -0.4665, "tp2=PUNCT": -0.0086, "tp2=S": 0.6809, "tp2=SUBJ": 0.7849, "tp2=TO": 1.1335, "tp2=W": -0.0177, "tp2p1=<s>+<s>": -0.0558, "tp2p1=<s>+S": 2.2948, "tp2p1=ADV+PREP": 2.5939, "tp2p1=BE+ADV": -0.1237, "tp2p1=CAP+CAP": 0.0169, "tp2p1=CAP+S": -0.6684, "tp2p1=CONJ+CAP": 0.8386, "tp2p1=DET+ADV": -1.5337, "tp2p1=DET+LY": -0.051, "tp2p1=DET+PUNCT": -1.2407, "tp2p1=DET+S": 1.4817, "tp2p1=DET+W": 0.8899, "tp2p1=DO+NEG": 3.196, "tp2p1=HAVE+W": -0.4077, "tp2p1=POSS+S": 0.2465, "tp2p1=PREP+CAP": -0.0257, "tp2p1=PREP+DET": -0.7828, "tp2p1=PUNCT+DET": 0.6797, "tp2p1=PUNCT+W": -0.1968, "tp2p1=S+ADV": 1.7247, "tp2p1=S+DET": 2.1968, "tp2p1=S+LY": 0.3408, "tp2p1=SUBJ+BE": -0.0894, "tp2p1=TO+DET": -0.185, "tp2p1=TO+LY": 0.2195, "tp2p1=W+PUNCT": -0.6525, "tp2p1=W+TO": -0.4806, "tp2p1=W+W": -0.3634}}, "words": {"abstract": {"model": {"bias": -1.4232, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "adj-nou", "phones": "ˈæ b s t ɹ æ k t", "role": "n"}, {"id": "vrb", "phones": "æ b s t ɹ ˈæ k t", "role": "v"}]}, "abuse": {"model": {"bias": -0.2386, "kind": "noun-verb", "weights": {"tn1=PREP": -0.0354, "w=of": -0.125}}, "senses": [{"id": "nou", "phones": "ɐ b j ˈuː s", "role": "n"}, {"id": "vrb", "phones": "ɐ b j ˈuː z", "role": "v"}]}, "abuses": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1=CAP": 0.4892, "tn1=PREP": -0.1999, "tp1=S": -0.7026, "w=her": 0.8644, "w=in": -2.7782, "w=of": -0.2066, "w=on": 0.5553}}, "senses": [{"id": "nou", "phones": "ɐ b j ˈuː s ᵻ z", "role": "n"}, {"id": "vrb", "phones": "ɐ b j ˈuː z ᵻ z", "role": "v"}]}, "addict": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ˈæ d ɪ k t", "role": "n"}, {"id": "vrb", "phones": "ɐ d ˈɪ k t", "role": "v"}]}, "advocate": {"model": {"bias": 0.4232, "kind": "noun-verb", "weights": {"n1=for": 0.7444, "n1=of": -0.4639, "tn1=W": 0.4732, "tp2p1=W+CONJ": 1.0504, "w=such": 0.286}}, "senses": [{"id": "nou", "phones": "ˈæ d v ə k ə t", "role": "n"}, {"id": "vrb", "phones": "ˈæ d v ə k ˌeɪ t", "role": "v"}]}, "affect": {"model": {"bias": [0.0, 2.1135], "kind": "senses", "weights": [{}, {"tn1=DET": 0.8624, "tn1=W": 0.9653, "tn2=W": 1.32, "w=positive": -1.064, "w=processing": -1.0641, "w=to": -0.5173, "w=with": -1.5969}]}, "senses": [{"id": "nou-psy", "phones": "ˈæ f ɛ k t", "role": "o"}, {"id": "affect", "phones": "ɐ f ˈɛ k t", "role": "o"}]}, "affiliate": {"model": {"bias": -0.2702, "kind": "noun-verb", "weights": {"tn1=CAP": -0.0366, "tp1=CAP": -1.4108}}, "senses": [{"id": "nou", "phones": "ɐ f ˈɪ l ɪ ə t", "role": "n"}, {"id": "vrb", "phones": "ɐ f ˈɪ l ɪ ˌeɪ t", "role": "v"}]}, "aged": {"model": {"bias": [0.0, 1.8989], "kind": "senses", "weights": [{}, {"p2=,": -0.4261, "tn1=NUM": 1.8997, "tn2=W": -1.6882, "tp1=PUNCT": 1.0739, "tp2=PUNCT": -0.0192}]}, "senses": [{"id": "adj", "phones": "ˈeɪ dʒ ɪ d", "role": "n"}, {"id": "aged", "phones": "ˈeɪ dʒ d", "role": "o"}]}, "aggregate": {"model": {"bias": 0.1582, "kind": "noun-verb", "weights": {"tn1=PREP": 0.0221, "tn1=PUNCT": 1.6356, "w=on": -0.6165}}, "senses": [{"id": "adj-nou", "phones": "ˈæ ɡ ɹ ə ɡ ə t", "role": "n"}, {"id": "vrb", "phones": "ˈæ ɡ ɹ ə ɡ eɪ t", "role": "v"}]}, "alternate": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1=PREP": 1.9202, "tn1=S": -0.5842, "tn1=W": -0.5308}}, "senses": [{"id": "adj-nou", "phones": "ˈɔː l t ɚ n ə t", "role": "n"}, {"id": "vrb", "phones": "ˈɔː l t ɚ n ˌeɪ t", "role": "v"}]}, "analyses": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1=PREP": -0.0544, "tn1=W": 0.2106, "tn2=S": 0.4328, "tp1=W": 0.0076, "tp2p1=PUNCT+DET": 0.1538, "w=and": 0.5906, "w=of": -0.9975, "w=the": 1.9568, "w=to": -1.303}}, "senses": [{"id": "nou", "phones": "ɐ n ˈæ l ɪ s ˌiː z", "role": "n"}, {"id": "vrb", "phones": "ˈæ n ə l ˌaɪ z ᵻ z", "role": "v"}]}, "animate": {"model": {"bias": 0.756, "kind": "noun-verb", "weights": {"n2=.": 0.2447, "tp1n1=PUNCT+PUNCT": 2.8412, "tp2=CONJ": 0.2856, "w=and": 1.4201, "w=inanimate": -1.0124, "w=nouns": -2.7755, "w=the": 0.0564}}, "senses": [{"id": "adj-nou", "phones": "ˈæ n ɪ m ə t", "role": "n"}, {"id": "vrb", "phones": "ˈæ n ɪ m ˌeɪ t", "role": "v"}]}, "appropriate": {"model": {"bias": -1.2222, "kind": "noun-verb", "weights": {"w=and": -0.6521, "w=the": -0.4891}}, "senses": [{"id": "adj", "phones": "ɐ p ɹ ˈoʊ p ɹ ɪ ə t", "role": "n"}, {"id": "vrb", "phones": "ɐ p ɹ ˈoʊ p ɹ ɪ ˌeɪ t", "role": "v"}]}, "approximate": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"w=to": 0.5854}}, "senses": [{"id": "adj-nou", "phones": "ɐ p ɹ ˈɑː k s ɪ m ə t", "role": "n"}, {"id": "vrb", "phones": "ɐ p ɹ ˈɑː k s ɪ m ˌeɪ t", "role": "v"}]}, "articulate": {"model": {"bias": 0.2485, "kind": "noun-verb", "weights": {"tn1=DET": 1.5659, "tn2=S": 0.1389, "tp1=W": 0.938, "tp2=DET": 0.3182, "w=rather": 1.1517, "w=the": 0.1256, "w=to": 1.4538}}, "senses": [{"id": "adj", "phones": "ɑːɹ t ˈɪ k j ʊ l ə t", "role": "n"}, {"id": "vrb", "phones": "ɑːɹ t ˈɪ k j ʊ l ˌeɪ t", "role": "v"}]}, "associate": {"model": {"bias": -0.0377, "kind": "noun-verb", "weights": {"p1=to": -0.0505, "tp1=TO": -0.0001, "w=to": -1.1947, "w=with": 3.3409}}, "senses": [{"id": "adj-nou", "phones": "ɐ s ˈoʊ s ɪ ə t", "role": "n"}, {"id": "vrb", "phones": "ɐ s ˈoʊ s ɪ ˌeɪ t", "role": "v"}]}, "attribute": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1=DET": 0.1997, "w=of": 0.6248, "w=people": 0.9925, "w=to": 2.9715}}, "senses": [{"id": "nou", "phones": "ˈæ t ɹ ɪ b j ˌuː t", "role": "n"}, {"id": "vrb", "phones": "ɐ t ɹ ˈɪ b j uː t", "role": "v"}]}, "august": {"model": {"bias": [-1.0989, 0.0, -0.9983], "kind": "senses", "weights": [{"cap": -3.3198}, {"cap": 2.0546, "p1=in": 0.2391, "tn1=CAP": -0.7363, "tn1=NUM": 0.9208, "tn1=PUNCT": 0.6581, "tn1=W": -1.6522, "tp1=CAP": -2.5493, "tp1=PREP": 0.8633, "tp1=W": -0.1918, "w=a": -0.5888, "w=to": 0.099}, {"cap": -0.9461, "p1=in": -0.3846, "tn1=CAP": 0.4667, "tn1=NUM": -0.3512, "tn1=PUNCT": -0.7681, "tn1=W": 0.2433, "tp1=CAP": 2.3558, "tp1=PREP": -0.7542, "tp1=W": 0.6002, "w=a": 0.5688, "w=is": 0.5984, "w=to": -0.1947}]}, "senses": [{"id": "adj", "phones": "ɔː ɡ ˈʌ s t", "role": "n"}, {"id": "august", "phones": "ˈɔː ɡ ə s t", "role": "o"}, {"id": "nam", "phones": "ˈaʊ ɡ ʊ s t", "role": "o"}]}, "axes": {"model": {"bias": [0.0, 0.0], "kind": "senses", "weights": [{}, {"n1=,": 1.9447, "n1=.": -0.0002, "n1=of": -0.9912, "n2=the": -0.4257, "p1=with": -0.5326, "tn1=CONJ": 1.6081, "tn1=PREP": -0.5018, "tn1n2=PUNCT+</s>": -0.3212, "tn1n2=W+PREP": 0.0485, "tn2=PREP": 0.1236, "tn2=PUNCT": -0.128, "tn2=W": -0.2739, "tp1=W": -0.0554, "tp1n1=W+PUNCT": -1.043, "tp2=PREP": -0.3958, "tp2p1=DET+W": -0.6666, "tp2p1=PUNCT+W": -0.0423, "w=a": -0.5673, "w=and": 0.4178, "w=are": -1.0853, "w=battle": 0.4046, "w=been": 1.1459, "w=found": 0.3953, "w=hand": 1.4434, "w=of": -0.0181, "w=stone": 0.7517, "w=three": -0.0084, "w=were": 0.4546, "w=with": -0.2894}]}, "senses": [{"id": "nou", "phones": "ˈæ k s iː z", "role": "n"}, {"id": "nou-vrb", "phones": "ˈæ k s ᵻ z", "role": "o"}]}, "bass": {"model": {"bias": [0.0, -2.463], "kind": "senses", "weights": [{}, {"cap": 0.4053, "n1=,": 1.0512, "tn1=W": -0.8322, "tn2=W": 3.7946, "tp1n1=W+PUNCT": 0.9143, "tp2p1=CONJ+W": 1.1261, "w=on": -0.2952}]}, "senses": [{"id": "bass", "phones": "b ˈeɪ s", "role": "o"}, {"id": "corp", "phones": "b ˈæ s", "role": "o"}]}, "blessed": {"model": {"bias": 3.8304, "kind": "noun-verb", "weights": {"tn1=CAP": -1.5734, "tn1=CONJ": 1.8327, "tn1=PREP": 3.4327, "tn1n2=CAP+CAP": -0.5754, "tn2=S": -0.3107, "tp1=BE": 0.335, "w=the": -0.4856}}, "senses": [{"id": "adj", "phones": "b l ˈɛ s ɪ d", "role": "n"}, {"id": "vrb", "phones": "b l ˈɛ s t", "role": "v"}]}, "bologna": {"model": {"bias": [0.0, 0.0], "kind": "senses", "weights": [{}, {"cap": -4.4773}]}, "senses": [{"id": "geo", "phones": "b ə l ˈoʊ n j ə", "role": "o"}, {"id": "bologna", "phones": "b ə l ˈoʊ n i", "role": "o"}]}, "bow": {"model": {"bias": [0.0, 0.0], "kind": "senses", "weights": [{}, {"cap": -1.1189, "n1=.": 0.1451, "n2=</s>": 0.166, "n2=stern": 0.8309, "n2=the": -0.1985, "p1=a": -0.8012, "p1=bulbous": 0.0001, "p1=the": 0.9125, "p2=,": -1.3116, "p2=in": 0.0408, "p2=of": -0.9055, "tn1=PUNCT": -0.832, "tn1=W": 1.1978, "tn1n2=PUNCT+</s>": 0.1795, "tn2=</s>": 0.3013, "tn2=ING": 0.7026, "tn2=PREP": -0.0871, "tn2=W": -0.0161, "tp1n1=DET+W": 0.0476, "tp1n1=W+PREP": 1.1761, "tp2p1=S+PREP": 0.1517, "tp2p1=W+DET": 1.1324, "w=a": 0.1062, "w=and": -0.1183, "w=arrow": -0.5654, "w=began": -0.145, "w=bulbous": 0.026, "w=by": -0.1991, "w=her": 1.2871, "w=stern": 0.1539, "w=to": 0.1322, "w=two": 0.171, "w=with": -0.5472}]}, "senses": [{"id": "nou-knot", "phones": "b ˈoʊ", "role": "o"}, {"id": "nou-ship", "phones": "b ˈaʊ", "role": "o"}]}, "buffet": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"cap": 1.535, "tn1=PUNCT": 2.016}}, "senses": [{"id": "nou", "phones": "b ə f ˈeɪ", "role": "n"}, {"id": "vrb", "phones": "b ˈʌ f ɪ t", "role": "v"}]}, "celtic": {"model": {"bias": [0.0, 0.0], "kind": "senses", "weights": [{}, {"n1=\"": -0.3944, "p1=for": -0.4006, "tn1=CAP": 1.3551, "tn1=PREP": -1.1369, "tn1=PUNCT": -0.092, "tn1=S": 1.0933, "tn1=W": 0.679, "tn1n2=PUNCT+</s>": -0.4472, "tn1n2=PUNCT+PUNCT": -0.3461, "tn1n2=S+W": -0.9009, "tn2=CONJ": 0.3047, "tn2=PUNCT": 0.8833, "tp1=DET": 0.2659, "tp1=PREP": -0.3465, "tp1n1=DET+W": 0.9212, "tp2=CAP": -0.6507, "tp2=DET": 0.3479, "w=as": -0.7458, "w=at": -0.2145, "w=his": -0.8049, "w=league": -0.9908, "w=of": 1.6415, "w=with": -0.1941}]}, "senses": [{"id": "adj-nou-sports", "phones": "s ˈɛ l t ɪ k", "role": "o"}, {"id": "celtic", "phones": "k ˈɛ l t ɪ k", "role": "o"}]}, "close": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"n1=.": 0.1493, "n1=to": -0.0028, "n2=</s>": 0.3607, "p1=the": 0.6636, "p2=at": 0.2526, "tn1=PREP": 0.2561, "tn1=TO": -0.5417, "tn1=W": -0.1547, "tn1n2=PREP+DET": 0.1611, "tn1n2=PUNCT+</s>": 0.1836, "tn2=</s>": 0.4755, "tp1=DET": 2.7533, "w=at": 3.6621}}, "senses": [{"id": "adj-nou", "phones": "k l ˈoʊ s", "role": "n"}, {"id": "vrb", "phones": "k l ˈoʊ z", "role": "v"}]}, "combine": {"model": {"bias": 4.8159, "kind": "noun-verb", "weights": {"tp1=DET": 0.5897}}, "senses": [{"id": "nou", "phones": "k ˈɑː m b aɪ n", "role": "n"}, {"id": "vrb", "phones": "k ə m b ˈaɪ n", "role": "v"}]}, "compact": {"model": {"bias": -1.4258, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "adj-nou", "phones": "k ˈɑː m p æ k t", "role": "n"}, {"id": "vrb", "phones": "k ə m p ˈæ k t", "role": "v"}]}, "compound": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1=DET": 0.307}}, "senses": [{"id": "nou", "phones": "k ˈɑː m p aʊ n d", "role": "n"}, {"id": "vrb", "phones": "k ə m p ˈaʊ n d", "role": "v"}]}, "compress": {"model": {"bias": [0.0, 1.7188], "kind": "senses", "weights": [{}, {"cap": -0.7845, "p1=to": 0.1723, "tn1=DET": 0.6114, "tn2=W": 1.2931, "tp1=PUNCT": -0.1787, "tp1=TO": 0.9235, "w=and": 0.5191, "w=in": -0.3431}]}, "senses": [{"id": "nou", "phones": "k ˈɑː m p ɹ ɛ s", "role": "n"}, {"id": "compress", "phones": "k ə m p ɹ ˈɛ s", "role": "o"}]}, "conduct": {"model": {"bias": 0.887, "kind": "noun-verb", "weights": {"n2=,": 0.9176, "tn1=W": 2.0793, "tn2=PUNCT": 0.1754, "w=and": 0.4426, "w=to": 1.2826}}, "senses": [{"id": "nou", "phones": "k ˈɑː n d ə k t", "role": "n"}, {"id": "vrb", "phones": "k ə n d ˈʌ k t", "role": "v"}]}, "confines": {"model": {"bias": 0.7004, "kind": "noun-verb", "weights": {"p2=<s>": 0.2753, "tp2=<s>": 0.6297, "tp2p1=<s>+CAP": 0.6949, "w=a": 1.3904}}, "senses": [{"id": "nou", "phones": "k ˈɑː n f aɪ n z", "role": "n"}, {"id": "vrb", "phones": "k ə n f ˈaɪ n z", "role": "v"}]}, "conflict": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "k ˈɑː n f l ɪ k t", "role": "n"}, {"id": "vrb", "phones": "k ə n f l ˈɪ k t", "role": "v"}]}, "conglomerate": {"model": {"bias": -1.3141, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "adj-nou", "phones": "k ə ŋ ɡ l ˈɑː m ɚ ɹ ə t", "role": "n"}, {"id": "vrb", "phones": "k ə ŋ ɡ l ˈɑː m ɚ ɹ ˌeɪ t", "role": "v"}]}, "conjugate": {"model": {"bias": -0.3299, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "adj-nou", "phones": "k ˈɑː n dʒ ə ɡ ə t", "role": "n"}, {"id": "vrb", "phones": "k ˈɑː n dʒ ə ɡ ˌeɪ t", "role": "v"}]}, "conscript": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn2=PUNCT": -0.1715}}, "senses": [{"id": "nou", "phones": "k ˈɑː n s k ɹ ɪ p t", "role": "n"}, {"id": "vrb", "phones": "k ə n s k ɹ ˈɪ p t", "role": "v"}]}, "console": {"model": {"bias": -0.3017, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "k ˈɑː n s oʊ l", "role": "n"}, {"id": "vrb", "phones": "k ə n s ˈoʊ l", "role": "v"}]}, "consort": {"model": {"bias": -1.0312, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "k ˈɑː n s ɔːɹ t", "role": "n"}, {"id": "vrb", "phones": "k ə n s ˈɔːɹ t", "role": "v"}]}, "construct": {"model": {"bias": 2.9231, "kind": "noun-verb", "weights": {"tn1=S": 0.4748}}, "senses": [{"id": "nou", "phones": "k ˈɑː n s t ɹ ə k t", "role": "n"}, {"id": "vrb", "phones": "k ə n s t ɹ ˈʌ k t", "role": "v"}]}, "consummate": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"p2=and": 0.4225, "tp1=CAP": 0.8112, "tp2p1=CONJ+CAP": 0.5906, "w=that": 0.1432}}, "senses": [{"id": "adj", "phones": "k ˈɑː n s ə m ə t", "role": "n"}, {"id": "vrb", "phones": "k ˈɑː n s ə m ˌeɪ t", "role": "v"}]}, "content": {"model": {"bias": [0.0, 3.7839], "kind": "senses", "weights": [{}, {"tp1=W": 0.0003}]}, "senses": [{"id": "adj-nou-vrb", "phones": "k ə n t ˈɛ n t", "role": "o"}, {"id": "nou", "phones": "k ˈɑː n t ɛ n t", "role": "n"}]}, "contest": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tp2=W": 0.3988, "w=to": 0.0215}}, "senses": [{"id": "nou", "phones": "k ˈɑː n t ɛ s t", "role": "n"}, {"id": "vrb", "phones": "k ə n t ˈɛ s t", "role": "v"}]}, "contract": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"w=a": -0.5108, "w=and": 0.4768}}, "senses": [{"id": "nou", "phones": "k ˈɑː n t ɹ æ k t", "role": "n"}, {"id": "vrb", "phones": "k ə n t ɹ ˈæ k t", "role": "v"}]}, "contrast": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "k ˈɑː n t ɹ æ s t", "role": "n"}, {"id": "vrb", "phones": "k ə n t ɹ ˈæ s t", "role": "v"}]}, "converse": {"model": {"bias": 1.1591, "kind": "noun-verb", "weights": {"n1=.": 0.0093, "n2=</s>": 0.0138, "tn1=PREP": 1.8614, "tn1=PUNCT": 0.6872, "tn1n2=PUNCT+</s>": 0.0335, "tp1=W": 1.4599, "tp2=W": 0.9733, "w=and": 0.3024}}, "senses": [{"id": "adj-nou", "phones": "k ˈɑː n v ɚ s", "role": "n"}, {"id": "vrb", "phones": "k ə n v ˈɜː s", "role": "v"}]}, "convert": {"model": {"bias": 2.8394, "kind": "noun-verb", "weights": {"tp1=CAP": -1.706, "tp2=S": 0.8561, "w=a": -0.235, "w=into": 1.0107, "w=to": 0.647}}, "senses": [{"id": "nou", "phones": "k ˈɑː n v ɚ t", "role": "n"}, {"id": "vrb", "phones": "k ə n v ˈɜː t", "role": "v"}]}, "convict": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "k ˈɑː n v ɪ k t", "role": "n"}, {"id": "vrb", "phones": "k ə n v ˈɪ k t", "role": "v"}]}, "coordinate": {"model": {"bias": 1.2383, "kind": "noun-verb", "weights": {"tn1=PUNCT": 0.4302, "w=and": 1.7973, "w=helped": 0.5834, "w=to": 0.3208}}, "senses": [{"id": "adj-nou", "phones": "k oʊ ˈɔːɹ d ɪ n ə t", "role": "n"}, {"id": "vrb", "phones": "k oʊ ˈɔːɹ d ɪ n ˌeɪ t", "role": "v"}]}, "correlate": {"model": {"bias": [0.0, 0.847], "kind": "senses", "weights": [{}, {"n1=in": -1.5399, "n1=with": 0.9018, "p1=neural": -0.0085, "tn1=W": 0.5253, "tp1=W": -1.1368, "w=neural": -0.5861, "w=not": 0.2444, "w=to": 2.0844, "w=with": 1.7693}]}, "senses": [{"id": "nou", "phones": "k ˈɔː ɹ əl ə t", "role": "n"}, {"id": "nou-vrb", "phones": "k ˈɔː ɹ ə l ˌeɪ t", "role": "o"}]}, "decrease": {"model": {"bias": 1.8055, "kind": "noun-verb", "weights": {"n1=in": -0.0154, "tn1=W": 0.6988, "tp2=W": 0.2771, "w=and": 1.2818, "w=pressure": 0.5654}}, "senses": [{"id": "nou", "phones": "d ˈiː k ɹ iː s", "role": "n"}, {"id": "vrb", "phones": "d ᵻ k ɹ ˈiː s", "role": "v"}]}, "defect": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1=PUNCT": 0.4175, "tp1=W": -0.4394, "w=to": 1.3903}}, "senses": [{"id": "nou", "phones": "d ˈiː f ɛ k t", "role": "n"}, {"id": "vrb", "phones": "d ᵻ f ˈɛ k t", "role": "v"}]}, "degenerate": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tp1=S": 3.1339}}, "senses": [{"id": "adj-nou", "phones": "d ᵻ dʒ ˈɛ n ɚ ɹ ə t", "role": "n"}, {"id": "vrb", "phones": "d ᵻ dʒ ˈɛ n ɚ ɹ ˌeɪ t", "role": "v"}]}, "delegate": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "d ˈɛ l ə ɡ ə t", "role": "n"}, {"id": "vrb", "phones": "d ˈɛ l ə ɡ ˌeɪ t", "role": "v"}]}, "deliberate": {"model": {"bias": -0.8233, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "adj", "phones": "d ᵻ l ˈɪ b ɚ ɹ ə t", "role": "n"}, {"id": "vrb", "phones": "d ᵻ l ˈɪ b ɚ ɹ ˌeɪ t", "role": "v"}]}, "desert": {"model": {"bias": -2.3, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "d ˈɛ z ɚ t", "role": "n"}, {"id": "vrb", "phones": "d ᵻ z ˈɜː t", "role": "v"}]}, "deviate": {"model": {"bias": 4.456, "kind": "noun-verb", "weights": {"tn1=PREP": 2.2926}}, "senses": [{"id": "nou", "phones": "d ˈiː v ɪ ə t", "role": "n"}, {"id": "vrb", "phones": "d ˈiː v ɪ ˌeɪ t", "role": "v"}]}, "diagnoses": {"model": {"bias": 0.5346, "kind": "noun-verb", "weights": {"tn2=PREP": 0.9903, "tp2=DET": 0.0485, "tp2=S": 0.0895, "tp2=W": -0.21}}, "senses": [{"id": "nou", "phones": "d aɪə ɡ n ˈoʊ s i z", "role": "n"}, {"id": "vrb", "phones": "d aɪə ɡ n ˈoʊ s ᵻ z", "role": "v"}]}, "diffuse": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"n2=the": 0.8518, "tn1=PREP": 1.7933, "tn1=W": -0.7432, "w=its": -0.8957, "w=membranes": 0.8939, "w=to": 2.1772}}, "senses": [{"id": "adj", "phones": "d ɪ f j ˈuː s", "role": "n"}, {"id": "vrb", "phones": "d ɪ f j ˈuː z", "role": "v"}]}, "discard": {"model": {"bias": 3.2689, "kind": "noun-verb", "weights": {"tp1=PUNCT": 1.6935}}, "senses": [{"id": "nou", "phones": "d ˈɪ s k ɑːɹ d", "role": "n"}, {"id": "vrb", "phones": "d ɪ s k ˈɑːɹ d", "role": "v"}]}, "discharge": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"p1=and": 0.0457, "w=and": 0.6339, "w=sea": 1.0031, "w=the": 0.647, "w=to": 0.5898}}, "senses": [{"id": "nou", "phones": "d ˈɪ s tʃ ɑːɹ dʒ", "role": "n"}, {"id": "vrb", "phones": "d ɪ s tʃ ˈɑːɹ dʒ", "role": "v"}]}, "discount": {"model": {"bias": -1.0279, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "d ˈɪ s k aʊ n t", "role": "n"}, {"id": "vrb", "phones": "d ɪ s k ˈaʊ n t", "role": "v"}]}, "document": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1=S": 0.2065, "w=to": 1.7204}}, "senses": [{"id": "nou", "phones": "d ˈɑː k j ʊ m ə n t", "role": "n"}, {"id": "vrb", "phones": "d ˈɑː k j ʊ m ˌɛ n t", "role": "v"}]}, "dove": {"model": {"bias": [0.0, -1.6196], "kind": "senses", "weights": [{}, {"tn1=PREP": 1.9864, "tn1=PUNCT": -0.2724, "tn1n2=PREP+DET": 0.3933, "tp1=DET": -0.847, "tp1=PUNCT": -0.1945, "w=the": -0.7337}]}, "senses": [{"id": "dove", "phones": "d ˈʌ v", "role": "o"}, {"id": "vrb", "phones": "d ˈoʊ v", "role": "v"}]}, "duplicate": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn2=S": -0.369, "w=and": -0.4913, "w=the": -0.5299}}, "senses": [{"id": "adj-nou", "phones": "d ˈuː p l ɪ k ə t", "role": "n"}, {"id": "vrb", "phones": "d ˈuː p l ɪ k ˌeɪ t", "role": "v"}]}, "elaborate": {"model": {"bias": -1.7982, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "adj", "phones": "ɪ l ˈæ b ɚ ɹ ə t", "role": "n"}, {"id": "vrb", "phones": "ɪ l ˈæ b ɚ ɹ ˌeɪ t", "role": "v"}]}, "entrance": {"model": {"bias": -0.0253, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ˈɛ n t ɹ ə n s", "role": "n"}, {"id": "vrb", "phones": "ɛ n t ɹ ˈæ n s", "role": "v"}]}, "escort": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"w=to": 0.2512}}, "senses": [{"id": "nou", "phones": "ˈɛ s k ɔːɹ t", "role": "n"}, {"id": "vrb", "phones": "ɛ s k ˈɔːɹ t", "role": "v"}]}, "estimate": {"model": {"bias": 0.8174, "kind": "noun-verb", "weights": {"n1=of": -0.0954, "w=and": 0.9096, "w=million": 0.0228}}, "senses": [{"id": "nou", "phones": "ˈɛ s t ɪ m ə t", "role": "n"}, {"id": "vrb", "phones": "ˈɛ s t ɪ m ˌeɪ t", "role": "v"}]}, "excuse": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ɛ k s k j ˈuː s", "role": "n"}, {"id": "vrb", "phones": "ɛ k s k j ˈuː z", "role": "v"}]}, "expatriate": {"model": {"bias": -0.8968, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ɛ k s p ˈeɪ t ɹ ɪ ə t", "role": "n"}, {"id": "vrb", "phones": "ɛ k s p ˈeɪ t ɹ ɪ ˌeɪ t", "role": "v"}]}, "exploit": {"model": {"bias": 2.292, "kind": "noun-verb", "weights": {"tn1=W": 1.4139}}, "senses": [{"id": "nou", "phones": "ˈɛ k s p l ɔɪ t", "role": "n"}, {"id": "vrb", "phones": "ɛ k s p l ˈɔɪ t", "role": "v"}]}, "export": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn2=CAP": 1.1816, "w=to": 1.5427}}, "senses": [{"id": "nou", "phones": "ˈɛ k s p oːɹ t", "role": "n"}, {"id": "vrb", "phones": "ɛ k s p ˈoːɹ t", "role": "v"}]}, "expose": {"model": {"bias": 4.8197, "kind": "noun-verb", "weights": {"tn1=S": 1.2553}}, "senses": [{"id": "nou", "phones": "ˌɛ k s p oʊ z ˈeɪ", "role": "n"}, {"id": "vrb", "phones": "ɛ k s p ˈoʊ z", "role": "v"}]}, "extract": {"model": {"bias": 1.2617, "kind": "noun-verb", "weights": {"tn1=S": 0.8543, "w=to": 0.3602}}, "senses": [{"id": "nou", "phones": "ˈɛ k s t ɹ æ k t", "role": "n"}, {"id": "vrb", "phones": "ɛ k s t ɹ ˈæ k t", "role": "v"}]}, "fragment": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "f ɹ ˈæ ɡ m ə n t", "role": "n"}, {"id": "vrb", "phones": "f ɹ æ ɡ m ˈɛ n t", "role": "v"}]}, "frequent": {"model": {"bias": -1.3123, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "adj", "phones": "f ɹ ˈiː k w ə n t", "role": "n"}, {"id": "vrb", "phones": "f ɹ ɪ k w ˈɛ n t", "role": "v"}]}, "graduate": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1=W": -1.4364, "tn2=PREP": -0.0919, "w=and": -0.2704}}, "senses": [{"id": "adj-nou", "phones": "ɡ ɹ ˈæ dʒ uː ə t", "role": "n"}, {"id": "vrb", "phones": "ɡ ɹ ˈæ dʒ uː ˌeɪ t", "role": "v"}]}, "house": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "h ˈaʊ s", "role": "n"}, {"id": "vrb", "phones": "h ˈaʊ z", "role": "v"}]}, "impact": {"model": {"bias": -0.4225, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ˈɪ m p æ k t", "role": "n"}, {"id": "vrb", "phones": "ɪ m p ˈæ k t", "role": "v"}]}, "implant": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"w=others": 0.3373}}, "senses": [{"id": "nou", "phones": "ˈɪ m p l æ n t", "role": "n"}, {"id": "vrb", "phones": "ɪ m p l ˈæ n t", "role": "v"}]}, "implement": {"model": {"bias": 2.4252, "kind": "noun-verb", "weights": {"tn1=W": 0.2051, "w=and": 0.5111}}, "senses": [{"id": "nou", "phones": "ˈɪ m p l ə m ə n t", "role": "n"}, {"id": "vrb", "phones": "ˈɪ m p l ə m ˌɛ n t", "role": "v"}]}, "import": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"w=from": 0.0728, "w=to": 0.8431}}, "senses": [{"id": "nou", "phones": "ˈɪ m p oːɹ t", "role": "n"}, {"id": "vrb", "phones": "ɪ m p ˈoːɹ t", "role": "v"}]}, "incense": {"model": {"bias": -2.2693, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ˈɪ n s ɛ n s", "role": "n"}, {"id": "vrb", "phones": "ɪ n s ˈɛ n s", "role": "v"}]}, "incline": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1n2=TO+W": 1.5038, "tp1=W": 1.2796}}, "senses": [{"id": "nou", "phones": "ˈɪ ŋ k l aɪ n", "role": "n"}, {"id": "vrb", "phones": "ɪ ŋ k l ˈaɪ n", "role": "v"}]}, "increase": {"model": {"bias": 1.672, "kind": "noun-verb", "weights": {"tn1=PREP": -0.3878, "tn1=W": 1.3402, "tn2=W": 0.5638, "tp2=W": 0.7385, "w=and": 0.1276}}, "senses": [{"id": "nou", "phones": "ˈɪ ŋ k ɹ iː s", "role": "n"}, {"id": "vrb", "phones": "ɪ ŋ k ɹ ˈiː s", "role": "v"}]}, "increment": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"p1=then": 0.8303, "tp1=ADV": 0.3399, "tp2p1=S+S": 0.6282, "w=then": 0.6473}}, "senses": [{"id": "nou", "phones": "ˈɪ ŋ k ɹ ə m ə n t", "role": "n"}, {"id": "vrb", "phones": "ˈɪ ŋ k ɹ ə m ˌɛ n t", "role": "v"}]}, "initiate": {"model": {"bias": 3.3647, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ɪ n ˈɪ ʃ ɪ ə t", "role": "n"}, {"id": "vrb", "phones": "ɪ n ˈɪ ʃ ɪ ˌeɪ t", "role": "v"}]}, "insert": {"model": {"bias": 2.6477, "kind": "noun-verb", "weights": {"cap": 3.3561, "n1=,": 1.7937, "p1=,": 0.131, "tp1=CAP": -0.6906, "tp1=PUNCT": 0.1015, "w=a": -0.9248, "w=and": 0.2643, "w=are": 0.3226, "w=is": -0.8648, "w=or": 0.9148}}, "senses": [{"id": "nou", "phones": "ˈɪ n s ɜː t", "role": "n"}, {"id": "vrb", "phones": "ɪ n s ˈɜː t", "role": "v"}]}, "instrument": {"model": {"bias": -1.5123, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ˈɪ n s t ɹ ə m ə n t", "role": "n"}, {"id": "vrb", "phones": "ˈɪ n s t ɹ ə m ˌɛ n t", "role": "v"}]}, "insult": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1=CAP": 0.7639, "w=to": 0.245}}, "senses": [{"id": "nou", "phones": "ˈɪ n s ʌ l t", "role": "n"}, {"id": "vrb", "phones": "ɪ n s ˈʌ l t", "role": "v"}]}, "interchange": {"model": {"bias": -0.1171, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ˈɪ n t ɚ tʃ ˌeɪ n dʒ", "role": "n"}, {"id": "vrb", "phones": "ˌɪ n t ɚ tʃ ˈeɪ n dʒ", "role": "v"}]}, "intimate": {"model": {"bias": -1.2482, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "adj", "phones": "ˈɪ n t ɪ m ə t", "role": "n"}, {"id": "vrb", "phones": "ˈɪ n t ɪ m ˌeɪ t", "role": "v"}]}, "intrigue": {"model": {"bias": [0.0, -2.2022], "kind": "senses", "weights": [{}, {"p1=to": 0.4253, "tn1=PUNCT": -1.3016, "tn2=PUNCT": 1.7017, "tp1=TO": 1.4468, "tp1=W": -0.3776, "tp2=DET": 0.1606, "w=of": -1.0977}]}, "senses": [{"id": "nou", "phones": "ˈɪ n t ɹ ɪ ɡ", "role": "n"}, {"id": "nou-vrb", "phones": "ɪ n t ɹ ˈiː ɡ", "role": "o"}]}, "invalid": {"model": {"bias": [0.0, -2.2695], "kind": "senses", "weights": [{}, {"cap": 0.5383, "n2=the": 0.227, "p2=a": 1.4097, "tn2=W": -0.6494, "tp1=BE": -0.5924, "tp1=DET": 2.9202, "tp1=POSS": 0.0335, "tp1n1=DET+PREP": 0.5838, "tp1n1=DET+PUNCT": 0.9869, "tp1n1=DET+W": -1.4506, "tp1n1=POSS+W": 0.7722, "tp2=W": 0.226, "tp2p1=W+POSS": 0.695, "w=he": 0.0229, "w=her": 0.203, "w=to": 0.5427}]}, "senses": [{"id": "adj", "phones": "ɪ n v ˈæ l ɪ d", "role": "n"}, {"id": "nou", "phones": "ˈɪ n v əl ɪ d", "role": "n"}]}, "invert": {"model": {"bias": 2.5922, "kind": "noun-verb", "weights": {"cap": 0.5552, "n1=sugar": -0.9297, "tp1=PUNCT": 0.8629, "tp2=W": 0.5131, "w=a": -0.7931, "w=as": 0.8548, "w=of": 1.6477, "w=sugar": -0.5558}}, "senses": [{"id": "adj-nou", "phones": "ˈɪ n v ɚ t", "role": "n"}, {"id": "vrb", "phones": "ɪ n v ˈɜː t", "role": "v"}]}, "invite": {"model": {"bias": 2.2544, "kind": "noun-verb", "weights": {"tn1=W": 0.8134, "tn2=S": 0.2035, "tn2=W": -0.0514, "w=and": 0.2557}}, "senses": [{"id": "nou", "phones": "ˈɪ n v aɪ t", "role": "n"}, {"id": "vrb", "phones": "ɪ n v ˈaɪ t", "role": "v"}]}, "isolate": {"model": {"bias": [0.0, 0.0], "kind": "senses", "weights": [{}, {"p1=to": 0.9665, "p2=a": -0.0169, "tn1=DET": 1.3071, "tn1=PREP": -0.1644, "tn1=S": 0.3905, "tn2=S": 0.393, "tn2=W": 0.4537, "tp1=TO": 0.0843, "tp1=W": -2.5788, "tp2=DET": -1.1791, "tp2=W": 0.5774, "w=from": 0.2089, "w=in": 0.3103, "w=they": 0.4931, "w=to": 2.0333, "w=with": -0.0693}]}, "senses": [{"id": "nou", "phones": "ˈaɪ s əl ə t", "role": "n"}, {"id": "isolate", "phones": "ˈaɪ s ə l ˌeɪ t", "role": "o"}]}, "jesus": {"model": {"bias": [0.0, -3.7371], "kind": "senses", "weights": [{}, {"tp1n1=W+CAP": 2.0292, "w=for": 1.3986, "w=of": -0.1475}]}, "senses": [{"id": "jesus", "phones": "dʒ ˈiː z ə s", "role": "o"}, {"id": "es", "phones": "h eɪ s ˈuː s", "role": "o"}]}, "job": {"model": {"bias": [0.0, 1000000.0], "kind": "senses", "weights": [{}, {}]}, "senses": [{"id": "bible", "phones": "dʒ ˈoʊ b", "role": "o"}, {"id": "job", "phones": "dʒ ˈɑː b", "role": "o"}]}, "laminate": {"model": {"bias": -0.3864, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "l ˈæ m ɪ n ə t", "role": "n"}, {"id": "vrb", "phones": "l ˈæ m ɪ n ˌeɪ t", "role": "v"}]}, "lead": {"model": {"bias": [0.0, 1.2397], "kind": "senses", "weights": [{}, {"first": -0.0302, "n1=roles": 0.0475, "n1=to": 1.244, "p1=<s>": -0.0211, "p1=the": 1.5303, "tn1=BE": -3.0491, "tn1=DET": 0.4039, "tn1=ED": -0.0013, "tn1=TO": 0.0953, "tn1=W": 0.7875, "tn2=PUNCT": 0.8273, "tn2=W": 0.1367, "tp1=<s>": -0.1429, "tp1=PREP": -0.5247, "tp1n1=CAP+PUNCT": -1.6296, "tp2=DET": 0.0248, "tp2=PREP": 0.2708, "tp2p1=<s>+<s>": -0.0138, "w=of": -1.4478, "w=red": -0.3899, "w=roles": 0.0134, "w=the": 0.2734, "w=to": 0.5064, "w=were": -0.2525}]}, "senses": [{"id": "nou", "phones": "l ˈɛ d", "role": "n"}, {"id": "nou-vrb", "phones": "l ˈiː d", "role": "o"}]}, "learned": {"model": {"bias": 5.3875, "kind": "noun-verb", "weights": {"tn1=S": -0.0131, "tn1=W": 0.237, "tn1n2=S+PREP": -0.0747, "tp1=DET": 1.5177, "w=and": -0.6358, "w=it": 0.235, "w=the": 0.558}}, "senses": [{"id": "adj", "phones": "l ˈɜː n ɪ d", "role": "n"}, {"id": "vrb", "phones": "l ˈɜː n d", "role": "v"}]}, "live": {"model": {"bias": 0.5332, "kind": "noun-verb", "weights": {"n1=in": 2.1724, "tn1=LY": 0.0986, "tn1=PREP": 0.4525, "tn1=W": -0.3904, "tn2=PREP": -0.2527, "tn2=W": 0.0514, "tp2=CAP": 0.1566, "w=in": 1.8919, "w=two": 0.9876}}, "senses": [{"id": "adj", "phones": "l ˈaɪ v", "role": "n"}, {"id": "vrb", "phones": "l ˈɪ v", "role": "v"}]}, "lives": {"model": {"bias": 2.4926, "kind": "noun-verb", "weights": {"n1=in": 1.099, "n1=on": 0.3569, "p2=<s>": 0.1897, "tn1=PREP": 0.9524, "tp2=<s>": 0.6529, "tp2=DET": 2.5636, "tp2=S": -0.5611, "w=in": 0.6375, "w=of": -0.5849, "w=sisters": -0.4628, "w=their": -0.6091, "w=where": 0.4337, "w=with": 0.3457}}, "senses": [{"id": "nou", "phones": "l ˈaɪ v z", "role": "n"}, {"id": "vrb", "phones": "l ˈɪ v z", "role": "v"}]}, "mate": {"model": {"bias": [0.0, 3.7842], "kind": "senses", "weights": [{}, {}]}, "senses": [{"id": "nou", "phones": "m ˈɑː t eɪ", "role": "n"}, {"id": "mate", "phones": "m ˈeɪ t", "role": "o"}]}, "minute": {"model": {"bias": [0.0, 2.3994], "kind": "senses", "weights": [{}, {"tn1=W": -0.7621, "tp1=PUNCT": 2.0219, "tp1=W": 0.9849, "tp1n1=DET+W": -0.9854, "tp1n1=PREP+W": -2.6316, "w=is": -1.3055, "w=the": 0.0011}]}, "senses": [{"id": "adj", "phones": "m aɪ n ˈuː t", "role": "n"}, {"id": "minute", "phones": "m ˈɪ n ɪ t", "role": "o"}]}, "misuse": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1=PREP": -0.7173, "tn1=W": 0.7709, "w=of": -0.5362}}, "senses": [{"id": "nou", "phones": "m ɪ s j ˈuː s", "role": "n"}, {"id": "vrb", "phones": "m ɪ s j ˈuː z", "role": "v"}]}, "mobile": {"model": {"bias": [3.3899, -3.3899, -1000000.0], "kind": "senses", "weights": [{"cap": -0.8729, "tn1=PUNCT": -0.228, "tn1=W": 0.2457, "tp1=PREP": -0.0274, "tp2=CAP": -1.0705, "w=of": -0.0162, "w=the": 0.0059}, {"cap": 0.8729, "tn1=PUNCT": 0.228, "tn1=W": -0.2457, "tp1=PREP": 0.0274, "tp2=CAP": 1.0705, "w=of": 0.0162, "w=the": -0.0059}, {}]}, "senses": [{"id": "mobile", "phones": "m ˈoʊ b əl", "role": "o"}, {"id": "geo", "phones": "m oʊ b ˈiː l", "role": "o"}, {"id": "nou-art", "phones": "m ˈoʊ b iː l", "role": "o"}]}, "moderate": {"model": {"bias": -2.0892, "kind": "noun-verb", "weights": {"tp2=W": -1.4834}}, "senses": [{"id": "adj-nou", "phones": "m ˈɑː d ɚ ɹ ə t", "role": "n"}, {"id": "vrb", "phones": "m ˈɑː d ɚ ɹ ˌeɪ t", "role": "v"}]}, "moped": {"model": {"bias": -0.6152, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "m ˈoʊ p ɛ d", "role": "n"}, {"id": "vrb", "phones": "m ˈoʊ p t", "role": "v"}]}, "mouth": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "m ˈaʊ θ", "role": "n"}, {"id": "vrb", "phones": "m ˈaʊ ð", "role": "v"}]}, "nestle": {"model": {"bias": [0.0, 0.821], "kind": "senses", "weights": [{}, {"cap": -4.8328, "p2=<s>": -0.4082, "tn1=PREP": 0.0083, "tn1n2=PREP+DET": 0.0343, "tp1=S": 0.1924, "tp2=<s>": -2.2373, "w=and": 0.1986}]}, "senses": [{"id": "nam", "phones": "n ˈɛ s l i", "role": "o"}, {"id": "vrb", "phones": "n ˈɛ s əl", "role": "v"}]}, "object": {"model": {"bias": -0.0958, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ˈɑː b dʒ ɛ k t", "role": "n"}, {"id": "vrb", "phones": "ə b dʒ ˈɛ k t", "role": "v"}]}, "ornament": {"model": {"bias": -0.605, "kind": "noun-verb", "weights": {"tp1=CONJ": -0.2638}}, "senses": [{"id": "nou", "phones": "ˈɔːɹ n ə m ə n t", "role": "n"}, {"id": "vrb", "phones": "ˈɔːɹ n ə m ˌɛ n t", "role": "v"}]}, "overthrow": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"w=and": 0.0392, "w=to": 2.3046}}, "senses": [{"id": "nou", "phones": "ˈoʊ v ɚ θ ɹ ˌoʊ", "role": "n"}, {"id": "vrb", "phones": "ˌoʊ v ɚ θ ɹ ˈoʊ", "role": "v"}]}, "pasty": {"model": {"bias": [0.0, 0.265], "kind": "senses", "weights": [{}, {"cap": 0.0961, "n2=.": -0.8336, "p1=the": 1.07, "tn1=W": -1.2005, "tn2=W": -0.731, "tp1=CAP": 2.3366, "tp1=DET": 1.4056, "tp1=PUNCT": 0.0692, "tp2=BE": -0.2509, "tp2=DET": 1.7276, "w=is": -0.1915, "w=products": -0.0998, "w=the": 0.401}]}, "senses": [{"id": "adj", "phones": "p ˈeɪ s t i", "role": "n"}, {"id": "nou", "phones": "p ˈæ s t i", "role": "n"}]}, "perfect": {"model": {"bias": -0.791, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "adj", "phones": "p ˈɜː f ɛ k t", "role": "n"}, {"id": "vrb", "phones": "p ɚ f ˈɛ k t", "role": "v"}]}, "perfume": {"model": {"bias": -0.1505, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "p ˈɜː f j uː m", "role": "n"}, {"id": "vrb", "phones": "p ɚ f j ˈuː m", "role": "v"}]}, "permit": {"model": {"bias": 1.6055, "kind": "noun-verb", "weights": {"tp1=S": 0.9875, "w=of": 0.1926}}, "senses": [{"id": "nou", "phones": "p ˈɜː m ɪ t", "role": "n"}, {"id": "vrb", "phones": "p ɚ m ˈɪ t", "role": "v"}]}, "pervert": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"w=the": 0.8871}}, "senses": [{"id": "nou", "phones": "p ˈɜː v ɚ t", "role": "n"}, {"id": "vrb", "phones": "p ɚ v ˈɜː t", "role": "v"}]}, "pigment": {"model": {"bias": -0.8014, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "p ˈɪ ɡ m ə n t", "role": "n"}, {"id": "vrb", "phones": "p ɪ ɡ m ˈɛ n t", "role": "v"}]}, "polish": {"model": {"bias": [0.0, 0.0], "kind": "senses", "weights": [{}, {"cap": -4.2652, "p2=<s>": -0.3353, "tn1=W": -0.3047, "tp2=<s>": -0.2069}]}, "senses": [{"id": "geo", "phones": "p ˈoʊ l ɪ ʃ", "role": "o"}, {"id": "polish", "phones": "p ˈɑː l ɪ ʃ", "role": "o"}]}, "postulate": {"model": {"bias": 0.5313, "kind": "noun-verb", "weights": {"tp1=S": 0.8861}}, "senses": [{"id": "nou", "phones": "p ˈɑː s tʃ əl ə t", "role": "n"}, {"id": "vrb", "phones": "p ˈɑː s tʃ ə l ˌeɪ t", "role": "v"}]}, "precipitate": {"model": {"bias": 1.6847, "kind": "noun-verb", "weights": {"tn1=W": 1.4355, "w=a": -0.5385, "w=and": 1.4685, "w=barium": 0.3849, "w=that": -1.2313}}, "senses": [{"id": "adj-nou", "phones": "p ɹ ɪ s ˈɪ p ɪ ɾ ə t", "role": "n"}, {"id": "vrb", "phones": "p ɹ ɪ s ˈɪ p ɪ t ˌeɪ t", "role": "v"}]}, "predicate": {"model": {"bias": -0.5296, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "p ɹ ˈɛ d ɪ k ə t", "role": "n"}, {"id": "vrb", "phones": "p ɹ ˈɛ d ɪ k ˌeɪ t", "role": "v"}]}, "present": {"model": {"bias": -0.3451, "kind": "noun-verb", "weights": {"w=in": -0.7651, "w=with": 0.9538}}, "senses": [{"id": "adj-nou", "phones": "p ɹ ˈɛ z ə n t", "role": "n"}, {"id": "vrb", "phones": "p ɹ ᵻ z ˈɛ n t", "role": "v"}]}, "produce": {"model": {"bias": 3.2498, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "p ɹ ˈoʊ d uː s", "role": "n"}, {"id": "vrb", "phones": "p ɹ ə d ˈuː s", "role": "v"}]}, "progress": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"n2=the": 0.6779, "tn1=PREP": -1.0081, "tn1=PUNCT": 0.2195, "tn2=DET": 1.6529, "tp1=S": 0.4983, "tp1n1=S+PUNCT": 2.3993, "w=as": 0.4898}}, "senses": [{"id": "nou", "phones": "p ɹ ˈɑː ɡ ɹ ɛ s", "role": "n"}, {"id": "vrb", "phones": "p ɹ ə ɡ ɹ ˈɛ s", "role": "v"}]}, "project": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "p ɹ ˈɑː dʒ ɛ k t", "role": "n"}, {"id": "vrb", "phones": "p ɹ ə dʒ ˈɛ k t", "role": "v"}]}, "protest": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "p ɹ ˈoʊ t ɛ s t", "role": "n"}, {"id": "vrb", "phones": "p ɹ ə t ˈɛ s t", "role": "v"}]}, "ravel": {"model": {"bias": [0.0, -2.4847], "kind": "senses", "weights": [{}, {"cap": -1.846}]}, "senses": [{"id": "nam", "phones": "ɹ ə v ˈɛ l", "role": "o"}, {"id": "nou", "phones": "ɹ ˈæ v əl", "role": "n"}]}, "read": {"model": {"bias": [0.0, 0.3195], "kind": "senses", "weights": [{}, {"cap": 1.1231, "n1=the": 0.2502, "n2=the": -0.4753, "n2=write": 0.1929, "p1=also": -0.5193, "p1=he": -0.049, "p1=to": 0.6309, "p2=,": -1.888, "tn1=DET": 0.4086, "tn1=PREP": -0.6246, "tn2=ADV": 1.6577, "tn2=CAP": -0.5068, "tn2=S": 0.4909, "tp1=BE": -1.9933, "tp1=MODAL": 1.342, "tp1=SUBJ": -1.2926, "tp1=TO": 1.4452, "tp1=W": 0.0334, "tp1n1=PUNCT+W": -0.5571, "tp2=BE": -0.8439, "tp2=MODAL": 0.8244, "tp2=PREP": 0.1362, "tp2p1=DO+NEG": 0.087, "tp2p1=SUBJ+ADV": -0.6786, "w=a": 0.0215, "w=and": 0.0657, "w=as": 0.2383, "w=be": -0.4351, "w=by": -0.139, "w=he": -0.4189, "w=its": 0.5206, "w=on": -0.6018, "w=the": -0.151, "w=to": 0.1999, "w=write": 0.11}]}, "senses": [{"id": "past", "phones": "ɹ ˈɛ d", "role": "o"}, {"id": "present", "phones": "ɹ ˈiː d", "role": "o"}]}, "reading": {"model": {"bias": [0.0, -3.5824], "kind": "senses", "weights": [{}, {"cap": 6.2904}]}, "senses": [{"id": "en", "phones": "ɹ ˈiː d ɪ ŋ", "role": "o"}, {"id": "geo", "phones": "ɹ ˈɛ d ɪ ŋ", "role": "o"}]}, "rebel": {"model": {"bias": -0.0121, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ɹ ˈɛ b əl", "role": "n"}, {"id": "vrb", "phones": "ɹ ᵻ b ˈɛ l", "role": "v"}]}, "record": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ɹ ˈɛ k ɚ d", "role": "n"}, {"id": "vrb", "phones": "ɹ ᵻ k ˈɔːɹ d", "role": "v"}]}, "recount": {"model": {"bias": 1.4237, "kind": "noun-verb", "weights": {"tn1n2=PREP+DET": 0.3032, "tp2=PREP": 1.75, "w=from": 0.1584, "w=he": 0.0186, "w=of": 1.8627}}, "senses": [{"id": "nou", "phones": "ɹ ˈiː k aʊ n t", "role": "n"}, {"id": "vrb", "phones": "ɹ ᵻ k ˈaʊ n t", "role": "v"}]}, "refund": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "ɹ ˈiː f ʌ n d", "role": "n"}, {"id": "vrb", "phones": "ɹ ᵻ f ˈʌ n d", "role": "v"}]}, "refuse": {"model": {"bias": 2.3718, "kind": "noun-verb", "weights": {"cap": 0.4878, "n1=to": 1.4828, "tn1=PUNCT": 0.7423, "tn1=TO": 1.5402, "tn1=W": -0.4851, "tn2=CAP": 0.4415, "tp1=PUNCT": 0.795, "w=the": 1.0147}}, "senses": [{"id": "nou", "phones": "ɹ ˈɛ f j uː s", "role": "n"}, {"id": "vrb", "phones": "ɹ ᵻ f j ˈuː z", "role": "v"}]}, "reject": {"model": {"bias": 3.7819, "kind": "noun-verb", "weights": {"tn2=CAP": 0.2139, "w=the": 0.2116}}, "senses": [{"id": "nou", "phones": "ɹ ˈiː dʒ ɛ k t", "role": "n"}, {"id": "vrb", "phones": "ɹ ᵻ dʒ ˈɛ k t", "role": "v"}]}, "rerelease": {"model": {"bias": [0.0, -2.1165], "kind": "senses", "weights": [{}, {"p1=to": 1.9787, "tn1=PREP": -0.6945, "tn1=PUNCT": -0.1691, "tp1=DET": -0.2498, "tp1=TO": 1.2617, "w=a": -0.1369, "w=the": -1.1077, "w=to": 2.0792}]}, "senses": [{"id": "rerelease", "phones": "ɹ ˈiə ɹ ə l ˌiː s", "role": "o"}, {"id": "vrb", "phones": "ɹ ˌiə ɹ ə l ˈiː s", "role": "v"}]}, "resume": {"model": {"bias": 3.202, "kind": "noun-verb", "weights": {"tn1=ING": 0.2006}}, "senses": [{"id": "nou", "phones": "ɹ ˈɛ z ə m ˌeɪ", "role": "n"}, {"id": "vrb", "phones": "ɹ ᵻ z ˈuː m", "role": "v"}]}, "retard": {"model": {"bias": 2.9004, "kind": "noun-verb", "weights": {"tn1=W": 1.9878, "tp1=PUNCT": -0.0618, "tp1=W": 1.1149, "tp2=W": 0.6665, "w=a": -0.6521}}, "senses": [{"id": "nou", "phones": "ɹ ˈiː t ɑːɹ d", "role": "n"}, {"id": "vrb", "phones": "ɹ ᵻ t ˈɑːɹ d", "role": "v"}]}, "rodeo": {"model": {"bias": [0.0, 3.3466], "kind": "senses", "weights": [{}, {"n1=,": -0.4021, "p1=del": -1.4939, "tp2p1=CAP+W": -1.5572, "w=del": -0.0945}]}, "senses": [{"id": "geo", "phones": "ɹ oʊ d ˈeɪ oʊ", "role": "o"}, {"id": "rodeo", "phones": "ɹ ˈoʊ d ɪ ˌoʊ", "role": "o"}]}, "row": {"model": {"bias": [0.0, -1000000.0], "kind": "senses", "weights": [{}, {}]}, "senses": [{"id": "1", "phones": "ɹ ˈoʊ", "role": "o"}, {"id": "2", "phones": "ɹ ˈaʊ", "role": "o"}]}, "sake": {"model": {"bias": [0.0, -1.5781], "kind": "senses", "weights": [{}, {"p2=for": 2.086, "tp1=PREP": -0.1808, "w=are": -0.1788, "w=for": 3.697}]}, "senses": [{"id": "jp", "phones": "s ˈɑː k eɪ", "role": "o"}, {"id": "sake", "phones": "s ˈeɪ k", "role": "o"}]}, "separate": {"model": {"bias": -0.1908, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "adj", "phones": "s ˈɛ p ɚ ɹ ə t", "role": "n"}, {"id": "vrb", "phones": "s ˈɛ p ɚ ɹ ˌeɪ t", "role": "v"}]}, "sow": {"model": {"bias": [0.0, 0.0], "kind": "senses", "weights": [{}, {"cap": -1.0132, "n1=,": 0.1666, "p1=to": 0.0266, "p2=the": -0.4073, "tn1=S": -0.1982, "tn1=W": 0.4926, "tn1n2=PUNCT+PUNCT": -1.267, "tn2=PREP": 0.2795, "tn2=S": 0.9062, "tn2=W": 0.3987, "tp1=CAP": -0.0118, "tp1=CONJ": 0.4021, "tp1=DET": -2.3168, "tp1=PUNCT": -0.3474, "tp1=SUBJ": 1.3059, "tp1=TO": 2.559, "tp1=W": -0.3511, "w=in": 0.4334, "w=plow": 0.0525, "w=reap": 1.1023}]}, "senses": [{"id": "nou", "phones": "s ˈaʊ", "role": "n"}, {"id": "sow", "phones": "s ˈoʊ", "role": "o"}]}, "subject": {"model": {"bias": -1.7854, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "adj-nou", "phones": "s ˈʌ b dʒ ɛ k t", "role": "n"}, {"id": "vrb", "phones": "s ə b dʒ ˈɛ k t", "role": "v"}]}, "subordinate": {"model": {"bias": -0.3507, "kind": "noun-verb", "weights": {"tn1=S": -0.9328}}, "senses": [{"id": "adj-nou", "phones": "s ə b ˈɔːɹ d ɪ n ə t", "role": "n"}, {"id": "vrb", "phones": "s ə b ˈɔːɹ d ɪ n ˌeɪ t", "role": "v"}]}, "supplement": {"model": {"bias": 0.4311, "kind": "noun-verb", "weights": {"p1=that": 0.2073, "tp2p1=S+DET": 0.541}}, "senses": [{"id": "nou", "phones": "s ˈʌ p l ə m ə n t", "role": "n"}, {"id": "vrb", "phones": "s ˈʌ p l ə m ˌɛ n t", "role": "v"}]}, "suspect": {"model": {"bias": 0.9786, "kind": "noun-verb", "weights": {"tn1=DET": 0.6479}}, "senses": [{"id": "adj-nou", "phones": "s ˈʌ s p ɛ k t", "role": "n"}, {"id": "vrb", "phones": "s ə s p ˈɛ k t", "role": "v"}]}, "syndicate": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {}}, "senses": [{"id": "nou", "phones": "s ˈɪ n d ɪ k ə t", "role": "n"}, {"id": "vrb", "phones": "s ˈɪ n d ɪ k ˌeɪ t", "role": "v"}]}, "tear": {"model": {"bias": 3.57, "kind": "noun-verb", "weights": {"cap": 0.1526, "tn1=PREP": 0.8405, "tn1=S": -0.7196, "tn1n2=PUNCT+S": 0.4728, "tn2=DET": 0.7506, "tn2=POS": 0.3234, "tp2=W": 1.1215, "w=a": 1.8769, "w=and": -0.1958, "w=gas": -4.9365, "w=he": 0.0479, "w=on": 1.6189, "w=the": 0.3044, "w=was": 0.2349}}, "senses": [{"id": "nou", "phones": "t ˈɪɹ", "role": "n"}, {"id": "vrb", "phones": "t ˈɛɹ", "role": "v"}]}, "transform": {"model": {"bias": [0.0, 0.0], "kind": "senses", "weights": [{}, {"p1=to": 1.1021, "p2=the": -0.1111, "tn1=PUNCT": -0.82, "tn2=W": 0.6763, "tp1=CAP": -0.792, "tp1=MODAL": 0.6594, "tp1=TO": 1.3088, "tp1=W": -0.5971, "tp2=DET": -1.032, "w=and": 0.5308, "w=fourier": -0.6977, "w=into": 2.5148, "w=is": -1.3963, "w=to": 0.5493}]}, "senses": [{"id": "nou", "phones": "t ɹ ˈæ n s f ɔːɹ m", "role": "n"}, {"id": "transform", "phones": "t ɹ æ n s f ˈɔːɹ m", "role": "o"}]}, "transplant": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1=S": -0.4211}}, "senses": [{"id": "nou", "phones": "t ɹ ˈæ n s p l æ n t", "role": "n"}, {"id": "vrb", "phones": "t ɹ æ n s p l ˈæ n t", "role": "v"}]}, "transport": {"model": {"bias": -0.0593, "kind": "noun-verb", "weights": {"tn2=CONJ": 0.7197, "tp2=W": -0.2861}}, "senses": [{"id": "nou", "phones": "t ɹ ˈæ n s p oːɹ t", "role": "n"}, {"id": "vrb", "phones": "t ɹ æ n s p ˈoːɹ t", "role": "v"}]}, "upset": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"p1=was": 0.1023, "p2=<s>": 0.5889, "tn2=W": 0.1647, "tp1=CAP": 0.076, "tp1n1=BE+PREP": 1.5371, "tp1n1=BE+PUNCT": 1.8533, "tp2=<s>": 0.6883, "tp2=BE": -0.7052, "w=in": 1.865, "w=that": -1.5572, "w=the": 1.5008, "w=was": 0.967, "w=with": -0.0303}}, "senses": [{"id": "nou", "phones": "ˈʌ p s ɛ t", "role": "n"}, {"id": "vrb", "phones": "ə p s ˈɛ t", "role": "v"}]}, "use": {"model": {"bias": 0.8581, "kind": "noun-verb", "weights": {"n1=.": -0.0025, "n2=</s>": -0.058, "tn1=W": 1.0201, "tn1n2=PUNCT+</s>": -0.0018, "tn2=</s>": -0.1052, "tp1=S": 1.1462, "tp2=S": 0.6539, "tp2=W": -0.3045, "w=the": 0.9995}}, "senses": [{"id": "nou", "phones": "j ˈuː s", "role": "n"}, {"id": "vrb", "phones": "j ˈuː z", "role": "v"}]}, "uses": {"model": {"bias": 4.9809, "kind": "noun-verb", "weights": {"tn1=PREP": -2.0, "tn1=S": 0.3249, "tn1=W": 0.4896, "tn2=PUNCT": 1.0271, "tp1=CAP": 0.1426, "tp2=DET": 0.6556}}, "senses": [{"id": "nou", "phones": "j ˈuː s ᵻ z", "role": "n"}, {"id": "vrb", "phones": "j ˈuː z ᵻ z", "role": "v"}]}, "wind": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"tn1=W": 0.1599, "tn2=S": -1.3768}}, "senses": [{"id": "nou", "phones": "w ˈɪ n d", "role": "n"}, {"id": "vrb", "phones": "w ˈaɪ n d", "role": "v"}]}, "winds": {"model": {"bias": 0.0, "kind": "noun-verb", "weights": {"n1=through": 4.0711, "n1=up": 0.093, "tp2=DET": 0.25, "tp2p1=DET+W": 1.2695, "w=the": 0.5108}}, "senses": [{"id": "nou", "phones": "w ˈɪ n d z", "role": "n"}, {"id": "vrb", "phones": "w ˈaɪ n d z", "role": "v"}]}, "wound": {"model": {"bias": [0.0, -0.8634], "kind": "senses", "weights": [{}, {"n1=on": 0.6389, "n1=up": 2.4926, "tn1=PREP": 0.7285, "tn1=W": 1.3481, "tn2=BE": -0.2465, "tp1=DET": -1.9609, "tp1=S": 0.0614, "tp1=W": -1.7887, "tp1n1=S+PREP": 0.1973, "tp2p1=W+S": 0.0609, "w=a": -0.1854, "w=and": -0.962, "w=coil": 1.3397, "w=of": -0.1924, "w=to": -0.2797, "w=with": 0.9452}]}, "senses": [{"id": "nou-vrb", "phones": "w ˈuː n d", "role": "o"}, {"id": "vrb", "phones": "w ˈaʊ n d", "role": "v"}]}}}1234567{ "words": 124926, "without_alignment": 0, "alignment_pairs": 1990, "cmudict_sha256": "81917843c7f44ce2b094ac63873c2c7a4cf802040792c455ba3ca406891c3d22", "lexicon_sha256": "3fc930345c6b3cabc533981c4b212fa309eec83913fcdbd42919338270d64b06"}1{"cmudict_commit": "74790861f652b15e4ac49015a90074ad62a27690", "cmudict_sha256": "81917843c7f44ce2b094ac63873c2c7a4cf802040792c455ba3ca406891c3d22", "homograph_commit": "8f008f021e88f8b71118a27ae655f1f3121162bc"}123version https://git-lfs.github.com/spec/v1oid sha256:68699ee87333f9140858a0bec683361c7c9965820b5fef8ab81bd928c98ad873size 349228123version https://git-lfs.github.com/spec/v1oid sha256:e1cd47c4e4a974477f431cb210bd9c403bf169bf89ce5bff0c580caaecacfb2csize 346668123version https://git-lfs.github.com/spec/v1oid sha256:892787538be1d50bf369795075f9f1a712b26ec1ba368bed6d7b49b29a397701size 323116123version https://git-lfs.github.com/spec/v1oid sha256:17471157751acf918677d1a422127a4a85ecad52f77944acf6f848f46bf0858dsize 397868123version https://git-lfs.github.com/spec/v1oid sha256:42939749279d9cec079c13532a3565edae570a7c035f0fe6c52ea25355c7e527size 311852123version https://git-lfs.github.com/spec/v1oid sha256:a72619c9b7287619f51bbfd2c35909ba554094f899a91692cbe1c4bbcbba180csize 334380.gitattributes+8
LICENSEAdded+202
README.mdAdded+95
code/dizione/LICENSEAdded+202
code/dizione/__init__.pyAdded+71
code/dizione/__main__.pyAdded+41
code/dizione/align.pyAdded+156
code/dizione/convert.pyAdded+414
code/dizione/data/abbreviations.txtAdded+103
code/dizione/data/chat.txtAdded+111
code/dizione/data/endings.txtAdded+130
code/dizione/data/exceptions.txtAdded+250
code/dizione/data/function_words.txtAdded+189
code/dizione/data/homograph_fixes.txtAdded+57
code/dizione/data/homograph_rules.txtAdded+39
code/dizione/data/letters.txtAdded+27
code/dizione/data/phrases.txtAdded+63
code/dizione/data/units.txtAdded+76
code/dizione/engine.pyAdded+277
code/dizione/g2p.pyAdded+95
code/dizione/homographs.pyAdded+198
code/dizione/morphology.pyAdded+217
code/dizione/normalize.pyAdded+1423
code/dizione/sentence.pyAdded+115
code/dizione/symbols.pyAdded+68
code/dizione/tables.pyAdded+103
code/tiny_voca/__init__.pyAdded+10
code/tiny_voca/arabic_frontend.pyAdded+337
code/tiny_voca/config.pyAdded+118
code/tiny_voca/infer.pyAdded+219
code/tiny_voca/model.pyAdded+447
code/tiny_voca/numbers.pyAdded+75
code/tiny_voca/text.pyAdded+317
config.jsonAdded+38
model.safetensorsAdded+3
phonemizer/LICENSE.cmudictAdded+33
phonemizer/LICENSE.homograph-dataAdded+202
phonemizer/align.jsonAdded+2070
phonemizer/g2p.jsonAdded+83
phonemizer/g2p.npzAdded+3
phonemizer/homographs.jsonAdded+1
phonemizer/lexicon.jsonAdded+7
phonemizer/lexicon.tsvAdded
phonemizer/sources.jsonAdded+1
samples/arcs_female_1.wavAdded+3
samples/arcs_female_2.wavAdded+3
samples/arcs_female_3.wavAdded+3
samples/arcs_female_4.wavAdded+3
samples/arcs_male_1.wavAdded+3
samples/arcs_male_2.wavAdded+3