useless-ai commited on
Commit
8aee88a
·
verified ·
1 Parent(s): bd4816b

v3: 173 h aligned, bundled phonemizer, sound-tag playback

Browse files
.gitattributes CHANGED
@@ -43,3 +43,4 @@ samples/07-fearful.wav filter=lfs diff=lfs merge=lfs -text
43
  samples/08-surprised.wav filter=lfs diff=lfs merge=lfs -text
44
  samples/09-calm.wav filter=lfs diff=lfs merge=lfs -text
45
  samples/10-whisper.wav filter=lfs diff=lfs merge=lfs -text
 
 
43
  samples/08-surprised.wav filter=lfs diff=lfs merge=lfs -text
44
  samples/09-calm.wav filter=lfs diff=lfs merge=lfs -text
45
  samples/10-whisper.wav filter=lfs diff=lfs merge=lfs -text
46
+ samples/11-default.wav filter=lfs diff=lfs merge=lfs -text
NOTICE CHANGED
@@ -13,10 +13,10 @@ Changes in fiato:
13
  - Support for tiny-voca's earlier byte-token feature files is removed.
14
 
15
  Changes in this fork (pitput):
16
- - Hebrew front end: Phonikud phoneme labels instead of eSpeak/dizione.
17
  - Eight delivery styles in place of the voices; whispered styles are not
18
  forced voiced.
19
  - Eight expression tags.
20
  - Features stored as 16-bit waveform and float16 mel; training can stream
21
  them from disk with background prefetching.
22
- - Inference reads Hebrew text through Phonikud.
 
13
  - Support for tiny-voca's earlier byte-token feature files is removed.
14
 
15
  Changes in this fork (pitput):
16
+ - Hebrew front end over the training phoneme inventory, instead of eSpeak/dizione.
17
  - Eight delivery styles in place of the voices; whispered styles are not
18
  forced voiced.
19
  - Eight expression tags.
20
  - Features stored as 16-bit waveform and float16 mel; training can stream
21
  them from disk with background prefetching.
22
+ - Inference reads Hebrew through the bundled phonemizer (phonemizer/NOTICE).
README.md CHANGED
@@ -28,46 +28,48 @@ It is a personal learning project, trained from scratch on synthetic speech. **P
28
 
29
  | Version | What changed |
30
  |---|---|
31
- | **v2** (this, November 21, 2026) | The delivery of each word is drawn instead of averaged: livelier melody and tempo, audible laughs and chuckles, pauses where a speaker would take them. More expressive training data. Cleaner whisper and breaths. Sighs and breaths tuned to the loudness and length of the data |
 
32
  | v1 (November 18, 2026) | First model. Steady, somewhat robotic delivery; laughs came out as a soft breath |
33
 
34
- v1 stays available as the `v1` tag: `git checkout v1`, or `revision="v1"` in `huggingface_hub`.
35
 
36
  ## Samples
37
 
38
- The 10 listening texts, synthesized with the default settings (temperature 0.55, seed 0).
39
 
40
  | Style | Text | Audio |
41
  |---|---|---|
42
- | default | לפי נתוני הלשכה המרכזית לסטטיסטיקה, אוכלוסיית ישראל גדלה בשנה האחרונה בכמאה ושמונים אלף איש. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v2/samples/01-default.wav"></audio> |
43
- | default, addressee f | מה שלומך? שמעתי שלא הרגשת טוב בשבוע שעבר. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v2/samples/02-default.wav"></audio> |
44
- | default | הרכבת לחיפה יוצאת בשבע ועשרים ומגיעה בשמונה וחצי, `<chuckle>` אם היא בכלל תגיע. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v2/samples/03-default.wav"></audio> |
45
- | excited | `<laugh>` אני לא מאמינה, קיבלנו את הדירה! | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v2/samples/04-excited.wav"></audio> |
46
- | sad | `<sigh>` חיכיתי לו כל הערב, והוא פשוט לא הגיע. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v2/samples/05-sad.wav"></audio> |
47
- | angry, addressee m | כמה פעמים אמרתי לך לסגור את הדלת?! | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v2/samples/06-angry.wav"></audio> |
48
- | fearful | שמעת את זה? `<gasp>` יש מישהו בחוץ. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v2/samples/07-fearful.wav"></audio> |
49
- | surprised | רגע, `<short pause>` הוא באמת התפטר? אחרי עשרים שנה? | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v2/samples/08-surprised.wav"></audio> |
50
- | calm | `<breath>` קחו נשימה עמוקה, `<long pause>` ותנו לגוף להירגע לאט לאט. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v2/samples/09-calm.wav"></audio> |
51
- | whisper | בוא נדבר בשקט, כולם כבר ישנים. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v2/samples/10-whisper.wav"></audio> |
 
52
 
53
  ## Usage
54
 
55
  ```bash
56
  git clone https://huggingface.co/useless-ai/pitput
57
  cd pitput
58
- pip install -r requirements.txt # PyTorch, Phonikud, onnxruntime, soundfile, huggingface_hub
59
 
60
  python -m pitput.infer --style excited --text "<laugh> אני לא מאמינה, קיבלנו את הדירה!" --output out.wav
61
  python -m pitput.infer --style default --addressee f --text "מה שלומך? שמעתי שלא הרגשת טוב." --output hello.wav
62
  ```
63
 
64
- On first use the Phonikud model (~300 MB) is downloaded to the Hugging Face cache. Options:
65
 
66
  | Option | Meaning |
67
  |---|---|
68
  | `--style` | `default`, `excited`, `sad`, `angry`, `fearful`, `surprised`, `calm`, `whisper` |
69
- | `--addressee m` / `f` | Gender of the person spoken to (לך, אותך, אמרת …). Without it Phonikud reads the masculine form |
70
- | `--temperature` | How freely the delivery is drawn (default 0.55). Lower is steadier, higher is livelier and less predictable; above ~1 it starts to break up |
71
  | `--seed` | Another seed gives another delivery of the same text (default 0). If a laugh or chuckle comes out weak, try another seed |
72
  | `--text-file` | Read the text from a UTF-8 file instead of `--text` |
73
  | `--speed` | 1.0 = as trained; 0.9 is 10% slower |
@@ -82,21 +84,23 @@ import soundfile as sf
82
  from pitput.infer import CHECKPOINT, load_model, speak_text
83
 
84
  model = load_model(CHECKPOINT) # inference.pt next to the package
85
- wave, utterances = speak_text(model, "שלום, <sigh> מה שלומך?", "calm", addressee="f", seed=0, temperature=0.55)
86
  sf.write("out.wav", wave.numpy(), model.config.sample_rate)
