tiny-voca-persian: two-voice model, code, samples, card
Browse filesFiles changed (20)
- .gitattributes+8
- LICENSEAdded+202
- README.mdAdded+76
- code/tiny_voca/__init__.pyAdded+10
- code/tiny_voca/config.pyAdded+118
- code/tiny_voca/fa_normalize.pyAdded+76
- code/tiny_voca/infer.pyAdded+219
- code/tiny_voca/model.pyAdded+447
- code/tiny_voca/text.pyAdded+260
- config.jsonAdded+38
- samples/fa_female_1.wavAdded+3
- samples/fa_female_2.wavAdded+3
- samples/fa_female_3.wavAdded+3
- samples/fa_female_4.wavAdded+3
- samples/fa_male_1.wavAdded+3
- samples/fa_male_2.wavAdded+3
- samples/fa_male_3.wavAdded+3
- samples/fa_male_4.wavAdded+3
- samples/texts.txtAdded+4
- tiny-voca-persian.ptAdded+3
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363738394041424332 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textsamples/fa_female_1.wav filter=lfs diff=lfs merge=lfs -textsamples/fa_female_2.wav filter=lfs diff=lfs merge=lfs -textsamples/fa_female_3.wav filter=lfs diff=lfs merge=lfs -textsamples/fa_female_4.wav filter=lfs diff=lfs merge=lfs -textsamples/fa_male_1.wav filter=lfs diff=lfs merge=lfs -textsamples/fa_male_2.wav filter=lfs diff=lfs merge=lfs -textsamples/fa_male_3.wav filter=lfs diff=lfs merge=lfs -textsamples/fa_male_4.wav filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576---license: apache-2.0language: - fapipeline_tag: text-to-speechlibrary_name: pytorchdatasets: - oddadmix/tiny-voca-persian-datasettags: - persian - farsi - tts - tiny-voca - multi-speaker---
# tiny-voca-persian
A Persian (Farsi) text-to-speech model with two voices, **male** (`fa_male`) and **female** (`fa_female`). It has 4.53Mparameters and was trained from scratch, with no pretrained weights, on[oddadmix/tiny-voca-persian-dataset](https://huggingface.co/datasets/oddadmix/tiny-voca-persian-dataset) (145 h after alignment checks, synthetic speech).It is built on the architecture and training code of [tiny-voca](https://huggingface.co/n4ze3m/tiny-voca) by Muhammed Nazeem (Apache-2.0).Demo: [oddadmix/tiny-voca-persian](https://huggingface.co/spaces/oddadmix/tiny-voca-persian).
Input is ordinary Persian text. The front end writes numbers out in words, normalizes letter forms and half-spaces, gets thepronunciation (including ezafe) from [mehdi-hf/persian-g2p-tiny](https://huggingface.co/mehdi-hf/persian-g2p-tiny) (MIT), andadds word stress by rule. The model then produces 24 kHz audio. The speech model runs about 90× faster than real time on one CPU thread;the G2P adds roughly 0.15–0.2 s for each new sentence on CPU.
## Evaluation
Speech from the model was transcribed with Whisper large-v3 and compared with the text. The held-out texts were never seen in training."Recordings" means the training-voice audio of the same texts, transcribed the same way.
| | voice | word error | char error | word error, recordings | char error, recordings | duration vs recordings ||---|---|---|---|---|---|---|| test (50 per voice) | male | 11.4% | 2.7% | 16.2% | 4.0% | 1.01 || test (50 per voice) | female | 12.5% | 2.6% | 18.4% | 4.2% | 1.00 || validation (50 per voice) | male | 14.6% | 2.9% | 19.5% | 4.5% | 1.00 || validation (50 per voice) | female | 13.3% | 2.8% | 18.0% | 4.2% | 1.00 |
Whisper's Persian spelling (half-spaces, joined words) differs from the reference text in many places, so word error is higheven on the recordings; character error is the more telling number.
## Files
- `tiny-voca-persian.pt`: the checkpoint (weights, config, front-end fingerprint, duration calibration phone +0.05 / pause −0.06).- `code/tiny_voca/`: inference code and the Persian front end (`text.py`, `fa_normalize.py`).- `samples/`: the same texts in both voices (`texts.txt`).
## Use
```bashpip install torch transformers soundfile huggingface_hub```
```pythonimport os, sys, soundfile as sfos.environ["TV_FA_G2P_REVISION"] = "3f6994c82e52628fe948102a7009d281fc9aa99d" # the G2P revision used in trainingsys.path.insert(0, "code")from tiny_voca.infer import load_model, speak_text
model = load_model("tiny-voca-persian.pt")wave, spoken = speak_text(model, "سلام، وقت بخیر. سفارش شما با موفقیت ثبت شد.", "fa_female") # or "fa_male"sf.write("out.wav", wave.numpy(), 24000)```
`speak_text` reads text of any length sentence by sentence and also takes `speed` (1.0 = normal), `pitch_shift` and `seed`.The G2P runs on CUDA when available; set `TV_FA_G2P_DEVICE=cpu` to force CPU.
## Limitations
- Persian in Arabic script only. Latin-script words are skipped.- The G2P sometimes adds an ezafe where none belongs, or misses one; stress is rule-based (last syllable; first for می/نمی verbs).- ONNX export is not available for this model yet.- All voices are synthetic.12345678910"""tiny-voca: a small two-voice TTS trained from scratch.
The speech model loads no pretrained weights. A pretrained phoneme recogniseris used only by the annotation step, and an ASR model only by evaluation."""
from .config import Configfrom .model import TinyVoca
__all__ = ["Config", "TinyVoca"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118from dataclasses import asdict, dataclassimport hashlibimport json
CHECKPOINT_FORMAT = 4 # 2-3: byte tokens + learned aligner (rejected explicitly).ANNOTATION_VERSION = 3# Architecture switches added after the released models (2026-11-29). They default# off, and a switch that is off is left out of to_dict (and so of the fingerprint# and of saved checkpoints): older configurations load and compare as before.ARCH_FLAGS = ("critic_log", "critic_highband", "voicing_gate", "pulsed_noise")
def _digest(value): return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
@dataclass(frozen=True)class Config: # Acoustic features (unchanged since feature schema 2; existing files are reused). sample_rate: int = 24000 hop: int = 256 n_fft: int = 1024 n_mels: int = 80 f0_min: float = 50.0 f0_max: float = 600.0 speakers: tuple[str, ...] = ("a000",) # Phoneme tokens from tiny_voca.text.SYMBOLS (Arabic front end ar-1). vocab_size: int = 41 # Persian inventory (text.py) # Text encoder and frame-level transformer. channels: int = 192 heads: int = 4 feedforward: int = 640 kernel: int = 7 encoder_layers: int = 4 prosody_layers: int = 2 acoustic_layers: int = 5 dropout: float = 0.1 predictor_channels: int = 128 # Source-filter waveform head: harmonic branch and noise branch STFT sizes, # causal/anticausal complex-cepstrum orders. synth_fft: int = 512 synth_hop: int = 128 noise_fft: int = 256 noise_hop: int = 64 cep_causal: int = 80 cep_anti: int = 16 noise_cep: int = 32 harmonic_limit: float = 0.47 max_tokens: int = 512 max_frames: int = 3000 mel_mean: float = -5.0 mel_scale: float = 5.0 energy_mean: float = -4.0 energy_scale: float = 2.0 pitch_reference_hz: float = 200.0 # Training only: spectrogram critics see |X|^0.3 instead of |X|; one more critic sees 4-12 kHz. critic_log: bool = False critic_highband: bool = False # Pulse train scaled by eps + (1 - eps) * voicing (recorded voicing in training, sigmoid of the prediction at inference). voicing_gate: bool = False # Noise modulated with the glottal phase in voiced frames; one more noise-head output per frame (the depth). pulsed_noise: bool = False
def __post_init__(self): from .text import SYMBOLS if self.vocab_size != len(SYMBOLS): raise ValueError(f"vocab_size must equal the phoneme inventory size {len(SYMBOLS)}") if self.channels % self.heads or (self.channels // self.heads) % 2: raise ValueError("channels must be divisible by heads with an even head width") if not self.speakers or len(set(self.speakers)) != len(self.speakers): raise ValueError("speaker names must be unique and nonempty") for fft, hop in ((self.synth_fft, self.synth_hop), (self.noise_fft, self.noise_hop)): if fft != 4 * hop or self.hop % hop: raise ValueError("synthesis windows need 4x overlap and a hop dividing the acoustic hop") if self.cep_causal + self.cep_anti >= self.synth_fft // 2 or self.noise_cep >= self.noise_fft // 2: raise ValueError("cepstrum orders must be well below half the synthesis FFT size") if min(self.encoder_layers, self.prosody_layers, self.acoustic_layers, self.kernel) < 1 or not self.kernel % 2: raise ValueError("layer counts must be positive and the kernel odd") if min(self.mel_scale, self.energy_scale) <= 0 or not 0 < self.harmonic_limit < 0.5: raise ValueError("invalid normalization scale or harmonic limit")
def to_dict(self): value = asdict(self) for key in ARCH_FLAGS: if not value[key]: del value[key] return value
@classmethod def from_dict(cls, value): return cls(**{**value, "speakers": tuple(value["speakers"])})
@property def fingerprint(self): return _digest(self.to_dict())
@property def acoustic_config(self): """Settings that determine stored wave/mel/prosody tensors. Tokens and durations are versioned separately by the annotation layer.""" fields = ("sample_rate", "hop", "n_fft", "n_mels", "f0_min", "f0_max") return {**{key: getattr(self, key) for key in fields}, "feature_version": 2, "pitch_reference_hz": 200, "log_floor": 1e-5}
@property def acoustic_fingerprint(self): return _digest(self.acoustic_config)
@property def legacy_feature_fingerprint(self): """Fingerprint written by the byte-token preparation (front end 2).
Feature files carrying it hold compatible acoustics and STALE tokens; only the annotation step may read them, and it ignores their tokens. """ fields = ("sample_rate", "hop", "n_fft", "n_mels", "f0_min", "f0_max", "speakers") return _digest({**{key: getattr(self, key) for key in fields}, "vocab_size": 259, "feature_version": 2, "frontend_version": 2, "pitch_reference_hz": 200, "log_floor": 1e-5})12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576"""Persian text normalization shared by the corpus builder and the front end.
normalize(text): Arabic letter forms -> Persian (ي ك ى -> ی ک ی), Persian/Arabic digits -> ASCII, tatweel and short-vowel marksremoved (tanwin ً and kasra ـِ kept: they change the reading, kasra forces an ezafe), spaces squeezed, and every numberwritten out in words (cardinals, decimals with ممیز, percent with درصد, thousands separators dropped)."""import re
_ONES = ["صفر", "یک", "دو", "سه", "چهار", "پنج", "شش", "هفت", "هشت", "نه", "ده", "یازده", "دوازده", "سیزده", "چهارده", "پانزده", "شانزده", "هفده", "هجده", "نوزده"]_TENS = ["", "", "بیست", "سی", "چهل", "پنجاه", "شصت", "هفتاد", "هشتاد", "نود"]_HUNDREDS = ["", "صد", "دویست", "سیصد", "چهارصد", "پانصد", "ششصد", "هفتصد", "هشتصد", "نهصد"]_SCALES = [(10 ** 12, "تریلیون"), (10 ** 9, "میلیارد"), (10 ** 6, "میلیون"), (1000, "هزار")]
def _below_1000(n): parts = [] if n >= 100: parts.append(_HUNDREDS[n // 100]); n %= 100 if n >= 20: parts.append(_TENS[n // 10]); n %= 10 if n: parts.append(_ONES[n]) return " و ".join(parts)
def number_words(n): """Cardinal in words: 1250 -> یک هزار و دویست و پنجاه (هزار alone for 1000-1999).""" if n == 0: return _ONES[0] parts = [] for value, name in _SCALES: if n >= value: q = n // value; n %= value parts.append(name if (value == 1000 and q == 1) else f"{number_words(q)} {name}") if n: parts.append(_below_1000(n)) return " و ".join(parts)
_DIGITS = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789")_LETTERS = str.maketrans({"ي": "ی", "ى": "ی", "ك": "ک", "ۀ": "هی", "ة": "ه", "ـ": None, "": None, "": None, "َ": None, "ُ": None, "ْ": None, "ّ": None, "ٰ": None, "ٔ": None})_THOUSANDS = re.compile(r"(?<=\d)[,٬](?=\d{3}\b)")_DECIMAL = re.compile(r"(\d+)[.٫/](\d+)")_PERCENT = re.compile(r"(\d+(?:[.٫]\d+)?)\s*[%٪]")_NUMBER = re.compile(r"\d+")
def _decimal(m): return f"{number_words(int(m.group(1)))} ممیز {number_words(int(m.group(2)))}"
def numbers_to_words(text): text = _THOUSANDS.sub("", text) text = _PERCENT.sub(lambda m: m.group(1) + " درصد", text) text = _DECIMAL.sub(_decimal, text) return _NUMBER.sub(lambda m: f" {number_words(int(m.group()))} ", text)
_MI = re.compile(r"(?<![\u0600-\u06FF\u200c])(ن?می) (?=[\u0600-\u06FF])")_HA = re.compile(r"(?<=[\u0600-\u06FF]) (ها|های|هایی|هایم|هایت|هایش|هایمان|هایتان|هایشان)(?![\u0600-\u06FF\u200c])")
def normalize(text): # ezafe written on a final he (خانهٔ, خانۀ) -> kasra, which the G2P reads as a forced ezafe text = text.replace("ه\u0654", "ه\u0650").replace("ۀ", "ه\u0650") text = text.translate(_DIGITS).translate(_LETTERS) text = numbers_to_words(text) text = re.sub(r"[ \t ]+", " ", text) text = re.sub(r" ? ?", "", text) text = re.sub(r" ([،؛:.!؟?])", r"\1", text) # verb prefix and plural suffix written with a space instead of ZWNJ (می توان, دوره های) -> one word text = _MI.sub("\\1\u200c", text) text = _HA.sub("\u200c\\1", text) return text.strip()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219import argparseimport osfrom pathlib import Pathimport reimport torchfrom .config import CHECKPOINT_FORMAT, Configfrom .model import TinyVoca, UtteranceTooLongfrom .text import (FRONTEND_VARIABLE, FRONTENDS, NothingToPronounce, frontend_fingerprint, passage_addressee, phonemize, sentence_addressee, set_frontend)
# The loudest sample of the audio that ``speak_text`` and the command return.PEAK = 0.99# Said when no sentence of a text could be read. The browser demo says the same.ENGLISH_ONLY = "only symbols, emoji or characters this voice cannot read were found"_SPACE = re.compile("[\\s" + chr(0xFEFF) + "]+") # JavaScript's \s, which the demo uses, takes U+FEFF too_SENTENCE_END = re.compile(r"""(?:(?<=[.!?؟…])|(?<=[.!?؟…]["')\]»]))\s+(?=\S)""")_NOT_AN_END = re.compile(r"(?:\b(?:mr|mrs|ms|dr|prof|sr|jr|st|vs|etc|no|inc|ltd|co|e\.g|i\.e|a\.m|p\.m)|\b[A-Z])\.$", re.IGNORECASE | re.ASCII)# Arabic abbreviations end in a dot after one letter: د. أحمد, أ. سارة, م. علي, ج.م., أ.د., ص.ب._NOT_AN_END_ARABIC = re.compile(r"(?:^|[\s(])(?:[\u0621-\u064A]\.)+$")_CLAUSE_END = re.compile(r"(?<=[,;:—،؛])\s+")_TEXT_END = re.compile("[\\s" + chr(0xFEFF) + "]+$")_CLOSING = "\"'”’)]»" # these may stand after the last mark: She said "go!"
def load_model(path, device="cpu", check_frontend=True): """``check_frontend=False`` lets a checkpoint speak tokens of the other front end (same inventory, slightly different conventions): for listening tests of the new phonemizer before the model is retrained on it.""" state = torch.load(path, map_location="cpu", weights_only=True) if state.get("format_version") != CHECKPOINT_FORMAT: raise ValueError("unsupported checkpoint format: byte-token checkpoints (format 2-3) cannot be used with this code") if check_frontend and state["frontend"]["fingerprint"] != frontend_fingerprint(): raise ValueError("checkpoint was trained with a different phoneme inventory/front end") model = TinyVoca(Config.from_dict(state["config"])) model.load_state_dict(state["model"], strict=True) calibration = state.get("duration_calibration") if calibration: model.duration_log_offset = (float(calibration["phone"]), float(calibration["pause"])) return model.to(device).eval()
def match_frontend(path): """Select the front end the checkpoint was trained with.""" wanted = torch.load(path, map_location="cpu", weights_only=True)["frontend"]["fingerprint"] for name in FRONTENDS: set_frontend(name) try: if frontend_fingerprint() == wanted: return name except ImportError: continue set_frontend(FRONTENDS[0]) return None
def sentences(text): """The sentences of ``text``, without a break after a title or an initial or inside a number. The browser demo splits the same way (``web/public/worker.js``); keep the two alike.""" parts, current = [], "" for piece in _SENTENCE_END.split(_SPACE.sub(" ", text).strip()): current = f"{current} {piece}" if current else piece if not _NOT_AN_END.search(current) and not _NOT_AN_END_ARABIC.search(current): parts.append(current) current = "" if current: parts.append(current) return [part for part in parts if any(char.isalnum() for char in part)]
def finished(text): """``text`` with a full stop added when it ends without a mark. Before a final mark the voice lengthens the last syllable and lets the sound fall; without one the audio breaks off. A face or another sign after the last word is no mark ("see you :)"), a comma or a colon is one. The browser demo does the same (``web/public/worker.js``); keep the two alike.""" body = _TEXT_END.sub("", text) if not body: return text last = _SPACE.split(body)[-1] if any(char.isalnum() for char in last): marked = last.rstrip(_CLOSING)[-1:] in tuple(".!?…,;:") else: marked = any(char in ".!?…" for char in last) or last in (",", ";", ":") return text if marked else body + "."
def shorter(text): """``text`` in smaller pieces: cut after commas and the like if it has any, else in two between words. ``[]`` for a single word.""" pieces = _CLAUSE_END.split(text) if len(pieces) > 1: return pieces words = text.split(" ") if len(words) < 2: return [] half = (len(words) + 1) // 2 return [" ".join(words[:half]), " ".join(words[half:])]
def limit_peak(wave, peak=PEAK): """``wave`` scaled down as a whole when its loudest sample is above ``peak``; quieter audio is returned as it is. The model sometimes peaks above 1.0, and that clips when the audio is saved as 16-bit samples.""" loudest = float(wave.abs().max()) if wave.numel() else 0.0 return wave * (peak / loudest) if loudest > peak else wave
def _voice(model, phones, voice, speed, pitch_shift, seed, pitch_range): """Phonemes -> (float waveform tensor, details): one call of the model.""" device = next(model.parameters()).device tokens = torch.tensor([phones.ids], device=device) stress = torch.tensor([phones.stress], device=device) speaker = torch.tensor([model.config.speakers.index(voice)], device=device) audio, lengths, details = model.synthesize(tokens, stress, torch.tensor([len(phones)], device=device), speaker, speed, pitch_shift, seed, pitch_range) if not torch.isfinite(audio).all(): raise RuntimeError("model produced non-finite audio") return audio[0, :int(lengths[0])].cpu(), details
def speak(model, text, voice, speed=1.0, pitch_shift=0.0, seed=0, pitch_range=1.0): """One utterance: text -> (float waveform tensor, phonemized text, details). Same front end as training. The audio is the model's output as it is and can peak above 1.0 (see ``limit_peak``). ``speak_text`` reads text of any length.""" phones = phonemize(text) if len(phones) > model.config.max_tokens: raise ValueError("text is too long for one utterance; speak_text splits it into sentences") wave, details = _voice(model, phones, voice, speed, pitch_shift, seed, pitch_range) return wave, phones, details
def speak_text(model, text, voice, speed=1.0, pitch_shift=0.0, seed=0, pitch_range=1.0, peak=PEAK): """Text of any length -> (float waveform tensor, phonemized utterances).
The text is read sentence by sentence and the audio is joined; the addressee gender the passage cues is carried to every sentence without a cue of its own. A text that ends without a mark gets a full stop (``finished``). A sentence too long for one call of the model (``max_tokens`` phonemes or ``max_frames`` frames) is cut after commas, then between words. A sentence with nothing to pronounce (another script, a face, signs only) is skipped; when no sentence could be read, ``NothingToPronounce`` says so. The audio is scaled down as a whole when it peaks above ``peak``, so that it can be saved as 16-bit samples without clipping; ``peak=None`` returns the model's output as it is.""" limit = model.config.max_tokens - 12 waves, spoken = [], [] # the addressee of the whole passage, for a sentence with no cue of its own ("يا مريم، تعالي. عايز أقولك حاجة.") addressee = passage_addressee(text)
def read(piece): try: phones = phonemize(piece, addressee=addressee if sentence_addressee(piece) is None else None) except NothingToPronounce: return if len(phones) <= limit: try: wave, _ = _voice(model, phones, voice, speed, pitch_shift, seed + len(waves), pitch_range) except UtteranceTooLong: pass else: waves.append(wave) spoken.append(phones) return pieces = shorter(piece) if not pieces: raise ValueError(f"one word is too long to speak: {piece[:40]!r}") for part in pieces: read(part)
for sentence in sentences(finished(text)): read(sentence) if not waves: raise NothingToPronounce(f"nothing in the text could be read: {ENGLISH_ONLY}") wave = torch.cat(waves) return (wave if peak is None else limit_peak(wave, peak)), spoken
def main(): parser = argparse.ArgumentParser(description="Generate speech from a trained tiny-voca inference checkpoint") parser.add_argument("--checkpoint", type=Path, required=True) source = parser.add_mutually_exclusive_group(required=True) source.add_argument("--text", help="Text of any length; it is read sentence by sentence") source.add_argument("--text-file", type=Path, help="Read the text from a file (UTF-8)") parser.add_argument("--voice", choices=Config().speakers, default=Config().speakers[0]) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--speed", type=float, default=1) parser.add_argument("--pitch-shift", type=float, default=0, help="Added to log F0 (0.058 is about one semitone)") parser.add_argument("--pitch-range", type=float, default=1, help="Scale pitch movement around the utterance mean (1 = as predicted)") parser.add_argument("--device", default="cpu") parser.add_argument("--frontend", choices=FRONTENDS, help="Phonemizer (default: TINY_VOCA_FRONTEND, else the one the checkpoint was trained with)") parser.add_argument("--allow-frontend-mismatch", action="store_true", help="Speak although the checkpoint was trained on the other front end's tokens") args = parser.parse_args() import soundfile as sf if args.frontend: set_frontend(args.frontend) elif FRONTEND_VARIABLE not in os.environ: match_frontend(args.checkpoint) model = load_model(args.checkpoint, args.device, check_frontend=not args.allow_frontend_mismatch) text = args.text if args.text is not None else args.text_file.read_text(encoding="utf-8") try: raw, spoken = speak_text(model, text, args.voice, args.speed, args.pitch_shift, pitch_range=args.pitch_range, peak=None) except NothingToPronounce: parser.exit(1, f"{ENGLISH_ONLY}. Nothing in the text could be read, so no file was written.\n") wave = limit_peak(raw) args.output.parent.mkdir(parents=True, exist_ok=True) # Float samples, never above PEAK: a later conversion to 16-bit does not clip. sf.write(args.output, wave.numpy(), model.config.sample_rate, subtype="FLOAT") for phones in spoken: print(" ".join(phones.symbols)) loudest = float(raw.abs().max()) scaled = f", scaled down to {PEAK}" if wave is not raw else "" print(f"Saved {len(wave)/model.config.sample_rate:.2f}s in {len(spoken)} utterance{'s' if len(spoken) != 1 else ''}; peak={loudest:.4f}{scaled}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447"""tiny-voca v2: feed-forward transformer with a pitch-driven source-filter head.
All weights start random. Tensor conventions: hidden [B,T,C], frame features[B,T], waveform [B,S]. Acoustic frame i is centred on sample ``i * hop``.
phoneme + stress + voice -> transformer encoder -> duration predictor -> repeat tokens by duration (supervised durations while training) -> frame transformer A -> pitch / voicing / energy -> frame transformer B -> filter parameters -> harmonic pulse train (from pitch) and noise, each shaped by its time-varying filter in the STFT domain -> 24 kHz waveform
The waveform head has no neural upsampling network. The oscillator supplies theperiodicity that a tiny decoder cannot render reliably on its own; the networkonly has to predict slowly varying spectral envelopes (complex cepstra), whichis what keeps the voice from sounding buzzy or unstable at this size."""
import mathimport torchfrom torch import nnfrom torch.nn import functional as Ffrom .config import Configfrom .text import PHONE_IDS, SYMBOL_TO_ID, VOWELS
# Config.voicing_gate: the pulse train keeps this share where the frame is unvoiced.VOICING_FLOOR = 0.1# Frame tracks that scale the sources (voicing gate, noise pulse depth) change# over a moving average of this many samples (4 ms at 24 kHz) instead of a step.TRACK_SMOOTHING = 97# Config.pulsed_noise: noise *= 1 + depth * (exp(KAPPA * (cos(theta) - 1)) - mean) in# voiced frames, depth = PULSE_DEPTH * sigmoid(noise-head output). The mean of the# bump over a cycle is exp(-KAPPA) * I0(KAPPA), so the noise power stays near one# for small depths; PULSE_DEPTH < 1 / mean keeps the factor positive.PULSE_KAPPA = 4.0PULSE_MEAN = math.exp(-PULSE_KAPPA) * sum((PULSE_KAPPA / 2) ** (2 * k) / math.factorial(k) ** 2 for k in range(30))PULSE_DEPTH = 4.0PULSE_DEPTH_BIAS = -5.0 # depth starts at PULSE_DEPTH * sigmoid(-5) = 0.027
class UtteranceTooLong(ValueError): """The utterance needs more frames than ``max_frames``: split the input."""
def length_mask(lengths, size=None): size = int(lengths.max()) if size is None else size return torch.arange(size, device=lengths.device)[None, :] < lengths[:, None]
def rotary_table(size, width, device): inverse = 1.0 / (10000 ** (torch.arange(0, width, 2, device=device, dtype=torch.float32) / width)) angle = torch.arange(size, device=device, dtype=torch.float32)[:, None] * inverse[None] return angle.cos(), angle.sin()
def rotate(x, table): cos, sin = table[0].to(x.dtype), table[1].to(x.dtype) a, b = x[..., 0::2], x[..., 1::2] return torch.stack((a * cos - b * sin, a * sin + b * cos), dim=-1).flatten(-2)
class Attention(nn.Module): """Self-attention with rotary (relative) positions: no absolute position table, so utterances longer than those seen in training stay in range."""
def __init__(self, channels, heads, dropout): super().__init__() self.heads, self.dropout = heads, dropout self.qkv = nn.Linear(channels, 3 * channels) self.out = nn.Linear(channels, channels)
def forward(self, x, mask, table): b, t, c = x.shape q, k, v = self.qkv(x).view(b, t, 3, self.heads, c // self.heads).permute(2, 0, 3, 1, 4) y = F.scaled_dot_product_attention(rotate(q, table), rotate(k, table), v, attn_mask=mask[:, None, None, :], dropout_p=self.dropout if self.training else 0.0) return self.out(y.transpose(1, 2).reshape(b, t, c))
class Block(nn.Module): def __init__(self, c): super().__init__() self.norm1 = nn.LayerNorm(c.channels) self.attention = Attention(c.channels, c.heads, c.dropout) self.norm2 = nn.LayerNorm(c.channels) self.depthwise = nn.Conv1d(c.channels, c.channels, c.kernel, padding=c.kernel // 2, groups=c.channels) self.expand = nn.Linear(c.channels, c.feedforward) self.project = nn.Linear(c.feedforward, c.channels) self.dropout = nn.Dropout(c.dropout)
def forward(self, x, mask, table): keep = mask[..., None] x = (x + self.dropout(self.attention(self.norm1(x), mask, table))) * keep # Mask before the convolution so padded positions cannot leak back in. y = self.depthwise((self.norm2(x) * keep).transpose(1, 2)).transpose(1, 2) y = self.project(self.dropout(F.gelu(self.expand(y)))) return (x + self.dropout(y)) * keep
class Stack(nn.Module): def __init__(self, c, layers): super().__init__() self.blocks = nn.ModuleList(Block(c) for _ in range(layers)) self.norm = nn.LayerNorm(c.channels) self.width = c.channels // c.heads
def forward(self, x, mask): table = rotary_table(x.shape[1], self.width, x.device) for block in self.blocks: x = block(x, mask, table) return self.norm(x) * mask[..., None]
class Predictor(nn.Module): def __init__(self, c, outputs): super().__init__() p = c.predictor_channels self.conv1 = nn.Conv1d(c.channels, p, 3, padding=1) self.conv2 = nn.Conv1d(p, p, 3, padding=1) self.norm1, self.norm2 = nn.LayerNorm(p), nn.LayerNorm(p) self.drop = nn.Dropout(c.dropout) self.out = nn.Linear(p, outputs)
def forward(self, x, mask): x = self.conv1((x * mask[..., None]).transpose(1, 2)).transpose(1, 2) x = self.drop(self.norm1(F.gelu(x))) * mask[..., None] x = self.conv2(x.transpose(1, 2)).transpose(1, 2) x = self.drop(self.norm2(F.gelu(x))) return self.out(x) * mask[..., None]
def pulse_train(f0, sample_rate, hop, limit=0.47, phase=None, return_phase=False): """Band-limited pulse train [B, T*hop] with unit power for f0 [B, T] in Hz (and, with ``return_phase``, its phase in [0, 2 pi), 0 at the pulse peak).
Frame values sit at samples i*hop and are interpolated in the log domain. The sum of all harmonics below ``limit * sample_rate`` has the closed form sin((K+1/2)x) / (2 sin(x/2)) - 1/2; the top harmonic fades in and out so the signal stays continuous while the pitch glides. Float64 keeps the phase exact. """ frames = f0.shape[1] knots = torch.log(f0.double().clamp_min(1.0)) knots = torch.cat((knots, knots[:, -1:]), dim=1) position = torch.arange(frames * hop, device=f0.device, dtype=torch.float64) / hop low = position.floor().long() weight = position - low frequency = torch.exp(knots[:, low] * (1 - weight) + knots[:, low + 1] * weight) theta = 2 * math.pi * torch.cumsum(frequency / sample_rate, dim=1) if phase is not None: theta = theta + phase.double()[:, None] theta = torch.remainder(theta, 2 * math.pi) harmonics = (limit * sample_rate / frequency).clamp_min(1.0) whole = torch.floor(harmonics) denominator = 2 * torch.sin(theta / 2) tiny = denominator.abs() < 1e-7 core = torch.where(tiny, whole, torch.sin((whole + 0.5) * theta) / torch.where(tiny, torch.ones_like(denominator), denominator) - 0.5) wave = core + (harmonics - whole) * torch.cos((whole + 1) * theta) wave = (wave * torch.sqrt(2.0 / harmonics)).float() return (wave, theta.float()) if return_phase else wave
def sample_track(values, hop, width=TRACK_SMOOTHING): """Frame values [B, T] (frame i centred on sample i*hop) as samples [B, T*hop]: the nearest frame's value, then a moving average over ``width`` samples, so a change ramps over a few milliseconds. The ends repeat the edge values.""" frames = values.shape[1] index = torch.div(torch.arange(frames * hop, device=values.device) + hop // 2, hop, rounding_mode="floor").clamp(max=frames - 1) track = values.index_select(1, index)[:, None] return F.avg_pool1d(F.pad(track, (width // 2, width // 2), mode="replicate"), width, stride=1)[:, 0]
def pulse_bump(theta): """The zero-mean glottal-cycle shape that modulates the noise.""" return torch.exp(PULSE_KAPPA * (torch.cos(theta) - 1)) - PULSE_MEAN
def filtered(source, response, fft, hop, window): """Time-varying filtering: response [B, frames, bins] multiplies the STFT.""" spectrum = torch.stft(source, fft, hop, window=window, center=True, pad_mode="constant", return_complex=True) if spectrum.shape[-1] != response.shape[1]: raise ValueError("filter frames do not match the source") return torch.istft(spectrum * response.transpose(1, 2), fft, hop, window=window, center=True, length=source.shape[-1])
def cepstrum_response(causal, anticausal, fft): """Complex frequency response exp(FFT(cepstrum)). Causal coefficients give a minimum-phase filter; anticausal ones add a maximum-phase part (glottal pulse).""" buffer = causal.new_zeros(*causal.shape[:-1], fft) buffer[..., :causal.shape[-1]] = causal if anticausal is not None: buffer[..., fft - anticausal.shape[-1]:] = anticausal.flip(-1) spectrum = torch.fft.rfft(buffer, dim=-1) return torch.polar(torch.exp(spectrum.real.clamp(-14, 6)), spectrum.imag)
class SourceFilter(nn.Module): """Harmonic-plus-noise synthesis controlled per frame by two linear heads."""
def __init__(self, c): super().__init__() self.config = c self.harmonic_steps, self.noise_steps = c.hop // c.synth_hop, c.hop // c.noise_hop self.harmonic = nn.Linear(c.channels, c.cep_causal + c.cep_anti + self.harmonic_steps) # With pulsed_noise the noise head has one more output: the pulse depth. self.noise = nn.Linear(c.channels, c.noise_cep + self.noise_steps + int(c.pulsed_noise)) for head, level in ((self.harmonic, -1.5), (self.noise, -2.5)): # start quiet and spectrally flat nn.init.zeros_(head.weight) nn.init.zeros_(head.bias) head.bias.data[0] = level if c.pulsed_noise: self.noise.bias.data[-1] = PULSE_DEPTH_BIAS # no pulsing at the start
def lifter(size, first): scale = 1.0 / (1.0 + torch.arange(first, first + size, dtype=torch.float32) / 4) if first == 0: scale[0] = 2.0 # coefficient 0 is the log gain and needs range return scale self.register_buffer("causal_lifter", lifter(c.cep_causal, 0), persistent=False) self.register_buffer("anti_lifter", lifter(c.cep_anti, 1), persistent=False) self.register_buffer("noise_lifter", lifter(c.noise_cep, 0), persistent=False) self.register_buffer("synth_window", torch.hann_window(c.synth_fft), persistent=False) self.register_buffer("noise_window", torch.hann_window(c.noise_fft), persistent=False)
@staticmethod def _take(values, index): return values.gather(1, index[..., None].expand(-1, -1, values.shape[-1]))
def _subframes(self, frames, lengths, steps): """Sub-frame j uses frame j // steps; indices past an utterance's end repeat its last sub-frame so padding never changes real audio. Two extra sub-frames cover the half window of zeros appended to the source.""" sub = torch.arange(steps * frames + 3, device=lengths.device)[None].expand(len(lengths), -1) return torch.minimum(sub, (steps * lengths - 1).clamp_min(0)[:, None])
@staticmethod def _shape(source, response, fft, hop, window): # Half a window of trailing zeros: the frames around an utterance's end are # then the same whether it stands alone or is padded inside a batch. return filtered(F.pad(source, (0, fft // 2)), response, fft, hop, window)[:, :source.shape[-1]]
def forward(self, hidden, f0, lengths, noise=None, phase=None, voicing=None): """``voicing`` [B, T] in [0, 1] (needed by ``voicing_gate`` and ``pulsed_noise``): the recorded voiced flag in training, the predicted probability at inference.""" c = self.config frames = hidden.shape[1] samples = frames * c.hop with torch.autocast(device_type=hidden.device.type, enabled=False): hidden = hidden.float() audible = length_mask(lengths * c.hop, samples) last = (lengths - 1).clamp_min(0)[:, None] # Harmonic branch: envelope interpolated between frames, one gain per sub-frame. h = self.harmonic(hidden) split = c.cep_causal + c.cep_anti sub = self._subframes(frames, lengths, self.harmonic_steps) here, following = sub // self.harmonic_steps, torch.minimum((sub + 1) // self.harmonic_steps, last) causal = 0.5 * (self._take(h[..., :c.cep_causal], here) + self._take(h[..., :c.cep_causal], following)) * self.causal_lifter anti = 0.5 * (self._take(h[..., c.cep_causal:split], here) + self._take(h[..., c.cep_causal:split], following)) * self.anti_lifter causal = torch.cat((causal[..., :1] + h[..., split:].flatten(1).gather(1, sub)[..., None], causal[..., 1:]), dim=-1) harmonic_response = cepstrum_response(causal, anti, c.synth_fft) # Noise branch: one envelope per frame, four gains per frame for sharp consonants. n = self.noise(hidden) sub = self._subframes(frames, lengths, self.noise_steps) shape = self._take(n[..., :c.noise_cep], sub // self.noise_steps) * self.noise_lifter gains = n[..., c.noise_cep:c.noise_cep + self.noise_steps] shape = torch.cat((shape[..., :1] + gains.flatten(1).gather(1, sub)[..., None], shape[..., 1:]), dim=-1) noise_response = cepstrum_response(shape, None, c.noise_fft) # Hold the last real pitch value through padding: the pitch glide inside an # utterance's final frame must not depend on what the batch was padded with. hold = torch.minimum(torch.arange(frames, device=f0.device)[None], last) f0 = f0.float().gather(1, hold) if not (c.voicing_gate or c.pulsed_noise): pulses = pulse_train(f0, c.sample_rate, c.hop, c.harmonic_limit, phase) * audible else: if voicing is None or voicing.shape != (hidden.shape[0], frames): raise ValueError("voicing_gate and pulsed_noise need the frame voicing [B, T]") voiced = sample_track(voicing.float().gather(1, hold), c.hop) pulses, theta = pulse_train(f0, c.sample_rate, c.hop, c.harmonic_limit, phase, return_phase=True) pulses = pulses * audible if c.voicing_gate: pulses = pulses * (VOICING_FLOOR + (1 - VOICING_FLOOR) * voiced) if noise is None: noise = torch.randn(hidden.shape[0], samples, device=hidden.device) if c.pulsed_noise: depth = sample_track(PULSE_DEPTH * torch.sigmoid(n[..., -1].gather(1, hold)), c.hop) noise = noise * (1 + voiced * depth * pulse_bump(theta)) wave = (self._shape(pulses, harmonic_response, c.synth_fft, c.synth_hop, self.synth_window) + self._shape(noise * audible, noise_response, c.noise_fft, c.noise_hop, self.noise_window)) return wave * audible
class TinyVoca(nn.Module): def __init__(self, config=Config()): super().__init__() self.config = c = config self.tokens = nn.Embedding(c.vocab_size, c.channels, padding_idx=0) self.stress = nn.Embedding(3, c.channels) self.voices = nn.Embedding(len(c.speakers), c.channels) self.encoder = Stack(c, c.encoder_layers) # Outputs per token: log(1 + frames) and, for pause-capable tokens, a # "has frames at all" logit. A pause is absent more often than present, so # one regression would average both cases into a pause that is too short. self.duration = Predictor(c, 2) self.frame_voices = nn.Embedding(len(c.speakers), c.channels) self.frame_position = nn.Linear(3, c.channels) self.prosody_stack = Stack(c, c.prosody_layers) # Outputs: continuous log(F0/reference), voiced logit, normalized log RMS energy. self.prosody_head = nn.Linear(c.channels, 3) self.prosody_projection = nn.Linear(3, c.channels) self.acoustic_stack = Stack(c, c.acoustic_layers) self.vocoder = SourceFilter(c) phones = torch.zeros(c.vocab_size, dtype=torch.bool) phones[sorted(PHONE_IDS)] = True self.register_buffer("phone_tokens", phones, persistent=False) # Inference-time duration calibration (log(1+frames) offsets for phones and # pause-capable tokens). The duration head is trained with MSE in the log # domain, which predicts the median length; the mean is longer by about # var/2, so plain predictions run fast. Set from the checkpoint's # "duration_calibration" entry by load_model; (0, 0) leaves them untouched. self.duration_log_offset = (0.0, 0.0) vowels = torch.zeros(c.vocab_size, dtype=torch.bool) vowels[[SYMBOL_TO_ID[v] for v in VOWELS]] = True self.register_buffer("vowel_tokens", vowels, persistent=False)
def encode(self, tokens, stress, lengths, speakers): if tokens.ndim != 2 or stress.shape != tokens.shape or lengths.shape != (tokens.shape[0],) or speakers.shape != lengths.shape: raise ValueError("expected tokens[B,N], stress[B,N], lengths[B], speakers[B]") if tokens.shape[1] > self.config.max_tokens or bool((lengths < 1).any()) or bool((lengths > tokens.shape[1]).any()): raise ValueError("invalid token length") mask = length_mask(lengths, tokens.shape[1]) x = (self.tokens(tokens) + self.stress(stress) + self.voices(speakers)[:, None]) * mask[..., None] return self.encoder(x, mask), mask
def expand(self, hidden, durations, token_mask, speakers): """Repeat token states by integer durations (zero is allowed for pause tokens) and add each frame's position inside its token.""" if durations.shape != token_mask.shape or bool((durations < 0).any()) or bool((durations[~token_mask] != 0).any()): raise ValueError("invalid durations") lengths = durations.sum(1) if bool((lengths < 1).any()): raise ValueError("utterance has no frames") if bool((lengths > self.config.max_frames).any()): raise UtteranceTooLong("utterance exceeds max_frames; split the input") size = int(lengths.max()) ends = durations.cumsum(1) frame = torch.arange(size, device=hidden.device)[None].expand(hidden.shape[0], size).contiguous() index = torch.searchsorted(ends, frame, right=True).clamp(max=durations.shape[1] - 1) owned = durations.gather(1, index).clamp_min(1) offset = frame - (ends.gather(1, index) - durations.gather(1, index)) relative = (offset.to(hidden.dtype) + 0.5) / owned features = torch.stack((relative, 1 - relative, torch.log1p(owned.to(hidden.dtype)) / 4), dim=-1) mask = frame < lengths[:, None] expanded = hidden.gather(1, index[..., None].expand(-1, -1, hidden.shape[-1])) expanded = expanded + self.frame_position(features) + self.frame_voices(speakers)[:, None] return expanded * mask[..., None], mask, lengths
def predict_prosody(self, frames, frame_mask): hidden = self.prosody_stack(frames, frame_mask) return hidden, self.prosody_head(hidden) * frame_mask[..., None]
@staticmethod def hard_prosody(prediction): """What the decoder is conditioned on when it is not teacher-forced.""" return torch.stack((prediction[..., 0].clamp(-2.0, 1.5), (prediction[..., 1] > 0).to(prediction.dtype), prediction[..., 2].clamp(-4.5, 3.0)), dim=-1)
def decode(self, prosody_hidden, condition, frame_mask): return self.acoustic_stack((prosody_hidden + self.prosody_projection(condition)) * frame_mask[..., None], frame_mask)
def frequency(self, log_f0): c = self.config return (c.pitch_reference_hz * torch.exp(log_f0.float())).clamp(c.f0_min, c.f0_max)
def duration_offset(self, tokens, dtype=torch.float32): phone, pause = self.duration_log_offset return torch.where(self.phone_tokens[tokens], torch.tensor(phone, dtype=dtype), torch.tensor(pause, dtype=dtype))
def predict_durations(self, hidden, mask, tokens, speed=1.0): output = self.duration(hidden, mask).float() log_frames = output[..., 0] + self.duration_offset(tokens, output.dtype) frames = torch.round(torch.expm1(log_frames.clamp(0, math.log1p(400))) / speed).long().clamp_min(1) # Every phoneme is audible for at least one frame. A pause-capable token # (edge, punctuation, word boundary) lasts its predicted length when the # presence logit says there is a pause, and vanishes otherwise. present = self.phone_tokens[tokens] | (output[..., 1] > 0) return torch.where(present, frames, torch.zeros_like(frames)) * mask
@staticmethod def widen_pitch(prosody, frame_mask, pitch_range): """Scale the predicted pitch movement around each utterance's voiced mean. Regression predicts a flatter contour than the recordings; values above 1 restore range (1.0 leaves the prediction untouched).""" if pitch_range == 1.0: return prosody voiced = ((prosody[..., 1] > 0) & frame_mask).to(prosody.dtype) mean = (prosody[..., 0] * voiced).sum(1, keepdim=True) / voiced.sum(1, keepdim=True).clamp_min(1) pitch = mean + (prosody[..., 0] - mean) * pitch_range return torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1) * frame_mask[..., None]
@staticmethod def pitch_wobble(shape, semitones, seed, device): """Small random pitch movement for the oscillator only (log-F0 units). Recorded pitch has cycle-to-cycle irregularity that a predicted contour lacks; two thirds of the wobble is slow drift, one third frame-level.""" generator = torch.Generator().manual_seed(seed + 7919) fast = torch.randn(shape, generator=generator) slow = F.avg_pool1d(torch.randn(shape[0], 1, shape[1] + 16, generator=generator), 17, stride=1)[:, 0] slow = slow / slow.std().clamp_min(1e-6) return ((2 * slow + fast) / 5 ** 0.5 * semitones * math.log(2) / 12).to(device)
@torch.inference_mode() def synthesize(self, tokens, stress, lengths, speakers, speed=1.0, pitch_shift=0.0, seed=0, pitch_range=1.0, pitch_jitter=0.0, voiced_vowels=True): """Free-running synthesis: predicted durations, pitch, voicing and energy.""" if not math.isfinite(speed) or not 0.25 <= speed <= 4 or not math.isfinite(pitch_shift) or not 0 <= pitch_range <= 3: raise ValueError("speed must be between 0.25 and 4, pitch_shift finite and pitch_range between 0 and 3") hidden, mask = self.encode(tokens, stress, lengths, speakers) durations = self.predict_durations(hidden, mask, tokens, speed) frames, frame_mask, frame_lengths = self.expand(hidden, durations, mask, speakers) prosody_hidden, prosody = self.predict_prosody(frames, frame_mask) if voiced_vowels: # The pitch tracker missed creaky vowels in the recordings, and the # voicing predictor learned to drop whole vowels (heard as a whispered # word). A vowel is voiced by definition, so its frames are kept voiced. ends = durations.cumsum(1) frame = torch.arange(frames.shape[1], device=tokens.device)[None].expand(len(lengths), -1).contiguous() owner = torch.searchsorted(ends, frame, right=True).clamp(max=tokens.shape[1] - 1) vowel = self.vowel_tokens[tokens].gather(1, owner) & frame_mask prosody = torch.cat((prosody[..., :1], torch.where(vowel, prosody[..., 1].clamp_min(2.0), prosody[..., 1])[..., None], prosody[..., 2:]), dim=-1) voicing = None if self.config.voicing_gate or self.config.pulsed_noise: voicing = torch.sigmoid(prosody[..., 1].float()) if voiced_vowels: voicing = torch.where(vowel, torch.ones_like(voicing), voicing) prosody = self.widen_pitch(prosody, frame_mask, pitch_range) acoustic = self.decode(prosody_hidden, self.hard_prosody(prosody), frame_mask) # One noise stream per row, drawn at the row's own length, so batching or # padding never changes a row's audio. noise = nn.utils.rnn.pad_sequence([torch.randn(int(n) * self.config.hop, generator=torch.Generator().manual_seed(seed + row)) for row, n in enumerate(frame_lengths)], batch_first=True) pitch = prosody[..., 0] + pitch_shift if pitch_jitter > 0: pitch = pitch + self.pitch_wobble(pitch.shape, pitch_jitter, seed, pitch.device) wave = self.vocoder(acoustic, self.frequency(pitch), frame_lengths, noise=noise.to(hidden.device), voicing=voicing) return wave, frame_lengths * self.config.hop, {"durations": durations, "prosody": prosody, "frame_mask": frame_mask}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260"""Persian (Farsi) front end: text -> phoneme tokens with a stress feature.
Same interface as the Egyptian front end it replaces, so the model, annotation and training code are unchanged.
text -> fa_normalize.normalize (numbers in words, letter forms, ZWNJ) -> phrases (split at pause punctuation, kept as tokens) -> persian-g2p-tiny per phrase (ByT5 G2P with ezafe and homograph handling, "Repr. 1" romanization) -> tokens
* A token is one phoneme. Repr. 1 -> tokens: a æ (written a), A ɑː, e, o, i iː, u uː, S ʃ, Z ʒ, C tʃ, j dʒ, y j, ? ʔ, q q (ق/غ), g ɡ; the rest are themselves. A doubled letter is a geminate: two identical tokens.* The ezafe (-e / -ye) is part of its word and never stressed.* Stress is a parallel feature on one vowel per word (1 = primary), by rule: the last vowel of the word; the first vowel of a verb with the prefix می / نمی; none on clitic function words (va, be, az, rA ...).* Punctuation, word boundaries and the utterance edges are tokens that may last zero frames.
The G2P runs on CUDA when available (TV_FA_G2P_DEVICE overrides). ``prefetch(texts)`` phonemizes many texts in batches(annotation). Phrase phonemes can also come from a cache file (TINY_VOCA_FA_CACHE = jsonl of {"p": phrase, "ph": repr1})."""
from dataclasses import dataclass, fieldimport hashlibimport jsonimport osimport re
from .fa_normalize import normalize
FRONTEND_VERSION = "fa-1"FRONTENDS = ("fa",)FRONTEND_VARIABLE = "TINY_VOCA_FRONTEND"_frontend = "fa"G2P_MODEL = "mehdi-hf/persian-g2p-tiny"G2P_REVISION = os.environ.get("TV_FA_G2P_REVISION") # None = latest; annotation records what was used
PAD, BOS, EOS, SP, UNK = "<pad>", "<bos>", "<eos>", "<sp>", "<unk>"SPECIALS = (PAD, BOS, EOS, SP, UNK)PUNCTUATION = (",", ".", "?", "!", ";", ":", "…")PAUSE_PUNCT = "،,.؟?!:;؛…"_PUNCT_MAP = {"،": ",", ",": ",", ".": ".", "؟": "?", "?": "?", "!": "!", "؛": ";", ";": ";", ":": ":", "…": "…"}CONSONANTS = ("b", "t", "d", "k", "ɡ", "q", "ʔ", "f", "v", "p", "s", "z", "ʃ", "ʒ", "x", "h", "tʃ", "dʒ", "m", "n", "l", "r", "j")VOWELS = ("a", "ɑː", "e", "o", "iː", "uː")PHONES = CONSONANTS + VOWELS# Append-only: changing the order or removing a symbol invalidates checkpoints.SYMBOLS = SPECIALS + PUNCTUATION + PHONESSYMBOL_TO_ID = {symbol: index for index, symbol in enumerate(SYMBOLS)}PHONE_SET = frozenset(PHONES)PHONE_IDS = frozenset(SYMBOL_TO_ID[p] for p in PHONES) | {SYMBOL_TO_ID[UNK]}VOICELESS = frozenset(("p", "t", "k", "q", "ʔ", "f", "s", "ʃ", "x", "h", "tʃ"))VOWEL_SET = frozenset(VOWELS)
_REPR1 = {"a": "a", "A": "ɑː", "e": "e", "o": "o", "i": "iː", "u": "uː", "S": "ʃ", "Z": "ʒ", "C": "tʃ", "j": "dʒ", "y": "j", "?": "ʔ", "q": "q", "g": "ɡ", "b": "b", "t": "t", "d": "d", "k": "k", "f": "f", "v": "v", "p": "p", "s": "s", "z": "z", "x": "x", "h": "h", "m": "m", "n": "n", "l": "l", "r": "r"}# clitic function words: no stress of their own_UNSTRESSED = frozenset(("va", "be", "az", "?az", "dar", "tA", "ke", "bA", "rA", "yA", "bar", "na", "?o", "o"))_FA_WORD = re.compile(r"[-ۿ]+")
class NothingToPronounce(ValueError): """The text has no Persian word to say."""
@dataclass(frozen=True)class Phonemized: symbols: tuple ids: tuple stress: tuple unknown: tuple optional: tuple = field(default=()) diacritized: tuple = field(default=()) # here: the G2P romanization of each phrase, for inspection
def __len__(self): return len(self.ids)
def frontend(): return _frontend
def set_frontend(name): if name not in FRONTENDS: raise ValueError(f"front end must be one of {FRONTENDS}, not {name!r}")
def frontend_identity(): return {"frontend_version": FRONTEND_VERSION, "phonemizer": f"{G2P_MODEL} (Repr. 1) + rule stress", "symbols": list(SYMBOLS)}
def _g2p_revision(): try: from huggingface_hub import HfApi return G2P_REVISION or HfApi().model_info(G2P_MODEL).sha except Exception: return G2P_REVISION or "unknown"
def frontend_runtime(): h = hashlib.sha256() for name in ("text.py", "fa_normalize.py"): h.update(open(os.path.join(os.path.dirname(__file__), name), "rb").read()) return {"phonemizer": h.hexdigest(), "g2p_model": G2P_MODEL, "g2p_revision": _g2p_revision()}
def frontend_fingerprint(): return hashlib.sha256(json.dumps(frontend_identity(), sort_keys=True, ensure_ascii=False).encode()).hexdigest()
_g2p = None_cache = None_mem = {}
def _get_g2p(): global _g2p if _g2p is None: import torch from transformers import AutoTokenizer, T5ForConditionalGeneration device = os.environ.get("TV_FA_G2P_DEVICE") or ("cuda" if torch.cuda.is_available() else "cpu") tok = AutoTokenizer.from_pretrained(G2P_MODEL, revision=G2P_REVISION) model = T5ForConditionalGeneration.from_pretrained(G2P_MODEL, revision=G2P_REVISION).eval().to(device) _g2p = (tok, model, device) return _g2p
def _run_g2p(phrases, batch=128): import torch tok, model, device = _get_g2p() order = sorted(range(len(phrases)), key=lambda i: len(phrases[i])) res = [None] * len(phrases) for s in range(0, len(order), batch): idx = order[s:s + batch] enc = tok([phrases[i] for i in idx], padding=True, truncation=True, max_length=512, return_tensors="pt").to(device) with torch.no_grad(): gen = model.generate(enc["input_ids"], attention_mask=enc["attention_mask"], num_beams=4, max_new_tokens=384) for i, o in zip(idx, tok.batch_decode(gen, skip_special_tokens=True)): res[i] = " ".join(o.split()) return res
def _load_cache(): global _cache if _cache is None: _cache = {} path = os.environ.get("TINY_VOCA_FA_CACHE") if path and os.path.exists(path): with open(path, encoding="utf-8") as f: for line in f: r = json.loads(line); _cache[r["p"]] = r["ph"] return _cache
def _phonemes(phrases): cache = _load_cache() todo = [p for p in dict.fromkeys(phrases) if p not in cache and p not in _mem] if todo: for p, r in zip(todo, _run_g2p(todo)): _mem[p] = r return [cache[p] if p in cache else _mem[p] for p in phrases]
def prefetch(texts): """Phonemize the phrases of many texts in large batches (annotation); later phonemize() calls hit memory.""" _phonemes([p for t in texts for p, _ in split_phrases(normalize(t))])
def sentence_addressee(text): """Interface parity with the Egyptian front end (Persian has no addressee-gender readings).""" return None
def passage_addressee(text): return None
def split_phrases(text): """[(phrase, punct)] split at pause punctuation; punct is the closing mark or '' at the end.""" parts = re.split(f"([{re.escape(PAUSE_PUNCT)}]+)", text) out = [] for i in range(0, len(parts), 2): ph = " ".join(parts[i].split()); pu = parts[i + 1][0] if i + 1 < len(parts) else "" if ph and _FA_WORD.search(ph): out.append((ph, pu)) elif pu and out: out[-1] = (out[-1][0], out[-1][1] or pu) return out
def _word_tokens(word): """Repr. 1 word -> (symbols, indices of the stem's vowels, unknown). The ezafe after '-' joins the word.""" stem, _, ezafe = word.partition("-") symbols, unknown, stem_vowels = [], [], [] for part, is_stem in ((stem, True), (ezafe, False)): for ch in part: sym = _REPR1.get(ch) if sym is None: symbols.append(UNK); unknown.append(ch); continue if is_stem and sym in VOWEL_SET: stem_vowels.append(len(symbols)) symbols.append(sym) return symbols, stem_vowels, unknown
def tokenize_repr1(repr1, words_fa=None): """Repr. 1 string of one phrase -> (symbols, stress, unknown). ``words_fa``: the phrase's Persian words, used to find verbs with the prefix می/نمی when the G2P kept the word count.""" words = repr1.split() prefixed = None if words_fa is not None and len(words_fa) == len(words): prefixed = [w.startswith(("می", "نمی")) for w in words_fa] symbols, stress, unknown = [], [], [] for w, word in enumerate(words): if w: symbols.append(SP); stress.append(0) s, vowels, unk = _word_tokens(word) st = [0] * len(s) if vowels and word.split("-")[0] not in _UNSTRESSED: first = prefixed[w] if prefixed is not None else (word.startswith(("mi", "nemi")) and len(vowels) >= 3) st[vowels[0] if first else vowels[-1]] = 1 symbols += s; stress += st; unknown += unk return symbols, stress, unknown
def phonemize(text, addressee=None): """``addressee`` is accepted for interface parity and ignored.""" if not isinstance(text, str) or not text.strip(): raise ValueError("text must not be empty") parts = split_phrases(normalize(text)) if not parts: raise NothingToPronounce("the text has nothing to pronounce") reprs = _phonemes([p for p, _ in parts]) symbols, stress, unknown, shown = [BOS], [0], [], [] for (phrase, pu), r in zip(parts, reprs): r = (r or "").strip() if not r: continue s, st, unk = tokenize_repr1(r, _FA_WORD.findall(phrase)) if symbols[-1] != BOS and symbols[-1] not in PUNCTUATION: symbols.append(SP); stress.append(0) symbols += s; stress += st; unknown += unk; shown.append(r) if pu: symbols.append(_PUNCT_MAP.get(pu, ",")); stress.append(0) symbols.append(EOS); stress.append(0) if not any(s in PHONE_SET for s in symbols): raise NothingToPronounce("the text has nothing to pronounce") return Phonemized(tuple(symbols), tuple(SYMBOL_TO_ID[s] for s in symbols), tuple(stress), tuple(unknown), tuple(0 for _ in symbols), tuple(shown))
def drop(ph, remove): """Copy of ``ph`` without the token positions in ``remove`` (interface parity; no optional tokens here).""" remove = set(remove) keep = [i for i in range(len(ph.symbols)) if i not in remove] pick = lambda seq: tuple(seq[i] for i in keep) if seq else seq return Phonemized(pick(ph.symbols), pick(ph.ids), pick(ph.stress), ph.unknown, pick(ph.optional), ph.diacritized)
def is_phone(token_ids): return [int(i) in PHONE_IDS for i in token_ids]1234567891011121314151617181920212223242526272829303132333435363738{ "sample_rate": 24000, "hop": 256, "n_fft": 1024, "n_mels": 80, "f0_min": 50.0, "f0_max": 600.0, "speakers": [ "fa_male", "fa_female" ], "vocab_size": 41, "channels": 192, "heads": 4, "feedforward": 640, "kernel": 7, "encoder_layers": 4, "prosody_layers": 2, "acoustic_layers": 5, "dropout": 0.1, "predictor_channels": 128, "synth_fft": 512, "synth_hop": 128, "noise_fft": 256, "noise_hop": 64, "cep_causal": 80, "cep_anti": 16, "noise_cep": 32, "harmonic_limit": 0.47, "max_tokens": 512, "max_frames": 3000, "mel_mean": -5.0, "mel_scale": 5.0, "energy_mean": -4.0, "energy_scale": 2.0, "pitch_reference_hz": 200.0, "voicing_gate": true}123version https://git-lfs.github.com/spec/v1oid sha256:6bb2a6a1ab8507a9279454864cbca00b752e32b9aac368436d4fd767378e4df8size 475692123version https://git-lfs.github.com/spec/v1oid sha256:eea8ecbcc739c4138839e9df67035b1b48da7286b5e150dd56e8cfd6a9495f05size 499244123version https://git-lfs.github.com/spec/v1oid sha256:e0e2daae6917ab6dbfc77abb18a585419fb274b4e9976d5060e2dfcd572d4665size 392748123version https://git-lfs.github.com/spec/v1oid sha256:3b2b498e83111936e5284962b52f764204641f61c4b4e9415411a0eed3653a3csize 377388123version https://git-lfs.github.com/spec/v1oid sha256:e711bf7a1396d1fe4a9103b5097542b885abfe1706523ab13f35297df2cd2d17size 533548123version https://git-lfs.github.com/spec/v1oid sha256:56f68427f47e050448a78f6eaf1e37fad9299fe886dd8cbbab2a6b89a848716esize 573484123version https://git-lfs.github.com/spec/v1oid sha256:8b0e84f7e28f132c964d85c36173761a875bd23ab50725fd885c6654d5e04de9size 450092123version https://git-lfs.github.com/spec/v1oid sha256:3f50b828a41cb7b5add7e4a8a857b8b61fc923b9393c02dccb9dadf5c4342521size 42142012341 سلام، وقت بخیر. سفارش شما با موفقیت ثبت شد و تا دو روز آینده به دستتان میرسد.2 جلسهی فردا ساعت ده صبح در دفتر مرکزی برگزار میشود. لطفاً گزارش هفتهی گذشته را همراه داشته باشید.3 ایران کشوری با تاریخ کهن و فرهنگی غنی است که هر سال میلیونها گردشگر را به خود جذب میکند.4 این هفته روی همهی محصولات تخفیف ویژه داریم و ارسال برای خریدهای امروز رایگان است.123version https://git-lfs.github.com/spec/v1oid sha256:09de0e79fb476779195876c27b5319f1bac76de43a26b662f820a09b3739abdbsize 18184809.gitattributes+8
LICENSEAdded+202
README.mdAdded+76
code/tiny_voca/__init__.pyAdded+10
code/tiny_voca/config.pyAdded+118
code/tiny_voca/fa_normalize.pyAdded+76
code/tiny_voca/infer.pyAdded+219
code/tiny_voca/model.pyAdded+447
code/tiny_voca/text.pyAdded+260
config.jsonAdded+38
samples/fa_female_1.wavAdded+3
samples/fa_female_2.wavAdded+3
samples/fa_female_3.wavAdded+3
samples/fa_female_4.wavAdded+3
samples/fa_male_1.wavAdded+3
samples/fa_male_2.wavAdded+3
samples/fa_male_3.wavAdded+3
samples/fa_male_4.wavAdded+3
samples/texts.txtAdded+4
tiny-voca-persian.ptAdded+3