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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
NOTICE
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pitput phonemizer
|
| 2 |
+
https://huggingface.co/useless-ai/pitput-phonemizer
|
| 3 |
+
|
| 4 |
+
renikud_onnx.py is from RenikudPlus by notmax123
|
| 5 |
+
(https://huggingface.co/notmax123/RenikudPlus), under the Apache License 2.0.
|
| 6 |
+
The number expander and the exact decoding are that file. One change was made
|
| 7 |
+
here: onnxruntime is imported only when G2P() loads an ONNX model, so reading
|
| 8 |
+
text does not require it.
|
| 9 |
+
|
| 10 |
+
The transformer and the weights in model.safetensors are ours, under the
|
| 11 |
+
Apache License 2.0. See LICENSE.
|
README.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- he
|
| 4 |
+
license: apache-2.0
|
| 5 |
+
library_name: pytorch
|
| 6 |
+
tags:
|
| 7 |
+
- hebrew
|
| 8 |
+
- g2p
|
| 9 |
+
- phonemization
|
| 10 |
+
- phonemes
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
# pitput phonemizer
|
| 14 |
+
|
| 15 |
+
A Hebrew grapheme-to-phoneme model: plain text in, IPA with stress out. **10,083,873 parameters**, about 40 MB. It reads a whole sentence at once, so the same letters can be two different words, and it can take the gender of the speaker and of the person being spoken to.
|
| 16 |
+
|
| 17 |
+
It is the pronunciation front end of [pitput](https://huggingface.co/useless-ai/pitput), a 5M-parameter Hebrew text-to-speech model. This release is the phonemizer on its own.
|
| 18 |
+
|
| 19 |
+
A name, a form of address or the story is enough to choose ืื, ืืืชื, ืืืจืช and the rest.
|
| 20 |
+
|
| 21 |
+
## Usage
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
pip install torch
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
```python
|
| 28 |
+
from phonemizer import Phonemizer
|
| 29 |
+
|
| 30 |
+
g2p = Phonemizer.from_pretrained("useless-ai/pitput-phonemizer")
|
| 31 |
+
|
| 32 |
+
g2p("ืฉืืื, ืื ืฉืืืื?")
|
| 33 |
+
# สalหom, mหa สlomฯหa?
|
| 34 |
+
|
| 35 |
+
g2p("ืื ื, ืื ืฉืืืื?") # the name is the cue
|
| 36 |
+
# dหana, mหa สlomหeฯ?
|
| 37 |
+
|
| 38 |
+
g2p("ืื ื, ืื ืฉืืืื?", listener="m") # an explicit listener wins
|
| 39 |
+
# dหana, mหa สlomฯหa?
|
| 40 |
+
|
| 41 |
+
g2p("ืื ื ืืืืงืช ืืช ืื", speaker="f")
|
| 42 |
+
# สanหi bodหeket สหet zหe
|
| 43 |
+
|
| 44 |
+
g2p("ืืืืืจ 1250 ืฉืงืืื") # digits are read as words first
|
| 45 |
+
# hameฯหiส สหelef matหajim veฯamiสหim สkalหim
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
From the command line, reading UTF-8 from a file or from the argument:
|
| 49 |
+
|
| 50 |
+
```bash
|
| 51 |
+
python phonemizer.py --text "ืื ื, ืื ืฉืืืื?"
|
| 52 |
+
python phonemizer.py --text-file story.txt --listener f --speaker f
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
| Argument | Meaning |
|
| 56 |
+
|---|---|
|
| 57 |
+
| `listener` | Who is being spoken to. Omitted: decide from the sentence. `"f"` or `"m"`: use that form for ืื, ืืืชื, ืฉืื, ืืืจืช, ืจืืืช and the rest. `"m"` overrides a feminine name. |
|
| 58 |
+
| `speaker` | Who is speaking. Omitted: unknown. `"f"` / `"m"`: first-person forms such as ืืืืงืช / ืืืืง. |
|
| 59 |
+
| `0` / `1` / `2` | The same two arguments as integers: unknown, man, woman. |
|
| 60 |
+
|
| 61 |
+
Niqqud is optional. A pointed letter is followed; an unpointed letter is still predicted from the sentence. Kamatz may be *a* or *o*, and shva may be *e* or silent, because the mark itself allows both. Stress is predicted either way: ordinary niqqud does not write it.
|
| 62 |
+
|
| 63 |
+
Text longer than 512 characters is split on sentence ends, then on commas, then on spaces.
|
| 64 |
+
|
| 65 |
+
## Model
|
| 66 |
+
|
| 67 |
+
A character transformer.
|
| 68 |
+
|
| 69 |
+
- One id per character (Hebrew letters, punctuation, digits, Latin letters and a few symbols), plus an optional vowel mark and consonant mark on that character, plus a speaker id and a listener id.
|
| 70 |
+
- 8 transformer layers, 320 channels, 5 heads, pre-norm, GELU, feed-forward width 1,280.
|
| 71 |
+
- Three heads on every character: 25 consonants, 6 vowels, stressed or not. Empty is one of the classes, so a letter can be silent (ื, ืข, ื) or vowelless.
|
| 72 |
+
- Decoding picks the best legal consonant and vowel for each letter, and one stressed vowel in the word. A geresh rewrites ืฆ ื ื as tส, ฯ, dส. A final ื before a pause is aฯ.
|
| 73 |
+
|
| 74 |
+
## Limitations
|
| 75 |
+
|
| 76 |
+
- ืืื and ืืืช are read with *ej* (`bหejn`, `bหejt`).
|
| 77 |
+
- With both inputs unknown, "ืจืืืช ืืช ืืกืจื ืืืืฉ, ืืืื?" is read as masculine. Set `listener` or `speaker` when the sentence does not carry the cue on its own.
|
| 78 |
+
- Foreign words written in Hebrew letters are pronounced as Hebrew. Acronyms are left as written.
|
| 79 |
+
- The number reading is a fixed set of rules, up to thousands, dates, times and a few fractions.
|
| 80 |
+
- This package returns a pronunciation. For audio, use [pitput](https://huggingface.co/useless-ai/pitput).
|
| 81 |
+
|
| 82 |
+
## License
|
| 83 |
+
|
| 84 |
+
Apache License 2.0, for the code and the weights.
|
| 85 |
+
|
| 86 |
+
RenikudPlus is by notmax123, Apache-2.0. The decoding and the number expander shipped here (`renikud_onnx.py`) are taken from its wrapper; see `NOTICE`. The transformer and its weights are trained by us.
|
| 87 |
+
|
| 88 |
+
## Files
|
| 89 |
+
|
| 90 |
+
| File | Contents |
|
| 91 |
+
|---|---|
|
| 92 |
+
| `model.safetensors` | The 10.1M weights |
|
| 93 |
+
| `config.json` | Width, layers, the character inventory, consonant and vowel names |
|
| 94 |
+
| `phonemizer.py` | `Phonemizer`, including `from_pretrained`, and the command line |
|
| 95 |
+
| `renikud_onnx.py` | Decoding and number expansion from RenikudPlus |
|
| 96 |
+
| `NOTICE`, `LICENSE` | Attribution and the Apache license |
|
| 97 |
+
|
| 98 |
+
## Acknowledgements
|
| 99 |
+
|
| 100 |
+
[RenikudPlus](https://huggingface.co/notmax123/RenikudPlus) for the per-letter distributions, the decoder and the number expander, and the text: Hebrew Wikipedia, HeDC4, news archives, HeSum and ivrit.ai.
|
config.json
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"width": 320,
|
| 3 |
+
"layers": 8,
|
| 4 |
+
"heads": 5,
|
| 5 |
+
"max_len": 512,
|
| 6 |
+
"characters": "ืืืืืืืืืืืืืืืื ืืกืขืคืฃืฆืฅืงืจืฉืช .,?!:;\"'-โโ()[]/โฆืดืณ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZโช%$โฌ&+=@#*",
|
| 7 |
+
"consonants": [
|
| 8 |
+
"โ
",
|
| 9 |
+
"b",
|
| 10 |
+
"v",
|
| 11 |
+
"d",
|
| 12 |
+
"h",
|
| 13 |
+
"z",
|
| 14 |
+
"ฯ",
|
| 15 |
+
"t",
|
| 16 |
+
"j",
|
| 17 |
+
"k",
|
| 18 |
+
"l",
|
| 19 |
+
"m",
|
| 20 |
+
"n",
|
| 21 |
+
"s",
|
| 22 |
+
"f",
|
| 23 |
+
"p",
|
| 24 |
+
"ts",
|
| 25 |
+
"tส",
|
| 26 |
+
"w",
|
| 27 |
+
"ส",
|
| 28 |
+
"ษก",
|
| 29 |
+
"ส",
|
| 30 |
+
"ส",
|
| 31 |
+
"ส",
|
| 32 |
+
"dส"
|
| 33 |
+
],
|
| 34 |
+
"vowels": [
|
| 35 |
+
"โ
",
|
| 36 |
+
"a",
|
| 37 |
+
"e",
|
| 38 |
+
"i",
|
| 39 |
+
"o",
|
| 40 |
+
"u"
|
| 41 |
+
],
|
| 42 |
+
"parameters": 10083873,
|
| 43 |
+
"decoder": {
|
| 44 |
+
"consonants": [
|
| 45 |
+
"โ
",
|
| 46 |
+
"b",
|
| 47 |
+
"v",
|
| 48 |
+
"d",
|
| 49 |
+
"h",
|
| 50 |
+
"z",
|
| 51 |
+
"ฯ",
|
| 52 |
+
"t",
|
| 53 |
+
"j",
|
| 54 |
+
"k",
|
| 55 |
+
"l",
|
| 56 |
+
"m",
|
| 57 |
+
"n",
|
| 58 |
+
"s",
|
| 59 |
+
"f",
|
| 60 |
+
"p",
|
| 61 |
+
"ts",
|
| 62 |
+
"tส",
|
| 63 |
+
"w",
|
| 64 |
+
"ส",
|
| 65 |
+
"ษก",
|
| 66 |
+
"ส",
|
| 67 |
+
"ส",
|
| 68 |
+
"ส",
|
| 69 |
+
"dส"
|
| 70 |
+
],
|
| 71 |
+
"vowels": [
|
| 72 |
+
"โ
",
|
| 73 |
+
"a",
|
| 74 |
+
"e",
|
| 75 |
+
"i",
|
| 76 |
+
"o",
|
| 77 |
+
"u"
|
| 78 |
+
],
|
| 79 |
+
"letter_constraints": {
|
| 80 |
+
"ื": [
|
| 81 |
+
19,
|
| 82 |
+
0
|
| 83 |
+
],
|
| 84 |
+
"ื": [
|
| 85 |
+
1,
|
| 86 |
+
2
|
| 87 |
+
],
|
| 88 |
+
"ื": [
|
| 89 |
+
20,
|
| 90 |
+
24
|
| 91 |
+
],
|
| 92 |
+
"ื": [
|
| 93 |
+
3
|
| 94 |
+
],
|
| 95 |
+
"ื": [
|
| 96 |
+
4,
|
| 97 |
+
0
|
| 98 |
+
],
|
| 99 |
+
"ื": [
|
| 100 |
+
2,
|
| 101 |
+
18,
|
| 102 |
+
0
|
| 103 |
+
],
|
| 104 |
+
"ื": [
|
| 105 |
+
5,
|
| 106 |
+
23
|
| 107 |
+
],
|
| 108 |
+
"ื": [
|
| 109 |
+
6
|
| 110 |
+
],
|
| 111 |
+
"ื": [
|
| 112 |
+
7
|
| 113 |
+
],
|
| 114 |
+
"ื": [
|
| 115 |
+
8,
|
| 116 |
+
0
|
| 117 |
+
],
|
| 118 |
+
"ื": [
|
| 119 |
+
9,
|
| 120 |
+
6
|
| 121 |
+
],
|
| 122 |
+
"ื": [
|
| 123 |
+
9,
|
| 124 |
+
6
|
| 125 |
+
],
|
| 126 |
+
"ื": [
|
| 127 |
+
10,
|
| 128 |
+
0
|
| 129 |
+
],
|
| 130 |
+
"ื": [
|
| 131 |
+
11
|
| 132 |
+
],
|
| 133 |
+
"ื": [
|
| 134 |
+
11
|
| 135 |
+
],
|
| 136 |
+
"ื ": [
|
| 137 |
+
12
|
| 138 |
+
],
|
| 139 |
+
"ื": [
|
| 140 |
+
12
|
| 141 |
+
],
|
| 142 |
+
"ืก": [
|
| 143 |
+
13
|
| 144 |
+
],
|
| 145 |
+
"ืข": [
|
| 146 |
+
19,
|
| 147 |
+
0
|
| 148 |
+
],
|
| 149 |
+
"ืค": [
|
| 150 |
+
15,
|
| 151 |
+
14
|
| 152 |
+
],
|
| 153 |
+
"ืฃ": [
|
| 154 |
+
15,
|
| 155 |
+
14
|
| 156 |
+
],
|
| 157 |
+
"ืฆ": [
|
| 158 |
+
16,
|
| 159 |
+
17
|
| 160 |
+
],
|
| 161 |
+
"ืฅ": [
|
| 162 |
+
16,
|
| 163 |
+
17
|
| 164 |
+
],
|
| 165 |
+
"ืง": [
|
| 166 |
+
9
|
| 167 |
+
],
|
| 168 |
+
"ืจ": [
|
| 169 |
+
21
|
| 170 |
+
],
|
| 171 |
+
"ืฉ": [
|
| 172 |
+
22,
|
| 173 |
+
13,
|
| 174 |
+
0
|
| 175 |
+
],
|
| 176 |
+
"ืช": [
|
| 177 |
+
7
|
| 178 |
+
]
|
| 179 |
+
},
|
| 180 |
+
"geresh": {
|
| 181 |
+
"ื": "ส",
|
| 182 |
+
"ื": "dส",
|
| 183 |
+
"ืฆ": "tส",
|
| 184 |
+
"ืฅ": "tส"
|
| 185 |
+
},
|
| 186 |
+
"vowel_cond_consonant": [
|
| 187 |
+
[
|
| 188 |
+
2.0558853149414062,
|
| 189 |
+
-1.5661203861236572,
|
| 190 |
+
-1.8470641374588013,
|
| 191 |
+
-1.505002737045288,
|
| 192 |
+
-1.02211332321167,
|
| 193 |
+
-0.04853866249322891
|
| 194 |
+
],
|
| 195 |
+
[
|
| 196 |
+
-0.3861868381500244,
|
| 197 |
+
0.05174676328897476,
|
| 198 |
+
0.12527510523796082,
|
| 199 |
+
-0.028752373531460762,
|
| 200 |
+
0.041624099016189575,
|
| 201 |
+
-0.06499745696783066
|
| 202 |
+
],
|
| 203 |
+
[
|
| 204 |
+
-0.7433532476425171,
|
| 205 |
+
0.011877692304551601,
|
| 206 |
+
1.0905321836471558,
|
| 207 |
+
0.11189278960227966,
|
| 208 |
+
-0.05516193434596062,
|
| 209 |
+
-1.0775662660598755
|
| 210 |
+
],
|
| 211 |
+
[
|
| 212 |
+
-0.05291063338518143,
|
| 213 |
+
0.032186925411224365,
|
| 214 |
+
-0.0205026064068079,
|
| 215 |
+
0.08015261590480804,
|
| 216 |
+
0.01773257553577423,
|
| 217 |
+
-0.004924353677779436
|
| 218 |
+
],
|
| 219 |
+
[
|
| 220 |
+
-2.148221015930176,
|
| 221 |
+
1.3921881914138794,
|
| 222 |
+
0.07633960247039795,
|
| 223 |
+
0.12979033589363098,
|
| 224 |
+
-0.026167241856455803,
|
| 225 |
+
0.4571599066257477
|
| 226 |
+
],
|
| 227 |
+
[
|
| 228 |
+
0.08750557154417038,
|
| 229 |
+
0.02296515926718712,
|
| 230 |
+
-0.011297930032014847,
|
| 231 |
+
0.010633253492414951,
|
| 232 |
+
0.03154299408197403,
|
| 233 |
+
-0.20912346243858337
|
| 234 |
+
],
|
| 235 |
+
[
|
| 236 |
+
-0.05249766632914543,
|
| 237 |
+
0.020739858970046043,
|
| 238 |
+
0.016914354637265205,
|
| 239 |
+
-0.04195062816143036,
|
| 240 |
+
0.11636413633823395,
|
| 241 |
+
-0.13308461010456085
|
| 242 |
+
],
|
| 243 |
+
[
|
| 244 |
+
0.09392710030078888,
|
| 245 |
+
0.03605668246746063,
|
| 246 |
+
-0.13852737843990326,
|
| 247 |
+
0.04698494076728821,
|
| 248 |
+
0.17176400125026703,
|
| 249 |
+
-0.16901783645153046
|
| 250 |
+
],
|
| 251 |
+
[
|
| 252 |
+
-1.1793149709701538,
|
| 253 |
+
0.2640126049518585,
|
| 254 |
+
0.21552670001983643,
|
| 255 |
+
0.5476393103599548,
|
| 256 |
+
0.2501775920391083,
|
| 257 |
+
0.09575966000556946
|
| 258 |
+
],
|
| 259 |
+
[
|
| 260 |
+
-0.04407894238829613,
|
| 261 |
+
0.03889898955821991,
|
| 262 |
+
-0.030560795217752457,
|
| 263 |
+
-0.020569605752825737,
|
| 264 |
+
0.11344551295042038,
|
| 265 |
+
-0.14528712630271912
|
| 266 |
+
],
|
| 267 |
+
[
|
| 268 |
+
-0.2083742469549179,
|
| 269 |
+
0.01165812835097313,
|
| 270 |
+
0.1277729570865631,
|
| 271 |
+
-0.047991350293159485,
|
| 272 |
+
0.01931094378232956,
|
| 273 |
+
0.12829315662384033
|
| 274 |
+
],
|
| 275 |
+
[
|
| 276 |
+
-0.18577775359153748,
|
| 277 |
+
-0.02709837816655636,
|
| 278 |
+
0.09419141709804535,
|
| 279 |
+
0.030572015792131424,
|
| 280 |
+
-0.12180599570274353,
|
| 281 |
+
0.1508447378873825
|
| 282 |
+
],
|
| 283 |
+
[
|
| 284 |
+
-0.36858320236206055,
|
| 285 |
+
-0.01120966486632824,
|
| 286 |
+
0.17201770842075348,
|
| 287 |
+
0.05194632709026337,
|
| 288 |
+
0.08133068680763245,
|
| 289 |
+
-0.013191970996558666
|
| 290 |
+
],
|
| 291 |
+
[
|
| 292 |
+
0.04303239658474922,
|
| 293 |
+
0.07304304093122482,
|
| 294 |
+
-0.20865139365196228,
|
| 295 |
+
0.09303245693445206,
|
| 296 |
+
0.046918127685785294,
|
| 297 |
+
-0.09259093552827835
|
| 298 |
+
],
|
| 299 |
+
[
|
| 300 |
+
0.12228260189294815,
|
| 301 |
+
-0.07249703258275986,
|
| 302 |
+
-0.0849895253777504,
|
| 303 |
+
0.013246608898043633,
|
| 304 |
+
-0.03485830873250961,
|
| 305 |
+
0.08394429087638855
|
| 306 |
+
],
|
| 307 |
+
[
|
| 308 |
+
-0.04998322203755379,
|
| 309 |
+
0.06000860035419464,
|
| 310 |
+
-0.01959080807864666,
|
| 311 |
+
0.020725056529045105,
|
| 312 |
+
0.039840005338191986,
|
| 313 |
+
-0.043523360043764114
|
| 314 |
+
],
|
| 315 |
+
[
|
| 316 |
+
0.11638890206813812,
|
| 317 |
+
0.07445990294218063,
|
| 318 |
+
-0.1305137425661087,
|
| 319 |
+
0.004047039896249771,
|
| 320 |
+
-0.05419695004820824,
|
| 321 |
+
0.06108556315302849
|
| 322 |
+
],
|
| 323 |
+
[
|
| 324 |
+
-0.19724972546100616,
|
| 325 |
+
-0.034976132214069366,
|
| 326 |
+
0.06169459968805313,
|
| 327 |
+
-0.015855753794312477,
|
| 328 |
+
-0.027550136670470238,
|
| 329 |
+
0.05923480913043022
|
| 330 |
+
],
|
| 331 |
+
[
|
| 332 |
+
-0.3348456025123596,
|
| 333 |
+
0.22713665664196014,
|
| 334 |
+
-0.20075362920761108,
|
| 335 |
+
0.0358857735991478,
|
| 336 |
+
-0.011174589395523071,
|
| 337 |
+
-0.2503642737865448
|
| 338 |
+
],
|
| 339 |
+
[
|
| 340 |
+
-1.9449368715286255,
|
| 341 |
+
0.6892146468162537,
|
| 342 |
+
0.245370551943779,
|
| 343 |
+
0.3311443030834198,
|
| 344 |
+
0.154145285487175,
|
| 345 |
+
0.4339560270309448
|
| 346 |
+
],
|
| 347 |
+
[
|
| 348 |
+
0.05475003272294998,
|
| 349 |
+
0.01950151100754738,
|
| 350 |
+
-0.05983944609761238,
|
| 351 |
+
0.034458283334970474,
|
| 352 |
+
-0.19372767210006714,
|
| 353 |
+
0.1767721325159073
|
| 354 |
+
],
|
| 355 |
+
[
|
| 356 |
+
-0.03782021254301071,
|
| 357 |
+
0.012280264869332314,
|
| 358 |
+
0.033034469932317734,
|
| 359 |
+
-0.014582433737814426,
|
| 360 |
+
-0.051449839025735855,
|
| 361 |
+
0.03353497385978699
|
| 362 |
+
],
|
| 363 |
+
[
|
| 364 |
+
-0.060684934258461,
|
| 365 |
+
-0.044933438301086426,
|
| 366 |
+
0.05265338346362114,
|
| 367 |
+
-0.017021559178829193,
|
| 368 |
+
-0.09895633906126022,
|
| 369 |
+
0.06269055604934692
|
| 370 |
+
],
|
| 371 |
+
[
|
| 372 |
+
0.07618965953588486,
|
| 373 |
+
-0.02923453599214554,
|
| 374 |
+
-0.06275764852762222,
|
| 375 |
+
-0.05367620661854744,
|
| 376 |
+
-0.07744879275560379,
|
| 377 |
+
-0.08506692945957184
|
| 378 |
+
],
|
| 379 |
+
[
|
| 380 |
+
-0.0465037003159523,
|
| 381 |
+
-0.09734100848436356,
|
| 382 |
+
0.0007880136254243553,
|
| 383 |
+
0.0030017103999853134,
|
| 384 |
+
0.049945246428251266,
|
| 385 |
+
0.04877772182226181
|
| 386 |
+
]
|
| 387 |
+
],
|
| 388 |
+
"stress_cond_consonant": [
|
| 389 |
+
[
|
| 390 |
+
1.099237084388733,
|
| 391 |
+
-1.1208546161651611
|
| 392 |
+
],
|
| 393 |
+
[
|
| 394 |
+
-0.037533003836870193,
|
| 395 |
+
0.081173837184906
|
| 396 |
+
],
|
| 397 |
+
[
|
| 398 |
+
-0.11353709548711777,
|
| 399 |
+
0.06654629856348038
|
| 400 |
+
],
|
| 401 |
+
[
|
| 402 |
+
-0.11013774573802948,
|
| 403 |
+
0.06517343968153
|
| 404 |
+
],
|
| 405 |
+
[
|
| 406 |
+
-0.05289340764284134,
|
| 407 |
+
0.01053832471370697
|
| 408 |
+
],
|
| 409 |
+
[
|
| 410 |
+
-0.07674909383058548,
|
| 411 |
+
0.09683341532945633
|
| 412 |
+
],
|
| 413 |
+
[
|
| 414 |
+
-0.15968438982963562,
|
| 415 |
+
0.14003583788871765
|
| 416 |
+
],
|
| 417 |
+
[
|
| 418 |
+
0.12982624769210815,
|
| 419 |
+
-0.13078394532203674
|
| 420 |
+
],
|
| 421 |
+
[
|
| 422 |
+
-0.10143479704856873,
|
| 423 |
+
0.13742035627365112
|
| 424 |
+
],
|
| 425 |
+
[
|
| 426 |
+
-8.551611244911328e-05,
|
| 427 |
+
0.01612981967628002
|
| 428 |
+
],
|
| 429 |
+
[
|
| 430 |
+
-0.09603605419397354,
|
| 431 |
+
0.06450540572404861
|
| 432 |
+
],
|
| 433 |
+
[
|
| 434 |
+
0.05364331603050232,
|
| 435 |
+
-0.048286404460668564
|
| 436 |
+
],
|
| 437 |
+
[
|
| 438 |
+
-0.03506581112742424,
|
| 439 |
+
0.016860803589224815
|
| 440 |
+
],
|
| 441 |
+
[
|
| 442 |
+
-0.033050645142793655,
|
| 443 |
+
0.02202325314283371
|
| 444 |
+
],
|
| 445 |
+
[
|
| 446 |
+
-0.11232742667198181,
|
| 447 |
+
0.09788762032985687
|
| 448 |
+
],
|
| 449 |
+
[
|
| 450 |
+
-0.14183156192302704,
|
| 451 |
+
0.1537134200334549
|
| 452 |
+
],
|
| 453 |
+
[
|
| 454 |
+
-0.04744111746549606,
|
| 455 |
+
0.07523421198129654
|
| 456 |
+
],
|
| 457 |
+
[
|
| 458 |
+
-0.0076216645538806915,
|
| 459 |
+
-0.017201552167534828
|
| 460 |
+
],
|
| 461 |
+
[
|
| 462 |
+
-0.3893127143383026,
|
| 463 |
+
0.4133819043636322
|
| 464 |
+
],
|
| 465 |
+
[
|
| 466 |
+
-0.17107519507408142,
|
| 467 |
+
0.16510096192359924
|
| 468 |
+
],
|
| 469 |
+
[
|
| 470 |
+
0.012823516502976418,
|
| 471 |
+
0.0017477222718298435
|
| 472 |
+
],
|
| 473 |
+
[
|
| 474 |
+
-0.007770264055579901,
|
| 475 |
+
0.02260502241551876
|
| 476 |
+
],
|
| 477 |
+
[
|
| 478 |
+
-0.023974472656846046,
|
| 479 |
+
-0.0013886622618883848
|
| 480 |
+
],
|
| 481 |
+
[
|
| 482 |
+
0.014667682349681854,
|
| 483 |
+
-0.0508955679833889
|
| 484 |
+
],
|
| 485 |
+
[
|
| 486 |
+
-0.11287879198789597,
|
| 487 |
+
0.11547784507274628
|
| 488 |
+
]
|
| 489 |
+
],
|
| 490 |
+
"stress_cond_vowel": [
|
| 491 |
+
[
|
| 492 |
+
2.0347506999969482,
|
| 493 |
+
-2.0360803604125977
|
| 494 |
+
],
|
| 495 |
+
[
|
| 496 |
+
-0.5543240308761597,
|
| 497 |
+
0.565310001373291
|
| 498 |
+
],
|
| 499 |
+
[
|
| 500 |
+
-0.4845571219921112,
|
| 501 |
+
0.5171681046485901
|
| 502 |
+
],
|
| 503 |
+
[
|
| 504 |
+
-0.1857353299856186,
|
| 505 |
+
0.1936979442834854
|
| 506 |
+
],
|
| 507 |
+
[
|
| 508 |
+
-0.5075444579124451,
|
| 509 |
+
0.5044676661491394
|
| 510 |
+
],
|
| 511 |
+
[
|
| 512 |
+
-0.16457495093345642,
|
| 513 |
+
0.14848999679088593
|
| 514 |
+
]
|
| 515 |
+
],
|
| 516 |
+
"cascade_cond": "softmax"
|
| 517 |
+
}
|
| 518 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dbbfa842a103f7b1d0f9eacc97a996244341eedbf659abe6083ebe379ec7c476
|
| 3 |
+
size 40346436
|
phonemizer.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hebrew grapheme to phoneme: plain text in, IPA with stress out.
|
| 2 |
+
|
| 3 |
+
from phonemizer import Phonemizer
|
| 4 |
+
g2p = Phonemizer.from_pretrained("useless-ai/pitput-phonemizer")
|
| 5 |
+
g2p("ืฉืืื, ืื ืฉืืืื?")
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import json
|
| 11 |
+
import struct
|
| 12 |
+
import sys
|
| 13 |
+
import threading
|
| 14 |
+
import unicodedata
|
| 15 |
+
import urllib.request
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
|
| 22 |
+
_HERE = Path(__file__).resolve().parent
|
| 23 |
+
if str(_HERE) not in sys.path:
|
| 24 |
+
sys.path.insert(0, str(_HERE))
|
| 25 |
+
import renikud_onnx
|
| 26 |
+
|
| 27 |
+
REPO = "useless-ai/pitput-phonemizer"
|
| 28 |
+
NEG = -1e30
|
| 29 |
+
|
| 30 |
+
# Mark ids, the same ones the network was trained with. A pointed letter is followed; an unpointed
|
| 31 |
+
# letter stays 0 and is predicted from the sentence. Kamats allows a or o, shva allows e or nothing.
|
| 32 |
+
V_UNPOINTED, V_NONE, V_A, V_KAMATS, V_E, V_SHVA, V_I, V_O, V_U = range(9)
|
| 33 |
+
VOWEL_MARK_ALLOWS = {V_NONE: {0}, V_A: {1}, V_KAMATS: {1, 4}, V_E: {2}, V_SHVA: {0, 2}, V_I: {3}, V_O: {4},
|
| 34 |
+
V_U: {5}}
|
| 35 |
+
C_UNPOINTED, C_DAGESH, C_NO_DAGESH, C_SHIN, C_SIN = range(5)
|
| 36 |
+
_BGDKPT = {"ื": (1, 2), "ื": (9, 6), "ื": (9, 6), "ืค": (15, 14), "ืฃ": (15, 14)} # (dagesh, no dagesh)
|
| 37 |
+
CONSONANT_MARK_ALLOWS = {}
|
| 38 |
+
for _letter, (_hard, _soft) in _BGDKPT.items():
|
| 39 |
+
CONSONANT_MARK_ALLOWS[(_letter, C_DAGESH)] = {_hard}
|
| 40 |
+
CONSONANT_MARK_ALLOWS[(_letter, C_NO_DAGESH)] = {_soft}
|
| 41 |
+
CONSONANT_MARK_ALLOWS[("ืฉ", C_SHIN)] = {22}
|
| 42 |
+
CONSONANT_MARK_ALLOWS[("ืฉ", C_SIN)] = {13}
|
| 43 |
+
|
| 44 |
+
_VOWEL_POINTS = {
|
| 45 |
+
"\u05b0": V_SHVA, "\u05b1": V_E, "\u05b2": V_A, "\u05b3": V_KAMATS, "\u05b4": V_I, "\u05b5": V_E,
|
| 46 |
+
"\u05b6": V_E, "\u05b7": V_A, "\u05b8": V_KAMATS, "\u05b9": V_O, "\u05ba": V_O, "\u05bb": V_U,
|
| 47 |
+
"\u05c4": V_O, "\u05c7": V_O,
|
| 48 |
+
}
|
| 49 |
+
_DAGESH, _SHIN_DOT, _SIN_DOT, _RAFE = "\u05bc", "\u05c1", "\u05c2", "\u05bf"
|
| 50 |
+
_GENDERS = {"unknown": 0, "m": 1, "man": 1, "male": 1, "f": 2, "woman": 2, "female": 2}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def gender(value):
|
| 54 |
+
"""0 unknown, 1 man, 2 woman. Accepts m/f and those integers; omitted means unknown."""
|
| 55 |
+
if value is None or value == "":
|
| 56 |
+
return 0
|
| 57 |
+
if isinstance(value, bool):
|
| 58 |
+
raise ValueError("speaker and listener are unknown, m, f, or 0, 1, 2")
|
| 59 |
+
if isinstance(value, int) and value in (0, 1, 2):
|
| 60 |
+
return value
|
| 61 |
+
if isinstance(value, str):
|
| 62 |
+
key = value.strip().lower()
|
| 63 |
+
if key in _GENDERS:
|
| 64 |
+
return _GENDERS[key]
|
| 65 |
+
if key in ("0", "1", "2"):
|
| 66 |
+
return int(key)
|
| 67 |
+
raise ValueError("speaker and listener are unknown, m, f, or 0, 1, 2")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _is_mark(char):
|
| 71 |
+
return unicodedata.combining(char) != 0 or char in _VOWEL_POINTS or char in (_DAGESH, _SHIN_DOT, _SIN_DOT, _RAFE)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def strip_niqqud(text):
|
| 75 |
+
"""Base characters, plus a vowel-mark id and a consonant-mark id for each one."""
|
| 76 |
+
bases, vowels, consonants = [], [], []
|
| 77 |
+
i, n = 0, len(text)
|
| 78 |
+
while i < n:
|
| 79 |
+
char = text[i]
|
| 80 |
+
if _is_mark(char):
|
| 81 |
+
i += 1
|
| 82 |
+
continue
|
| 83 |
+
vowel, consonant = V_UNPOINTED, C_UNPOINTED
|
| 84 |
+
i += 1
|
| 85 |
+
while i < n and _is_mark(text[i]):
|
| 86 |
+
mark = text[i]
|
| 87 |
+
if "\u05d0" <= char <= "\u05ea":
|
| 88 |
+
if mark in _VOWEL_POINTS:
|
| 89 |
+
vowel = _VOWEL_POINTS[mark]
|
| 90 |
+
elif mark == _DAGESH and char in _BGDKPT:
|
| 91 |
+
consonant = C_DAGESH
|
| 92 |
+
elif mark == _RAFE and char in _BGDKPT and consonant != C_DAGESH:
|
| 93 |
+
consonant = C_NO_DAGESH
|
| 94 |
+
elif char == "ืฉ" and mark == _SHIN_DOT:
|
| 95 |
+
consonant = C_SHIN
|
| 96 |
+
elif char == "ืฉ" and mark == _SIN_DOT:
|
| 97 |
+
consonant = C_SIN
|
| 98 |
+
i += 1
|
| 99 |
+
bases.append(char)
|
| 100 |
+
vowels.append(vowel)
|
| 101 |
+
consonants.append(consonant)
|
| 102 |
+
return "".join(bases), vowels, consonants
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def apply_mark_constraints(consonant, vowel, text, vowel_marks, consonant_marks):
|
| 106 |
+
"""A written point rules out the classes it cannot be. Unpointed letters are left alone."""
|
| 107 |
+
consonant = consonant.copy()
|
| 108 |
+
vowel = vowel.copy()
|
| 109 |
+
for t, char in enumerate(text):
|
| 110 |
+
allowed = VOWEL_MARK_ALLOWS.get(int(vowel_marks[t]))
|
| 111 |
+
if allowed is not None:
|
| 112 |
+
for i in range(vowel.shape[1]):
|
| 113 |
+
if i not in allowed:
|
| 114 |
+
vowel[t, i] = NEG
|
| 115 |
+
allowed = CONSONANT_MARK_ALLOWS.get((char, int(consonant_marks[t])))
|
| 116 |
+
if allowed is not None:
|
| 117 |
+
for i in range(consonant.shape[1]):
|
| 118 |
+
if i not in allowed:
|
| 119 |
+
consonant[t, i] = NEG
|
| 120 |
+
return consonant, vowel
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class Student(nn.Module):
|
| 124 |
+
def __init__(self, config):
|
| 125 |
+
super().__init__()
|
| 126 |
+
width, layers, heads = config["width"], config["layers"], config["heads"]
|
| 127 |
+
vocab = len(config["characters"]) + 2
|
| 128 |
+
self.chars = nn.Embedding(vocab, width, padding_idx=0)
|
| 129 |
+
self.vowel_marks = nn.Embedding(9, width)
|
| 130 |
+
self.consonant_marks = nn.Embedding(5, width)
|
| 131 |
+
self.positions = nn.Embedding(config["max_len"], width)
|
| 132 |
+
self.speaker = nn.Embedding(3, width)
|
| 133 |
+
self.listener = nn.Embedding(3, width)
|
| 134 |
+
layer = nn.TransformerEncoderLayer(width, heads, 4 * width, dropout=0.1, activation="gelu",
|
| 135 |
+
batch_first=True, norm_first=True)
|
| 136 |
+
self.encoder = nn.TransformerEncoder(layer, layers, enable_nested_tensor=False)
|
| 137 |
+
self.norm = nn.LayerNorm(width)
|
| 138 |
+
self.consonant = nn.Linear(width, len(config["consonants"]))
|
| 139 |
+
self.vowel = nn.Linear(width, len(config["vowels"]))
|
| 140 |
+
self.stress = nn.Linear(width, 2)
|
| 141 |
+
|
| 142 |
+
def forward(self, chars, vowel_marks, consonant_marks, speaker, listener):
|
| 143 |
+
n = chars.shape[1]
|
| 144 |
+
x = (self.chars(chars) + self.vowel_marks(vowel_marks) + self.consonant_marks(consonant_marks)
|
| 145 |
+
+ self.positions(torch.arange(n, device=chars.device))[None]
|
| 146 |
+
+ (self.speaker(speaker) + self.listener(listener))[:, None])
|
| 147 |
+
x = self.norm(self.encoder(x, src_key_padding_mask=chars == 0))
|
| 148 |
+
return self.consonant(x), self.vowel(x), self.stress(x)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class _Fixed:
|
| 152 |
+
def __init__(self, outputs):
|
| 153 |
+
self.outputs = outputs
|
| 154 |
+
|
| 155 |
+
def run(self, names, feeds):
|
| 156 |
+
return self.outputs
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _decoder(meta):
|
| 160 |
+
"""RenikudPlus's exact decoding, fed from saved tables instead of its ONNX model."""
|
| 161 |
+
g2p = renikud_onnx.G2P.__new__(renikud_onnx.G2P)
|
| 162 |
+
g2p._consonant_vocab = {i: symbol for i, symbol in enumerate(meta["consonants"])}
|
| 163 |
+
g2p._vowel_vocab = {i: symbol for i, symbol in enumerate(meta["vowels"])}
|
| 164 |
+
g2p._letter_constraints = {letter: list(allowed) for letter, allowed in meta["letter_constraints"].items()}
|
| 165 |
+
g2p._geresh_map = dict(meta["geresh"])
|
| 166 |
+
g2p._wv_c = np.asarray(meta["vowel_cond_consonant"], dtype=np.float32)
|
| 167 |
+
g2p._ws_c = np.asarray(meta["stress_cond_consonant"], dtype=np.float32)
|
| 168 |
+
g2p._ws_v = np.asarray(meta["stress_cond_vowel"], dtype=np.float32)
|
| 169 |
+
g2p._cond_softmax = meta.get("cascade_cond", "softmax") == "softmax"
|
| 170 |
+
n_cons = g2p._wv_c.shape[0]
|
| 171 |
+
g2p._forbidden = np.ones((ord("ืช") - ord("ื") + 1, n_cons), dtype=bool)
|
| 172 |
+
for letter, allowed in g2p._letter_constraints.items():
|
| 173 |
+
if "ื" <= letter <= "ืช":
|
| 174 |
+
g2p._forbidden[ord(letter) - ord("ื"), list(allowed)] = False
|
| 175 |
+
g2p._vocab = {}
|
| 176 |
+
g2p._cls_id = 0
|
| 177 |
+
g2p._sep_id = 0
|
| 178 |
+
g2p.supports_gender = False
|
| 179 |
+
g2p.supports_exact_map = True
|
| 180 |
+
g2p.exact_map_default = True
|
| 181 |
+
g2p._lexicon = None
|
| 182 |
+
return g2p
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def load_safetensors(path):
|
| 186 |
+
dtypes = {"F32": np.float32, "F16": np.float16, "I64": np.int64, "I32": np.int32, "BOOL": np.bool_}
|
| 187 |
+
with open(path, "rb") as f:
|
| 188 |
+
header_len = struct.unpack("<Q", f.read(8))[0]
|
| 189 |
+
header = json.loads(f.read(header_len))
|
| 190 |
+
blob = f.read()
|
| 191 |
+
tensors = {}
|
| 192 |
+
for name, meta in header.items():
|
| 193 |
+
if name == "__metadata__":
|
| 194 |
+
continue
|
| 195 |
+
start, end = meta["data_offsets"]
|
| 196 |
+
array = np.frombuffer(blob, dtype=dtypes[meta["dtype"]], count=(end - start) // np.dtype(dtypes[meta["dtype"]]).itemsize,
|
| 197 |
+
offset=start).reshape(meta["shape"]).copy()
|
| 198 |
+
tensors[name] = torch.from_numpy(array)
|
| 199 |
+
return tensors
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _download(repo, filename):
|
| 203 |
+
folder = Path.home() / ".cache" / "pitput" / repo.replace("/", "--")
|
| 204 |
+
dest = folder / filename
|
| 205 |
+
if dest.is_file() and dest.stat().st_size > 0:
|
| 206 |
+
return dest
|
| 207 |
+
folder.mkdir(parents=True, exist_ok=True)
|
| 208 |
+
url = f"https://huggingface.co/{repo}/resolve/main/{filename}"
|
| 209 |
+
temporary = dest.with_suffix(dest.suffix + ".part")
|
| 210 |
+
request = urllib.request.Request(url, headers={"User-Agent": "pitput-phonemizer"})
|
| 211 |
+
with urllib.request.urlopen(request, timeout=120) as response, open(temporary, "wb") as out:
|
| 212 |
+
while True:
|
| 213 |
+
chunk = response.read(1 << 20)
|
| 214 |
+
if not chunk:
|
| 215 |
+
break
|
| 216 |
+
out.write(chunk)
|
| 217 |
+
temporary.replace(dest)
|
| 218 |
+
return dest
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
class Phonemizer:
|
| 222 |
+
def __init__(self, folder):
|
| 223 |
+
folder = Path(folder)
|
| 224 |
+
self.config = json.loads((folder / "config.json").read_text(encoding="utf-8"))
|
| 225 |
+
self.char_id = {char: i + 2 for i, char in enumerate(self.config["characters"])}
|
| 226 |
+
self.model = Student(self.config)
|
| 227 |
+
self.model.load_state_dict(load_safetensors(folder / "model.safetensors"))
|
| 228 |
+
self.model.eval()
|
| 229 |
+
self._g2p = _decoder(self.config["decoder"])
|
| 230 |
+
self._lock = threading.Lock()
|
| 231 |
+
|
| 232 |
+
@classmethod
|
| 233 |
+
def from_pretrained(cls, repo_or_path):
|
| 234 |
+
path = Path(repo_or_path)
|
| 235 |
+
if path.is_dir():
|
| 236 |
+
return cls(path)
|
| 237 |
+
folder = _download(repo_or_path, "config.json").parent
|
| 238 |
+
_download(repo_or_path, "model.safetensors")
|
| 239 |
+
return cls(folder)
|
| 240 |
+
|
| 241 |
+
def __call__(self, text, *, speaker=None, listener=None):
|
| 242 |
+
speaker, listener = gender(speaker), gender(listener)
|
| 243 |
+
text = renikud_onnx.normalize_numbers(text)
|
| 244 |
+
text = unicodedata.normalize("NFD", renikud_onnx.normalize_graphemes(text))
|
| 245 |
+
base, vowels, consonants = strip_niqqud(text)
|
| 246 |
+
parts, offset = [], 0
|
| 247 |
+
for window in renikud_onnx.split_for_decode(base, self.config["max_len"]):
|
| 248 |
+
n = len(window)
|
| 249 |
+
if n:
|
| 250 |
+
parts.append(self._window(window, vowels[offset:offset + n], consonants[offset:offset + n],
|
| 251 |
+
speaker, listener))
|
| 252 |
+
offset += n
|
| 253 |
+
return "".join(parts)
|
| 254 |
+
|
| 255 |
+
def _window(self, window, vowels, consonants, speaker, listener):
|
| 256 |
+
ids = [self.char_id.get(char, 1) for char in window]
|
| 257 |
+
chars = torch.tensor([ids], dtype=torch.long)
|
| 258 |
+
vowel_marks = torch.tensor([vowels], dtype=torch.long)
|
| 259 |
+
consonant_marks = torch.tensor([consonants], dtype=torch.long)
|
| 260 |
+
with torch.inference_mode():
|
| 261 |
+
consonant, vowel, stress = self.model(chars, vowel_marks, consonant_marks,
|
| 262 |
+
torch.tensor([speaker]), torch.tensor([listener]))
|
| 263 |
+
consonant, vowel = apply_mark_constraints(consonant[0].float().numpy(), vowel[0].float().numpy(),
|
| 264 |
+
window, vowels, consonants)
|
| 265 |
+
stress = stress[0].float().numpy()
|
| 266 |
+
padded = [np.concatenate([np.zeros((1, head.shape[1]), np.float32), head.astype(np.float32),
|
| 267 |
+
np.zeros((1, head.shape[1]), np.float32)])[None]
|
| 268 |
+
for head in (consonant, vowel, stress)]
|
| 269 |
+
with self._lock:
|
| 270 |
+
self._g2p._session = _Fixed(padded)
|
| 271 |
+
return self._g2p._phonemize_window(window, speaker, listener)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def main():
|
| 275 |
+
parser = argparse.ArgumentParser(description="Hebrew text to IPA")
|
| 276 |
+
parser.add_argument("--text", help="the sentence, in UTF-8")
|
| 277 |
+
parser.add_argument("--text-file", type=Path, help="a UTF-8 text file")
|
| 278 |
+
parser.add_argument("--listener", default=None, help="who is spoken to: m, f, or omit to decide")
|
| 279 |
+
parser.add_argument("--speaker", default=None, help="who is speaking: m, f, or omit")
|
| 280 |
+
parser.add_argument("--model", default=None, help="a local folder or a Hub repo id")
|
| 281 |
+
args = parser.parse_args()
|
| 282 |
+
if (args.text is None) == (args.text_file is None):
|
| 283 |
+
parser.error("pass one of --text and --text-file")
|
| 284 |
+
text = args.text if args.text is not None else args.text_file.read_text(encoding="utf-8")
|
| 285 |
+
source = args.model or (str(_HERE) if (_HERE / "model.safetensors").is_file() else REPO)
|
| 286 |
+
print(Phonemizer.from_pretrained(source)(text, speaker=args.speaker, listener=args.listener))
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
if __name__ == "__main__":
|
| 290 |
+
main()
|
renikud_onnx.py
ADDED
|
@@ -0,0 +1,1387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""renikud_onnx โ single-file wrapper for the RenikudPlus ONNX models.
|
| 2 |
+
|
| 3 |
+
Usage: put this file next to your script, then `from renikud_onnx import G2P`.
|
| 4 |
+
Requires: onnxruntime, numpy. Bundles the Hebrew number front end.
|
| 5 |
+
|
| 6 |
+
One optional decode layer beyond the neural graph: a force-only runtime
|
| 7 |
+
lexicon (`lexicon=` โ a surface -> IPA map that always wins where it
|
| 8 |
+
matches). Off unless you pass one.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import re
|
| 14 |
+
import unicodedata
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
# --------------------------------------------------------------------------
|
| 19 |
+
# Number words
|
| 20 |
+
# --------------------------------------------------------------------------
|
| 21 |
+
|
| 22 |
+
MASC_UNITS = ["ืืคืก", "ืืื", "ืฉื ืืื", "ืฉืืืฉื", "ืืจืืขื", "ืืืืฉื", "ืฉืืฉื", "ืฉืืขื", "ืฉืืื ื", "ืชืฉืขื", "ืขืฉืจื"]
|
| 23 |
+
FEM_UNITS = ["ืืคืก", "ืืืช", "ืฉืชืืื", "ืฉืืืฉ", "ืืจืืข", "ืืืฉ", "ืฉืฉ", "ืฉืืข", "ืฉืืื ื", "ืชืฉืข", "ืขืฉืจ"]
|
| 24 |
+
|
| 25 |
+
# Construct ("smikhut") forms, used for 2 before a counted noun and for the
|
| 26 |
+
# 3..10 multipliers of ืืืคืื.
|
| 27 |
+
MASC_CONSTRUCT = {2: "ืฉื ื", 3: "ืฉืืืฉืช", 4: "ืืจืืขืช", 5: "ืืืฉืช", 6: "ืฉืฉืช", 7: "ืฉืืขืช",
|
| 28 |
+
8: "ืฉืืื ืช", 9: "ืชืฉืขืช", 10: "ืขืฉืจืช"}
|
| 29 |
+
FEM_CONSTRUCT = {2: "ืฉืชื"}
|
| 30 |
+
|
| 31 |
+
MASC_TEENS = ["ืืื ืขืฉืจ", "ืฉื ืื ืขืฉืจ", "ืฉืืืฉื ืขืฉืจ", "ืืจืืขื ืขืฉืจ", "ืืืืฉื ืขืฉืจ",
|
| 32 |
+
"ืฉืืฉื ืขืฉืจ", "ืฉืืขื ืขืฉืจ", "ืฉืืื ื ืขืฉืจ", "ืชืฉืขื ืขืฉืจ"]
|
| 33 |
+
FEM_TEENS = ["ืืืช ืขืฉืจื", "ืฉืชืื ืขืฉืจื", "ืฉืืืฉ ืขืฉืจื", "ืืจืืข ืขืฉืจื", "ืืืฉ ืขืฉืจื",
|
| 34 |
+
"ืฉืฉ ืขืฉืจื", "ืฉืืข ืขืฉืจื", "ืฉืืื ื ืขืฉืจื", "ืชืฉืข ืขืฉืจื"]
|
| 35 |
+
|
| 36 |
+
TENS = {2: "ืขืฉืจืื", 3: "ืฉืืืฉืื", 4: "ืืจืืขืื", 5: "ืืืืฉืื",
|
| 37 |
+
6: "ืฉืืฉืื", 7: "ืฉืืขืื", 8: "ืฉืืื ืื", 9: "ืชืฉืขืื"}
|
| 38 |
+
|
| 39 |
+
HUNDREDS = {1: "ืืื", 2: "ืืืชืืื", 3: "ืฉืืืฉ ืืืืช", 4: "ืืจืืข ืืืืช", 5: "ืืืฉ ืืืืช",
|
| 40 |
+
6: "ืฉืฉ ืืืืช", 7: "ืฉืืข ืืืืช", 8: "ืฉืืื ื ืืืืช", 9: "ืชืฉืข ืืืืช"}
|
| 41 |
+
|
| 42 |
+
ORD_MASC = {1: "ืจืืฉืื", 2: "ืฉื ื", 3: "ืฉืืืฉื", 4: "ืจืืืขื", 5: "ืืืืฉื",
|
| 43 |
+
6: "ืฉืืฉื", 7: "ืฉืืืขื", 8: "ืฉืืื ื", 9: "ืชืฉืืขื", 10: "ืขืฉืืจื"}
|
| 44 |
+
ORD_FEM = {1: "ืจืืฉืื ื", 2: "ืฉื ืืื", 3: "ืฉืืืฉืืช", 4: "ืจืืืขืืช", 5: "ืืืืฉืืช",
|
| 45 |
+
6: "ืฉืืฉืืช", 7: "ืฉืืืขืืช", 8: "ืฉืืื ืืช", 9: "ืชืฉืืขืืช", 10: "ืขืฉืืจืืช"}
|
| 46 |
+
|
| 47 |
+
MONTHS = {1: "ืื ืืืจ", 2: "ืคืืจืืืจ", 3: "ืืจืฅ", 4: "ืืคืจืื", 5: "ืืื", 6: "ืืื ื",
|
| 48 |
+
7: "ืืืื", 8: "ืืืืืกื", 9: "ืกืคืืืืจ", 10: "ืืืงืืืืจ", 11: "ื ืืืืืจ", 12: "ืืฆืืืจ"}
|
| 49 |
+
MONTH_NAMES = set(MONTHS.values())
|
| 50 |
+
|
| 51 |
+
FRACTIONS = {
|
| 52 |
+
(1, 2): "ืืฆื", (1, 3): "ืฉืืืฉ", (1, 4): "ืจืืข", (2, 3): "ืฉื ื ืฉืืืฉืื",
|
| 53 |
+
(3, 4): "ืฉืืืฉืช ืจืืขื", (1, 5): "ืืืืฉืืช", (2, 5): "ืฉืชื ืืืืฉืืืช",
|
| 54 |
+
(3, 5): "ืฉืืืฉ ืืืืฉืืืช", (4, 5): "ืืจืืข ืืืืฉืืืช", (1, 6): "ืฉืืฉืืช",
|
| 55 |
+
(1, 8): "ืฉืืื ืืช", (3, 8): "ืฉืืืฉ ืฉืืื ืืืช", (1, 10): "ืขืฉืืจืืช",
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
MASC, FEM = "m", "f"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _vav(word: str) -> str:
|
| 62 |
+
"""Attach the conjunction ื to a word (orthography only; the model does the
|
| 63 |
+
phonology, so no โu/ve sandhi is applied here)."""
|
| 64 |
+
return "ื" + word
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _units(n: int, gender: str) -> str:
|
| 68 |
+
return (MASC_UNITS if gender == MASC else FEM_UNITS)[n]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _teens(n: int, gender: str) -> str:
|
| 72 |
+
return (MASC_TEENS if gender == MASC else FEM_TEENS)[n - 11]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _thousands_words(k: int) -> list[str]:
|
| 76 |
+
"""The ืืืฃ / ืืืคืื group for a multiplier `k` (1 .. 999)."""
|
| 77 |
+
if k == 1:
|
| 78 |
+
return ["ืืืฃ"]
|
| 79 |
+
if k == 2:
|
| 80 |
+
return ["ืืืคืืื"]
|
| 81 |
+
if k in MASC_CONSTRUCT:
|
| 82 |
+
return [MASC_CONSTRUCT[k], "ืืืคืื"]
|
| 83 |
+
return cardinal(k, MASC).split() + ["ืืืฃ"]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _sub_thousand_groups(n: int, gender: str) -> list[list[str]]:
|
| 87 |
+
"""Split 1..999 into word groups (hundreds / tens+units)."""
|
| 88 |
+
groups: list[list[str]] = []
|
| 89 |
+
if n >= 100:
|
| 90 |
+
groups.append(HUNDREDS[n // 100].split())
|
| 91 |
+
n %= 100
|
| 92 |
+
if n >= 20:
|
| 93 |
+
tail = [TENS[n // 10]]
|
| 94 |
+
if n % 10:
|
| 95 |
+
tail.append(_vav(_units(n % 10, gender)))
|
| 96 |
+
groups.append(tail)
|
| 97 |
+
elif n >= 11:
|
| 98 |
+
groups.append(_teens(n, gender).split())
|
| 99 |
+
elif n >= 1:
|
| 100 |
+
groups.append([_units(n, gender)])
|
| 101 |
+
return groups
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def cardinal(n: int, gender: str = FEM, construct: bool = False) -> str:
|
| 105 |
+
"""Hebrew cardinal for 0 .. 999,999.
|
| 106 |
+
|
| 107 |
+
`construct` yields ืฉื ื / ืฉืชื (2) and ืฉืืืฉืช โฆ ืขืฉืจืช (3..10), the forms used
|
| 108 |
+
before a counted noun in the gold asset.
|
| 109 |
+
"""
|
| 110 |
+
if n < 0:
|
| 111 |
+
return "ืืื ืืก " + cardinal(-n, gender, construct)
|
| 112 |
+
if n == 0:
|
| 113 |
+
return "ืืคืก"
|
| 114 |
+
if construct:
|
| 115 |
+
table = MASC_CONSTRUCT if gender == MASC else FEM_CONSTRUCT
|
| 116 |
+
if n in table:
|
| 117 |
+
return table[n]
|
| 118 |
+
groups: list[list[str]] = []
|
| 119 |
+
if n >= 1000:
|
| 120 |
+
groups.append(_thousands_words(n // 1000))
|
| 121 |
+
n %= 1000
|
| 122 |
+
groups.extend(_sub_thousand_groups(n, gender))
|
| 123 |
+
# The conjunction lands on the final component only, and only when that
|
| 124 |
+
# component does not already carry one (โฆืฉืืืฉืื ืืฉื ืืื keeps a single ื).
|
| 125 |
+
if len(groups) > 1 and not any(w.startswith("ื") for w in groups[-1]):
|
| 126 |
+
groups[-1] = [_vav(groups[-1][0])] + groups[-1][1:]
|
| 127 |
+
return " ".join(w for g in groups for w in g)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def ordinal(n: int, gender: str = MASC, definite: bool = False) -> str:
|
| 131 |
+
"""Hebrew ordinal. Above 10 Hebrew uses the definite cardinal
|
| 132 |
+
(``ื-11`` โ ืืืืช ืขืฉืจื), which is what the gold asset does."""
|
| 133 |
+
table = ORD_MASC if gender == MASC else ORD_FEM
|
| 134 |
+
if n in table:
|
| 135 |
+
word = table[n]
|
| 136 |
+
return ("ื" + word) if definite else word
|
| 137 |
+
card = cardinal(n, FEM if gender == FEM else MASC)
|
| 138 |
+
return ("ื" + card) if definite else card
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def spell_digits(digits: str) -> str:
|
| 142 |
+
"""Digit-by-digit reading (identifiers, phone numbers, codes)."""
|
| 143 |
+
return " ".join(FEM_UNITS[int(d)] for d in digits)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# --------------------------------------------------------------------------
|
| 147 |
+
# Gender of the counted noun
|
| 148 |
+
# --------------------------------------------------------------------------
|
| 149 |
+
|
| 150 |
+
# ึพืื plurals that are feminine, and ึพืืช plurals that are masculine: the two
|
| 151 |
+
# classes the ending heuristic gets wrong.
|
| 152 |
+
FEM_IM_PLURALS = {
|
| 153 |
+
"ืฉื ืื", "ื ืฉืื", "ืืืืื", "ืืืฆืื", "ืืืืจืื", "ืืืืื", "ืชืื ืื", "ืคืขืืื",
|
| 154 |
+
"ืืื ืื", "ืขืฆืื", "ืืื ืื", "ืฆืคืจื ืืื", "ืฉืขืืจืื",
|
| 155 |
+
}
|
| 156 |
+
MASC_OT_PLURALS = {
|
| 157 |
+
"ืฉืืืื ืืช", "ืืืกืืืช", "ืืงืืืืช", "ืืืืืช", "ืงืืืืช", "ืืืืืืช", "ืจืืืืืช",
|
| 158 |
+
"ืืืืช", "ืฉืืืช", "ืืืืืช", "ืงืืจืืช", "ืืืืขืืช", "ืฉืืืขืืช", "ืจืขืืื ืืช",
|
| 159 |
+
"ืืืื ืืช", "ืื ืืืช", "ืืืืืืช", "ืกืืื ืื", "ืืจืืืช", "ื ืืกืื",
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
# Explicit singular / irregular entries. Everything else falls through to the
|
| 163 |
+
# ending heuristic below.
|
| 164 |
+
NOUN_GENDER = {
|
| 165 |
+
# feminine
|
| 166 |
+
"ืฉืขื": FEM, "ืฉืขืืช": FEM, "ืืงื": FEM, "ืืงืืช": FEM, "ืฉื ืื": FEM, "ืฉื ืืืช": FEM,
|
| 167 |
+
"ืฉื ื": FEM, "ืฉื ืืช": FEM, "ืื ื": FEM, "ืื ืืช": FEM, "ืืืก": FEM, "ืืืกืืช": FEM,
|
| 168 |
+
"ืงืืื": FEM, "ืงืืืืช": FEM, "ืคืขื": FEM, "ืคืขืืื": FEM, "ืืช": FEM, "ืื ืืช": FEM,
|
| 169 |
+
"ืืขืื": FEM, "ืืขืืืช": FEM, "ืืืกื": FEM, "ืืืกืืช": FEM, "ืืืฉื": FEM, "ื ืฉืื": FEM,
|
| 170 |
+
"ืืืจื": FEM, "ืืืจืืช": FEM, "ืขืื ื": FEM, "ืขืื ืืช": FEM, "ืฉืืจื": FEM, "ืฉืืจืืช": FEM,
|
| 171 |
+
"ืื ืืช": FEM, "ืื ืืืืช": FEM, "ืืกืขืื": FEM, "ืืกืขืืืช": FEM, "ืคืืืฉื": FEM, "ืคืืืฉืืช": FEM,
|
| 172 |
+
"ืืืืื": FEM, "ืืืืืืช": FEM, "ืืฉืืื": FEM, "ืืฉืืืืช": FEM, "ืืืืจืช": FEM, "ืืืืจืืช": FEM,
|
| 173 |
+
"ืืขืืคื": FEM, "ืืขืืคืืช": FEM, "ืืืืฆื": FEM, "ืืืืฆืืช": FEM, "ืืืื": FEM, "ืืืืืช": FEM,
|
| 174 |
+
"ืืืช": FEM, "ืืืชืืช": FEM, "ืจืื": FEM, "ืจืืืืื": FEM, "ืื": FEM, "ืืืืื": FEM,
|
| 175 |
+
"ืขืื": FEM, "ืขืื ืืื": FEM, "ืืืื": FEM, "ืืืื ืืื": FEM, "ืขืืจ": FEM, "ืขืจืื": FEM,
|
| 176 |
+
"ืืจืฅ": FEM, "ืืจื": FEM, "ื ืคืฉ": FEM, "ืืืชื": FEM, "ืืืชืืช": FEM,
|
| 177 |
+
# masculine
|
| 178 |
+
"ืฉืงื": MASC, "ืฉืงืืื": MASC, 'ืฉ"ื': MASC, "ืืืืจื": FEM, "ืืืืจืืช": FEM,
|
| 179 |
+
"ืืืืจ": MASC, "ืืืืจืื": MASC, "ืืืจื": MASC, "ืืืจื": MASC,
|
| 180 |
+
"ืืื": MASC, "ืืืื": MASC, "ืืื": MASC, "ืืืืฉ": MASC, "ืืืืฉืื": MASC, "ืืืืฉื": MASC,
|
| 181 |
+
"ืฉืืืข": MASC, "ืฉืืืขืืช": MASC, "ืืืฉ": MASC, "ืื ืฉืื": MASC, "ืืื": MASC, "ืืืืื": MASC,
|
| 182 |
+
"ืื": MASC, "ืื ืื": MASC, "ืืืจ": MASC, "ืืืจืื": MASC, "ืขืืื": MASC, "ืขืืืืื": MASC,
|
| 183 |
+
"ืกืคืจ": MASC, "ืกืคืจืื": MASC, "ืืื": MASC, "ืืืืื": MASC, "ืืชืื": MASC, "ืืชืืืื": MASC,
|
| 184 |
+
"ืชืคืื": MASC, "ืชืคืืืื": MASC, "ืืจืืืก": MASC, "ืืจืืืกืื": MASC,
|
| 185 |
+
"ืืืจ": MASC, "ืืืจืื": MASC, "ืงืืืืืืจ": MASC, "ืงืืื": MASC, "ืืืืจ": MASC,
|
| 186 |
+
"ืืืืืื": MASC, "ืืืืืืจื": MASC, "ืืืฃ": MASC, "ืืืื": MASC, "ืืืืืื": MASC,
|
| 187 |
+
"ืืืฆืจ": MASC, "ืืืฆืจืื": MASC, "ืืฉืชืชืฃ": MASC, "ืืฉืชืชืคืื": MASC,
|
| 188 |
+
"ืื ืืื": MASC, "ืื ืืื ืื": MASC, "ืืฉืจื": MASC, "ืืฉืจืืื": MASC,
|
| 189 |
+
"ืกืืืื ื": MASC, "ืกืืืื ืืื": MASC, "ืืืืจ": MASC, "ืืืืจืื": MASC,
|
| 190 |
+
"ืขื": MASC, "ืขืืื": MASC, "ืืืชื": MASC, "ืืืชืืื": MASC, "ืืืืจ": MASC, "ืืืืจืื": MASC,
|
| 191 |
+
"ื ืจืฉื": MASC, "ื ืจืฉืืื": MASC, "ืคืืขื": MASC, "ืคืืขืืื": MASC,
|
| 192 |
+
'ืง"ื': MASC, 'ืง"ื': MASC, 'ื"ืจ': MASC, 'ืงื"ืฉ': MASC, 'ื"ื': MASC, 'ืก"ื': MASC,
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
# Prefix letters that can be glued onto a Hebrew word.
|
| 196 |
+
_PREFIX_RE = re.compile(r"^(?:[ืืืืืฉื]?ื|[ืืืืืฉืื])")
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _strip_prefix(word: str) -> str:
|
| 200 |
+
if len(word) > 3:
|
| 201 |
+
stripped = _PREFIX_RE.sub("", word, count=1)
|
| 202 |
+
if len(stripped) >= 2:
|
| 203 |
+
return stripped
|
| 204 |
+
return word
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def noun_gender(word: str) -> str | None:
|
| 208 |
+
"""Gender of a counted noun, or None when `word` does not look like one.
|
| 209 |
+
|
| 210 |
+
Order: explicit lexicon โ irregular-plural sets โ ending heuristic.
|
| 211 |
+
Returning None (rather than defaulting) is what lets the caller tell
|
| 212 |
+
"8 ืฉืขืืช" (counted) apart from "ื-8 ืฉืืืืชื" (an hour).
|
| 213 |
+
"""
|
| 214 |
+
word = word.strip(".,!?;:\"'()[]โโ-")
|
| 215 |
+
if not word:
|
| 216 |
+
return None
|
| 217 |
+
for candidate in (word, _strip_prefix(word)):
|
| 218 |
+
if candidate in NOUN_GENDER:
|
| 219 |
+
return NOUN_GENDER[candidate]
|
| 220 |
+
if candidate in FEM_IM_PLURALS:
|
| 221 |
+
return FEM
|
| 222 |
+
if candidate in MASC_OT_PLURALS:
|
| 223 |
+
return MASC
|
| 224 |
+
stem = _strip_prefix(word)
|
| 225 |
+
if len(stem) < 3:
|
| 226 |
+
return None
|
| 227 |
+
if stem.endswith("ืืืช") or stem.endswith("ืืช"):
|
| 228 |
+
return FEM
|
| 229 |
+
if stem.endswith("ืื") or stem.endswith("ืืื"):
|
| 230 |
+
return MASC
|
| 231 |
+
return None
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# --------------------------------------------------------------------------
|
| 235 |
+
# Context vocabularies
|
| 236 |
+
# --------------------------------------------------------------------------
|
| 237 |
+
|
| 238 |
+
# A numeral within 3 tokens after one of these is an identifier, not a count.
|
| 239 |
+
CODE_NOUNS = {
|
| 240 |
+
"ืงืื", "ืืกืคืจ", "ืืืงืื", "ืกืืกืื", "ืกืืกืื", "ืกืืืืช", "ืืจืงืื", "ืืืคืื",
|
| 241 |
+
"ืฉืืืื", "ืกื ืืฃ", "ืืืื", "ืืจืืืก", "ืืฉืจืื", "ืคืืืืกื", "ืืืื ื",
|
| 242 |
+
"ืืฉืืื", "ืืืืช", "ืช.ื", 'ืช"ื', "ืจืืฉืืื", "ืืืืืช", "ืคื ืืื", "ืกืืื",
|
| 243 |
+
"ืกืืืืจื", "ืืฉืื", "ืืืฉื", "ืื ืง", "ืืืฉื", "ื", "ืื ืขืื",
|
| 244 |
+
}
|
| 245 |
+
# A bare numeral right after one of these is an ordinal.
|
| 246 |
+
ORDINAL_NOUNS = {
|
| 247 |
+
"ืงืืื", "ืคืขื", "ืืงืื", "ืคืจืง", "ืืืง", "ืขืื ื", "ืืกื", "ืฉืืจื", "ืฉืื",
|
| 248 |
+
"ืืืชื", "ืจืืขืื", "ืกืืืื", "ืืืืืจ",
|
| 249 |
+
}
|
| 250 |
+
HOUR_CUES = {"ืฉืขื", "ืืฉืขื", "ืืฉืขื", "ืืฉืขื", "ืฉืขืื", "ืืฉืขืื"}
|
| 251 |
+
DAY_OF_MONTH_CUES = {"ืืืืืฉ", "ืืืืืฉ", "ืืืืืฉ"}
|
| 252 |
+
YEAR_CUES = {"ืฉื ืช", "ืืฉื ืช", "ืืฉื ืช", "ืืฉื ืช", "ืฉื ื", "ืืฉื ื"}
|
| 253 |
+
|
| 254 |
+
_PUNCT_TAIL = ".,!?;:\"')]โฆ"
|
| 255 |
+
_HEB = "ึ-ืช"
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
# --------------------------------------------------------------------------
|
| 259 |
+
# Sub-expanders
|
| 260 |
+
# --------------------------------------------------------------------------
|
| 261 |
+
|
| 262 |
+
def _hour_word(h: int) -> str:
|
| 263 |
+
"""12-hour clock hour, feminine (the gold asset always converts 24hโ12h)."""
|
| 264 |
+
h = h % 24
|
| 265 |
+
if h == 0:
|
| 266 |
+
h = 12
|
| 267 |
+
if h > 12:
|
| 268 |
+
h -= 12
|
| 269 |
+
return cardinal(h, FEM)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def expand_time(hh: int, mm: int) -> str:
|
| 273 |
+
"""`hh:mm` โ spoken Hebrew. ืืจืืข / ืืืฆื / ืจืืข ืึพ / ืขืฉืจืื ืึพ."""
|
| 274 |
+
hour = _hour_word(hh)
|
| 275 |
+
if mm == 0:
|
| 276 |
+
return hour
|
| 277 |
+
if mm == 15:
|
| 278 |
+
return hour + " ืืจืืข"
|
| 279 |
+
if mm == 30:
|
| 280 |
+
return hour + " ืืืฆื"
|
| 281 |
+
if mm == 45:
|
| 282 |
+
return "ืจืืข ื" + _hour_word(hh + 1)
|
| 283 |
+
if mm < 30:
|
| 284 |
+
return hour + " " + _vav(cardinal(mm, MASC))
|
| 285 |
+
if mm > 30:
|
| 286 |
+
return cardinal(60 - mm, MASC) + " ื" + _hour_word(hh + 1)
|
| 287 |
+
return hour
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def expand_date(day: int, month: int, year: int | None) -> str:
|
| 291 |
+
"""`D.M[.YYYY]` โ masculine day + ื+month + feminine year."""
|
| 292 |
+
out = cardinal(day, MASC) + " ื" + MONTHS[month]
|
| 293 |
+
if year is not None:
|
| 294 |
+
out += " " + cardinal(year, FEM)
|
| 295 |
+
return out
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def expand_year(n: int) -> str:
|
| 299 |
+
return cardinal(n, FEM)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def _decimal_words(int_part: str, frac_part: str, gender: str) -> str:
|
| 303 |
+
ip, fp = int(int_part), frac_part
|
| 304 |
+
if fp == "5":
|
| 305 |
+
# X.5 โ "X ืืืฆื", the dominant reading in the gold asset.
|
| 306 |
+
if ip == 0:
|
| 307 |
+
return "ืืฆื"
|
| 308 |
+
return cardinal(ip, gender) + " ืืืฆื"
|
| 309 |
+
if len(fp) == 2:
|
| 310 |
+
# Price reading: 19.90 โ "ืชืฉืข ืขืฉืจื ืชืฉืขืื".
|
| 311 |
+
return cardinal(ip, FEM if ip != 1 else MASC) + " " + cardinal(int(fp), FEM)
|
| 312 |
+
head = cardinal(ip, MASC) if ip == 1 else cardinal(ip, FEM)
|
| 313 |
+
return head + " ื ืงืืื " + " ".join(FEM_UNITS[int(d)] for d in fp)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _grouped_digits(groups: list[str]) -> str:
|
| 317 |
+
"""Phone / serial numbers: hyphen groups read digit by digit, except the
|
| 318 |
+
1-800 style service numbers whose 3-digit groups are read as numbers."""
|
| 319 |
+
if groups and groups[0] in {"1", "*"} and len(groups) > 1 and len(groups[1]) == 3:
|
| 320 |
+
out = [spell_digits(groups[0]) if len(groups[0]) > 1 else FEM_UNITS[int(groups[0])]]
|
| 321 |
+
out[0] = MASC_UNITS[int(groups[0])] if len(groups[0]) == 1 else out[0]
|
| 322 |
+
for g in groups[1:]:
|
| 323 |
+
out.append(cardinal(int(g), FEM))
|
| 324 |
+
return " ".join(out)
|
| 325 |
+
return " ".join(spell_digits(g) for g in groups)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
# --------------------------------------------------------------------------
|
| 329 |
+
# Token-level driver
|
| 330 |
+
# --------------------------------------------------------------------------
|
| 331 |
+
|
| 332 |
+
_TOKEN_RE = re.compile(
|
| 333 |
+
rf"^(?P<pre>[{_HEB}\"']{{0,4}})(?P<sep>-?)(?P<body>\d[\d.,:/%\-]*?)(?P<post>[{re.escape(_PUNCT_TAIL)}]*)$"
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def _next_noun_gender(next_words: list[str]) -> tuple[str | None, str | None]:
|
| 338 |
+
"""(gender, noun) of the first following token that looks like a noun.
|
| 339 |
+
Only the immediately-following token is consulted โ a numeral in Hebrew
|
| 340 |
+
binds to the noun it precedes."""
|
| 341 |
+
if not next_words:
|
| 342 |
+
return None, None
|
| 343 |
+
w = next_words[0]
|
| 344 |
+
g = noun_gender(w)
|
| 345 |
+
return g, (w if g else None)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def _is_code_context(prev_words: list[str]) -> bool:
|
| 349 |
+
# A cue belongs to the first numeral that follows it: stop the search at
|
| 350 |
+
# the previous numeral so "ืงืื 500 ืืขืืืช 500 ืืืฉ" reads the second 500 as
|
| 351 |
+
# a number, not as a code.
|
| 352 |
+
for i in range(len(prev_words) - 1, -1, -1):
|
| 353 |
+
if any(c.isdigit() for c in prev_words[i]):
|
| 354 |
+
prev_words = prev_words[i + 1:]
|
| 355 |
+
break
|
| 356 |
+
for w in prev_words[-3:]:
|
| 357 |
+
base = w.strip(_PUNCT_TAIL + "-")
|
| 358 |
+
if base in CODE_NOUNS or _strip_prefix(base) in CODE_NOUNS:
|
| 359 |
+
return True
|
| 360 |
+
return False
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def _in_set(word: str, vocab: set[str]) -> bool:
|
| 364 |
+
return word in vocab or _strip_prefix(word) in vocab
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _prev_base(prev_words: list[str], k: int = 1) -> str:
|
| 368 |
+
if len(prev_words) < k:
|
| 369 |
+
return ""
|
| 370 |
+
return prev_words[-k].strip(_PUNCT_TAIL + "-")
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def _month_follows(next_words: list[str]) -> bool:
|
| 374 |
+
if not next_words:
|
| 375 |
+
return False
|
| 376 |
+
w = next_words[0].strip(_PUNCT_TAIL)
|
| 377 |
+
if w in DAY_OF_MONTH_CUES:
|
| 378 |
+
return True
|
| 379 |
+
stripped = re.sub(rf"^[ืืืื]", "", w, count=1)
|
| 380 |
+
return w in MONTH_NAMES or stripped in MONTH_NAMES
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def expand_integer(body: str, pre: str, prev_words: list[str], next_words: list[str]) -> str:
|
| 384 |
+
"""The main decision tree for a bare integer token."""
|
| 385 |
+
digits = body
|
| 386 |
+
n = int(digits)
|
| 387 |
+
|
| 388 |
+
# 1. identifiers -> digit by digit
|
| 389 |
+
if (len(digits) >= 5
|
| 390 |
+
or (len(digits) >= 3 and _is_code_context(prev_words))
|
| 391 |
+
or (len(digits) > 1 and digits[0] == "0")):
|
| 392 |
+
return spell_digits(digits)
|
| 393 |
+
|
| 394 |
+
# 2. years
|
| 395 |
+
if _prev_base(prev_words) in YEAR_CUES or (len(digits) == 4 and 1500 <= n <= 2200
|
| 396 |
+
and _prev_base(prev_words) in YEAR_CUES):
|
| 397 |
+
return expand_year(n)
|
| 398 |
+
|
| 399 |
+
# 3. day of month
|
| 400 |
+
if _month_follows(next_words) and 1 <= n <= 31:
|
| 401 |
+
return cardinal(n, MASC)
|
| 402 |
+
|
| 403 |
+
# 4. ordinal: the "ื-N" construction, or a bare numeral after an ordinal noun
|
| 404 |
+
prev = _prev_base(prev_words)
|
| 405 |
+
prev_stripped = prev if prev in ORDINAL_NOUNS else _strip_prefix(prev)
|
| 406 |
+
if pre.endswith("ื") and n <= 999:
|
| 407 |
+
# "ื-N": the definite article is already in `pre` and gets re-attached
|
| 408 |
+
# by the caller, so the ordinal itself is produced bare.
|
| 409 |
+
g = NOUN_GENDER.get(prev_stripped) or noun_gender(prev) or MASC
|
| 410 |
+
return ordinal(n, g)
|
| 411 |
+
if prev_stripped in ORDINAL_NOUNS and n <= 10:
|
| 412 |
+
return ordinal(n, NOUN_GENDER.get(prev_stripped, MASC))
|
| 413 |
+
|
| 414 |
+
# 5. counted noun follows -> agree with it
|
| 415 |
+
g, _noun = _next_noun_gender(next_words)
|
| 416 |
+
if g is not None:
|
| 417 |
+
if n == 2:
|
| 418 |
+
return cardinal(2, g, construct=True)
|
| 419 |
+
return cardinal(n, g)
|
| 420 |
+
|
| 421 |
+
# 6. hour context
|
| 422 |
+
if (pre in {"ื", "ื", "ื"} or prev in {"ืขื", "ืืขื"}
|
| 423 |
+
or prev in HOUR_CUES or _prev_base(prev_words, 2) in HOUR_CUES):
|
| 424 |
+
if 0 <= n <= 24 and not _is_code_context(prev_words):
|
| 425 |
+
return _hour_word(n)
|
| 426 |
+
|
| 427 |
+
# 7. bare numeral: absolute (feminine) series, 1 -> ืืื
|
| 428 |
+
return cardinal(n, MASC if n == 1 else FEM)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
def expand_body(body: str, pre: str, prev_words: list[str], next_words: list[str]) -> str:
|
| 432 |
+
"""Expand the numeric core of a token (no prefix, no trailing punctuation)."""
|
| 433 |
+
# -- percent -------------------------------------------------------
|
| 434 |
+
if body.endswith("%"):
|
| 435 |
+
core = body[:-1]
|
| 436 |
+
# thousands separators may appear inside a percent core ("51,034%")
|
| 437 |
+
if re.fullmatch(r"\d{1,3}(?:,\d{3})+", core):
|
| 438 |
+
core = core.replace(",", "")
|
| 439 |
+
# The source sometimes writes both the sign and the word ("10% ืืืื").
|
| 440 |
+
tail = "" if (next_words and next_words[0].strip(_PUNCT_TAIL) in {"ืืืื", "ืืืืืื"}) else " ืืืื"
|
| 441 |
+
if "." in core:
|
| 442 |
+
ip, fp = core.split(".", 1)
|
| 443 |
+
return _decimal_words(ip, fp, MASC) + tail
|
| 444 |
+
return cardinal(int(core), MASC) + tail
|
| 445 |
+
|
| 446 |
+
# -- clock ---------------------------------------------------------
|
| 447 |
+
m = re.fullmatch(r"(\d{1,2}):(\d{2})", body)
|
| 448 |
+
if m:
|
| 449 |
+
return expand_time(int(m.group(1)), int(m.group(2)))
|
| 450 |
+
|
| 451 |
+
# -- fraction / date with slash ------------------------------------
|
| 452 |
+
m = re.fullmatch(r"(\d{1,2})/(\d{1,4})", body)
|
| 453 |
+
if m:
|
| 454 |
+
a, b = int(m.group(1)), int(m.group(2))
|
| 455 |
+
if (a, b) in FRACTIONS:
|
| 456 |
+
return FRACTIONS[(a, b)]
|
| 457 |
+
if 1 <= b <= 12 and 1 <= a <= 31:
|
| 458 |
+
return expand_date(a, b, None)
|
| 459 |
+
return cardinal(a, FEM) + " " + cardinal(b, FEM)
|
| 460 |
+
|
| 461 |
+
# -- phone / serial with hyphens -----------------------------------
|
| 462 |
+
if "-" in body:
|
| 463 |
+
groups = body.split("-")
|
| 464 |
+
if all(g.isdigit() for g in groups) and len(groups) >= 2:
|
| 465 |
+
if len(groups) >= 3 or any(len(g) >= 5 for g in groups):
|
| 466 |
+
return _grouped_digits(groups)
|
| 467 |
+
if all(len(g) <= 2 for g in groups): # score line, e.g. 3-0
|
| 468 |
+
return " ".join(cardinal(int(g), FEM) for g in groups)
|
| 469 |
+
return _grouped_digits(groups)
|
| 470 |
+
|
| 471 |
+
# -- thousands separators ------------------------------------------
|
| 472 |
+
if re.fullmatch(r"\d{1,3}(?:,\d{3})+", body):
|
| 473 |
+
n = int(body.replace(",", ""))
|
| 474 |
+
g, _ = _next_noun_gender(next_words)
|
| 475 |
+
if n >= 1_000_000:
|
| 476 |
+
head = n // 1_000_000
|
| 477 |
+
rest = n % 1_000_000
|
| 478 |
+
word = "ืืืืืื" if head == 1 else cardinal(head, MASC, construct=True) + " ืืืืืื"
|
| 479 |
+
return word if rest == 0 else word + " " + cardinal(rest, g or MASC)
|
| 480 |
+
return cardinal(n, g or MASC)
|
| 481 |
+
|
| 482 |
+
# -- dates ----------------------------------------------------------
|
| 483 |
+
m = re.fullmatch(r"(\d{1,2})\.(\d{1,2})\.(\d{4})", body)
|
| 484 |
+
if m:
|
| 485 |
+
d, mo, y = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
| 486 |
+
if 1 <= d <= 31 and 1 <= mo <= 12:
|
| 487 |
+
return expand_date(d, mo, y)
|
| 488 |
+
m = re.fullmatch(r"(\d{1,2})\.(\d{4})", body)
|
| 489 |
+
if m and 1 <= int(m.group(1)) <= 12:
|
| 490 |
+
return "ื" + MONTHS[int(m.group(1))] + " " + cardinal(int(m.group(2)), FEM)
|
| 491 |
+
|
| 492 |
+
# -- one decimal point ---------------------------------------------
|
| 493 |
+
m = re.fullmatch(r"(\d+)\.(\d+)", body)
|
| 494 |
+
if m:
|
| 495 |
+
ip_s, fp_s = m.group(1), m.group(2)
|
| 496 |
+
ip, fp = int(ip_s), int(fp_s)
|
| 497 |
+
clock_cue = (_prev_base(prev_words) in HOUR_CUES)
|
| 498 |
+
# "ื-1.9" style: a prefixed D.M with a plausible month and no unit noun
|
| 499 |
+
# after it is a date, not a decimal.
|
| 500 |
+
unit_follows = bool(next_words) and noun_gender(next_words[0]) is not None
|
| 501 |
+
if (not clock_cue and pre in {"ื", "ื", "ื"} and len(fp_s) <= 2
|
| 502 |
+
and 1 <= fp <= 12 and 1 <= ip <= 31 and not unit_follows):
|
| 503 |
+
return expand_date(ip, fp, None)
|
| 504 |
+
if clock_cue and len(fp_s) == 2:
|
| 505 |
+
return expand_time(ip, fp)
|
| 506 |
+
g, _ = _next_noun_gender(next_words)
|
| 507 |
+
return _decimal_words(ip_s, fp_s, g or FEM)
|
| 508 |
+
|
| 509 |
+
# -- plain integer ---------------------------------------------------
|
| 510 |
+
if body.isdigit():
|
| 511 |
+
return expand_integer(body, pre, prev_words, next_words)
|
| 512 |
+
|
| 513 |
+
# -- anything else: read the digits, keep separators as words --------
|
| 514 |
+
return re.sub(r"\d+", lambda mm: cardinal(int(mm.group()), FEM), body)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def expand_token(token: str, prev_words: list[str] | None = None,
|
| 518 |
+
next_words: list[str] | None = None) -> str:
|
| 519 |
+
"""Expand a single whitespace-delimited token; returns it unchanged when it
|
| 520 |
+
carries no digit."""
|
| 521 |
+
prev_words = list(prev_words or [])
|
| 522 |
+
next_words = list(next_words or [])
|
| 523 |
+
if not any(ch.isdigit() for ch in token):
|
| 524 |
+
return token
|
| 525 |
+
m = _TOKEN_RE.match(token)
|
| 526 |
+
if not m:
|
| 527 |
+
# Fall back: expand digit runs in place.
|
| 528 |
+
return re.sub(r"\d+", lambda mm: cardinal(int(mm.group()), FEM), token)
|
| 529 |
+
pre, body, post = m.group("pre"), m.group("body"), m.group("post")
|
| 530 |
+
try:
|
| 531 |
+
words = expand_body(body, pre, prev_words, next_words)
|
| 532 |
+
except (ValueError, KeyError, IndexError):
|
| 533 |
+
# Unsupported numeric format: honest passthrough beats a crash. This is
|
| 534 |
+
# the module's stated policy for surviving digits (see .normalize), and
|
| 535 |
+
# it must hold for the shipped inference front end, which is on by
|
| 536 |
+
# default (number_norm="auto") and sees arbitrary input.
|
| 537 |
+
return token
|
| 538 |
+
if pre:
|
| 539 |
+
words = pre + words
|
| 540 |
+
return words + post
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
_HAS_DIGIT = re.compile(r"\d")
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
class HebrewNumberNormalizer:
|
| 547 |
+
"""Sentence-level driver. Stateless; kept as a class so callers can hold
|
| 548 |
+
one instance and so future options (dialect, ordinal policy) have a home."""
|
| 549 |
+
|
| 550 |
+
def __call__(self, text: str) -> str:
|
| 551 |
+
return self.normalize(text)
|
| 552 |
+
|
| 553 |
+
def normalize(self, text: str) -> str:
|
| 554 |
+
if not _HAS_DIGIT.search(text):
|
| 555 |
+
return text
|
| 556 |
+
tokens = text.split()
|
| 557 |
+
out: list[str] = []
|
| 558 |
+
for i, tok in enumerate(tokens):
|
| 559 |
+
if _HAS_DIGIT.search(tok):
|
| 560 |
+
expanded = expand_token(tok, prev_words=tokens[:i], next_words=tokens[i + 1:])
|
| 561 |
+
out.append(expanded)
|
| 562 |
+
else:
|
| 563 |
+
out.append(tok)
|
| 564 |
+
result = " ".join(out)
|
| 565 |
+
# A digit that survived (unsupported format) is left as-is: better an
|
| 566 |
+
# honest passthrough than a wrong guess.
|
| 567 |
+
return result
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
_DEFAULT = HebrewNumberNormalizer()
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def normalize_numbers(text: str) -> str:
|
| 574 |
+
"""Expand every numeric expression in `text`. No-op on digit-free text."""
|
| 575 |
+
return _DEFAULT.normalize(text)
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def contains_digit(text: str) -> bool:
|
| 579 |
+
return bool(_HAS_DIGIT.search(text))
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
import sys
|
| 585 |
+
import warnings
|
| 586 |
+
|
| 587 |
+
#: max_position_embeddings (2048) minus CLS + SEP. Measured: 2046 OK, 2047 raises.
|
| 588 |
+
SAFE_CHUNK_CHARS = 2046
|
| 589 |
+
|
| 590 |
+
#: Hebrew letters alef..tav. Hebrew punctuation (geresh, gershayim, maqaf) is
|
| 591 |
+
#: outside this range and is legitimately passed through by the decoder.
|
| 592 |
+
HEBREW_LETTER_RE = re.compile(r"[ื-ืช]")
|
| 593 |
+
|
| 594 |
+
_SENTENCE_ENDS = ".!?;\n\rโฆื"
|
| 595 |
+
_CLAUSE_ENDS = ",:โโ"
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
class RawHebrewLeakError(ValueError):
|
| 599 |
+
"""Raw Hebrew letters survived into what should be an IPA string."""
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def _split_after(text: str, terminators: str) -> list[str]:
|
| 603 |
+
pieces: list[str] = []
|
| 604 |
+
start = i = 0
|
| 605 |
+
n = len(text)
|
| 606 |
+
while i < n:
|
| 607 |
+
if text[i] in terminators:
|
| 608 |
+
j = i + 1
|
| 609 |
+
while j < n and text[j] in terminators:
|
| 610 |
+
j += 1
|
| 611 |
+
while j < n and text[j].isspace():
|
| 612 |
+
j += 1
|
| 613 |
+
pieces.append(text[start:j])
|
| 614 |
+
start = i = j
|
| 615 |
+
else:
|
| 616 |
+
i += 1
|
| 617 |
+
if start < n:
|
| 618 |
+
pieces.append(text[start:])
|
| 619 |
+
return pieces
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def _split_words(text: str) -> list[str]:
|
| 623 |
+
pieces: list[str] = []
|
| 624 |
+
start = i = 0
|
| 625 |
+
n = len(text)
|
| 626 |
+
while i < n:
|
| 627 |
+
if text[i].isspace():
|
| 628 |
+
j = i
|
| 629 |
+
while j < n and text[j].isspace():
|
| 630 |
+
j += 1
|
| 631 |
+
pieces.append(text[start:j])
|
| 632 |
+
start = i = j
|
| 633 |
+
else:
|
| 634 |
+
i += 1
|
| 635 |
+
if start < n:
|
| 636 |
+
pieces.append(text[start:])
|
| 637 |
+
return pieces
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def _pack(pieces: list[str], limit: int) -> list[str]:
|
| 641 |
+
out: list[str] = []
|
| 642 |
+
cur = ""
|
| 643 |
+
for piece in pieces:
|
| 644 |
+
if cur and len(cur) + len(piece) > limit:
|
| 645 |
+
out.append(cur)
|
| 646 |
+
cur = piece
|
| 647 |
+
else:
|
| 648 |
+
cur += piece
|
| 649 |
+
if cur:
|
| 650 |
+
out.append(cur)
|
| 651 |
+
return out
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def split_for_decode(text: str, limit: int = SAFE_CHUNK_CHARS,
|
| 655 |
+
warn_on_hard_cut: bool = True) -> list[str]:
|
| 656 |
+
"""Split into decode windows of at most `limit` characters, losslessly.
|
| 657 |
+
|
| 658 |
+
``"".join(split_for_decode(t)) == t``; ``len(text) <= limit`` returns
|
| 659 |
+
``[text]`` unchanged.
|
| 660 |
+
"""
|
| 661 |
+
if limit <= 0:
|
| 662 |
+
raise ValueError(f"limit must be positive, got {limit}")
|
| 663 |
+
if len(text) <= limit:
|
| 664 |
+
return [text]
|
| 665 |
+
|
| 666 |
+
out: list[str] = []
|
| 667 |
+
for sent_chunk in _pack(_split_after(text, _SENTENCE_ENDS), limit):
|
| 668 |
+
if len(sent_chunk) <= limit:
|
| 669 |
+
out.append(sent_chunk)
|
| 670 |
+
continue
|
| 671 |
+
for clause_chunk in _pack(_split_after(sent_chunk, _CLAUSE_ENDS), limit):
|
| 672 |
+
if len(clause_chunk) <= limit:
|
| 673 |
+
out.append(clause_chunk)
|
| 674 |
+
continue
|
| 675 |
+
for word_chunk in _pack(_split_words(clause_chunk), limit):
|
| 676 |
+
if len(word_chunk) <= limit:
|
| 677 |
+
out.append(word_chunk)
|
| 678 |
+
continue
|
| 679 |
+
if warn_on_hard_cut:
|
| 680 |
+
warnings.warn(
|
| 681 |
+
f"[long-input] a {len(word_chunk)}-character run with no "
|
| 682 |
+
f"whitespace exceeds the {limit}-character decode window; "
|
| 683 |
+
f"cutting it mid-token.",
|
| 684 |
+
RuntimeWarning, stacklevel=2,
|
| 685 |
+
)
|
| 686 |
+
out.extend(word_chunk[i:i + limit]
|
| 687 |
+
for i in range(0, len(word_chunk), limit))
|
| 688 |
+
|
| 689 |
+
assert "".join(out) == text, "split_for_decode is not lossless"
|
| 690 |
+
return out
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
def check_no_raw_hebrew(output: str, text: str, mode: str = "warn",
|
| 694 |
+
where: str = "phonemize") -> str:
|
| 695 |
+
"""Fail loudly when raw Hebrew letters survive into an IPA string."""
|
| 696 |
+
if mode == "ignore":
|
| 697 |
+
return output
|
| 698 |
+
leaked = HEBREW_LETTER_RE.findall(output)
|
| 699 |
+
if not leaked:
|
| 700 |
+
return output
|
| 701 |
+
sample = "".join(dict.fromkeys(leaked))[:20]
|
| 702 |
+
msg = (
|
| 703 |
+
f"[{where}] RAW HEBREW IN OUTPUT: {len(leaked)} Hebrew letter(s) "
|
| 704 |
+
f"({sample}) survived into what should be an IPA string โ the tail of the "
|
| 705 |
+
f"input was never transcribed. input={len(text)} chars, "
|
| 706 |
+
f"output={len(output)} chars."
|
| 707 |
+
)
|
| 708 |
+
if mode == "raise":
|
| 709 |
+
raise RawHebrewLeakError(msg)
|
| 710 |
+
print(f"WARNING: {msg}", file=sys.stderr)
|
| 711 |
+
return output
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
ALEF_ORD = ord("ื")
|
| 721 |
+
TAF_ORD = ord("ืช")
|
| 722 |
+
STRESS_MARK = "ห"
|
| 723 |
+
ORTHOGRAPHIC_MARKERS = ("'", '"')
|
| 724 |
+
NEG = -1e30
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
def _log_softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:
|
| 728 |
+
x = x - x.max(axis=axis, keepdims=True)
|
| 729 |
+
return x - np.log(np.exp(x).sum(axis=axis, keepdims=True))
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def _softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:
|
| 733 |
+
e = np.exp(x - x.max(axis=axis, keepdims=True))
|
| 734 |
+
return e / e.sum(axis=axis, keepdims=True)
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
def _onehot(idx: np.ndarray, n: int) -> np.ndarray:
|
| 738 |
+
out = np.zeros((idx.shape[0], n), dtype=np.float32)
|
| 739 |
+
out[np.arange(idx.shape[0]), idx] = 1.0
|
| 740 |
+
return out
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def _is_hebrew(char: str) -> bool:
|
| 744 |
+
return ALEF_ORD <= ord(char) <= TAF_ORD
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
def normalize_graphemes(text: str) -> str:
|
| 748 |
+
text = re.sub(r"[ืณ'`ยด]", "'", text)
|
| 749 |
+
text = re.sub(r'[ืด""]', '"', text)
|
| 750 |
+
return text
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
# ==========================================================================
|
| 754 |
+
# THE ALIGNER, AND THE FORCE-ONLY LEXICON
|
| 755 |
+
# --------------------------------------------------------------------------
|
| 756 |
+
# The force lexicon is off unless `lexicon=` is passed; the aligner validates
|
| 757 |
+
# its entries at load time.
|
| 758 |
+
# ==========================================================================
|
| 759 |
+
|
| 760 |
+
#: punctuation stripped off an IPA token before comparing it to a replacement.
|
| 761 |
+
PUNCT_STRIP = ".,?!:;\"'()-โโฆยซยป"
|
| 762 |
+
|
| 763 |
+
_IPA_ASCII_FIXUPS = {"g": "ษก", "x": "ฯ", "r": "ส"}
|
| 764 |
+
|
| 765 |
+
|
| 766 |
+
def normalize_ipa(text: str) -> str:
|
| 767 |
+
"""ASCII stand-ins to canonical IPA."""
|
| 768 |
+
for old, new in _IPA_ASCII_FIXUPS.items():
|
| 769 |
+
text = text.replace(old, new)
|
| 770 |
+
return text
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
# --- the aligner -----------------------------------------------------------
|
| 774 |
+
ALIGN_LETTER_CONSONANTS: dict[str, tuple[str, ...]] = {
|
| 775 |
+
"ื": ("ส", ""), "ื": ("b", "v"), "ื": ("ษก", "dส"), "ื": ("d",),
|
| 776 |
+
"ื": ("h", ""), "ื": ("v", "w", ""), "ื": ("z", "ส"), "ื": ("ฯ",),
|
| 777 |
+
"ื": ("t",), "ื": ("j", ""), "ื": ("k", "ฯ"), "ื": ("k", "ฯ"),
|
| 778 |
+
"ื": ("l", ""), "ื": ("m",), "ื": ("m",), "ื ": ("n",), "ื": ("n",),
|
| 779 |
+
"ืก": ("s",), "ืข": ("ส", ""), "ืค": ("p", "f"), "ืฃ": ("p", "f"),
|
| 780 |
+
"ืฆ": ("ts", "tส"), "ืฅ": ("ts", "tส"), "ืง": ("k",), "ืจ": ("ส",),
|
| 781 |
+
"ืฉ": ("ส", "s", ""), "ืช": ("t",),
|
| 782 |
+
}
|
| 783 |
+
ALIGN_VOWELS = ("a", "e", "i", "o", "u")
|
| 784 |
+
ALIGN_SPECIAL_CHARS = ("'", '"')
|
| 785 |
+
FURTIVE_PATAH_LETTER = "ื"
|
| 786 |
+
FINAL_HE_LETTER = "ื"
|
| 787 |
+
_GERESH = "'"
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
def _ctx_free(w: str, i: int) -> bool:
|
| 791 |
+
return True
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
def _ctx_geresh_after(w: str, i: int) -> bool:
|
| 795 |
+
return i + 1 < len(w) and w[i + 1] == _GERESH
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
def _ctx_dalet_gimel_geresh(w: str, i: int) -> bool:
|
| 799 |
+
return i + 2 < len(w) and w[i + 1] == "ื" and w[i + 2] == _GERESH
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
def _ctx_final_vav_after_alef(w: str, i: int) -> bool:
|
| 803 |
+
if i == 0 or w[i - 1] != "ื":
|
| 804 |
+
return False
|
| 805 |
+
return all(c in ALIGN_SPECIAL_CHARS for c in w[i + 1:])
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
#: optional extra aligner cells (letter, extra consonant, predicate, name).
|
| 809 |
+
#: OFF by default; `align_cells=()` is the standard aligner.
|
| 810 |
+
EXTRA_CELLS: tuple[tuple[str, str, object, str], ...] = (
|
| 811 |
+
("ืก", "z", _ctx_free, "samz"),
|
| 812 |
+
("ืช", "s", _ctx_geresh_after, "tafs"),
|
| 813 |
+
("ื", "", _ctx_dalet_gimel_geresh, "daled0"),
|
| 814 |
+
("ื", "j", _ctx_final_vav_after_alef, "vavj"),
|
| 815 |
+
)
|
| 816 |
+
EXTRA_BY_NAME = {c[3]: c for c in EXTRA_CELLS}
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
def resolve_align_cells(spec) -> tuple:
|
| 820 |
+
"""`()`/None -> standard; "extended" -> all four cells; or an iterable of names."""
|
| 821 |
+
if not spec:
|
| 822 |
+
return ()
|
| 823 |
+
if isinstance(spec, str):
|
| 824 |
+
spec = EXTRA_BY_NAME.keys() if spec.lower() in ("extended", "w4") else [
|
| 825 |
+
s for s in re.split(r"[,\s]+", spec) if s
|
| 826 |
+
]
|
| 827 |
+
out = []
|
| 828 |
+
for name in spec:
|
| 829 |
+
if isinstance(name, tuple):
|
| 830 |
+
out.append(name)
|
| 831 |
+
elif name in EXTRA_BY_NAME:
|
| 832 |
+
out.append(EXTRA_BY_NAME[name])
|
| 833 |
+
else:
|
| 834 |
+
raise ValueError(f"unknown aligner cell {name!r}; known: {sorted(EXTRA_BY_NAME)}")
|
| 835 |
+
return tuple(out)
|
| 836 |
+
|
| 837 |
+
|
| 838 |
+
def align_word(heb_word: str, ipa_word: str, cells: tuple = ()) -> list[tuple[str, str]] | None:
|
| 839 |
+
"""DP alignment of a Hebrew surface to an IPA string, or None if illegal.
|
| 840 |
+
|
| 841 |
+
`cells=()` is the standard aligner; a non-empty `cells` widens it.
|
| 842 |
+
"""
|
| 843 |
+
if not ipa_word or ipa_word.count(STRESS_MARK) > 1:
|
| 844 |
+
return None
|
| 845 |
+
|
| 846 |
+
extra: dict[str, list] = {}
|
| 847 |
+
for letter, cons, pred, *_ in cells:
|
| 848 |
+
extra.setdefault(letter, []).append((cons, pred))
|
| 849 |
+
|
| 850 |
+
from functools import lru_cache
|
| 851 |
+
|
| 852 |
+
@lru_cache(maxsize=None)
|
| 853 |
+
def search(h_idx: int, i_idx: int):
|
| 854 |
+
if h_idx == len(heb_word) and i_idx == len(ipa_word):
|
| 855 |
+
return ()
|
| 856 |
+
if h_idx == len(heb_word):
|
| 857 |
+
return None
|
| 858 |
+
char = heb_word[h_idx]
|
| 859 |
+
if char in ALIGN_SPECIAL_CHARS:
|
| 860 |
+
res = search(h_idx + 1, i_idx)
|
| 861 |
+
if res is not None:
|
| 862 |
+
return ((char, ""),) + res
|
| 863 |
+
return None
|
| 864 |
+
if char not in ALIGN_LETTER_CONSONANTS:
|
| 865 |
+
return None
|
| 866 |
+
allowed_cons = list(ALIGN_LETTER_CONSONANTS[char])
|
| 867 |
+
for cons, pred in extra.get(char, ()):
|
| 868 |
+
if cons not in allowed_cons and pred(heb_word, h_idx):
|
| 869 |
+
allowed_cons.append(cons)
|
| 870 |
+
rest_ipa = ipa_word[i_idx:]
|
| 871 |
+
is_final_he = (
|
| 872 |
+
char == FINAL_HE_LETTER
|
| 873 |
+
and h_idx > 0
|
| 874 |
+
and all(c in ALIGN_SPECIAL_CHARS for c in heb_word[h_idx + 1:])
|
| 875 |
+
)
|
| 876 |
+
for cons in allowed_cons:
|
| 877 |
+
if cons and not rest_ipa.startswith(cons):
|
| 878 |
+
continue
|
| 879 |
+
c_len = len(cons)
|
| 880 |
+
for has_stress in (True, False):
|
| 881 |
+
if has_stress and is_final_he:
|
| 882 |
+
continue
|
| 883 |
+
s_len = 0
|
| 884 |
+
if has_stress:
|
| 885 |
+
if (c_len < len(rest_ipa)) and rest_ipa[c_len] == STRESS_MARK:
|
| 886 |
+
s_len = 1
|
| 887 |
+
else:
|
| 888 |
+
continue
|
| 889 |
+
for v in (*ALIGN_VOWELS, ""):
|
| 890 |
+
if has_stress and not v:
|
| 891 |
+
continue
|
| 892 |
+
if v and is_final_he and not cons:
|
| 893 |
+
continue
|
| 894 |
+
v_start = c_len + s_len
|
| 895 |
+
if v and rest_ipa[v_start:].startswith(v):
|
| 896 |
+
v_len = len(v)
|
| 897 |
+
elif not v:
|
| 898 |
+
v_len = 0
|
| 899 |
+
else:
|
| 900 |
+
continue
|
| 901 |
+
total_step = v_start + v_len
|
| 902 |
+
res = search(h_idx + 1, i_idx + total_step)
|
| 903 |
+
if res is not None:
|
| 904 |
+
return ((char, rest_ipa[:total_step]),) + res
|
| 905 |
+
if char == FURTIVE_PATAH_LETTER:
|
| 906 |
+
for cons in allowed_cons:
|
| 907 |
+
if not cons:
|
| 908 |
+
continue
|
| 909 |
+
for has_stress in (True, False):
|
| 910 |
+
prefix = STRESS_MARK + "a" if has_stress else "a"
|
| 911 |
+
if rest_ipa.startswith(prefix + cons):
|
| 912 |
+
step = len(prefix) + len(cons)
|
| 913 |
+
res = search(h_idx + 1, i_idx + step)
|
| 914 |
+
if res is not None:
|
| 915 |
+
return ((char, rest_ipa[:step]),) + res
|
| 916 |
+
return None
|
| 917 |
+
|
| 918 |
+
result = search(0, 0)
|
| 919 |
+
return list(result) if result is not None else None
|
| 920 |
+
|
| 921 |
+
|
| 922 |
+
# ==========================================================================
|
| 923 |
+
# THE FORCE-ONLY RUNTIME LEXICON
|
| 924 |
+
# ==========================================================================
|
| 925 |
+
|
| 926 |
+
class LexiconEntryError(ValueError):
|
| 927 |
+
"""One or more force-lexicon entries failed alignment validation."""
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
#: characters stripped from the ENDS of a Hebrew token when looking the token up.
|
| 931 |
+
#: Deliberately excludes `'` `"` `-`: those are part of the surface, and are
|
| 932 |
+
#: exactly the keys the candidate store cannot hold.
|
| 933 |
+
LEX_EDGE_STRIP = ".,?!:;()[]{}โฆยซยปึพโโ"
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
class ForceLexicon:
|
| 937 |
+
"""A user-supplied `surface -> IPA` map that ALWAYS wins where it matches.
|
| 938 |
+
|
| 939 |
+
It is keyed on the RAW surface **including separators** (gershayim, geresh,
|
| 940 |
+
hyphen), normalized with this module's `normalize_graphemes`.
|
| 941 |
+
|
| 942 |
+
Every entry is validated with `align_word` at load time. Entries that fail
|
| 943 |
+
are collected and reported; by default the constructor raises with the full
|
| 944 |
+
list. `on_invalid="report"` keeps them out of the map and exposes them on
|
| 945 |
+
`.rejected` instead โ nothing is ever silently dropped.
|
| 946 |
+
"""
|
| 947 |
+
|
| 948 |
+
def __init__(self, source, align_cells: tuple = (), on_invalid: str = "raise") -> None:
|
| 949 |
+
if on_invalid not in ("raise", "report"):
|
| 950 |
+
raise ValueError("on_invalid must be 'raise' or 'report'")
|
| 951 |
+
pairs = self._read(source)
|
| 952 |
+
self.entries: dict[str, str] = {}
|
| 953 |
+
self.rejected: list[tuple[str, str, str]] = [] # (surface, ipa, reason)
|
| 954 |
+
for raw_surface, raw_ipa in pairs:
|
| 955 |
+
surface = normalize_graphemes(unicodedata.normalize("NFD", raw_surface)).strip()
|
| 956 |
+
ipa = normalize_ipa(raw_ipa.strip())
|
| 957 |
+
if not surface or not ipa:
|
| 958 |
+
self.rejected.append((raw_surface, raw_ipa, "empty surface or IPA"))
|
| 959 |
+
continue
|
| 960 |
+
reason = self._validate(surface, ipa, align_cells)
|
| 961 |
+
if reason is not None:
|
| 962 |
+
self.rejected.append((raw_surface, raw_ipa, reason))
|
| 963 |
+
continue
|
| 964 |
+
self.entries[surface] = ipa
|
| 965 |
+
if self.rejected and on_invalid == "raise":
|
| 966 |
+
lines = "\n".join(f" {s!r} -> {i!r}: {why}" for s, i, why in self.rejected)
|
| 967 |
+
raise LexiconEntryError(
|
| 968 |
+
f"{len(self.rejected)} force-lexicon entr"
|
| 969 |
+
f"{'y' if len(self.rejected) == 1 else 'ies'} failed validation "
|
| 970 |
+
f"(pass on_invalid='report' to collect instead of raising):\n{lines}"
|
| 971 |
+
)
|
| 972 |
+
|
| 973 |
+
# -- loading ------------------------------------------------------------
|
| 974 |
+
@staticmethod
|
| 975 |
+
def _read(source) -> list[tuple[str, str]]:
|
| 976 |
+
if isinstance(source, dict):
|
| 977 |
+
return list(source.items())
|
| 978 |
+
pairs = []
|
| 979 |
+
with open(source, encoding="utf-8") as fh:
|
| 980 |
+
for lineno, line in enumerate(fh, 1):
|
| 981 |
+
line = line.rstrip("\n").rstrip("\r")
|
| 982 |
+
if not line.strip() or line.lstrip().startswith("#"):
|
| 983 |
+
continue
|
| 984 |
+
parts = line.split("\t")
|
| 985 |
+
if len(parts) < 2:
|
| 986 |
+
raise LexiconEntryError(
|
| 987 |
+
f"{source}:{lineno}: expected 'surface<TAB>IPA', got {line!r}")
|
| 988 |
+
pairs.append((parts[0], parts[1]))
|
| 989 |
+
return pairs
|
| 990 |
+
|
| 991 |
+
# -- validation ---------------------------------------------------------
|
| 992 |
+
@staticmethod
|
| 993 |
+
def _validate(surface: str, ipa: str, align_cells: tuple) -> str | None:
|
| 994 |
+
"""None when the entry aligns; otherwise the reason it does not."""
|
| 995 |
+
if align_word(surface, ipa, align_cells) is not None:
|
| 996 |
+
return None
|
| 997 |
+
if "-" in surface:
|
| 998 |
+
# A hyphen is a real key character but the aligner has no
|
| 999 |
+
# rule for it: validate the compound segment by segment, which
|
| 1000 |
+
# requires the IPA to carry the same number of separators.
|
| 1001 |
+
hs = surface.split("-")
|
| 1002 |
+
ps = re.split(r"[-\s]", ipa)
|
| 1003 |
+
if len(hs) != len(ps):
|
| 1004 |
+
return (f"hyphenated surface has {len(hs)} segments but the IPA has "
|
| 1005 |
+
f"{len(ps)} โ split the IPA on '-' or a space to validate it")
|
| 1006 |
+
for h, p in zip(hs, ps):
|
| 1007 |
+
if align_word(h, p, align_cells) is None:
|
| 1008 |
+
return f"segment {h!r} does not align to {p!r}"
|
| 1009 |
+
return None
|
| 1010 |
+
if any(ch not in ALIGN_LETTER_CONSONANTS and ch not in ALIGN_SPECIAL_CHARS
|
| 1011 |
+
for ch in surface):
|
| 1012 |
+
bad = "".join(sorted({ch for ch in surface
|
| 1013 |
+
if ch not in ALIGN_LETTER_CONSONANTS
|
| 1014 |
+
and ch not in ALIGN_SPECIAL_CHARS}))
|
| 1015 |
+
return f"surface contains character(s) the aligner has no rule for: {bad!r}"
|
| 1016 |
+
return "IPA does not align to the surface under align_word"
|
| 1017 |
+
|
| 1018 |
+
# -- lookup -------------------------------------------------------------
|
| 1019 |
+
def lookup(self, token: str) -> str | None:
|
| 1020 |
+
"""Match the raw whitespace-delimited token, then the token with edge
|
| 1021 |
+
punctuation stripped. Separators inside the surface are preserved."""
|
| 1022 |
+
if token in self.entries:
|
| 1023 |
+
return self.entries[token]
|
| 1024 |
+
stripped = token.strip(LEX_EDGE_STRIP)
|
| 1025 |
+
if stripped and stripped in self.entries:
|
| 1026 |
+
return self.entries[stripped]
|
| 1027 |
+
return None
|
| 1028 |
+
|
| 1029 |
+
def __len__(self) -> int:
|
| 1030 |
+
return len(self.entries)
|
| 1031 |
+
|
| 1032 |
+
def __contains__(self, token: str) -> bool:
|
| 1033 |
+
return self.lookup(token) is not None
|
| 1034 |
+
|
| 1035 |
+
|
| 1036 |
+
def apply_force_lexicon(text: str, ipa: str, lex: "ForceLexicon") -> tuple[str, list[dict]]:
|
| 1037 |
+
"""Overwrite every output word whose Hebrew token is in `lex`.
|
| 1038 |
+
|
| 1039 |
+
Word alignment is positional (`re.finditer(r"\\S+", ...)` on the Hebrew vs
|
| 1040 |
+
`.split()` on the IPA), the same correspondence `apply_gate` uses; if the two
|
| 1041 |
+
counts disagree the override is skipped for that string rather than guessed.
|
| 1042 |
+
Leading/trailing IPA punctuation on the replaced token is preserved.
|
| 1043 |
+
"""
|
| 1044 |
+
heb_tokens = [m.group() for m in re.finditer(r"\S+", text)]
|
| 1045 |
+
words = ipa.split()
|
| 1046 |
+
forced: list[dict] = []
|
| 1047 |
+
if len(heb_tokens) != len(words):
|
| 1048 |
+
return ipa, forced
|
| 1049 |
+
for wi, tok_heb in enumerate(heb_tokens):
|
| 1050 |
+
repl = lex.lookup(tok_heb)
|
| 1051 |
+
if repl is None:
|
| 1052 |
+
continue
|
| 1053 |
+
tok = words[wi]
|
| 1054 |
+
lead = len(tok) - len(tok.lstrip(PUNCT_STRIP))
|
| 1055 |
+
trail = len(tok) - len(tok.rstrip(PUNCT_STRIP))
|
| 1056 |
+
core = tok[lead: len(tok) - trail] if trail else tok[lead:]
|
| 1057 |
+
if core == repl:
|
| 1058 |
+
continue
|
| 1059 |
+
words[wi] = tok[:lead] + repl + (tok[len(tok) - trail:] if trail else "")
|
| 1060 |
+
forced.append({"wi": wi, "surface": tok_heb, "from": core, "to": repl})
|
| 1061 |
+
return " ".join(words), forced
|
| 1062 |
+
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
class G2P:
|
| 1066 |
+
def __init__(self, model_path: str, exact_map: bool = True,
|
| 1067 |
+
chunk_chars: int | None = SAFE_CHUNK_CHARS,
|
| 1068 |
+
align_cells=(),
|
| 1069 |
+
lexicon=None,
|
| 1070 |
+
on_invalid_lexicon: str = "raise") -> None:
|
| 1071 |
+
# `chunk_chars` is the long-input decode window. The default 2,046 is the
|
| 1072 |
+
# encoder's hard wall (2,048 positions - CLS/SEP); None disables windowing
|
| 1073 |
+
# and lets onnxruntime raise past the wall.
|
| 1074 |
+
# align_cells : () standard (default), or "extended" -- widens the
|
| 1075 |
+
# aligner used to validate `lexicon` entries.
|
| 1076 |
+
# lexicon : dict or TSV path, force-only override
|
| 1077 |
+
self._chunk_chars = chunk_chars
|
| 1078 |
+
import onnxruntime as ort # number expansion and decoding do not need it
|
| 1079 |
+
self._session = ort.InferenceSession(model_path)
|
| 1080 |
+
meta = self._session.get_modelmeta().custom_metadata_map
|
| 1081 |
+
self._vocab: dict[str, int] = json.loads(meta["vocab"])
|
| 1082 |
+
self._consonant_vocab: dict[int, str] = {int(k): v for k, v in json.loads(meta["consonant_vocab"]).items()}
|
| 1083 |
+
self._vowel_vocab: dict[int, str] = {int(k): v for k, v in json.loads(meta["vowel_vocab"]).items()}
|
| 1084 |
+
self._cls_id = int(meta["cls_token_id"])
|
| 1085 |
+
self._sep_id = int(meta["sep_token_id"])
|
| 1086 |
+
self._letter_constraints: dict[str, list[int]] = {
|
| 1087 |
+
k: v for k, v in json.loads(meta["letter_consonant_constraints"]).items()
|
| 1088 |
+
}
|
| 1089 |
+
self._geresh_map: dict[str, str] = json.loads(meta.get("geresh_map", "{}"))
|
| 1090 |
+
# Models exported with --gender-inputs expose FiLM speaker conditioning.
|
| 1091 |
+
# Older 2-input models don't; phonemize() then ignores the arguments.
|
| 1092 |
+
input_names = {i.name for i in self._session.get_inputs()}
|
| 1093 |
+
self.supports_gender = {"speaker", "target_speaker"} <= input_names
|
| 1094 |
+
|
| 1095 |
+
# Exact structured-cascade MAP decode. Needs the conditioning column
|
| 1096 |
+
# blocks of the cascade heads, which models exported before this feature
|
| 1097 |
+
# don't carry; those fall back to greedy argmax + margin stress.
|
| 1098 |
+
cond_keys = ("vowel_cond_consonant", "stress_cond_consonant", "stress_cond_vowel")
|
| 1099 |
+
self.supports_exact_map = all(k in meta for k in cond_keys)
|
| 1100 |
+
self.exact_map_default = exact_map and self.supports_exact_map
|
| 1101 |
+
if self.supports_exact_map:
|
| 1102 |
+
# [C, V], [C, S], [V, S]
|
| 1103 |
+
self._wv_c = np.asarray(json.loads(meta["vowel_cond_consonant"]), dtype=np.float32)
|
| 1104 |
+
self._ws_c = np.asarray(json.loads(meta["stress_cond_consonant"]), dtype=np.float32)
|
| 1105 |
+
self._ws_v = np.asarray(json.loads(meta["stress_cond_vowel"]), dtype=np.float32)
|
| 1106 |
+
self._cond_softmax = meta.get("cascade_cond", "softmax") == "softmax"
|
| 1107 |
+
n_cons = self._wv_c.shape[0]
|
| 1108 |
+
# [letter, consonant] True = this consonant class is illegal here.
|
| 1109 |
+
self._forbidden = np.ones((TAF_ORD - ALEF_ORD + 1, n_cons), dtype=bool)
|
| 1110 |
+
for letter, allowed in self._letter_constraints.items():
|
| 1111 |
+
self._forbidden[ord(letter) - ALEF_ORD, list(allowed)] = False
|
| 1112 |
+
|
| 1113 |
+
self._align_cells = resolve_align_cells(align_cells)
|
| 1114 |
+
self.last_forced: list = []
|
| 1115 |
+
self._lexicon = None
|
| 1116 |
+
if lexicon is not None:
|
| 1117 |
+
self._lexicon = ForceLexicon(lexicon, align_cells=self._align_cells,
|
| 1118 |
+
on_invalid=on_invalid_lexicon)
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
|
| 1122 |
+
def _tokenize(self, text: str) -> tuple[list[int], list[int], list[tuple[int, int]]]:
|
| 1123 |
+
"""Tokenize character by character, return ids, mask, and offset mapping."""
|
| 1124 |
+
normalized = unicodedata.normalize("NFD", text)
|
| 1125 |
+
unk_id = self._vocab.get("[UNK]", 0)
|
| 1126 |
+
ids = [self._cls_id]
|
| 1127 |
+
offsets = [(0, 0)] # CLS
|
| 1128 |
+
for i, c in enumerate(normalized):
|
| 1129 |
+
ids.append(self._vocab.get(c, unk_id))
|
| 1130 |
+
offsets.append((i, i + 1))
|
| 1131 |
+
ids.append(self._sep_id)
|
| 1132 |
+
offsets.append((0, 0)) # SEP
|
| 1133 |
+
mask = [1] * len(ids)
|
| 1134 |
+
return ids, mask, offsets
|
| 1135 |
+
|
| 1136 |
+
def _best_stress_per_word(
|
| 1137 |
+
self,
|
| 1138 |
+
offsets: list[tuple[int, int]],
|
| 1139 |
+
text: str,
|
| 1140 |
+
stress_logits: np.ndarray,
|
| 1141 |
+
vowel_preds: np.ndarray,
|
| 1142 |
+
) -> set[int]:
|
| 1143 |
+
word_spans = [(m.start(), m.end()) for m in re.finditer(r"\S+", text)]
|
| 1144 |
+
words: dict[int, list[int]] = {i: [] for i in range(len(word_spans))}
|
| 1145 |
+
for tok_idx, (start, end) in enumerate(offsets):
|
| 1146 |
+
if end - start != 1:
|
| 1147 |
+
continue
|
| 1148 |
+
for word_idx, (ws, we) in enumerate(word_spans):
|
| 1149 |
+
if ws <= start < we:
|
| 1150 |
+
words[word_idx].append(tok_idx)
|
| 1151 |
+
break
|
| 1152 |
+
stressed: set[int] = set()
|
| 1153 |
+
for toks in words.values():
|
| 1154 |
+
if not toks:
|
| 1155 |
+
continue
|
| 1156 |
+
# Stress must sit with a vowel (CหV); never emit trailing ห.
|
| 1157 |
+
vowel_toks = [
|
| 1158 |
+
t for t in toks
|
| 1159 |
+
if self._vowel_vocab.get(int(vowel_preds[t]), "โ
") != "โ
"
|
| 1160 |
+
]
|
| 1161 |
+
if not vowel_toks:
|
| 1162 |
+
continue
|
| 1163 |
+
# Margin (yes โ no), not the raw yes-logit: raw logits differ in scale
|
| 1164 |
+
# across tokens.
|
| 1165 |
+
stressed.add(max(vowel_toks, key=lambda t: stress_logits[t, 1] - stress_logits[t, 0]))
|
| 1166 |
+
return stressed
|
| 1167 |
+
|
| 1168 |
+
def _exact_map(
|
| 1169 |
+
self,
|
| 1170 |
+
offsets: list[tuple[int, int]],
|
| 1171 |
+
text: str,
|
| 1172 |
+
consonant_logits: np.ndarray,
|
| 1173 |
+
vowel_logits: np.ndarray,
|
| 1174 |
+
stress_logits: np.ndarray,
|
| 1175 |
+
):
|
| 1176 |
+
"""Closed-form MAP over the joint cascade energy.
|
| 1177 |
+
|
| 1178 |
+
E(c, v, s) = log P(c) + log P(v | c) + log P(s | c, v)
|
| 1179 |
+
|
| 1180 |
+
The graph emits vowel/stress logits conditioned on the model's own
|
| 1181 |
+
upstream softmax; subtracting that conditioning back out recovers the
|
| 1182 |
+
unconditioned head logits, after which conditioning on ANY (c, v) is an
|
| 1183 |
+
exact column addition. No early argmax anywhere, so the one-stress-per-
|
| 1184 |
+
word constraint is free to flip both the vowel and the consonant.
|
| 1185 |
+
"""
|
| 1186 |
+
cond_c = _softmax(consonant_logits) if self._cond_softmax else _onehot(
|
| 1187 |
+
consonant_logits.argmax(-1), consonant_logits.shape[-1]
|
| 1188 |
+
)
|
| 1189 |
+
base_v = vowel_logits - cond_c @ self._wv_c # [S, V]
|
| 1190 |
+
cond_v = _softmax(vowel_logits) if self._cond_softmax else _onehot(
|
| 1191 |
+
vowel_logits.argmax(-1), vowel_logits.shape[-1]
|
| 1192 |
+
)
|
| 1193 |
+
base_s = stress_logits - cond_c @ self._ws_c - cond_v @ self._ws_v # [S, 2]
|
| 1194 |
+
|
| 1195 |
+
logc = _log_softmax(consonant_logits) # [S, C]
|
| 1196 |
+
logv = _log_softmax(base_v[:, None, :] + self._wv_c[None, :, :]) # [S, C, V]
|
| 1197 |
+
logs = _log_softmax(
|
| 1198 |
+
base_s[:, None, None, :]
|
| 1199 |
+
+ self._ws_c[None, :, None, :]
|
| 1200 |
+
+ self._ws_v[None, None, :, :]
|
| 1201 |
+
) # [S, C, V, 2]
|
| 1202 |
+
E = logc[:, :, None, None] + logv[:, :, :, None] + logs # [S, C, V, 2]
|
| 1203 |
+
|
| 1204 |
+
# Per-letter consonant legality, and "stress needs a vowel".
|
| 1205 |
+
for t, (start, end) in enumerate(offsets):
|
| 1206 |
+
if end - start == 1 and _is_hebrew(text[start:end]):
|
| 1207 |
+
E[t, self._forbidden[ord(text[start]) - ALEF_ORD]] = NEG
|
| 1208 |
+
E[:, :, 0, 1] = NEG
|
| 1209 |
+
|
| 1210 |
+
S, C, V = E.shape[:3]
|
| 1211 |
+
flat_u = E[:, :, :, 0].reshape(S, C * V)
|
| 1212 |
+
flat_s = E[:, :, :, 1].reshape(S, C * V)
|
| 1213 |
+
arg_u, arg_s = flat_u.argmax(-1), flat_s.argmax(-1)
|
| 1214 |
+
best_u = flat_u[np.arange(S), arg_u]
|
| 1215 |
+
best_s = flat_s[np.arange(S), arg_s]
|
| 1216 |
+
gain = best_s - best_u
|
| 1217 |
+
|
| 1218 |
+
char_tok = {
|
| 1219 |
+
start: t
|
| 1220 |
+
for t, (start, end) in enumerate(offsets)
|
| 1221 |
+
if end - start == 1 and _is_hebrew(text[start:end])
|
| 1222 |
+
}
|
| 1223 |
+
stressed: set[int] = set()
|
| 1224 |
+
for m in re.finditer(r"\S+", text):
|
| 1225 |
+
toks = [char_tok[i] for i in range(m.start(), m.end()) if i in char_tok]
|
| 1226 |
+
cands = [t for t in toks if best_s[t] > NEG / 2]
|
| 1227 |
+
if cands:
|
| 1228 |
+
stressed.add(max(cands, key=lambda t: gain[t]))
|
| 1229 |
+
|
| 1230 |
+
flat = np.where(np.isin(np.arange(S), list(stressed)), arg_s, arg_u)
|
| 1231 |
+
return flat // V, flat % V, stressed
|
| 1232 |
+
|
| 1233 |
+
def phonemize(
|
| 1234 |
+
self,
|
| 1235 |
+
text: str,
|
| 1236 |
+
speaker: int = 0,
|
| 1237 |
+
target_speaker: int = 0,
|
| 1238 |
+
exact_map: bool | None = None,
|
| 1239 |
+
on_hebrew_leak: str = "warn",
|
| 1240 |
+
number_norm: str = "auto",
|
| 1241 |
+
) -> str:
|
| 1242 |
+
"""Convert unvocalized Hebrew text to IPA.
|
| 1243 |
+
|
| 1244 |
+
Inputs longer than `chunk_chars` (default 2,046 โ the encoder's
|
| 1245 |
+
2,048-position table minus CLS/SEP, measured) are split on sentence, then
|
| 1246 |
+
comma, then word boundaries and decoded window by window. Inputs at or
|
| 1247 |
+
below it are byte-for-byte unchanged from the pre-wrapper. A
|
| 1248 |
+
`[ื-ืช]`-in-output backstop then reports (default) or raises on any raw
|
| 1249 |
+
Hebrew that survives into the IPA string.
|
| 1250 |
+
"""
|
| 1251 |
+
if number_norm == "auto" and contains_digit(text):
|
| 1252 |
+
# Hebrew number front end: digits never appear
|
| 1253 |
+
# in training text, so a digit reaching the model is guaranteed-wrong
|
| 1254 |
+
# output (and mis-aligns the word after it). Runs BEFORE windowing โ
|
| 1255 |
+
# the expander lengthens text (up to ~3.9x on digit-dense input).
|
| 1256 |
+
text = normalize_numbers(text)
|
| 1257 |
+
text = normalize_graphemes(text)
|
| 1258 |
+
normalized = unicodedata.normalize("NFD", text)
|
| 1259 |
+
windows = (split_for_decode(normalized, limit=self._chunk_chars)
|
| 1260 |
+
if self._chunk_chars else [normalized])
|
| 1261 |
+
# The windows are contiguous substrings, so concatenating their outputs
|
| 1262 |
+
# preserves the original separators by construction.
|
| 1263 |
+
result = "".join(
|
| 1264 |
+
self._phonemize_window(w, speaker, target_speaker, exact_map)
|
| 1265 |
+
for w in windows
|
| 1266 |
+
)
|
| 1267 |
+
return check_no_raw_hebrew(result, text, mode=on_hebrew_leak,
|
| 1268 |
+
where="renikud_onnx.G2P.phonemize")
|
| 1269 |
+
|
| 1270 |
+
def _phonemize_window(
|
| 1271 |
+
self,
|
| 1272 |
+
normalized: str,
|
| 1273 |
+
speaker: int = 0,
|
| 1274 |
+
target_speaker: int = 0,
|
| 1275 |
+
exact_map: bool | None = None,
|
| 1276 |
+
) -> str:
|
| 1277 |
+
"""One session run + decode over an already normalized/NFD window."""
|
| 1278 |
+
ids, mask, offsets = self._tokenize(normalized)
|
| 1279 |
+
|
| 1280 |
+
feeds = {
|
| 1281 |
+
"input_ids": np.array([ids], dtype=np.int64),
|
| 1282 |
+
"attention_mask": np.array([mask], dtype=np.int64),
|
| 1283 |
+
}
|
| 1284 |
+
if self.supports_gender:
|
| 1285 |
+
feeds["speaker"] = np.array([speaker], dtype=np.int64)
|
| 1286 |
+
feeds["target_speaker"] = np.array([target_speaker], dtype=np.int64)
|
| 1287 |
+
|
| 1288 |
+
consonant_logits, vowel_logits, stress_logits = self._session.run(
|
| 1289 |
+
["consonant_logits", "vowel_logits", "stress_logits"],
|
| 1290 |
+
feeds,
|
| 1291 |
+
)
|
| 1292 |
+
# logits shape: [1, seq_len, num_classes]
|
| 1293 |
+
use_exact = self.exact_map_default if exact_map is None else exact_map
|
| 1294 |
+
if use_exact and not self.supports_exact_map:
|
| 1295 |
+
raise ValueError(
|
| 1296 |
+
"this model was exported without the cascade conditioning metadata; "
|
| 1297 |
+
"re-export it, or pass exact_map=False for the greedy decode"
|
| 1298 |
+
)
|
| 1299 |
+
if use_exact:
|
| 1300 |
+
consonant_preds, vowel_preds, stressed_positions = self._exact_map(
|
| 1301 |
+
offsets,
|
| 1302 |
+
normalized,
|
| 1303 |
+
consonant_logits[0].astype(np.float32),
|
| 1304 |
+
vowel_logits[0].astype(np.float32),
|
| 1305 |
+
stress_logits[0].astype(np.float32),
|
| 1306 |
+
)
|
| 1307 |
+
else:
|
| 1308 |
+
consonant_preds = consonant_logits[0].argmax(axis=-1)
|
| 1309 |
+
vowel_preds = vowel_logits[0].argmax(axis=-1)
|
| 1310 |
+
stressed_positions = self._best_stress_per_word(
|
| 1311 |
+
offsets, normalized, stress_logits[0], vowel_preds
|
| 1312 |
+
)
|
| 1313 |
+
|
| 1314 |
+
result = []
|
| 1315 |
+
prev_end = 0
|
| 1316 |
+
|
| 1317 |
+
for tok_idx, (start, end) in enumerate(offsets):
|
| 1318 |
+
if end - start != 1:
|
| 1319 |
+
# CLS, SEP โ skip
|
| 1320 |
+
if end > start:
|
| 1321 |
+
prev_end = end
|
| 1322 |
+
continue
|
| 1323 |
+
|
| 1324 |
+
# Pass through any characters skipped by the tokenizer
|
| 1325 |
+
if start > prev_end:
|
| 1326 |
+
result.append(normalized[prev_end:start])
|
| 1327 |
+
|
| 1328 |
+
char = normalized[start:end]
|
| 1329 |
+
prev_end = end
|
| 1330 |
+
|
| 1331 |
+
if not _is_hebrew(char):
|
| 1332 |
+
if char in ORTHOGRAPHIC_MARKERS:
|
| 1333 |
+
pass
|
| 1334 |
+
else:
|
| 1335 |
+
result.append(char)
|
| 1336 |
+
continue
|
| 1337 |
+
|
| 1338 |
+
cid = int(consonant_preds[tok_idx])
|
| 1339 |
+
allowed = self._letter_constraints.get(char)
|
| 1340 |
+
if allowed is not None and cid not in allowed:
|
| 1341 |
+
cid = max(allowed, key=lambda x: consonant_logits[0][tok_idx, x])
|
| 1342 |
+
consonant = self._consonant_vocab.get(cid, "โ
")
|
| 1343 |
+
|
| 1344 |
+
# Geresh rule: if next char is apostrophe, force geresh consonant variant
|
| 1345 |
+
if char in self._geresh_map and end < len(normalized) and normalized[end] == "'":
|
| 1346 |
+
consonant = self._geresh_map[char]
|
| 1347 |
+
|
| 1348 |
+
vowel = self._vowel_vocab.get(int(vowel_preds[tok_idx]), "โ
")
|
| 1349 |
+
stress = tok_idx in stressed_positions
|
| 1350 |
+
|
| 1351 |
+
# Assemble IPA chunk: [consonant][ห][vowel]
|
| 1352 |
+
# Exception: word-final ื with vowel a โ furtive patah flips to [ห]aฯ
|
| 1353 |
+
word_final = end >= len(normalized) or not normalized[end].isalpha()
|
| 1354 |
+
chunk = ""
|
| 1355 |
+
if char == "ื" and word_final and vowel == "a":
|
| 1356 |
+
if stress:
|
| 1357 |
+
chunk += STRESS_MARK
|
| 1358 |
+
chunk += "aฯ"
|
| 1359 |
+
else:
|
| 1360 |
+
if consonant != "โ
":
|
| 1361 |
+
chunk += consonant
|
| 1362 |
+
if stress and vowel != "โ
":
|
| 1363 |
+
chunk += STRESS_MARK
|
| 1364 |
+
if vowel != "โ
":
|
| 1365 |
+
chunk += vowel
|
| 1366 |
+
result.append(chunk)
|
| 1367 |
+
|
| 1368 |
+
if prev_end < len(normalized):
|
| 1369 |
+
result.append(normalized[prev_end:])
|
| 1370 |
+
|
| 1371 |
+
out_str = "".join(result)
|
| 1372 |
+
|
| 1373 |
+
# ---- force-lexicon post-pass (no-op unless a lexicon was passed) ----
|
| 1374 |
+
# Operates on whitespace-delimited words, normalizing runs of inter-word
|
| 1375 |
+
# whitespace to single spaces. Leading/trailing whitespace of the window
|
| 1376 |
+
# is preserved so that concatenating windows stays lossless; the
|
| 1377 |
+
# reference texts carry none, so a single-window decode is bit-identical
|
| 1378 |
+
# to the reference.
|
| 1379 |
+
if self._lexicon is not None:
|
| 1380 |
+
lead_ws = out_str[:len(out_str) - len(out_str.lstrip())]
|
| 1381 |
+
trail_ws = out_str[len(out_str.rstrip()):]
|
| 1382 |
+
body = out_str.strip()
|
| 1383 |
+
body, self.last_forced = apply_force_lexicon(
|
| 1384 |
+
normalized.strip(), body, self._lexicon)
|
| 1385 |
+
out_str = lead_ws + body + trail_ws
|
| 1386 |
+
|
| 1387 |
+
return out_str
|