87
  ```
88
 
89
- `temperature=None` plays the model's own settings instead (word choices at 0.5, melody at 0.3).
90
 
91
  ### What the input must look like
92
 
93
- - **Plain Hebrew in spoken form.** There is no text normalizer: write numbers, dates, times, acronyms and
94
- foreign words out in Hebrew words (`בשבע ועשרים`, not `7:20`). Characters it can't read are skipped.
95
- - **No niqqud needed.** [Phonikud](https://github.com/thewh1teagle/phonikud) vocalizes each sentence in context
96
- and adds stress; the model reads its phonemes.
97
  - **Tags** go where the sound should be, in English inside the Hebrew: `<laugh>`, `<chuckle>`, `<sigh>`,
98
  `<breath>`, `<gasp>`, `<throat-clearing>`, `<short pause>`, `<long pause>`.
 
99
  - **Punctuation** shapes the delivery (`, . ? ! …`). Long texts are read sentence by sentence.
 
100
 
101
  ## Model
102
 
@@ -104,7 +108,7 @@ A fork of [fiato](https://huggingface.co/cfahlgren1/fiato), itself a fork of
104
  [tiny-voca](https://github.com/n4ze3m/tiny-voca): a FastSpeech2-style model with a built-in
105
  differentiable source-filter vocoder, so there is no separate neural vocoder.
106
 
107
- - **Input:** 47 tokens: 29 Phonikud phonemes, 5 punctuation marks, word boundary, utterance edges and the 8
108
  expression tags. Stress is a parallel feature, not a token.
109
  - **Text encoder:** 4 transformer layers, 192 channels, with the style embedding added to every token.
110
  - **Word delivery codes:** each word or tag gets one of 32 learned delivery codes, chosen by a small recurrent
@@ -114,76 +118,76 @@ differentiable source-filter vocoder, so there is no separate neural vocoder.
114
  it, for the whole sentence at once.
115
  - **Frame level:** the style embedding is added again; a frame-level flow (2 layers) draws the pitch, voicing and
116
  energy contour, and 5 transformer layers predict the acoustic features.
117
- - **Vocoder:** a harmonic pulse train, on voiced frames only, plus noise, each shaped by a complex cepstrum per frame.
118
- - **Sounds tuned after training:** the sigh and breath directions inside the two flows were adjusted so sighs come
119
- out as loud and as long as in the data and breaths not too long.
120
  - **Size:** 4,991,888 parameters at inference (20 MB checkpoint); the weights are a moving average over training.
121
  Training also uses parameters that are not in the checkpoint (discriminators, a reference encoder for the
122
  delivery codes, an auxiliary mel head).
123
 
124
  ## Training data
125
 
126
- The dataset is **synthetic only**, with no recorded human speech: about 73,500 clips (152 h) of one synthetic
127
- voice, of which 70,864 training clips (148 h) passed forced alignment. 160 held-out sentences (20 per style) were
128
  kept for validation and 160 for test.
129
 
130
  - **Text:** Hebrew sentences from news (archive, HeSum, RSS), HeDC4 web text and stories, Hebrew
131
  Wikipedia, ivrit.ai transcripts and LLM-written scenes, among them emotional, dialogue-heavy scenes written for
132
- the expressive styles and sounds.
133
  - **Spoken form:** an LLM rewrote numbers, dates, money, acronyms and Latin script as Hebrew words, and every answer
134
  was checked by code.
135
  - **Addressee gender:** an LLM decided the gender of ambiguous second-person words (לך, אותך, אמרת) in context.
136
- The audio and the training phonemes follow the same decision.
 
137
  - **Styles:** an LLM picked a style for each dialogue sentence and inserted the tags; calm and whisper were assigned
138
  to plain statements, and some expressive sentences were recorded in a second style. Each style was rendered with
139
  one fixed delivery instruction; default is a bright, friendly delivery.
140
 
141
- | Style | Clips synthesized |
142
  |---|---|
143
- | default | 52,576 |
144
- | calm | 5,087 |
145
- | whisper | 4,912 |
146
- | fearful | 2,614 |
147
- | angry | 2,314 |
148
- | sad | 2,145 |
149
- | excited | 1,936 |
150
- | surprised | 1,888 |
151
-
152
- Tags in the aligned training clips (at most 2 per clip): short pause 2,270, breath 1,627, chuckle 1,085,
153
- sigh 936, long pause 924, gasp 798, laugh 796, throat-clearing 389.
154
- - **Labels:** Phonikud phonemes with the addressee decisions applied, phonemized word by word with the tags at
155
- their positions. Durations come from forced alignment with
156
  [facebook/wav2vec2-lv-60-espeak-cv-ft](https://huggingface.co/facebook/wav2vec2-lv-60-espeak-cv-ft), which is used
157
  only for labeling and is not part of the model. A tag owns the sound up to the neighbouring phonemes.
158
 
159
  ## Limitations
160
 
161
- - **Laughs and chuckles are not reliable.** They are a few dB quieter than in the data, and some draws leave them
162
- faint; another `--seed` usually helps. `<breath>` is quiet.
163
- - **Melody and emphasis:** the melody is less varied than a human reading, and the emphasis of a sentence sometimes
164
- lands on the wrong word. Tempo changes less within a sentence than in the data.
165
- - **Temperature trades life for stability:** at 0.3 and below the delivery gets flat; above ~1 words can be
166
  mispronounced and the sound can break.
167
- - **Fearful is the weakest style:** many of its training clips failed alignment.
168
- - **Pronunciation follows Phonikud,** including its mistakes (e.g. וואו read as "vaʔu").
169
- - **Second person defaults to masculine** unless `--addressee f` is given; there is no per-word decision at
170
- inference.
171
  - One voice only. Sentences are synthesized independently, with no prosody carried between them.
172
 
173
  ## License
174
 
175
  - **Code** (`pitput/`): Apache License 2.0. It is a fork of fiato by cfahlgren1 and tiny-voca by Muhammed Nazeem,
176
  both Apache-2.0; see `NOTICE`, `LICENSE` and `LICENSE.tiny-voca`.
177
- - **Weights and audio samples: private research use only, not licensed for redistribution or any commercial use.**
178
- - **Phonikud** ([thewh1teagle/phonikud-onnx](https://huggingface.co/thewh1teagle/phonikud-onnx), MIT) is downloaded
179
- at first use and is not included here.
180
 
181
  ## Files
182
 
183
  | File | Contents |
184
  |---|---|
185
  | `inference.pt` | Weights, model configuration and front-end fingerprint (loaded with `weights_only=True`) |
186
- | `pitput/` | Inference code: `infer.py` (command line and `speak_text`), `model.py`, `text.py` (phoneme tokens), `g2p.py` (Phonikud and addressee gender), `labels.py`, `config.py` |
 
187
  | `samples/` | The audio above |
188
  | `config.json`, `recipe.json` | Model and training settings of this version |
189
  | `requirements.txt` | Python dependencies |
@@ -192,5 +196,6 @@ kept for validation and 160 for test.
192
  ## Acknowledgements
193
 
194
  [tiny-voca](https://github.com/n4ze3m/tiny-voca) for the architecture and training recipe,
195
- [fiato](https://huggingface.co/cfahlgren1/fiato) for expression tags on it, [Phonikud](https://github.com/thewh1teagle/phonikud)
196
- for Hebrew vocalization and phonemes, and the Hebrew text sources: HeDC4, HeSum, Hebrew Wikipedia and ivrit.ai.
 
 
28
 
29
  | Version | What changed |
30
  |---|---|
31
+ | **v3** (this, November 24, 2026) | More speech (173 h aligned), including fillers (אהמ, הממ, אהה) and more of every expressive style. Pronunciation comes from the phonemizer shipped here, which also chooses לך, אותך, אמרת from the sentence. Sound tags are drawn from the codes that rendered them fully in the data |
32
+ | **v2** (November 21, 2026) | The delivery of each word is drawn instead of averaged: livelier melody and tempo, audible laughs and chuckles, pauses where a speaker would take them. More expressive training data. Cleaner whisper and breaths. Sighs and breaths tuned to the loudness and length of the data |
33
  | v1 (November 18, 2026) | First model. Steady, somewhat robotic delivery; laughs came out as a soft breath |
34
 
35
+ Older versions stay available as tags: `git checkout v2`, or `revision="v2"` in `huggingface_hub`.
36
 
37
  ## Samples
38
 
39
+ The listening texts, synthesized with the default settings (the model's own playback: word codes at 0.5, melody at 0.3, pitch range 1.2, seed 0).
40
 
41
  | Style | Text | Audio |
42
  |---|---|---|
43
+ | default | לפי נתוני הלשכה המרכזית לסטטיסטיקה, אוכלוסיית ישראל גדלה בשנה האחרונה בכמאה ושמונים אלף איש. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v3/samples/01-default.wav"></audio> |
44
+ | default, addressee f | מה שלומך? שמעתי שלא הרגשת טוב בשבוע שעבר. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v3/samples/02-default.wav"></audio> |
45
+ | default | הרכבת לחיפה יוצאת בשבע ועשרים ומגיעה בשמונה וחצי, `<chuckle>` אם היא בכלל תגיע. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v3/samples/03-default.wav"></audio> |
46
+ | excited | `<laugh>` אני לא מאמינה, קיבלנו את הדירה! | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v3/samples/04-excited.wav"></audio> |
47
+ | sad | `<sigh>` חיכיתי לו כל הערב, והוא פשוט לא הגיע. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v3/samples/05-sad.wav"></audio> |
48
+ | angry, addressee m | כמה פעמים אמרתי לך לסגור את הדלת?! | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v3/samples/06-angry.wav"></audio> |
49
+ | fearful | שמעת את זה? `<gasp>` יש מישהו בחוץ. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v3/samples/07-fearful.wav"></audio> |
50
+ | surprised | רגע, `<short pause>` הוא באמת התפטר? אחרי עשרים שנה? | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v3/samples/08-surprised.wav"></audio> |
51
+ | calm | `<breath>` קחו נשימה עמוקה, `<long pause>` ותנו לגוף להירגע לאט לאט. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v3/samples/09-calm.wav"></audio> |
52
+ | whisper | בוא נדבר בשקט, כולם כבר ישנים. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v3/samples/10-whisper.wav"></audio> |
53
+ | default | אהמ... רק שאלה אחת קטנה. זה היה, אממ, ביום שלישי, נראה לי. | <audio controls src="https://huggingface.co/useless-ai/pitput/resolve/v3/samples/11-default.wav"></audio> |
54
 
55
  ## Usage
56
 
57
  ```bash
