Xeven7 commited on
Commit
bbac2cd
·
verified ·
1 Parent(s): 660303d

Upload folder using huggingface_hub

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Xeven7
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,3 +1,282 @@
1
  ---
2
  license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ language:
4
+ - bn
5
+ - en
6
+ pipeline_tag: text-to-speech
7
+ tags:
8
+ - text-to-speech
9
+ - onnx
10
+ - bengali
11
+ - onnxruntime
12
+ - tiny
13
+ datasets:
14
+ - ai4bharat/Rasa
15
  ---
16
+
17
+ # tiny-swara
18
+
19
+ **tiny-swara** is a tiny, absurdly fast Bengali text-to-speech model with two
20
+ voices, **BF** (female) and **BM** (male).
21
+
22
+ It packs the entire pipeline — phoneme encoder, duration predictor, prosody
23
+ stacks and a source-filter waveform generator — into **4.5M parameters and an
24
+ 8.2 MiB INT8 file**. On just **2 CPU threads** it renders **4.75 seconds of
25
+ speech in 103 ms: 45.9× faster than real time**, with about 4.6 seconds of
26
+ headroom before playback even catches up. No GPU. No cloud. No waiting.
27
+
28
+ Built on the [tiny-voca](https://huggingface.co/n4ze3m/tiny-voca) architecture,
29
+ with a source-filter waveform generator instead of a neural vocoder.
30
+
31
+ <audio controls src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/int8-female.mp3"></audio>
32
+
33
+ | | |
34
+ | ----------------- | ---------------------------------------------- |
35
+ | Parameters | 4,537,483 |
36
+ | Voices | BF, BM (Bengali) |
37
+ | Input | Bengali text, phonemized with espeak-ng (`bn`) |
38
+ | Output | 24 kHz mono |
39
+ | Format | ONNX (opset 17) |
40
+ | Recommended model | `onnx/tiny-swara-int8.onnx` |
41
+ | License | Apache-2.0 |
42
+
43
+ ## Files
44
+
45
+ | File | Size | Contents |
46
+ | --------------------------- | -------: | ---------------------------------------------------- |
47
+ | `onnx/tiny-swara-int8.onnx` | 8.24 MiB | INT8-quantized model, recommended |
48
+ | `onnx/tiny-swara.onnx` | 20.4 MiB | FP32 model, reference |
49
+ | `config.json` | | Model settings, phoneme vocabulary, voices |
50
+ | `inventory.json` | | Phoneme inventory and fallback mappings |
51
+ | `lexicon.json` | | English-to-Bengali word mappings for code-mixed text |
52
+ | `tiny_voca/text.py` | | Bengali-patched frontend: text to phoneme tokens |
53
+ | `tiny_voca/__init__.py` | | Package marker |
54
+ | `inference.py` | | ONNX inference, CLI and Python API |
55
+ | `requirements.txt` | | Python dependencies |
56
+ | `samples/` | | MP3 samples used on this page (64 kbps mono) |
57
+
58
+ SHA256:
59
+
60
+ - `onnx/tiny-swara.onnx`: `cef829cff4b6cb38554e32d8f96b9b51f96a4c0e9cb2e406b53ac79d5923d630`
61
+ - `onnx/tiny-swara-int8.onnx`: `f3080233715cf22ebf519cfc1f81a8ebe4c937c0cdce0285b2cf51998c64eabb`
62
+
63
+ ## Samples
64
+
65
+ The first table uses recordings exported from the notebook. The second table was
66
+ generated with the packaged `inference.py` and the INT8 model, so it also serves
67
+ as an INT8 check. All files here are MP3 at 64 kbps mono to keep the repository
68
+ small; the model itself outputs 24 kHz mono WAV.
69
+
70
+ ### Female (BF) and male (BM)
71
+
72
+ | Text | Female (BF) | Male (BM) |
73
+ | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
74
+ | আমার order কোথায়? | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/bf-1.mp3"></audio> | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/bm-1.mp3"></audio> |
75
+ | গতকাল আমি খুব ব্যস্ত ছিলাম, তাই সন্ধ্যায় তোমাকে ফোন করতে পারিনি। | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/bf-2.mp3"></audio> | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/bm-2.mp3"></audio> |
76
+ | Hello বন্ধুরা, আপনারা কেমন আছেন? | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/bf-3.mp3"></audio> | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/bm-3.mp3"></audio> |
77
+ | বাহ, এই ছোট মডেলটি তো দারুণ! আমি মুগ্ধ। | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/bf-4.mp3"></audio> | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/bm-4.mp3"></audio> |
78
+ | আমি তোমাকে পছন্দ করি। | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/bf-5.mp3"></audio> | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/bm-5.mp3"></audio> |
79
+
80
+ ### INT8 model
81
+
82
+ | Text | Voice | Audio |
83
+ | ----------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------- |
84
+ | আমার সোনার বাংলা, আমি তোমায় ভালোবাসি। | BF | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/int8-female.mp3"></audio> |
85
+ | আজকের তারিখ ২০ নভেম্বর ২০২৬, তাপমাত্রা ৩২ ডিগ্রি সেলসিয়াস। | BM | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/int8-male.mp3"></audio> |
86
+ | Hello, আমি আপনার order টি confirm করেছি। | BF | <audio controls preload="none" src="https://huggingface.co/Xeven7/tiny-swara/resolve/main/samples/int8-code-mixed.mp3"></audio> |
87
+
88
+ ## Usage
89
+
90
+ ### Python script
91
+
92
+ ```bash
93
+ pip install -r requirements.txt
94
+ sudo apt install espeak-ng # or: brew install espeak-ng
95
+
96
+ python inference.py \
97
+ --text "আমি ভালো আছি, আপনার অর্ডার কনফার্ম হয়েছে।" \
98
+ --voice BF \
99
+ --output hello.wav
100
+ ```
101
+
102
+ | Option | Default | Meaning |
103
+ | --------------- | --------------------------- | ----------------------------------------------- |
104
+ | `--text` | | Text to speak |
105
+ | `--text-file` | | Read the text from a file instead of `--text` |
106
+ | `--voice` | `BF` | `BF` (female) or `BM` (male) |
107
+ | `--output` | `tiny-swara.wav` | Output WAV path |
108
+ | `--model` | `onnx/tiny-swara-int8.onnx` | Path to an ONNX file |
109
+ | `--speed` | `1.0` | Speaking rate; larger is faster |
110
+ | `--pitch-shift` | `0.0` | Added to log F0; 0.058 is about one semitone |
111
+ | `--pitch-range` | `1.0` | Scales pitch movement around the utterance mean |
112
+
113
+ Text is read one sentence at a time, so text of any length works. Output is
114
+ peak-normalized to 0.9 before it is written.
115
+
116
+ ### Python API
117
+
118
+ ```python
119
+ from inference import TinySwara
120
+
121
+ tts = TinySwara(voice="BF") # INT8 model by default
122
+ tts.save("আমি ভালো আছি।", "hello.wav")
123
+
124
+ # Sentence-level streaming: each chunk is complete before it is yielded.
125
+ for audio in tts.stream("প্রথম বাক্য। দ্বিতীয় বাক্য।"):
126
+ play(audio) # float32 mono at 24 kHz
127
+ ```
128
+
129
+ `inference.py` sets `TINY_VOCA_INVENTORY`, `TINY_VOCA_LEXICON` and
130
+ `TINY_VOCA_FRONTEND` before importing `tiny_voca.text`, so the patched frontend
131
+ is wired up automatically. The frontend must be the Bengali-patched version
132
+ shipped here; the upstream tiny-voca `text.py` has no Bengali lexicon support.
133
+
134
+ ### ONNX directly
135
+
136
+ The graph takes phoneme ids and stress values; text is converted to ids outside
137
+ the graph by `tiny_voca/text.py`. The ids are the positions in `vocab` in
138
+ `config.json`.
139
+
140
+ ```python
141
+ import numpy as np
142
+ import onnxruntime as ort
143
+
144
+ session = ort.InferenceSession("onnx/tiny-swara-int8.onnx")
145
+ one = lambda value: np.array([value], dtype=np.float32)
146
+
147
+ audio, durations = session.run(None, {
148
+ "tokens": np.array([[1, 62, 23, 64, 6, 2]], dtype=np.int64), # <bos> ami . <eos>
149
+ "stress": np.array([[0, 1, 0, 0, 0, 0]], dtype=np.int64),
150
+ "voice": np.array([0], dtype=np.int64), # 0 = BF, 1 = BM
151
+ "speed": one(1.0),
152
+ "pitch_shift": one(0.0),
153
+ "pitch_range": one(1.0),
154
+ })
155
+ ```
156
+
157
+ | Input | Type | Shape | Meaning |
158
+ | ------------- | ------- | ------ | ------------------------------------------ |
159
+ | `tokens` | int64 | [1, N] | Phoneme ids, including `<bos>` and `<eos>` |
160
+ | `stress` | int64 | [1, N] | 0 none, 1 primary, 2 secondary |
161
+ | `voice` | int64 | [1] | 0 = BF, 1 = BM |
162
+ | `speed` | float32 | [1] | 1.0 as predicted; larger is faster |
163
+ | `pitch_shift` | float32 | [1] | Added to log F0 |
164
+ | `pitch_range` | float32 | [1] | Scales pitch movement |
165
+
166
+ | Output | Type | Shape | Meaning |
167
+ | ----------- | ------- | ------------ | --------------------------------------------- |
168
+ | `audio` | float32 | [1, samples] | Waveform at 24 kHz |
169
+ | `durations` | int64 | [1, N] | Length of each token in frames of 256 samples |
170
+
171
+ The model reads one utterance per call, up to 512 tokens and 32 seconds. Split
172
+ longer text into sentences. The raw graph output can be quiet, so scale it to a
173
+ usable level before saving 16-bit samples:
174
+
175
+ ```python
176
+ audio = audio[0]
177
+ audio *= 0.9 / np.abs(audio).max()
178
+ ```
179
+
180
+ ## Model
181
+
182
+ Text is converted to phonemes with [espeak-ng](https://github.com/espeak-ng/espeak-ng)
183
+ (`-v bn --ipa`) by `tiny_voca/text.py` and mapped onto a Bengali phoneme
184
+ inventory. Phonemes that are not in the inventory are rewritten with the
185
+ fallback rules in `inventory.json`. Known English words in code-mixed text are
186
+ replaced with their Bengali spelling using `lexicon.json`; other Latin words are
187
+ phonemized with the English (`en-us`) voice and mapped back through the same
188
+ fallbacks. The token stream matches training: `<bos>`, `<sp>` between words,
189
+ explicit punctuation tokens, and `<eos>`.
190
+
191
+ A transformer encoder (4 blocks) reads the phonemes and a duration predictor
192
+ gives each one a length in frames. Two frame-level transformer stacks (2 and 5
193
+ blocks) predict pitch, voicing and energy and then the parameters of the
194
+ waveform generator. All blocks use 192 channels, 4 heads and rotary position
195
+ embeddings. The waveform is produced by a source-filter synthesizer instead of a
196
+ neural vocoder: a band-limited pulse train at the predicted pitch and a noise
197
+ signal are each shaped by a time-varying filter predicted once per frame
198
+ (256 samples, 10.7 ms).
199
+
200
+ | | |
201
+ | -------------- | ------------------------------------------------------------- |
202
+ | Vocabulary | 77 tokens (Bengali IPA phonemes, punctuation, special tokens) |
203
+ | Encoder | 4 blocks, 192 channels, 4 heads |
204
+ | Frame stacks | 2 + 5 blocks, 192 channels, 4 heads |
205
+ | Waveform | Source-filter, hop 256 |
206
+ | Training steps | 60,000 |
207
+
208
+ ## Training
209
+
210
+ | | |
211
+ |---|---|
212
+ | Dataset | [ai4bharat/Rasa](https://huggingface.co/datasets/ai4bharat/Rasa), Bengali subset, styles WIKI, CONV, BOOK, NEWS, SANGRAH, INDIC |
213
+ | Hours / clips | 11.5 h, 6,275 train / 112 validation / 61 test clips after filtering |
214
+ | Steps | 60,000 |
215
+ | Hardware | 1 × Tesla T4 on Kaggle, in two sessions (about 10.5 h and 7 h) |
216
+ | Alignment | `facebook/wav2vec2-lv-60-espeak-cv-ft`, relaxed gates (weak-phone fraction 0.5, token probability 0.3); 97% of training clips kept |
217
+
218
+ - Architecture and recipe from tiny-voca: multi-resolution spectral losses for
219
+ the first 8,000 steps, then adversarial (GAN) training with multi-period and
220
+ multi-resolution discriminators.
221
+ - All 60,000 steps ran on one Kaggle Tesla T4 across the two sessions above.
222
+
223
+ ## Evaluation
224
+
225
+ These are internal validation numbers on held-out Rasa clips. No listening test
226
+ with a panel of Bengali speakers has been run yet.
227
+
228
+ | Metric | Value |
229
+ |---|---:|
230
+ | Mel loss, teacher-forced (lower is better) | 0.70 |
231
+ | Mel loss, predicted durations | 0.72 |
232
+ | Pitch error (semitones) | 2.07 |
233
+ | Voicing accuracy | 0.93 |
234
+ | Pause accuracy | 0.90 |
235
+
236
+ ## Performance
237
+
238
+ This is the fun part. Measured with the INT8 model on CPU using 2 ONNX Runtime
239
+ threads:
240
+
241
+ | | |
242
+ |---|---:|
243
+ | Inference (2 threads) | 103 ms |
244
+ | Generated audio | 4.75 s |
245
+ | Real-time factor | 45.9× |
246
+ | Headroom over playback | ~4.6 s |
247
+
248
+ The test sentence is the 66-token line "গতকাল আমি খুব ব্যস্ত ছিলাম, তাই সন্ধ্যায়
249
+ তোমাকে ফোন করতে পারিনি।". The 103 ms covers the ONNX graph only; phonemization
250
+ with espeak-ng adds about 70 ms on a desktop CPU, and writing the WAV is
251
+ negligible. Speed depends on the CPU and thread count.
252
+
253
+ ## Intended use
254
+
255
+ Research and personal projects. Not for impersonating any real person.
256
+
257
+ ## Limitations
258
+
259
+ - Bengali with limited code-mixed English; two fixed voices, no voice cloning.
260
+ - Code-mixed English is handled word by word through a small lexicon (213
261
+ entries) plus fallback rules. Foreign names, unusual spellings and words
262
+ outside the lexicon are often mispronounced.
263
+ - Numbers and abbreviations depend on espeak-ng's Bengali frontend.
264
+ - The same text is always read the same way. There is no sampling of prosody.
265
+ - No frame-level streaming; `inference.py` streams sentence by sentence.
266
+ - The INT8 model is smaller and faster, but its output differs slightly from
267
+ the FP32 reference.
268
+
269
+ ## License
270
+
271
+ The weights and code are released under Apache-2.0. tiny-swara is built on the
272
+ tiny-voca architecture by Muhammed Nazeem; see
273
+ [n4ze3m/tiny-voca](https://huggingface.co/n4ze3m/tiny-voca). The phoneme
274
+ inventory and lexicon were produced for this model. The training recordings
275
+ come from AI4Bharat Rasa; follow its terms when redistributing derived audio.
276
+
277
+ ## Credits
278
+
279
+ - tiny-voca architecture and training code by n4ze3m (Apache-2.0).
280
+ - Bengali recordings from AI4Bharat Rasa.
281
+ - Aligner: `facebook/wav2vec2-lv-60-espeak-cv-ft`.
282
+ - Phonemizer: [espeak-ng](https://github.com/espeak-ng/espeak-ng).
config.json ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": {
3
+ "sample_rate": 24000,
4
+ "hop": 256,
5
+ "speakers": [
6
+ "BF",
7
+ "BM"
8
+ ],
9
+ "vocab_size": 77,
10
+ "channels": 192,
11
+ "heads": 4,
12
+ "feedforward": 640,
13
+ "kernel": 7,
14
+ "encoder_layers": 4,
15
+ "prosody_layers": 2,
16
+ "acoustic_layers": 5,
17
+ "max_tokens": 512,
18
+ "max_frames": 3000
19
+ },
20
+ "step": 60000,
21
+ "sample_rate": 24000,
22
+ "hop": 256,
23
+ "voices": [
24
+ "BF",
25
+ "BM"
26
+ ],
27
+ "frontend": "espeak",
28
+ "frontend_fingerprint": "54cece4f400be1fbb56c30bbeedbcdcf5d432702e6d8c6389f44fbb79dc4c94b",
29
+ "stress": {
30
+ "none": 0,
31
+ "primary": 1,
32
+ "secondary": 2
33
+ },
34
+ "onnx": {
35
+ "file": "onnx/tiny-swara.onnx",
36
+ "inputs": [
37
+ "tokens",
38
+ "stress",
39
+ "voice",
40
+ "speed",
41
+ "pitch_shift",
42
+ "pitch_range"
43
+ ],
44
+ "outputs": [
45
+ "audio",
46
+ "durations"
47
+ ]
48
+ },
49
+ "vocab": {
50
+ "<pad>": 0,
51
+ "<bos>": 1,
52
+ "<eos>": 2,
53
+ "<sp>": 3,
54
+ "<unk>": 4,
55
+ ",": 5,
56
+ ".": 6,
57
+ "?": 7,
58
+ "!": 8,
59
+ ";": 9,
60
+ ":": 10,
61
+ "\"": 11,
62
+ "'": 12,
63
+ "(": 13,
64
+ ")": 14,
65
+ "—": 15,
66
+ "…": 16,
67
+ "ɾ": 17,
68
+ "n": 18,
69
+ "ʃ": 19,
70
+ "k": 20,
71
+ "t": 21,
72
+ "b": 22,
73
+ "m": 23,
74
+ "l": 24,
75
+ "p": 25,
76
+ "d": 26,
77
+ "h": 27,
78
+ "ʈ": 28,
79
+ "ɟ": 29,
80
+ "ɡ": 30,
81
+ "kʰ": 31,
82
+ "j": 32,
83
+ "tʃʰ": 33,
84
+ "tʃ": 34,
85
+ "ŋ": 35,
86
+ "dʒ": 36,
87
+ "bʰ": 37,
88
+ "tʰ": 38,
89
+ "dʰ": 39,
90
+ "r.": 40,
91
+ "ɖ": 41,
92
+ "s": 42,
93
+ "f": 43,
94
+ "r": 44,
95
+ "ʈʰ": 45,
96
+ "ɡʰ": 46,
97
+ "w": 47,
98
+ "ɟʰ": 48,
99
+ "dʰː": 49,
100
+ "ɖʰ": 50,
101
+ "tː": 51,
102
+ "ɟː": 52,
103
+ "dʒː": 53,
104
+ "kʰː": 54,
105
+ "tʰː": 55,
106
+ "ɡː": 56,
107
+ "cʰ": 57,
108
+ "bː": 58,
109
+ "dː": 59,
110
+ "c": 60,
111
+ "ɔ": 61,
112
+ "a": 62,
113
+ "e": 63,
114
+ "i": 64,
115
+ "o": 65,
116
+ "u": 66,
117
+ "æ": 67,
118
+ "oː": 68,
119
+ "ã": 69,
120
+ "aː": 70,
121
+ "õ": 71,
122
+ "ũ": 72,
123
+ "ɔ̃": 73,
124
+ "ə": 74,
125
+ "ɔː": 75,
126
+ "iː": 76
127
+ },
128
+ "speakers": [
129
+ "BF",
130
+ "BM"
131
+ ]
132
+ }
inference.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ tiny-swara ONNX inference.
3
+
4
+ Expected repository layout:
5
+ tiny-swara/
6
+ inference.py
7
+ config.json
8
+ inventory.json
9
+ lexicon.json
10
+ tiny_voca/
11
+ __init__.py
12
+ text.py # patched Bengali tiny-voca frontend
13
+ onnx/
14
+ tiny-swara-int8.onnx
15
+ tiny-swara.onnx # optional FP32 model
16
+
17
+ System dependency: espeak-ng
18
+ Python dependencies: numpy, onnxruntime
19
+
20
+ The frontend module must be the Bengali-patched tiny_voca.text from the
21
+ training/export environment. The ONNX graph itself accepts phoneme IDs,
22
+ not raw text.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import json
29
+ import os
30
+ import re
31
+ import wave
32
+ from pathlib import Path
33
+ from typing import Iterator
34
+
35
+ import numpy as np
36
+ import onnxruntime as ort
37
+
38
+ ROOT = Path(__file__).resolve().parent
39
+
40
+ # Set these BEFORE importing tiny_voca.text because it loads the inventory
41
+ # and lexicon when the module is imported.
42
+ os.environ["TINY_VOCA_INVENTORY"] = str(ROOT / "inventory.json")
43
+ os.environ["TINY_VOCA_LEXICON"] = str(ROOT / "lexicon.json")
44
+ os.environ.setdefault("TINY_VOCA_FRONTEND", "espeak")
45
+
46
+ from tiny_voca import text as frontend # noqa: E402
47
+
48
+
49
+ def load_config() -> dict:
50
+ path = ROOT / "config.json"
51
+ if not path.exists():
52
+ raise FileNotFoundError(f"Missing model config: {path}")
53
+ return json.loads(path.read_text(encoding="utf-8"))
54
+
55
+
56
+ CONFIG = load_config()
57
+ SPEAKERS = CONFIG.get("speakers", ["BF", "BM"])
58
+ SAMPLE_RATE = int(CONFIG.get("sample_rate", 24000))
59
+
60
+
61
+ def resolve_model(model: str | Path | None = None) -> Path:
62
+ if model:
63
+ path = Path(model)
64
+ if not path.is_absolute():
65
+ path = ROOT / path
66
+ if path.is_file():
67
+ return path
68
+ raise FileNotFoundError(f"Model file not found: {path}")
69
+
70
+ candidates = [
71
+ ROOT / "onnx" / "tiny-swara-int8.onnx",
72
+ ROOT / "tiny-swara-int8.onnx",
73
+ ROOT / "onnx" / "tiny-swara.onnx",
74
+ ROOT / "tiny-swara.onnx",
75
+ ROOT / "tiny-bn-int8.onnx",
76
+ ROOT / "tiny-bn.onnx",
77
+ ]
78
+ for path in candidates:
79
+ if path.is_file():
80
+ return path
81
+ raise FileNotFoundError(
82
+ "Could not find an ONNX model. Put tiny-swara-int8.onnx in onnx/ "
83
+ "or pass --model PATH."
84
+ )
85
+
86
+
87
+ def split_sentences(text: str) -> list[str]:
88
+ """Split at sentence endings while retaining punctuation."""
89
+ text = re.sub(r"\s+", " ", text).strip()
90
+ if not text:
91
+ return []
92
+
93
+ parts = re.split(r"(?<=[.!?।…])\s+", text)
94
+ result = []
95
+ for part in parts:
96
+ part = part.strip()
97
+ if not part:
98
+ continue
99
+ if not re.search(r"[.!?।…][\"'’”)\]]*$", part):
100
+ part += "."
101
+ result.append(part)
102
+ return result
103
+
104
+
105
+ class TinySwara:
106
+ def __init__(
107
+ self,
108
+ model: str | Path | None = None,
109
+ voice: str = "BF",
110
+ speed: float = 1.0,
111
+ pitch_shift: float = 0.0,
112
+ pitch_range: float = 1.0,
113
+ providers: list[str] | None = None,
114
+ ):
115
+ if voice not in SPEAKERS:
116
+ raise ValueError(
117
+ f"Unknown voice {voice!r}. Available voices: {', '.join(SPEAKERS)}"
118
+ )
119
+
120
+ self.voice = voice
121
+ self.voice_id = SPEAKERS.index(voice)
122
+ self.speed = float(speed)
123
+ self.pitch_shift = float(pitch_shift)
124
+ self.pitch_range = float(pitch_range)
125
+ self.model_path = resolve_model(model)
126
+
127
+ self.session = ort.InferenceSession(
128
+ str(self.model_path),
129
+ providers=providers or ["CPUExecutionProvider"],
130
+ )
131
+
132
+ required_inputs = {
133
+ "tokens", "stress", "voice", "speed", "pitch_shift", "pitch_range"
134
+ }
135
+ actual_inputs = {item.name for item in self.session.get_inputs()}
136
+ missing = required_inputs - actual_inputs
137
+ if missing:
138
+ raise RuntimeError(
139
+ f"ONNX model is missing expected inputs: {sorted(missing)}. "
140
+ f"Found: {sorted(actual_inputs)}"
141
+ )
142
+
143
+ def synthesize_chunk(self, text: str) -> np.ndarray:
144
+ """Generate one sentence/utterance and return mono float32 audio."""
145
+ phones = frontend.phonemize(text)
146
+
147
+ if phones.unknown:
148
+ raise ValueError(
149
+ f"Unmapped phonemes in {text!r}: {phones.unknown}. "
150
+ "Check inventory.json and lexicon.json."
151
+ )
152
+
153
+ inputs = {
154
+ "tokens": np.asarray([phones.ids], dtype=np.int64),
155
+ "stress": np.asarray([phones.stress], dtype=np.int64),
156
+ "voice": np.asarray([self.voice_id], dtype=np.int64),
157
+ "speed": np.asarray([self.speed], dtype=np.float32),
158
+ "pitch_shift": np.asarray([self.pitch_shift], dtype=np.float32),
159
+ "pitch_range": np.asarray([self.pitch_range], dtype=np.float32),
160
+ }
161
+
162
+ audio, _durations = self.session.run(["audio", "durations"], inputs)
163
+ wave = np.asarray(audio[0], dtype=np.float32).reshape(-1)
164
+
165
+ if wave.size == 0 or not np.isfinite(wave).all():
166
+ raise RuntimeError("ONNX model returned empty or non-finite audio.")
167
+
168
+ peak = float(np.max(np.abs(wave)))
169
+ if peak > 0:
170
+ wave = wave * (0.9 / peak)
171
+
172
+ return wave
173
+
174
+ def stream(self, text: str) -> Iterator[np.ndarray]:
175
+ """
176
+ Yield one generated sentence at a time.
177
+ This is sentence-level streaming: each sentence is generated fully
178
+ before it is yielded; it is not frame-by-frame neural streaming.
179
+ """
180
+ sentences = split_sentences(text)
181
+ if not sentences:
182
+ raise ValueError("Text is empty.")
183
+
184
+ for sentence in sentences:
185
+ yield self.synthesize_chunk(sentence)
186
+
187
+ def synthesize(self, text: str) -> np.ndarray:
188
+ """Generate a complete utterance by joining sentence audio chunks."""
189
+ chunks = list(self.stream(text))
190
+ return np.concatenate(chunks) if len(chunks) > 1 else chunks[0]
191
+
192
+ def save(self, text: str, output_path: str | Path) -> Path:
193
+ output_path = Path(output_path)
194
+ if not output_path.is_absolute():
195
+ output_path = Path.cwd() / output_path
196
+ output_path.parent.mkdir(parents=True, exist_ok=True)
197
+ audio = self.synthesize(text)
198
+ pcm = np.clip(audio * 32767.0, -32768, 32767).astype("<i2")
199
+ with wave.open(str(output_path), "wb") as f:
200
+ f.setnchannels(1)
201
+ f.setsampwidth(2)
202
+ f.setframerate(SAMPLE_RATE)
203
+ f.writeframes(pcm.tobytes())
204
+ return output_path
205
+
206
+
207
+ def main() -> None:
208
+ parser = argparse.ArgumentParser(description="tiny-swara Bengali ONNX TTS")
209
+ parser.add_argument("--text", help="Text to synthesize")
210
+ parser.add_argument("--text-file", help="UTF-8 text file to synthesize")
211
+ parser.add_argument("--output", default="tiny-swara.wav")
212
+ parser.add_argument("--model", help="Optional ONNX model path")
213
+ parser.add_argument("--voice", default="BF", choices=SPEAKERS)
214
+ parser.add_argument("--speed", type=float, default=1.0)
215
+ parser.add_argument("--pitch-shift", type=float, default=0.0)
216
+ parser.add_argument("--pitch-range", type=float, default=1.0)
217
+ args = parser.parse_args()
218
+
219
+ if bool(args.text) == bool(args.text_file):
220
+ parser.error("Provide exactly one of --text or --text-file.")
221
+
222
+ text = (
223
+ Path(args.text_file).read_text(encoding="utf-8")
224
+ if args.text_file
225
+ else args.text
226
+ )
227
+
228
+ tts = TinySwara(
229
+ model=args.model,
230
+ voice=args.voice,
231
+ speed=args.speed,
232
+ pitch_shift=args.pitch_shift,
233
+ pitch_range=args.pitch_range,
234
+ )
235
+ saved = tts.save(text, args.output)
236
+ print(f"Saved: {saved} ({SAMPLE_RATE} Hz, voice={args.voice})")
237
+ print(f"Model: {tts.model_path}")
238
+
239
+
240
+ if __name__ == "__main__":
241
+ main()
inventory.json ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "voice": "bn",
3
+ "consonants": [
4
+ "ɾ",
5
+ "n",
6
+ "ʃ",
7
+ "k",
8
+ "t",
9
+ "b",
10
+ "m",
11
+ "l",
12
+ "p",
13
+ "d",
14
+ "h",
15
+ "ʈ",
16
+ "ɟ",
17
+ "ɡ",
18
+ "kʰ",
19
+ "j",
20
+ "tʃʰ",
21
+ "tʃ",
22
+ "ŋ",
23
+ "dʒ",
24
+ "bʰ",
25
+ "tʰ",
26
+ "dʰ",
27
+ "r.",
28
+ "ɖ",
29
+ "s",
30
+ "f",
31
+ "r",
32
+ "ʈʰ",
33
+ "ɡʰ",
34
+ "w",
35
+ "ɟʰ",
36
+ "dʰː",
37
+ "ɖʰ",
38
+ "tː",
39
+ "ɟː",
40
+ "dʒː",
41
+ "kʰː",
42
+ "tʰː",
43
+ "ɡː",
44
+ "cʰ",
45
+ "bː",
46
+ "dː",
47
+ "c"
48
+ ],
49
+ "vowels": [
50
+ "ɔ",
51
+ "a",
52
+ "e",
53
+ "i",
54
+ "o",
55
+ "u",
56
+ "æ",
57
+ "oː",
58
+ "ã",
59
+ "aː",
60
+ "õ",
61
+ "ũ",
62
+ "ɔ̃",
63
+ "ə",
64
+ "ɔː",
65
+ "iː"
66
+ ],
67
+ "voiceless": [
68
+ "ʃ",
69
+ "k",
70
+ "t",
71
+ "p",
72
+ "h",
73
+ "ʈ",
74
+ "kʰ",
75
+ "tʃʰ",
76
+ "tʃ",
77
+ "tʰ",
78
+ "s",
79
+ "f",
80
+ "ʈʰ",
81
+ "tː",
82
+ "kʰː",
83
+ "tʰː",
84
+ "cʰ",
85
+ "c"
86
+ ],
87
+ "fallback": {
88
+ "ʈʈ": [
89
+ "ʈ"
90
+ ],
91
+ "kː": [
92
+ "k"
93
+ ],
94
+ "ĩ": [
95
+ "i"
96
+ ],
97
+ "ẽ": [
98
+ "e"
99
+ ],
100
+ "pː": [
101
+ "p"
102
+ ],
103
+ "ɡʰː": [
104
+ "ɡː"
105
+ ],
106
+ "p̃": [
107
+ "p"
108
+ ],
109
+ "l̩": [
110
+ "l"
111
+ ],
112
+ "ʈʰʈʰ": [
113
+ "ʈ"
114
+ ],
115
+ "ɖɖ": [
116
+ "ɖ"
117
+ ],
118
+ "æ": [
119
+ "a"
120
+ ],
121
+ "ɑ": [
122
+ "a"
123
+ ],
124
+ "ɛ": [
125
+ "e"
126
+ ],
127
+ "ɪ": [
128
+ "i"
129
+ ],
130
+ "ᵻ": [
131
+ "i"
132
+ ],
133
+ "ʊ": [
134
+ "u"
135
+ ],
136
+ "ʌ": [
137
+ "ɔ"
138
+ ],
139
+ "ə": [
140
+ "ɔ"
141
+ ],
142
+ "ɐ": [
143
+ "ɔ"
144
+ ],
145
+ "ɜ": [
146
+ "ɔ"
147
+ ],
148
+ "ɚ": [
149
+ "ɔ",
150
+ "ɾ"
151
+ ],
152
+ "ɝ": [
153
+ "ɔ",
154
+ "ɾ"
155
+ ],
156
+ "ɔː": [
157
+ "ɔ"
158
+ ],
159
+ "ɔːɹ": [
160
+ "ɔ",
161
+ "ɾ"
162
+ ],
163
+ "ɹ": [
164
+ "ɾ"
165
+ ],
166
+ "θ": [
167
+ "tʰ"
168
+ ],
169
+ "ð": [
170
+ "d"
171
+ ],
172
+ "v": [
173
+ "b"
174
+ ],
175
+ "f": [
176
+ "p"
177
+ ],
178
+ "z": [
179
+ "dʒ"
180
+ ],
181
+ "ʒ": [
182
+ "ʃ"
183
+ ],
184
+ "w": [
185
+ "o"
186
+ ],
187
+ "aɪ": [
188
+ "a",
189
+ "i"
190
+ ],
191
+ "aʊ": [
192
+ "a",
193
+ "u"
194
+ ],
195
+ "eɪ": [
196
+ "e",
197
+ "i"
198
+ ],
199
+ "oʊ": [
200
+ "o",
201
+ "u"
202
+ ],
203
+ "ɔɪ": [
204
+ "ɔ",
205
+ "i"
206
+ ]
207
+ },
208
+ "aligner_labels": {
209
+ "tʰː": "tː"
210
+ }
211
+ }
lexicon.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"order": "অর্ডার", "orders": "অর্ডারস", "refund": "রিফান্ড", "refunded": "রিফান্ডেড", "status": "স্ট্যাটাস", "delivery": "ডেলিভারি", "account": "অ্যাকাউন্ট", "phone": "ফোন", "mobile": "মোবাইল", "number": "নাম্বার", "password": "পাসওয়ার্ড", "login": "লগইন", "email": "ইমেইল", "payment": "পেমেন্ট", "cancel": "ক্যানসেল", "cancelled": "ক্যানসেলড", "confirm": "কনফার্ম", "booking": "বুকিং", "ticket": "টিকিট", "call": "কল", "message": "মেসেজ", "app": "অ্যাপ", "website": "ওয়েবসাইট", "online": "অনলাইন", "update": "আপডেট", "download": "ডাউনলোড", "internet": "ইন্টারনেট", "okay": "ওকে", "ok": "ওকে", "sorry": "সরি", "thanks": "থ্যাঙ্কস", "hello": "হ্যালো", "help": "হেল্প", "support": "সাপোর্ট", "service": "সার্ভিস", "customer": "কাস্টমার", "address": "অ্যাড্রেস", "card": "কার্ড", "bank": "ব্যাংক", "balance": "ব্যালেন্স", "recharge": "রিচার্জ", "data": "ডাটা", "offer": "অফার", "discount": "ডিসকাউন্ট", "id": "আইডি", "otp": "ও টি পি", "version": "ভার্সন", "tracking": "ট্র্যাকিং", "track": "ট্র্যাক", "orderid": "অর্ডার আইডি", "search": "সার্চ", "find": "ফাইন্ড", "check": "চেক", "show": "শো", "open": "ওপেন", "close": "ক্লোজ", "start": "স্টার্ট", "stop": "স্টপ", "pause": "পজ", "resume": "রিজিউম", "skip": "স্কিপ", "next": "নেক্সট", "previous": "প্রিভিয়াস", "back": "ব্যাক", "save": "সেভ", "delete": "ডিলিট", "remove": "রিমুভ", "edit": "এডিট", "change": "চেঞ্জ", "reset": "রিসেট", "retry": "রিট্রাই", "send": "সেন্ড", "share": "শেয়ার", "copy": "কপি", "paste": "পেস্ট", "upload": "আপলোড", "select": "সিলেক্ট", "submit": "সাবমিট", "apply": "অ্যাপ্লাই", "enable": "এনেবল", "disable": "ডিসেবল", "turn": "টার্ন", "switch": "সুইচ", "time": "টাইম", "date": "ডেট", "today": "টুডে", "tomorrow": "টুমরো", "yesterday": "ইয়েস্টারডে", "week": "উইক", "month": "মান্থ", "year": "ইয়ার", "morning": "মর্নিং", "evening": "ইভিনিং", "night": "নাইট", "minute": "মিনিট", "minutes": "মিনিটস", "hour": "আওয়ার", "hours": "আওয়ারস", "alarm": "অ্যালার্ম", "reminder": "রিমাইন্ডার", "schedule": "শিডিউল", "meeting": "মিটিং", "appointment": "অ্যাপয়েন্টমেন্ট", "deadline": "ডেডলাইন", "late": "লেট", "early": "আর্লি", "screen": "স্ক্রিন", "battery": "ব্যাটারি", "charge": "চার্জ", "charger": "চার্জার", "wifi": "ওয়াইফাই", "network": "নেটওয়ার্ক", "signal": "সিগন্যাল", "bluetooth": "ব্লুটুথ", "volume": "ভলিউম", "sound": "সাউন্ড", "mute": "মিউট", "notification": "নোটিফিকেশন", "notifications": "নোটিফিকেশনস", "setting": "সেটিং", "settings": "সেটিংস", "link": "লিংক", "url": "ইউ আর এল", "file": "ফাইল", "files": "ফাইলস", "folder": "ফোল্ডার", "photo": "ফটো", "photos": "ফটোজ", "video": "ভিডিও", "audio": "অডিও", "music": "মিউজিক", "camera": "ক্যামেরা", "mic": "মাইক", "speaker": "স্পিকার", "browser": "ব্রাউজার", "tab": "ট্যাব", "page": "পেজ", "login_id": "লগইন আইডি", "username": "ইউজারনেম", "profile": "প্রোফাইল", "logout": "লগআউট", "signup": "সাইনআপ", "pin": "পিন", "code": "কোড", "qr": "কিউ আর", "scan": "স্ক্যান", "price": "প্রাইস", "cost": "কস্ট", "amount": "অ্যামাউন্ট", "total": "টোটাল", "bill": "বিল", "invoice": "ইনভয়েস", "receipt": "রিসিট", "upi": "ইউ পি আই", "wallet": "ওয়ালেট", "cash": "ক্যাশ", "pay": "পে", "paid": "পেইড", "due": "ডিউ", "pending": "পেন্ডিং", "completed": "কমপ্লিটেড", "failed": "ফেইল্ড", "success": "সাকসেস", "error": "এরর", "issue": "ইস্যু", "problem": "প্রবলেম", "fix": "ফিক্স", "solution": "সলিউশন", "plan": "প্ল্যান", "limit": "লিমিট", "location": "লোকেশন", "map": "ম্যাপ", "route": "রুট", "weather": "ওয়েদার", "temperature": "টেম্পারেচার", "news": "নিউজ", "notes": "নোটস", "note": "নোট", "list": "লিস্ট", "item": "আইটেম", "items": "আইটেমস", "cart": "কার্ট", "checkout": "চেকআউট", "coupon": "কুপন", "voucher": "ভাউচার", "return": "রিটার্ন", "exchange": "এক্সচেঞ্জ", "warranty": "ওয়ারেন্টি", "complaint": "কমপ্লেইন্ট", "please": "প্লিজ", "welcome": "ওয়েলকাম", "bye": "বাই", "goodbye": "গুডবাই", "good": "গুড", "nice": "নাইস", "great": "গ্রেট", "fine": "ফাইন", "sure": "শিওর", "yes": "ইয়েস", "no": "নো", "maybe": "মেবি", "wait": "ওয়েট", "hold": "হোল্ড", "done": "ডান", "ready": "রেডি", "clear": "ক্লিয়ার", "exact": "এক্স্যাক্ট", "extra": "এক্সট্রা", "free": "ফ্রি", "fast": "ফাস্ট", "slow": "স্লো", "important": "ইম্পর্ট্যান্ট", "urgent": "আর্জেন্ট"}
onnx/tiny-swara-int8.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3080233715cf22ebf519cfc1f81a8ebe4c937c0cdce0285b2cf51998c64eabb
3
+ size 8643037
tiny-bn.onnx → onnx/tiny-swara.onnx RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:67e54b22ec15e3c8367dc30fd7970aba77b132e79eb10ceaecf97dc6bf813e22
3
  size 21387142
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cef829cff4b6cb38554e32d8f96b9b51f96a4c0e9cb2e406b53ac79d5923d630
3
  size 21387142
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ numpy>=1.24
2
+ onnxruntime>=1.16
samples/bf-1.mp3 ADDED
Binary file (11 kB). View file
 
samples/bf-2.mp3 ADDED
Binary file (38.3 kB). View file
 
samples/bf-3.mp3 ADDED
Binary file (21.5 kB). View file
 
samples/bf-4.mp3 ADDED
Binary file (28.5 kB). View file
 
samples/bf-5.mp3 ADDED
Binary file (14.6 kB). View file
 
samples/bm-1.mp3 ADDED
Binary file (10.2 kB). View file
 
samples/bm-2.mp3 ADDED
Binary file (34.2 kB). View file
 
samples/bm-3.mp3 ADDED
Binary file (17.7 kB). View file
 
samples/bm-4.mp3 ADDED
Binary file (25.6 kB). View file
 
samples/bm-5.mp3 ADDED
Binary file (13.1 kB). View file
 
samples/int8-code-mixed.mp3 ADDED
Binary file (27.5 kB). View file
 
samples/int8-female.mp3 ADDED
Binary file (26.9 kB). View file
 
samples/int8-male.mp3 ADDED
Binary file (45 kB). View file
 
tiny_voca/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """Bengali front end for tiny-swara (patched from tiny-voca).
2
+
3
+ Only :mod:`tiny_voca.text` is needed for ONNX inference.
4
+ """
tiny_voca/text.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """English front end: text -> phoneme tokens with a stress feature.
2
+
3
+ The same code runs during annotation, training-set preparation and inference,
4
+ so tokens can never drift between them. Two programs can produce the phonemes:
5
+
6
+ * ``espeak`` (front-end version 3, the default): eSpeak NG, as described below.
7
+ The current checkpoints and annotations were made with it.
8
+ * ``own`` (front-end version 4): the separate ``dizione`` package, a dictionary
9
+ built from CMUdict, a small model for unknown words and rules. No eSpeak, so
10
+ the whole system can be shipped under a permissive licence. Same 76 symbols.
11
+
12
+ Choose with ``set_frontend("own")`` or ``TINY_VOCA_FRONTEND=own``. Everything
13
+ below about tokens holds for both; the rest of this note is the eSpeak path.
14
+
15
+ * eSpeak NG (``en-us``) is the only pronunciation source. It is an external
16
+ rule-based program: no neural G2P and no downloaded weights.
17
+ * A token is one eSpeak phoneme exactly as eSpeak segments it (``--sep``), for
18
+ example ``t``, ``aɪ``, ``ɑːɹ`` or ``n̩``. This is also the label inventory of
19
+ the phoneme recogniser used for offline forced alignment, so one aligned
20
+ label corresponds to exactly one token.
21
+ * Lexical stress is a parallel feature (0 none, 1 primary, 2 secondary), not a
22
+ token, so it never has to be given audio frames.
23
+ * Punctuation, word boundaries and the utterance edges are explicit tokens that
24
+ may last zero frames. They carry pauses when the recording has them.
25
+
26
+ Versions 1 and 2 encoded IPA as UTF-8 bytes and piped text to eSpeak without a
27
+ final newline; eSpeak NG 1.51 then drops the last character of the input, so
28
+ the final phonemes of every clause were wrong. Version 3 terminates the input
29
+ and has a regression test for it.
30
+ """
31
+
32
+ from dataclasses import dataclass
33
+ import hashlib
34
+ import json
35
+ import os
36
+ import re
37
+ import shutil
38
+ import subprocess
39
+ import unicodedata
40
+
41
+ FRONTEND_VERSION = 3
42
+ ESPEAK_VOICE = "en-us"
43
+ SEPARATOR = "_"
44
+ FRONTENDS = ("espeak", "own")
45
+ FRONTEND_VARIABLE = "TINY_VOCA_FRONTEND"
46
+ _frontend = os.environ.get(FRONTEND_VARIABLE, "espeak")
47
+ if _frontend not in FRONTENDS:
48
+ raise ValueError(f"{FRONTEND_VARIABLE} must be one of {FRONTENDS}, not {_frontend!r}")
49
+
50
+ PAD, BOS, EOS, SP, UNK = "<pad>", "<bos>", "<eos>", "<sp>", "<unk>"
51
+ SPECIALS = (PAD, BOS, EOS, SP, UNK)
52
+ PUNCTUATION = (",", ".", "?", "!", ";", ":", '"', "'", "(", ")", "—", "…")
53
+ CONSONANTS = ("p", "b", "t", "d", "k", "ɡ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h",
54
+ "m", "n", "ŋ", "l", "ɹ", "j", "w", "tʃ", "dʒ", "ɾ", "ʔ")
55
+ VOWELS = ("ə", "ɐ", "ɚ", "ᵻ", "ɪ", "i", "iː", "ɛ", "æ", "ʌ", "ɑː", "ɔ", "ɔː", "ʊ", "uː", "ɜː",
56
+ "eɪ", "aɪ", "ɔɪ", "oʊ", "aʊ", "iə", "oː",
57
+ "ɑːɹ", "ɔːɹ", "oːɹ", "ɪɹ", "ɛɹ", "ʊɹ", "aɪɚ", "aɪə", "əl", "n̩")
58
+ PHONES = CONSONANTS + VOWELS
59
+ # Append-only: changing the order or removing a symbol invalidates checkpoints.
60
+ SYMBOLS = SPECIALS + PUNCTUATION + PHONES
61
+ SYMBOL_TO_ID = {symbol: index for index, symbol in enumerate(SYMBOLS)}
62
+ PHONE_SET = frozenset(PHONES)
63
+ PHONE_IDS = frozenset(SYMBOL_TO_ID[p] for p in PHONES) | {SYMBOL_TO_ID[UNK]}
64
+ VOICELESS = frozenset(("p", "t", "k", "f", "θ", "s", "ʃ", "h", "tʃ", "ʔ"))
65
+ VOWEL_SET = frozenset(VOWELS)
66
+ STRESS_MARKS = {"ˈ": 1, "ˌ": 2}
67
+
68
+ # eSpeak phonemes outside the inventory (foreign words, rare allophones) map to
69
+ # the closest inventory phone(s). Anything else becomes <unk> and is reported.
70
+ FALLBACK = {
71
+ "r": ("ɹ",), "ɻ": ("ɹ",), "ʁ": ("ɹ",), "x": ("k",), "ç": ("h",), "ɬ": ("l",), "ɫ": ("l",), "ɲ": ("n", "j"),
72
+ "ts": ("t", "s"), "dz": ("d", "z"), "β": ("v",), "ɣ": ("ɡ",), "ʎ": ("l", "j"),
73
+ "a": ("æ",), "aː": ("ɑː",), "ɑ": ("ɑː",), "ɒ": ("ɑː",), "ɑ̃": ("ɑː",), "ɔ̃": ("ɔː",), "ɛ̃": ("æ",),
74
+ "e": ("eɪ",), "eː": ("eɪ",), "o": ("oʊ",), "u": ("uː",), "y": ("uː",), "yː": ("uː",),
75
+ "ø": ("ɜː",), "øː": ("ɜː",), "œ": ("ɜː",), "ɜ": ("ɜː",), "ɛː": ("ɛ",), "ɪː": ("ɪ",),
76
+ "əʊ": ("oʊ",), "eə": ("ɛɹ",), "ɪə": ("iə",), "ʊə": ("ʊɹ",), "aʊɚ": ("aʊ", "ɚ"), "l̩": ("əl",), "m̩": ("ə", "m"),
77
+ }
78
+
79
+ # --- bengali-patch ---
80
+ INVENTORY_VARIABLE = "TINY_VOCA_INVENTORY"
81
+ ALIGNER_LABELS = {} # inventory phone -> label of the aligner recogniser (when they differ)
82
+ if os.environ.get(INVENTORY_VARIABLE):
83
+ _inv = json.load(open(os.environ[INVENTORY_VARIABLE], encoding="utf-8"))
84
+ ESPEAK_VOICE = _inv["voice"]
85
+ CONSONANTS = tuple(_inv["consonants"])
86
+ VOWELS = tuple(_inv["vowels"])
87
+ VOICELESS = frozenset(_inv["voiceless"])
88
+ FALLBACK = {k: tuple(v) for k, v in _inv["fallback"].items()}
89
+ ALIGNER_LABELS = dict(_inv.get("aligner_labels", {}))
90
+ PHONES = CONSONANTS + VOWELS
91
+ SYMBOLS = SPECIALS + PUNCTUATION + PHONES
92
+ SYMBOL_TO_ID = {symbol: index for index, symbol in enumerate(SYMBOLS)}
93
+ PHONE_SET = frozenset(PHONES)
94
+ PHONE_IDS = frozenset(SYMBOL_TO_ID[p] for p in PHONES) | {SYMBOL_TO_ID[UNK]}
95
+ VOWEL_SET = frozenset(VOWELS)
96
+
97
+ _QUOTES = str.maketrans({"‘": "'", "’": "'", "‚": "'", "‛": "'", "`": "'", "´": "'",
98
+ "“": '"', "”": '"', "„": '"', "‟": '"', "«": '"', "»": '"',
99
+ "–": "—", "―": "—", "।": ".", "॥": ".", "[": "(", "{": "(", "]": ")", "}": ")"})
100
+ _PUNCTUATION_CHARS = frozenset(PUNCTUATION)
101
+ ABBREVIATIONS = {"mr", "mrs", "ms", "dr", "prof", "st", "jr", "sr", "vs", "etc"}
102
+ _LANGUAGE_TAG = re.compile(r"\((?:_?[a-z0-9]_?){2,3}(?:-(?:_?[a-z0-9]_?)+)*\)")
103
+
104
+
105
+ class NothingToPronounce(ValueError):
106
+ """The text has no word, number or letter to say: only marks, emoji and the like."""
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class Phonemized:
111
+ symbols: tuple
112
+ ids: tuple
113
+ stress: tuple
114
+ unknown: tuple # eSpeak phonemes that had no inventory mapping
115
+
116
+ def __len__(self):
117
+ return len(self.ids)
118
+
119
+
120
+ def frontend():
121
+ """Name of the program that produces the phonemes: ``"espeak"`` or ``"own"``."""
122
+ return _frontend
123
+
124
+
125
+ def set_frontend(name):
126
+ """Select the phonemizer for this process. Tokens of the two front ends
127
+ must not be mixed: annotations and checkpoints record which one made them."""
128
+ global _frontend
129
+ if name not in FRONTENDS:
130
+ raise ValueError(f"front end must be one of {FRONTENDS}, not {name!r}")
131
+ _frontend = name
132
+
133
+
134
+ def _dizione():
135
+ try:
136
+ import dizione
137
+ except ImportError as error:
138
+ raise RuntimeError('the "own" front end needs the dizione package: pip install dizione') from error
139
+ if tuple(dizione.symbols.SYMBOLS) != SYMBOLS:
140
+ raise RuntimeError("dizione's symbol inventory differs from this model's")
141
+ return dizione
142
+
143
+
144
+ def frontend_identity():
145
+ if _frontend == "own":
146
+ phonemizer = _dizione()
147
+ return {"frontend_version": phonemizer.VERSION, "phonemizer": "dizione", "symbols": list(SYMBOLS)}
148
+ return {"frontend_version": FRONTEND_VERSION, "voice": ESPEAK_VOICE, "separator": SEPARATOR,
149
+ "symbols": list(SYMBOLS), "fallback": {key: list(value) for key, value in sorted(FALLBACK.items())}}
150
+
151
+
152
+ def frontend_runtime():
153
+ """What an annotation run records about the exact program behind its
154
+ tokens: the eSpeak version, or the fingerprint of the phonemizer build."""
155
+ if _frontend == "own":
156
+ return {"phonemizer": _dizione().identity()["fingerprint"]}
157
+ return {"espeak_version": espeak_version()}
158
+
159
+
160
+ def frontend_fingerprint():
161
+ return hashlib.sha256(json.dumps(frontend_identity(), sort_keys=True, ensure_ascii=False).encode()).hexdigest()
162
+
163
+
164
+ def normalize_text(text):
165
+ text = unicodedata.normalize("NFKC", text).translate(_QUOTES)
166
+ text = re.sub(r"\.{3,}", "…", text)
167
+ text = re.sub(r"-{2,}|\s-\s", "—", text)
168
+ return re.sub(r"\s+", " ", text).strip()
169
+
170
+
171
+ def chunks(text):
172
+ """Yield ``(is_punctuation, piece)``. Decimals, clock times, digit groups,
173
+ contractions, title abbreviations and initialisms stay inside the text piece
174
+ for eSpeak; every other punctuation mark becomes its own token."""
175
+ start = 0
176
+ for i, char in enumerate(text):
177
+ if char not in _PUNCTUATION_CHARS:
178
+ continue
179
+ previous = text[i-1] if i else ""
180
+ following = text[i+1] if i+1 < len(text) else ""
181
+ if char == "'" and previous.isalnum() and following.isalnum():
182
+ continue
183
+ if char in ".,:" and previous.isdigit() and following.isdigit():
184
+ continue
185
+ if char == ".":
186
+ word = re.search(r"([A-Za-z]+)$", text[:i])
187
+ if word and word[1].lower() in ABBREVIATIONS:
188
+ continue
189
+ if previous.isalpha() and following.isalpha():
190
+ continue
191
+ if text[start:i].strip():
192
+ yield False, text[start:i].strip()
193
+ yield True, char
194
+ start = i+1
195
+ if text[start:].strip():
196
+ yield False, text[start:].strip()
197
+
198
+
199
+ def espeak_executable():
200
+ executable = shutil.which("espeak-ng")
201
+ if executable is None:
202
+ raise RuntimeError("Install espeak-ng on the cloud machine before preprocessing/inference")
203
+ return executable
204
+
205
+
206
+ def espeak_version():
207
+ return subprocess.run([espeak_executable(), "--version"], capture_output=True, text=True, check=True, timeout=10).stdout.strip()
208
+
209
+
210
+ def espeak_words(piece, voice=None):
211
+ """Phonemize one text piece. Returns words as lists of ``(phone, stress)``.
212
+
213
+ The input must end with a newline: eSpeak NG 1.51 silently drops the last
214
+ character of unterminated standard input.
215
+ """
216
+ result = subprocess.run(
217
+ [espeak_executable(), "-q", "--ipa", "--sep=" + SEPARATOR, "-v", voice or ESPEAK_VOICE, "--stdin"],
218
+ input=piece.rstrip("\n") + "\n", text=True, capture_output=True, check=True, timeout=30)
219
+ return parse_espeak(result.stdout)
220
+
221
+
222
+
223
+
224
+
225
+
226
+
227
+
228
+
229
+ def parse_espeak(output):
230
+ words = []
231
+ for word in _LANGUAGE_TAG.sub("", output).split():
232
+ units = []
233
+ for unit in word.split(SEPARATOR):
234
+ stress = 0
235
+ for mark, level in STRESS_MARKS.items():
236
+ if mark in unit:
237
+ stress = stress or level
238
+ unit = unit.replace(mark, "")
239
+ unit = "".join(c for c in unit if unicodedata.category(c) != "Cf" and c not in "()")
240
+ if unit:
241
+ units.append((unit, stress))
242
+ if units:
243
+ words.append(units)
244
+ return words
245
+
246
+
247
+ def canonical(phone):
248
+ """Map an eSpeak phoneme to inventory phones; ``None`` when unknown."""
249
+ if phone in PHONE_SET:
250
+ return (phone,)
251
+ if phone in FALLBACK:
252
+ return FALLBACK[phone]
253
+ stripped = "".join(c for c in unicodedata.normalize("NFD", phone) if not unicodedata.combining(c))
254
+ for candidate in (stripped, stripped.replace("ː", ""), stripped + "ː"):
255
+ if candidate != phone and candidate in PHONE_SET:
256
+ return (candidate,)
257
+ if candidate != phone and candidate in FALLBACK:
258
+ return FALLBACK[candidate]
259
+ return None
260
+
261
+
262
+ def tokenize(pieces):
263
+ """Build the token sequence from ``(is_punctuation, value)`` pieces where a
264
+ text piece's value is the parsed eSpeak word list. Pure function (testable
265
+ without eSpeak)."""
266
+ symbols, stress, unknown = [BOS], [0], []
267
+ for punctuation, value in pieces:
268
+ if punctuation:
269
+ if symbols[-1] != value: # collapse repeats such as "!!"
270
+ symbols.append(value)
271
+ stress.append(0)
272
+ continue
273
+ for word in value:
274
+ if symbols[-1] in PHONE_SET or symbols[-1] == UNK:
275
+ symbols.append(SP)
276
+ stress.append(0)
277
+ for phone, level in word:
278
+ mapped = canonical(phone)
279
+ if mapped is None:
280
+ unknown.append(phone)
281
+ mapped = (UNK,)
282
+ # A fallback may expand to several phones: stress goes to its first vowel.
283
+ carrier = next((i for i, item in enumerate(mapped) if item in VOWEL_SET), 0)
284
+ for index, item in enumerate(mapped):
285
+ symbols.append(item)
286
+ stress.append(level if index == carrier else 0)
287
+ symbols.append(EOS)
288
+ stress.append(0)
289
+ if not any(s in PHONE_SET or s == UNK for s in symbols):
290
+ raise NothingToPronounce("the text has nothing to pronounce")
291
+ return Phonemized(tuple(symbols), tuple(SYMBOL_TO_ID[s] for s in symbols), tuple(stress), tuple(unknown))
292
+
293
+
294
+ LATIN_RUN = re.compile(r"[A-Za-z][A-Za-z']*")
295
+
296
+ def load_lexicon():
297
+ path = os.environ.get("TINY_VOCA_LEXICON")
298
+ if not path:
299
+ return {}
300
+ with open(path, encoding="utf-8") as f:
301
+ data = json.load(f)
302
+ return {str(k).lower(): str(v) for k, v in data.items()}
303
+
304
+ LEXICON = load_lexicon()
305
+
306
+
307
+ def espeak_mixed(piece):
308
+ 'Phonemize Bengali text and route known Latin words through the Bengali lexicon.'
309
+ words = []
310
+ position = 0
311
+
312
+ for match in LATIN_RUN.finditer(piece):
313
+ prefix = piece[position:match.start()]
314
+ if prefix.strip():
315
+ words += espeak_words(prefix)
316
+
317
+ latin_word = match.group()
318
+ bengali_spelling = LEXICON.get(latin_word.casefold())
319
+ if bengali_spelling:
320
+ words += espeak_words(bengali_spelling, voice="bn")
321
+ else:
322
+ words += espeak_words(latin_word, voice="en-us")
323
+
324
+ position = match.end()
325
+
326
+ suffix = piece[position:]
327
+ if suffix.strip():
328
+ words += espeak_words(suffix)
329
+
330
+ return words
331
+
332
+
333
+
334
+
335
+
336
+
337
+
338
+
339
+ def phonemize(text):
340
+ if not isinstance(text, str) or not text.strip():
341
+ raise ValueError("text must not be empty")
342
+ if _frontend == "own":
343
+ return tokenize(_dizione().pieces(text))
344
+ pieces = []
345
+ for punctuation, piece in chunks(normalize_text(text)):
346
+ pieces.append((True, piece) if punctuation else (False, espeak_mixed(piece)))
347
+ return tokenize(pieces)
348
+
349
+
350
+ def is_phone(token_ids):
351
+ """Boolean list/tensor helper: tokens that must be realised as audio."""
352
+ return [int(i) in PHONE_IDS for i in token_ids]