58
  git clone https://huggingface.co/useless-ai/pitput
59
  cd pitput
60
+ pip install -r requirements.txt # PyTorch, numpy, soundfile
61
 
62
  python -m pitput.infer --style excited --text "<laugh> אני לא מאמינה, קיבלנו את הדירה!" --output out.wav
63
  python -m pitput.infer --style default --addressee f --text "מה שלומך? שמעתי שלא הרגשת טוב." --output hello.wav
64
  ```
65
 
66
+ The phonemizer (about 40 MB) is included. Options:
67
 
68
  | Option | Meaning |
69
  |---|---|
70
  | `--style` | `default`, `excited`, `sad`, `angry`, `fearful`, `surprised`, `calm`, `whisper` |
71
+ | `--addressee m` / `f` | Gender of the person spoken to (לך, אותך, אמרת …). Without it, the sentence decides: a name, a form of address or the story is enough |
72
+ | `--temperature` | How freely the delivery is drawn. Omitted, the model uses its own playback (word codes at 0.5, melody at 0.3). `0` is the most likely delivery; higher is livelier and less predictable; above ~1 it starts to break up |
73
  | `--seed` | Another seed gives another delivery of the same text (default 0). If a laugh or chuckle comes out weak, try another seed |
74
  | `--text-file` | Read the text from a UTF-8 file instead of `--text` |
75
  | `--speed` | 1.0 = as trained; 0.9 is 10% slower |
 
84
  from pitput.infer import CHECKPOINT, load_model, speak_text
85
 
86
  model = load_model(CHECKPOINT) # inference.pt next to the package
87
+ wave, utterances = speak_text(model, "שלום, <sigh> מה שלומך?", "calm", addressee="f", seed=0)
88
  sf.write("out.wav", wave.numpy(), model.config.sample_rate)
89
  ```
90
 
91
+ Passing `temperature=0.55` plays the way v2 did, with one temperature for both the word codes and the melody.
92
 
93
  ### What the input must look like
94
 
95
+ - **Plain Hebrew in spoken form.** There is no text normalizer for dates and acronyms: write those out in Hebrew
96
+ words (`בשבע ועשרים`, not `7:20`). A digit string is read as a number. Characters it can't read are skipped.
97
+ - **No niqqud needed.** The phonemizer reads each sentence in context and adds stress. A pointed letter is
98
+ followed; an unpointed letter is still predicted from the sentence.
99
  - **Tags** go where the sound should be, in English inside the Hebrew: `<laugh>`, `<chuckle>`, `<sigh>`,
100
  `<breath>`, `<gasp>`, `<throat-clearing>`, `<short pause>`, `<long pause>`.
101
+ - **Fillers** אהמ and אממ are read "emm", הממ as a hum, אהה as a long "a".
102
  - **Punctuation** shapes the delivery (`, . ? ! …`). Long texts are read sentence by sentence.
103
+ - The voice is a woman's, including first person (בודקת, not בודק).
104
 
105
  ## Model
106
 
 
108
  [tiny-voca](https://github.com/n4ze3m/tiny-voca): a FastSpeech2-style model with a built-in
109
  differentiable source-filter vocoder, so there is no separate neural vocoder.
110
 
111
+ - **Input:** 47 tokens: 29 phonemes, 5 punctuation marks, word boundary, utterance edges and the 8
112
  expression tags. Stress is a parallel feature, not a token.
113
  - **Text encoder:** 4 transformer layers, 192 channels, with the style embedding added to every token.
114
  - **Word delivery codes:** each word or tag gets one of 32 learned delivery codes, chosen by a small recurrent
 
118
  it, for the whole sentence at once.
119
  - **Frame level:** the style embedding is added again; a frame-level flow (2 layers) draws the pitch, voicing and
120
  energy contour, and 5 transformer layers predict the acoustic features.
121
+ - **Vocoder:** a harmonic pulse train, on voiced frames only, plus noise shaped by 64 cepstral coefficients per frame.
 
 
122
  - **Size:** 4,991,888 parameters at inference (20 MB checkpoint); the weights are a moving average over training.
123
  Training also uses parameters that are not in the checkpoint (discriminators, a reference encoder for the
124
  delivery codes, an auxiliary mel head).
125
 
126
  ## Training data
127
 
128
+ The dataset is **synthetic only**, with no recorded human speech: about 91,600 clips (180 h) of one synthetic
129
+ voice, of which 86,438 training clips (173 h) passed forced alignment. 160 held-out sentences (20 per style) were
130
  kept for validation and 160 for test.
131
 
132
  - **Text:** Hebrew sentences from news (archive, HeSum, RSS), HeDC4 web text and stories, Hebrew
133
  Wikipedia, ivrit.ai transcripts and LLM-written scenes, among them emotional, dialogue-heavy scenes written for
134
+ the expressive styles and sounds, plus short lines with hesitation fillers.
135
  - **Spoken form:** an LLM rewrote numbers, dates, money, acronyms and Latin script as Hebrew words, and every answer
136
  was checked by code.
137
  - **Addressee gender:** an LLM decided the gender of ambiguous second-person words (לך, אותך, אמרת) in context.
138
+ The audio follows that decision. Where the decided words of a sentence agree, the phonemes use that listener;
139
+ otherwise the phonemizer decides from the sentence.
140
  - **Styles:** an LLM picked a style for each dialogue sentence and inserted the tags; calm and whisper were assigned
141
  to plain statements, and some expressive sentences were recorded in a second style. Each style was rendered with
142
  one fixed delivery instruction; default is a bright, friendly delivery.
143
 
144
+ | Style | Aligned training clips |
145
  |---|---|
146
+ | default | 54,318 |
147
+ | calm | 5,438 |
148
+ | whisper | 4,867 |
149
+ | surprised | 4,638 |
150
+ | angry | 4,556 |
151
+ | excited | 4,533 |
152
+ | sad | 4,120 |
153
+ | fearful | 3,968 |
154
+
155
+ Tags in the aligned clips (at most 2 per clip): breath 4,008, short pause 3,277, long pause 2,704,
156
+ chuckle 2,236, laugh 2,161, gasp 2,103, sigh 2,005, throat-clearing 1,101.
157
+ - **Labels:** phonemes from the phonemizer in this repository, with stress and the tags at their positions.
158
+ Durations come from forced alignment with
159
  [facebook/wav2vec2-lv-60-espeak-cv-ft](https://huggingface.co/facebook/wav2vec2-lv-60-espeak-cv-ft), which is used
160
  only for labeling and is not part of the model. A tag owns the sound up to the neighbouring phonemes.
161
 
162
  ## Limitations
163
 
164
+ - **Laughs and chuckles vary.** Some draws are full and some are thin; another `--seed` usually helps.
165
+ `<breath>` and `<sigh>` are quieter than speech, as they are in the data.
166
+ - **Melody and emphasis:** the melody is less varied than the recordings, and the emphasis of a sentence sometimes
167
+ lands on the wrong word. A tag does not reliably change the tone of the words after it.
168
+ - **Temperature trades life for stability:** the default playback is the steadier one. Above ~1, words can be
169
  mispronounced and the sound can break.
170
+ - **Fearful is the weakest style:** more of its clips failed alignment than the other styles.
171
+ - **Pronunciation follows the bundled phonemizer.** בין and בית are read with *ej* (`bˈejn`, `bˈejt`). With no
172
+ listener and no cue in the sentence, "ראית את הסרט החדש, מיכל?" is read as masculine; `--addressee f` fixes it.
173
+ - **The speaker is a woman.** First person follows that (בודקת). There is no men's voice.
174
  - One voice only. Sentences are synthesized independently, with no prosody carried between them.
175
 
176
  ## License
177
 
178
  - **Code** (`pitput/`): Apache License 2.0. It is a fork of fiato by cfahlgren1 and tiny-voca by Muhammed Nazeem,
179
  both Apache-2.0; see `NOTICE`, `LICENSE` and `LICENSE.tiny-voca`.
180
+ - **Phonemizer** (`phonemizer/`, code and weights): Apache License 2.0. `renikud_onnx.py` is from RenikudPlus by
181
+ notmax123, Apache-2.0; see `phonemizer/NOTICE`.
182
+ - **TTS weights and audio samples: private research use only, not licensed for redistribution or any commercial use.**
183
 
184
  ## Files
185
 
186
  | File | Contents |
187
  |---|---|
188
  | `inference.pt` | Weights, model configuration and front-end fingerprint (loaded with `weights_only=True`) |
189
+ | `pitput/` | Inference code: `infer.py` (command line and `speak_text`), `model.py`, `text.py` (phoneme tokens), `read.py` (Hebrew to a label) |
190
+ | `phonemizer/` | The pronunciation model: `phonemizer.py`, `model.safetensors` (40 MB), `config.json` |
191
  | `samples/` | The audio above |
192
  | `config.json`, `recipe.json` | Model and training settings of this version |
193
  | `requirements.txt` | Python dependencies |
 
196
  ## Acknowledgements
197
 
198
  [tiny-voca](https://github.com/n4ze3m/tiny-voca) for the architecture and training recipe,
199
+ [fiato](https://huggingface.co/cfahlgren1/fiato) for expression tags on it,
200
+ [RenikudPlus](https://huggingface.co/notmax123/RenikudPlus) for the phonemizer's per-letter distributions,
201
+ decoder and number reading, and the Hebrew text sources: HeDC4, HeSum, Hebrew Wikipedia and ivrit.ai.
config.json CHANGED
@@ -48,35 +48,35 @@
48
  [
49
  0.0,
50
  0.0,
 
51
  0.0,
52
  0.0,
53
  0.0,
54
  0.0,
55
  0.0,
56
  0.0,
57
- 0.2127,
58
  0.0,
59
- 0.1338,
60
  0.0,
61
  0.0,
 
62
  0.0,
63
- 0.2522,
64
  0.0,
65
  0.0,
66
- 0.0088,
67
- 0.0154,
68
  0.0,
69
  0.0,
 
 
 
70
  0.0,
71
  0.0,
72
  0.0,
73
  0.0,
74
  0.0,
75
- 0.0482,
76
- 0.1645,
77
- 0.1118,
78
- 0.0241,
79
- 0.0285,
80
  0.0
81
  ]
82
  ],
@@ -85,35 +85,35 @@
85
  [
86
  0.0,
87
  0.0,
 
88
  0.0,
89
- 0.0632,
90
  0.0,
91
- 0.0105,
92
- 0.009,
93
  0.0,
94
- 0.1053,
95
  0.0,
96
- 0.1684,
97
  0.0,
 
98
  0.0,
99
  0.0,
100
- 0.1504,
101
- 0.1248,
102
  0.0,
 
103
  0.0,
104
  0.0,
 
105
  0.0,
 
106
  0.0,
 
 
107
  0.0,
108
- 0.0135,
109
- 0.0331,
110
  0.0,
111
  0.0,
112
- 0.0135,
113
- 0.1579,
114
- 0.1504,
115
  0.0,
116
  0.0,
 
 
 
 
117
  0.0
118
  ]
119
  ],
@@ -122,35 +122,35 @@
122
  [
123
  0.0,
124
  0.0,
125
- 0.0187,
126
- 0.1042,
127
  0.0,
128
  0.0,
129
- 0.0729,
130
  0.0,
131
- 0.2,
132
  0.0,
133
- 0.1062,
134
  0.0,
 
135
  0.0,
 
136
  0.0,
137
- 0.0625,
138
  0.0,
139
  0.0,
 
140
  0.0,
141
- 0.0208,
142
  0.0,
143
- 0.0146,
 
144
  0.0,
145
  0.0,
146
  0.0,
147
  0.0,
148
  0.0,
149
  0.0,
150
- 0.1458,
151
- 0.1958,
152
- 0.0583,
153
  0.0,
 
154
  0.0
155
  ]
156
  ],
@@ -159,35 +159,35 @@
159
  [
160
  0.0,
161
  0.0,
 
162
  0.0,
163
- 0.1053,
164
- 0.0,
165
  0.0,
166
  0.0,
167
  0.0,
168
- 0.1779,
169
  0.0,
170
- 0.1011,
171
  0.0,
172
  0.0,
 
 
173
  0.0,
174
- 0.0568,
175
- 0.1758,
176
  0.0,
 
177
  0.0,
 
178
  0.0,
 
 
179
  0.0,
180
  0.0,
181
  0.0,
182
  0.0,
183
  0.0,
184
- 0.0126,
185
- 0.0,
186
- 0.0126,
187
- 0.1716,
188
- 0.1863,
189
  0.0,
190
  0.0,
 
 
191
  0.0
192
  ]
193
  ],
@@ -196,35 +196,35 @@
196
  [
197
  0.0,
198
  0.0,
 
 
199
  0.0,
200
  0.0,
201
  0.0,
202
  0.0,
203
  0.0,
 
204
  0.0,
205
- 0.3765,
206
- 0.0647,
207
- 0.1199,
208
  0.0,
 
 
 
209
  0.0,
210
  0.0,
211
- 0.1295,
212
  0.0,
213
  0.0,
214
  0.0,
215
- 0.0192,
 
216
  0.0,
217
  0.0,
218
  0.0,
219
- 0.0192,
220
  0.0,
221
- 0.0192,
222
  0.0,
223
  0.0,
224
- 0.0935,
225
- 0.1247,
226
- 0.0336,
227
  0.0,
 
 
228
  0.0
229
  ]
230
  ],
@@ -232,25 +232,24 @@
232
  "<throat-clearing>",
233
  [
234
  0.0,
 
 
235
  0.0,
236
- 0.015,
237
- 0.0,
238
- 0.015,
239
- 0.0,
240
- 0.4361,
241
  0.0,
242
  0.0,
243
  0.0,
244
- 0.3008,
245
  0.0,
246
  0.0,
247
  0.0,
248
- 0.0526,
249
- 0.1805,
250
  0.0,
 
 
 
 
251
  0.0,
252
  0.0,
253
  0.0,
 
254
  0.0,
255
  0.0,
256
  0.0,
@@ -259,6 +258,7 @@
259
  0.0,
260
  0.0,
261
  0.0,
 
262
  0.0,
263
  0.0,
264
  0.0,
 
48
  [
49
  0.0,
50
  0.0,
51
+ 0.2527,
52
  0.0,
53
  0.0,
54
  0.0,
55
  0.0,
56
  0.0,
57
  0.0,
58
+ 0.2343,
59
  0.0,
 
60
  0.0,
61
  0.0,
62
+ 0.1216,
63
  0.0,
 
64
  0.0,
65
  0.0,
 
 
66
  0.0,
67
  0.0,
68
+ 0.0128,
69
+ 0.1348,
70
+ 0.1374,
71
  0.0,
72
  0.0,
73
  0.0,
74
  0.0,
75
  0.0,
76
+ 0.0,
77
+ 0.055,
78
+ 0.0515,
79
+ 0.0,
 
80
  0.0
81
  ]
82
  ],
 
85
  [
86
  0.0,
87
  0.0,
88
+ 0.1345,
89
  0.0,
 
90
  0.0,
91
+ 0.0145,
 
92
  0.0,
 
93
  0.0,
 
94
  0.0,
95
+ 0.1633,
96
  0.0,
97
  0.0,
 
 
98
  0.0,
99
+ 0.1402,
100
  0.0,
101
  0.0,
102
+ 0.029,
103
  0.0,
104
+ 0.047,
105
  0.0,
106
+ 0.1937,
107
+ 0.1411,
108
  0.0,
 
 
109
  0.0,
110
  0.0,
 
 
 
111
  0.0,
112
  0.0,
113
+ 0.0247,
114
+ 0.0202,
115
+ 0.0917,
116
+ 0.0,
117
  0.0
118
  ]
119
  ],
 
122
  [
123
  0.0,
124
  0.0,
125
+ 0.0563,
126
+ 0.0,
127
  0.0,
128
  0.0,
 
129
  0.0,
 
130
  0.0,
 
131
  0.0,
132
+ 0.1556,
133
  0.0,
134
+ 0.0797,
135
  0.0,
136
+ 0.1289,
137
  0.0,
138
  0.0,
139
+ 0.0259,
140
  0.0,
141
+ 0.0379,
142
  0.0,
143
+ 0.1859,
144
+ 0.1998,
145
  0.0,
146
  0.0,
147
  0.0,
148
  0.0,
149
  0.0,
150
  0.0,
151
+ 0.0553,
 
 
152
  0.0,
153
+ 0.0748,
154
  0.0
155
  ]
156
  ],
 
159
  [
160
  0.0,
161
  0.0,
162
+ 0.0581,
163
  0.0,
164
+ 0.0296,
 
165
  0.0,
166
  0.0,
167
  0.0,
 
168
  0.0,
169
+ 0.1762,
170
  0.0,
171
  0.0,
172
+ 0.0374,
173
+ 0.1963,
174
  0.0,
 
 
175
  0.0,
176
+ 0.0176,
177
  0.0,
178
+ 0.0537,
179
  0.0,
180
+ 0.147,
181
+ 0.1323,
182
  0.0,
183
  0.0,
184
  0.0,
185
  0.0,
186
  0.0,
 
 
 
 
 
187
  0.0,
188
  0.0,
189
+ 0.0906,
190
+ 0.0612,
191
  0.0
192
  ]
193
  ],
 
196
  [
197
  0.0,
198
  0.0,
199
+ 0.1039,
200
+ 0.0,
201
  0.0,
202
  0.0,
203
  0.0,
204
  0.0,
205
  0.0,
206
+ 0.3542,
207
  0.0,
 
 
 
208
  0.0,
209
+ 0.085,
210
+ 0.1188,
211
+ 0.0176,
212
  0.0,
213
  0.0,
 
214
  0.0,
215
  0.0,
216
  0.0,
217
+ 0.0821,
218
+ 0.1147,
219
  0.0,
220
  0.0,
221
  0.0,
 
222
  0.0,
 
223
  0.0,
224
  0.0,
 
 
 
225
  0.0,
226
+ 0.0482,
227
+ 0.0755,
228
  0.0
229
  ]
230
  ],
 
232
  "<throat-clearing>",
233
  [
234
  0.0,
235
+ 0.0555,
236
+ 0.083,
237
  0.0,
 
 
 
 
 
238
  0.0,
239
  0.0,
240
  0.0,
 
241
  0.0,
242
  0.0,
243
  0.0,
 
 
244
  0.0,
245
+ 0.3564,
246
+ 0.2682,
247
+ 0.164,
248
+ 0.0315,
249
  0.0,
250
  0.0,
251
  0.0,
252
+ 0.0273,
253
  0.0,
254
  0.0,
255
  0.0,
 
258
  0.0,
259
  0.0,
260
  0.0,
261
+ 0.014,
262
  0.0,
263
  0.0,
264
  0.0,
inference.pt CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c0fa04292d3b399958a65fbb74c70bcbe14e26b6257045d2768624454e06bbe3
3
- size 20066151
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00e5af56d1a9206ecd6d9fb70f48c426153cf60fb3ace79bc1ec1a62b9619aa8
3
+ size 20064726
phonemizer/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.
phonemizer/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.
phonemizer/config.json ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ }
phonemizer/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dbbfa842a103f7b1d0f9eacc97a996244341eedbf659abe6083ebe379ec7c476
3
+ size 40346436
phonemizer/phonemizer.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
phonemizer/renikud_onnx.py ADDED
@@ -0,0 +1,1387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
pitput/__init__.py CHANGED
@@ -1,8 +1,8 @@
1
  """pitput: a small Hebrew text-to-speech model, a fork of fiato (itself a fork of tiny-voca). See NOTICE.
2
 
3
  One voice in 8 delivery styles, which take the place of fiato's voices, and 8
4
- expression tags. Text goes through Phonikud (``pitput.g2p``) and is phonemized
5
- word by word (``pitput.labels``) exactly as for the training clips.
6
 
7
  Nothing is imported here, so ``pitput.text`` works without PyTorch.
8
  """
 
1
  """pitput: a small Hebrew text-to-speech model, a fork of fiato (itself a fork of tiny-voca). See NOTICE.
2
 
3
  One voice in 8 delivery styles, which take the place of fiato's voices, and 8
4
+ expression tags. Text goes through the phonemizer shipped beside this package
5
+ (``pitput.read``) exactly as for the training clips.
6
 
7
  Nothing is imported here, so ``pitput.text`` works without PyTorch.
8
  """
pitput/infer.py CHANGED
@@ -16,7 +16,7 @@ from .text import NothingToPronounce, frontend_fingerprint, hebrew_label, phonem
16
 
17
  CHECKPOINT = Path(__file__).resolve().parent.parent / "inference.pt"
18
  # The temperature of the published samples; None plays the model's own playback settings.
19
- TEMPERATURE = 0.55
20
  # The loudest sample of the audio that ``speak_text`` and the command return.
21
  PEAK = 0.99
22
  NOTHING = "nothing in the text could be read (Hebrew words only)"
@@ -162,7 +162,8 @@ def main():
162
  parser.add_argument("--pitch-shift", type=float, default=0, help="Added to log F0 (0.058 is about one semitone)")
163
  parser.add_argument("--pitch-range", type=float, help="Scale pitch movement around the utterance mean (default: the model's pitch_range; 1 = as predicted)")
164
  parser.add_argument("--temperature", type=float, default=TEMPERATURE, help="How freely the delivery of each word is drawn: 0 = the most likely, "
165
- "higher = livelier and more varied (default 0.55)")
 
166
  parser.add_argument("--seed", type=int, default=0, help="Another seed gives another delivery of the same text")
167
  parser.add_argument("--device", default="cpu")
168
  args = parser.parse_args()
 
16
 
17
  CHECKPOINT = Path(__file__).resolve().parent.parent / "inference.pt"
18
  # The temperature of the published samples; None plays the model's own playback settings.
19
+ TEMPERATURE = None
20
  # The loudest sample of the audio that ``speak_text`` and the command return.
21
  PEAK = 0.99
22
  NOTHING = "nothing in the text could be read (Hebrew words only)"
 
162
  parser.add_argument("--pitch-shift", type=float, default=0, help="Added to log F0 (0.058 is about one semitone)")
163
  parser.add_argument("--pitch-range", type=float, help="Scale pitch movement around the utterance mean (default: the model's pitch_range; 1 = as predicted)")
164
  parser.add_argument("--temperature", type=float, default=TEMPERATURE, help="How freely the delivery of each word is drawn: 0 = the most likely, "
165
+ "higher = livelier and more varied (default: the model's playback, "
166
+ "word codes at 0.5 and melody at 0.3)")
167
  parser.add_argument("--seed", type=int, default=0, help="Another seed gives another delivery of the same text")
168
  parser.add_argument("--device", default="cpu")
169
  args = parser.parse_args()
pitput/model.py CHANGED
@@ -351,6 +351,24 @@ class Planner(nn.Module):
351
  codes[:, unit] = previous
352
  return codes
353
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
 
355
  class WordFlow(nn.Module):
356
  """The codes of all units of a sentence drawn from noise at once (rectified flow),
 
351
  codes[:, unit] = previous
352
  return codes
353
 
354
+ def sample_soft(self, text, speakers, temperature):
355
+ """Codes drawn as ``sample`` draws them at ``temperature`` > 0 (Gumbel-max), as one-hot rows [B,U,codes]
356
+ whose gradient is the softmax's (straight-through): a loss on what the codes produce reaches the planner."""
357
+ rows, previous, state = [], torch.full(text.shape[:1], self.start, dtype=torch.long, device=text.device), None
358
+ embedding = None
359
+ for unit in range(text.shape[1]):
360
+ step = self.text(text[:, unit]) + (self.code(previous) if embedding is None else embedding) + self.voice(speakers)
361
+ hidden, state = self.rnn(step[:, None], state)
362
+ logits = self.out(hidden[:, 0]).float() / temperature
363
+ gumbel = -torch.log(-torch.log(torch.rand_like(logits).clamp(1e-9, 1 - 1e-9)))
364
+ soft = torch.softmax(logits + gumbel, -1)
365
+ hard = F.one_hot(soft.argmax(-1), soft.shape[-1]).float()
366
+ row = hard + soft - soft.detach()
367
+ rows.append(row)
368
+ embedding = row.to(self.code.weight.dtype) @ self.code.weight[:soft.shape[-1]]
369
+ previous = hard.argmax(-1)
370
+ return torch.stack(rows, 1)
371
+
372
 
373
  class WordFlow(nn.Module):
374
  """The codes of all units of a sentence drawn from noise at once (rectified flow),
pitput/read.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plain Hebrew to the label string this model was trained on.
2
+
3
+ The phonemizer ships in ``phonemizer/`` next to this package. The speaker is a
4
+ woman, the voice of the model. ``addressee`` ("m" or "f") is who is spoken to;
5
+ omitted, the sentence decides. Hesitation sounds have fixed readings, and a
6
+ doubled furtive patah at the end of a word is repaired.
7
+ """
8
+ import importlib.util
9
+ import re
10
+ from pathlib import Path
11
+
12
+ PHONEMIZER = Path(__file__).resolve().parents[1] / "phonemizer"
13
+ SPEAKER = "f"
14
+ TAGS = ("laugh", "chuckle", "sigh", "breath", "gasp", "throat-clearing", "short pause", "long pause")
15
+ _TAG = re.compile("(<(?:" + "|".join("[ _]".join(map(re.escape, tag.split(" "))) for tag in TAGS) + ")>)")
16
+ _JOINER = re.compile("(?<=[\u05d0-\u05ea])[-\u05be](?=[\u05d0-\u05ea])")
17
+ _LETTERS = re.compile("[\u05d0-\u05ea]+")
18
+ _FILLERS = (
19
+ (re.compile("^א+ה*מ+$"), "ʔˈem"),
20
+ (re.compile("^ה+מ+$"), "hmm"),
21
+ (re.compile("^אה{2,}$"), "ʔˈa"),
22
+ )
23
+ _FURTIVE = re.compile("([iu]a)ʔa(?=[^\\w]*$)")
24
+ _HEBREW = re.compile("[^\u05d0-\u05ea]")
25
+ PUNCT = {".": ".", ",": ",", "!": "!", "?": "?", "…": "…",
26
+ ";": ",", ":": ",", "-": ",", "\u2013": ",", "\u2014": ",", "\u05be": ","}
27
+
28
+ _g2p = None
29
+
30
+
31
+ def punctuation(text):
32
+ out = ""
33
+ for char in text.replace("...", "…"):
34
+ symbol = PUNCT.get(char)
35
+ if symbol and not out.endswith(symbol):
36
+ out += symbol
37
+ return out
38
+
39
+
40
+ def _filler(word):
41
+ core = "".join(_LETTERS.findall(word))
42
+ if not core or _LETTERS.sub("", word).strip(".,…!?\"'״׳ "):
43
+ return None
44
+ return next((ipa for pattern, ipa in _FILLERS if pattern.match(core)), None)
45
+
46
+
47
+ def _repair(text, ipa):
48
+ words, read = text.split(), ipa.split()
49
+ if len(words) != len(read):
50
+ return ipa
51
+ out = []
52
+ for word, phones in zip(words, read):
53
+ fixed = _filler(word)
54
+ if fixed:
55
+ phones = fixed + "".join(char for char in phones if not char.isalpha() and char != "ˈ")
56
+ elif _HEBREW.sub("", word).endswith(("יע", "וע")):
57
+ phones = _FURTIVE.sub(r"\1", phones)
58
+ out.append(phones)
59
+ return " ".join(out)
60
+
61
+
62
+ def phonemizer():
63
+ global _g2p
64
+ if _g2p is None:
65
+ script = PHONEMIZER / "phonemizer.py"
66
+ if not script.is_file():
67
+ raise FileNotFoundError(f"phonemizer weights not found at {PHONEMIZER}")
68
+ spec = importlib.util.spec_from_file_location("pitput_phonemizer", script)
69
+ module = importlib.util.module_from_spec(spec)
70
+ spec.loader.exec_module(module)
71
+ _g2p = module.Phonemizer.from_pretrained(PHONEMIZER)
72
+ return _g2p
73
+
74
+
75
+ def label_text(text, addressee=None):
76
+ """Plain Hebrew, tags allowed, -> a label (words, stress, punctuation, tags)."""
77
+ if addressee not in (None, "m", "f"):
78
+ raise ValueError('addressee must be "m", "f", or omitted')
79
+ listener = addressee
80
+ pieces = []
81
+ for part in _TAG.split(" ".join(text.split())):
82
+ if _TAG.fullmatch(part):
83
+ pieces.append("<" + part[1:-1].replace("_", " ") + ">")
84
+ elif part.strip():
85
+ plain = _JOINER.sub(" ", part.strip())
86
+ ipa = phonemizer()(plain, speaker=SPEAKER, listener=listener)
87
+ for word in _repair(plain, ipa).split():
88
+ core = "".join(char for char in word if char.isalpha())
89
+ marks = punctuation("".join(char for char in word if char in PUNCT))
90
+ if core:
91
+ pieces.append(core + marks)
92
+ elif marks and pieces and not pieces[-1].startswith("<"):
93
+ pieces[-1] += marks
94
+ if not any(not piece.startswith("<") for piece in pieces):
95
+ raise ValueError("the text has nothing to pronounce")
96
+ return " ".join(pieces)
pitput/text.py CHANGED
@@ -171,29 +171,20 @@ def phonemize(label):
171
  return tokenize(pieces(label))
172
 
173
 
174
- _g2p = None
175
-
176
-
177
  def hebrew_label(text, addressee=None):
178
  """Plain Hebrew (optionally with expression tags such as ``<sigh>``) -> a label string.
179
 
180
- Phonikud vocalizes the sentence as a whole (context), then ``pitput.labels``
181
- phonemizes it word by word exactly as for the training clips. The text must
182
- already be in spoken form (numbers and acronyms written out)."""
183
- global _g2p
184
- from .g2p import G2P
185
- from .labels import label
186
- tags, words = [], []
187
- for part in _EXPRESSION.split(expression_tokens(" ".join(text.split()))):
188
- if part in EXPRESSIONS:
189
- tags.append({"i": len(words), "tag": part[1:-1].replace("_", " ")})
190
- else:
191
- words.extend(part.split())
192
- if not words:
193
- raise NothingToPronounce("the text has nothing to pronounce")
194
- if _g2p is None:
195
- _g2p = G2P()
196
- return label(_g2p.vocalize(" ".join(words), addressee=addressee), {}, tags)
197
 
198
 
199
  def is_phone(token_ids):
 
171
  return tokenize(pieces(label))
172
 
173
 
 
 
 
174
  def hebrew_label(text, addressee=None):
175
  """Plain Hebrew (optionally with expression tags such as ``<sigh>``) -> a label string.
176
 
177
+ The phonemizer shipped beside this package reads the sentence. The speaker is
178
+ a woman; ``addressee`` ("m" or "f") is who is spoken to, and when it is omitted
179
+ the sentence decides. The text must already be in spoken form (numbers and
180
+ acronyms written out)."""
181
+ from .read import label_text
182
+ try:
183
+ return label_text(text, addressee)
184
+ except ValueError as error:
185
+ if "nothing to pronounce" in str(error):
186
+ raise NothingToPronounce("the text has nothing to pronounce") from None
187
+ raise
 
 
 
 
 
 
188
 
189
 
190
  def is_phone(token_ids):
recipe.json CHANGED
@@ -22,6 +22,8 @@
22
  "expression_weight": 5.0,
23
  "ema_decay": 0.999,
24
  "flow_untrusted_weight": 1.0,
 
 
25
  "weights": {
26
  "duration": 1.0,
27
  "pause": 1.0,
@@ -35,15 +37,16 @@
35
  "commitment": 0.25,
36
  "planner": 1.0,
37
  "flow": 1.0,
38
- "duration_flow": 1.0
 
39
  },
40
  "branched_from": null,
41
- "annotation": "dbe8c7f516e860c6f6c92f68d00c3c0f2862dc12574ebc74b474a3ba620aa6c0",
42
  "frontend": "d78567bd1892b2dec5a33d791fa537c1e0b0223742141cd5420335f73142fc13",
43
- "train_utterances": 70864,
44
  "datasets": [
45
- "38de51b54e96081b3e775be22d31e1185aebaa8eadf9e5642e3997e80a06c956",
46
- "1ced508eeb0ed0c4a7c5a09590f3f17f339fc9dc8604b965ac0c3bbb30926cdd"
47
  ],
48
- "step": 46000
49
  }
 
22
  "expression_weight": 5.0,
23
  "ema_decay": 0.999,
24
  "flow_untrusted_weight": 1.0,
25
+ "sound_codes": true,
26
+ "tag_crops": true,
27
  "weights": {
28
  "duration": 1.0,
29
  "pause": 1.0,
 
37
  "commitment": 0.25,
38
  "planner": 1.0,
39
  "flow": 1.0,
40
+ "duration_flow": 1.0,
41
+ "tag_level": 2.0
42
  },
43
  "branched_from": null,
44
+ "annotation": "57c16ecc840f57c53279a881f9e41c47691492b12d6fb52953cdff902dfc0c3e",
45
  "frontend": "d78567bd1892b2dec5a33d791fa537c1e0b0223742141cd5420335f73142fc13",
46
+ "train_utterances": 86438,
47
  "datasets": [
48
+ "87782f985a4a9daff29a536b339ad0e00597ef1a80ac0e783ce8b40d46c0f9f1",
49
+ "aad53fc9315e5fe414b0e5fe36db533907b34270ac737e4ef73dd7007998ecbc"
50
  ],
51
+ "step": 60000
52
  }
requirements.txt CHANGED
@@ -1,6 +1,3 @@
1
  torch>=2.5
 
2
  soundfile
3
- phonikud>=0.4.1
4
- phonikud-onnx>=1.0.6
5
- onnxruntime
6
- huggingface_hub
 
1
  torch>=2.5
2
+ numpy
3
  soundfile
 
 
 
 
samples/01-default.wav CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:6370797bd60fe8cce3b7bd5e9687e8664e1370f0e1d05e80f47211c42ed74992
3
- size 360492
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:171c1019efdec98da87806bae8e2fdb40f3c7412de0f788e053dc6c477703682
3
+ size 384044
samples/02-default.wav CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d7631e69ddaeb6176a2d39a5e5b144c42086c169a9dc20e8ff643a29fde6b5e5
3
- size 223276
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:abbbe85f3d37ef417ce72103240729cccf44ed5ad81ca0c6554c2c19cd65c799
3
+ size 213548
samples/03-default.wav CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0a3ffea70f20e4c0a270c9f39b77b449fd69dff459a86b055c2cdd0eb24e582c
3
- size 297516
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7868f401a63fda0ea46f17399aaa5bd4aee33b90fdc23f7bcae8281bca6ed74b
3
+ size 347180
samples/04-excited.wav CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:68d7c9a7f6be4d9b6aa18beadcd81df749df19822a674b1f4c9b46993f0ae9ec
3
- size 179244
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:197abfa61adfe964a0e64ffecd6d9d0bf39acbbbe625affff2e4a4df6f3208cc
3
+ size 184364
samples/05-sad.wav CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:5022376d684a7d60c7dab75e69e5b5d5ec6b25462d9dc1582daa5c61131cd9df
3
- size 221740
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ba7a0179faa86cdacd5d3bc1e78c10de221e08b8af93515e8e3dee3e002bd67f
3
+ size 266796
samples/06-angry.wav CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2e17679ecb2e917b6136ce27ee1513087996e4edddbe0e903b6f1c55c9bbce3f
3
- size 177708
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:747b2d808d379a1804f3ea66d304ece2364da9ff74044a240fabb870ae702e6b
3
+ size 148012
samples/07-fearful.wav CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:fbfdbbf494e5a15c4df00a9fa529a04b2395350bac3c55495c824e8236a66cd6
3
- size 175148
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37472fe2dc55c8bc13a28bb8416baa932f18408c4af13db1b6efa69c00e07c3e
3
+ size 192044
samples/08-surprised.wav CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:9983284bdd310adfa33c28834acafa9f0770ecbc41e814061d927119e09ec201
3
- size 270892
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc7a91651810598b1de2103da59bf7c916136196d4aa869e7212217b7b89dd83
3
+ size 272428
samples/09-calm.wav CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:fd9ad6d312af40c999296fb0f5058128e40295b75efe2794d6a4c5cb32c282fa
3
- size 289324
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8b1d6a9880c1ed637fd01c261a0dc0bb709112a63dc10dd8853ec86da402b33
3
+ size 274988
samples/10-whisper.wav CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:446062faf651bcd2c5e797c1b481841fa223184bde0948bf22612bdf9a1974de
3
- size 165420
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c91586691b193ef91d4e03ffa5d7d17efefe3b96b1937280b5c977cc43488b7
3
+ size 190508
samples/11-default.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1181ffe37dd4a9b31ec225e4879f19ca9701f642fc4057c5c2c4ae8e44bf9658
3
+ size 350252