Release self-contained experimental Persian TTS with verified offline CPU inference
Browse filesFiles changed (33)
- .gitattributes+2
- LICENSEAdded+201
- NOTICEAdded+6
- README.mdAdded+111
- SHA256SUMS.jsonAdded+126
- acoustic.safetensorsAdded+3
- environment.jsonAdded+13
- examples/example.txtAdded+2
- examples/reference.wavAdded+3
- examples/standalone.jsonAdded+56
- examples/standalone.wavAdded+3
- frontend/added_tokens.jsonAdded+127
- frontend/config.jsonAdded+32
- frontend/generation_config.jsonAdded+6
- frontend/model.safetensorsAdded+3
- frontend/overlay.jsonAdded+1
- frontend/special_tokens_map.jsonAdded+23
- frontend/tokenizer_config.jsonAdded+1040
- gooya_config.jsonAdded+234
- gooya_tts/__init__.pyAdded+2
- gooya_tts/hifigan.pyAdded+292
- gooya_tts/networks.pyAdded+469
- gooya_tts/normalize.pyAdded+77
- gooya_tts/runtime.pyAdded+89
- gooya_tts/words.pyAdded+21
- infer.pyAdded+13
- licenses/HiFi-GAN-MIT.txtAdded+21
- licenses/Negara-Apache-2.0.txtAdded+202
- provenance.jsonAdded+27
- pyproject.tomlAdded+12
- requirements.txtAdded+7
- verification.jsonAdded+25
- vocoder.safetensorsAdded+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 lines333435363732 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 -textexamples/reference.wav filter=lfs diff=lfs merge=lfs -textexamples/standalone.wav filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 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.123456Gooya experimental Persian TTS release.GrainSpeech: Zitao Liang and Chang Gao, Apache-2.0; includes EfficientSpeech-derived code by Rowel Atienza (2023), Apache-2.0.HiFi-GAN source and adapted generator: MIT, see licenses/HiFi-GAN-MIT.txt.Negara v7.1 teacher/frontend: Apache-2.0, see licenses/Negara-Apache-2.0.txt.Modifications: Persian vocabulary, 100-mel output, contextual encoder, duration supervision, speaker-adapted vocoder, frontend distillation, and standalone runtime.Dataset attribution and limitations are in README.md; this package does not relicense source datasets.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111---language:- falicense: apache-2.0pipeline_tag: text-to-speechtags:- pytorch- persian- grainspeech- hifi-gan- experimental- single-speakermodel_name: Gooya RizehPizeh v2 expbase_model:- Reza2kn/negara-g2p-clean-v7.1datasets:- Reza2kn/nasle-mana-clean-chunked-30s-avasanj---
# Gooya RizehPizeh v2 exp
Self-contained experimental Persian text-to-speech: **9,451,575 parameters**, including G2P, a contextual GrainSpeech acoustic model, and a tiny speaker-adapted HiFi-GAN vocoder. Produces 24 kHz mono WAV audio. The entire stack is included in this repository and runs offline after downloading and installing dependencies.
This is the stack used for the September 24 listening comparison. It includes the full 8.07M Negara v7.1 model and its overlay. No Vocos, AvaSanj, training corpus, external checkpoint, Lightning, or remote inference service is required.
## Quick start
Python 3.10+; CPU is the default. CUDA is optional. PyTorch is a separate runtime dependency: the model weight size is not the installation size or peak RAM requirement. Old-device speed, Windows, mobile and browser inference have not been benchmarked.
```bashpython -m pip install huggingface_hubhf download Reza2kn/Gooya-RizehPizeh-v2-exp --local-dir Gooya-RizehPizeh-v2-exppython -m pip install -r Gooya-RizehPizeh-v2-exp/requirements.txtpython Gooya-RizehPizeh-v2-exp/infer.py --text "سلام، امروز حال شما چطوره؟" --output speech.wav```
For a smaller CPU-only installation on Linux, install CPU PyTorch before the requirements:
```bashpython -m pip install torch --index-url https://download.pytorch.org/whl/cpupython -m pip install -r Gooya-RizehPizeh-v2-exp/requirements.txt```
To reproduce the included longer sample:
```bashpython Gooya-RizehPizeh-v2-exp/infer.py --text-file Gooya-RizehPizeh-v2-exp/examples/example.txt --output sample.wav```
Pass `--device cuda` for GPU inference or `--threads 2` to limit CPU threads. The CLI also writes a JSON trace containing normalized text, generated phonemes, and segment durations. Model inference uses local files only. For fully offline use after setup, set `HF_HUB_OFFLINE=1` and `TRANSFORMERS_OFFLINE=1`.
## Python API
Install the included Python package once:
```bashpython -m pip install ./Gooya-RizehPizeh-v2-exp```
```pythonimport soundfile as sffrom gooya_tts import GooyaTTS
model = GooyaTTS("Gooya-RizehPizeh-v2-exp", device="cpu")audio, trace = model.synthesize("سلام، امروز حال شما چطوره؟", return_details=True)sf.write("speech.wav", audio, model.sample_rate, subtype="FLOAT")
# Alternatively download the complete model snapshot explicitly:# model = GooyaTTS.from_pretrained("Reza2kn/Gooya-RizehPizeh-v2-exp", device="cpu")```
## Components and size
| Component | Parameters ||---|---:|| Negara v7.1 | 8,067,456 || Contextual GrainSpeech acoustic model | 437,685 || Tiny HiFi-GAN | 946,434 || **Total** | **9,451,575** |
Counts include fixed bins and weight-normalization parameters. Weights are FP32 safetensors; nominal parameter storage is about 37.81 MB, plus configs, tokenizer, code and examples. Training-only discriminators and optimizers are omitted. Exact file sizes and SHA-256 checksums are in `SHA256SUMS.json`.
## Inference behavior
The frontend deterministically expands supported number forms, then predicts case-sensitive Negara phonemes. Input is divided at commas, sentence punctuation and newlines. It adds 150 ms comma gaps and 300 ms sentence gaps, matching the listening comparison; these gaps are fixed rather than learned prosody. Acoustic durations, pitch and energy are predicted from phones. Tiny HiFi-GAN receives 100-bin mel features with hop 256 at 24 kHz.
Negara uses beam width 5 and exact surface-word/raw-phone overlay matches. The overlay does not apply when word counts disagree. Inputs are not silently truncated. If G2P fails to emit EOS within 512 tokens or produces unsupported symbols, inference raises an error; use shorter phrases rather than accepting incomplete audio. Word-count disagreements produce a warning and remain visible in the trace. This is not a speech-completeness guarantee.
## Training and provenance
Acoustic/vocoder training uses the dataset's `label` field, not Koochik or Gemini ASR replacements. Source: [Nasle Mana](https://huggingface.co/datasets/Reza2kn/nasle-mana-clean-chunked-30s-avasanj), revision `606ecdc1d93a77c6f3a452ab5721774248cdf587`. After machine G2P/alignment filtering: 9,255 training excerpts / 19.10 hours and 2,337 development excerpts / 5.48 hours, with disjoint source recording groups. It did not consume every second of the source's approximately 41.4 labeled hours.
Architecture derives from [GrainSpeech](https://github.com/lab-emi/GrainSpeech), commit `8b38829809a6f86a9699371adc487c1efb875b05`, with a contextual bidirectional GRU, explicit boundary duration handling, and a 100-bin mel projection. The prosody variant trained for 50 epochs; the packaged best development checkpoint is step 10,413. The waveform generator derives from [HiFi-GAN V2](https://github.com/jik876/hifi-gan), with a new 100-mel input layer and 50,000 speaker-adaptation updates; selection used a fixed 96-excerpt development subset. See `provenance.json` for hashes and selected steps.
## Limitations
Uses full Negara v7.1 plus its exact-match correction overlay. This frontend is the stronger reference used in our comparisons, but this complete TTS stack has no comprehensive human intelligibility or naturalness benchmark.
User listening found the tiny vocoder acceptable for these samples, but speech can still be robotic. Proper names, colloquial spelling, ezafe, unfamiliar text, numbers, phrase boundaries and long inputs may fail. No MOS score, human pronunciation accuracy, real-time factor, memory ceiling, or device compatibility claim is made. A successful waveform or low training loss does not establish naturalness.
## Licensing and attribution
Release code and distributed modifications are Apache-2.0. Preserve the bundled Apache and MIT notices: GrainSpeech/EfficientSpeech and Negara use Apache-2.0; HiFi-GAN uses MIT. See `LICENSE`, `NOTICE`, and `licenses/`. Dataset copyrights and usage terms remain with their respective sources; this repository does not grant new rights to source recordings or imply speaker endorsement.
## Files
- `frontend/`: complete G2P model/tokenizer and overlay where applicable.- `acoustic.safetensors`, `vocoder.safetensors`: inference-only weights.- `gooya_config.json`, `gooya_tts/`, `infer.py`: standalone architecture, normalization, runtime and CLI.- `examples/`: requested Persian sample and standalone output.- `provenance.json`, `verification.json`, `SHA256SUMS.json`: provenance, verification receipt and integrity checks.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126{ "LICENSE": { "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", "bytes": 11357 }, "NOTICE": { "sha256": "094cc69de33f864e265f17eb8ecf33085ad2554554254b4b231d30d50bd81f65", "bytes": 588 }, "README.md": { "sha256": "b0ab50b1b0250b48a7bfcc494ac0c1cf5f7d70d63fc6180c472ca944e707ffc4", "bytes": 6818 }, "acoustic.safetensors": { "sha256": "91a1f668b7312058c9d8769caca158f254a5897bac1f61099222ef90a358f8b2", "bytes": 1763212 }, "environment.json": { "sha256": "e0f4cb8ae822fe87ffdd82e4deb8adcd9d8a462b3ebb845aa70c07105c9f65d7", "bytes": 276 }, "examples/example.txt": { "sha256": "c6b045cef670a8e4d774471f9d0bf475531e9fa79685641fb018bd97c1e492aa", "bytes": 383 }, "examples/reference.wav": { "sha256": "87b276e0963da49cf07de685f7ab1e4fcab256195b97ae92663b4ad2b3acf2b7", "bytes": 1671696 }, "examples/standalone.json": { "sha256": "90b57291a395de03b800bb27f7d5b2819e9da34d63d34a8ba2af9c2ce39a5f8e", "bytes": 2530 }, "examples/standalone.wav": { "sha256": "e999d1a8078150b5063e2884a1039b5a26f9778b718310be7658055c40304c8b", "bytes": 1671696 }, "frontend/added_tokens.json": { "sha256": "0004781309423057d33b9edf50d2669253d4347873ea33d4e7755cb866f23883", "bytes": 3018 }, "frontend/config.json": { "sha256": "a9ada2eff93810c2aa3bb251ba9c2edb7124f9ac4f947617aa9c18f45add2129", "bytes": 791 }, "frontend/generation_config.json": { "sha256": "e6bacb7faf7c3268de56b772c5b53f926545e0507686216bee531d2abc997fba", "bytes": 112 }, "frontend/model.safetensors": { "sha256": "2d89883abe07082cfb291203c1e5609f8974e71ca04d6c3e73bf2d32f8b715cf", "bytes": 32275776 }, "frontend/overlay.json": { "sha256": "9e063c2f26db4f56f6a93fef33f1f2a25423318ff7073b9954fddf4c4085412f", "bytes": 7003 }, "frontend/special_tokens_map.json": { "sha256": "7dc2ed3d3cc896f2e2e053dc1635d8b1d0e2b50094f0ae963a4d7fda6f4ced06", "bytes": 413 }, "frontend/tokenizer_config.json": { "sha256": "7f65014e433cc8c5c57951c1645eae6d3af3fb6fd8f5b7e56ec89f2ef228bb69", "bytes": 23033 }, "gooya_config.json": { "sha256": "9e2f6effb65c65efc1d030d81dca122c3024a17eb687386c2a8f4968ba15f796", "bytes": 4832 }, "gooya_tts/__init__.py": { "sha256": "b3bf2aa08a6e6d1a79f58ad742daeaf42844cf6c0a7888fcba6add3ef84cb2db", "bytes": 53 }, "gooya_tts/hifigan.py": { "sha256": "7b1518b88012a32b4339ea5b18603bf0728beb6eb5bf44d11dd3032bbb0017a4", "bytes": 10455 }, "gooya_tts/networks.py": { "sha256": "71cae5846af1369ca689e970a6fa191881137cc71f6daaa7dc554b52227f099a", "bytes": 16856 }, "gooya_tts/normalize.py": { "sha256": "12dc5440d0c74d6476d6260c0276594bed27c60b997c1034dc12b425e3201df9", "bytes": 3150 }, "gooya_tts/runtime.py": { "sha256": "e64d4a5c10f77ccd7af0129f21f2a889626e148ad2748b74b11cf44f2f05ab27", "bytes": 6812 }, "gooya_tts/words.py": { "sha256": "d764587724b171ae0d05d7f067fa950c8e02210150474979c4a55d8b35b4ee24", "bytes": 715 }, "infer.py": { "sha256": "b12929e3c01fc56efa0a8254f163aab37b01a8e0dd529ceb3a44590be90c54c8", "bytes": 1238 }, "licenses/HiFi-GAN-MIT.txt": { "sha256": "dc2e017a9a4430fbd21aa83345310fa34b7050d6c1d7a06d30436f7e5c4be2f4", "bytes": 1087 }, "licenses/Negara-Apache-2.0.txt": { "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", "bytes": 11358 }, "provenance.json": { "sha256": "5d6bbefcdc0e05294ebf121e7f71e78979fdfe6bc498debf95eaa4ec008b97e2", "bytes": 1121 }, "pyproject.toml": { "sha256": "d0a0e921f1a41abec9ffad5e909bdf46a4aa52f1d15a26a55aa993b698f85dc7", "bytes": 327 }, "requirements.txt": { "sha256": "9bb7a77f19f45c7839d92eb6e923df6f50739b01bd6793c5e5192257e20e5cbe", "bytes": 115 }, "verification.json": { "sha256": "7352ddcd2021a34962d8f40ee35203457b195cdac137ee9a5e95fc312b3d3700", "bytes": 971 }, "vocoder.safetensors": { "sha256": "081fb32646d70590e52926115b13481753c6d846647111a502cc93c3295a0a67", "bytes": 3807768 }}123version https://git-lfs.github.com/spec/v1oid sha256:91a1f668b7312058c9d8769caca158f254a5897bac1f61099222ef90a358f8b2size 176321212345678910111213{ "tested_platform": "Linux x86_64 CPU", "python": "3.13.11", "packages": { "torch": "2.14.0+cpu", "transformers": "5.17.0", "safetensors": "0.8.0", "numpy": "2.5.3", "soundfile": "0.14.0", "einops": "0.8.2", "huggingface_hub": "1.33.0" }}12به جای اینکه مدل رو مجبور کنن جواب رو توکن توکن بنویسه که طول میکشه، ازش فقط میپرسن فلان چیز چطوره؟ چندتا گزینه هم میدن.بعد مدل همین که به گزینه ها نگاه کنه ، درصد احتمال هرگزینه رو میبینه، بدون هیچ محاسبه اضافی123version https://git-lfs.github.com/spec/v1oid sha256:87b276e0963da49cf07de685f7ab1e4fcab256195b97ae92663b4ad2b3acf2b7size 16716961234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556{ "text": "به جای اینکه مدل رو مجبور کنن جواب رو توکن توکن بنویسه که طول میکشه، ازش فقط میپرسن فلان چیز چطوره؟ چندتا گزینه هم میدن.\nبعد مدل همین که به گزینه ها نگاه کنه ، درصد احتمال هرگزینه رو میبینه، بدون هیچ محاسبه اضافی", "model": "Gooya-RizehPizeh-v2-exp", "parameters": { "total": 9451575, "acoustic": 437685, "vocoder": 946434, "g2p": 8067456 }, "sample_rate": 24000, "segments": [ { "text": "به جای اینکه مدل رو مجبور کنن جواب رو توکن توکن بنویسه که طول میکشه،", "normalized": "به جای اینکه مدل رو مجبور کنن جواب رو توکن توکن بنویسه که طول میکشه،", "phonemes": "be jAye inke model ro majbur konan javAb ro tokon tokon benevise ke tul mikeshe", "word_count_matches": true, "duration_seconds": 5.088 }, { "text": "ازش فقط میپرسن فلان چیز چطوره؟", "normalized": "ازش فقط میپرسن فلان چیز چطوره؟", "phonemes": "azaS faqat miporsen folAn Ciz Cetoreh", "word_count_matches": true, "duration_seconds": 2.72 }, { "text": "چندتا گزینه هم میدن.", "normalized": "چندتا گزینه هم میدن.", "phonemes": "CandtA gozine ham midan", "word_count_matches": true, "duration_seconds": 1.5786666666666667 }, { "text": "بعد مدل همین که به گزینه ها نگاه کنه ،", "normalized": "بعد مدل همین که به گزینه ها نگاه کنه ،", "phonemes": "bad model hamin ke be gozinehA negA kone", "word_count_matches": false, "duration_seconds": 2.56 }, { "text": "درصد احتمال هرگزینه رو میبینه،", "normalized": "درصد احتمال هرگزینه رو میبینه،", "phonemes": "darsad ehtemAle hargozine ro mibine", "word_count_matches": true, "duration_seconds": 2.4426666666666668 }, { "text": "بدون هیچ محاسبه اضافی", "normalized": "بدون هیچ محاسبه اضافی", "phonemes": "beduneye hiC mohAsebeye ezAfi", "word_count_matches": true, "duration_seconds": 1.9733333333333334 } ], "duration_seconds": 17.412666666666667}123version https://git-lfs.github.com/spec/v1oid sha256:e999d1a8078150b5063e2884a1039b5a26f9778b718310be7658055c40304c8bsize 1671696123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127{ "<extra_id_0>": 259, "<extra_id_100>": 359, "<extra_id_101>": 360, "<extra_id_102>": 361, "<extra_id_103>": 362, "<extra_id_104>": 363, "<extra_id_105>": 364, "<extra_id_106>": 365, "<extra_id_107>": 366, "<extra_id_108>": 367, "<extra_id_109>": 368, "<extra_id_10>": 269, "<extra_id_110>": 369, "<extra_id_111>": 370, "<extra_id_112>": 371, "<extra_id_113>": 372, "<extra_id_114>": 373, "<extra_id_115>": 374, "<extra_id_116>": 375, "<extra_id_117>": 376, "<extra_id_118>": 377, "<extra_id_119>": 378, "<extra_id_11>": 270, "<extra_id_120>": 379, "<extra_id_121>": 380, "<extra_id_122>": 381, "<extra_id_123>": 382, "<extra_id_124>": 383, "<extra_id_12>": 271, "<extra_id_13>": 272, "<extra_id_14>": 273, "<extra_id_15>": 274, "<extra_id_16>": 275, "<extra_id_17>": 276, "<extra_id_18>": 277, "<extra_id_19>": 278, "<extra_id_1>": 260, "<extra_id_20>": 279, "<extra_id_21>": 280, "<extra_id_22>": 281, "<extra_id_23>": 282, "<extra_id_24>": 283, "<extra_id_25>": 284, "<extra_id_26>": 285, "<extra_id_27>": 286, "<extra_id_28>": 287, "<extra_id_29>": 288, "<extra_id_2>": 261, "<extra_id_30>": 289, "<extra_id_31>": 290, "<extra_id_32>": 291, "<extra_id_33>": 292, "<extra_id_34>": 293, "<extra_id_35>": 294, "<extra_id_36>": 295, "<extra_id_37>": 296, "<extra_id_38>": 297, "<extra_id_39>": 298, "<extra_id_3>": 262, "<extra_id_40>": 299, "<extra_id_41>": 300, "<extra_id_42>": 301, "<extra_id_43>": 302, "<extra_id_44>": 303, "<extra_id_45>": 304, "<extra_id_46>": 305, "<extra_id_47>": 306, "<extra_id_48>": 307, "<extra_id_49>": 308, "<extra_id_4>": 263, "<extra_id_50>": 309, "<extra_id_51>": 310, "<extra_id_52>": 311, "<extra_id_53>": 312, "<extra_id_54>": 313, "<extra_id_55>": 314, "<extra_id_56>": 315, "<extra_id_57>": 316, "<extra_id_58>": 317, "<extra_id_59>": 318, "<extra_id_5>": 264, "<extra_id_60>": 319, "<extra_id_61>": 320, "<extra_id_62>": 321, "<extra_id_63>": 322, "<extra_id_64>": 323, "<extra_id_65>": 324, "<extra_id_66>": 325, "<extra_id_67>": 326, "<extra_id_68>": 327, "<extra_id_69>": 328, "<extra_id_6>": 265, "<extra_id_70>": 329, "<extra_id_71>": 330, "<extra_id_72>": 331, "<extra_id_73>": 332, "<extra_id_74>": 333, "<extra_id_75>": 334, "<extra_id_76>": 335, "<extra_id_77>": 336, "<extra_id_78>": 337, "<extra_id_79>": 338, "<extra_id_7>": 266, "<extra_id_80>": 339, "<extra_id_81>": 340, "<extra_id_82>": 341, "<extra_id_83>": 342, "<extra_id_84>": 343, "<extra_id_85>": 344, "<extra_id_86>": 345, "<extra_id_87>": 346, "<extra_id_88>": 347, "<extra_id_89>": 348, "<extra_id_8>": 267, "<extra_id_90>": 349, "<extra_id_91>": 350, "<extra_id_92>": 351, "<extra_id_93>": 352, "<extra_id_94>": 353, "<extra_id_95>": 354, "<extra_id_96>": 355, "<extra_id_97>": 356, "<extra_id_98>": 357, "<extra_id_99>": 358, "<extra_id_9>": 268}1234567891011121314151617181920212223242526272829303132{ "architectures": [ "T5ForConditionalGeneration" ], "classifier_dropout": 0.0, "d_ff": 512, "d_kv": 64, "d_model": 512, "decoder_start_token_id": 0, "dense_act_fn": "gelu_new", "dropout_rate": 0.1, "dtype": "float32", "eos_token_id": 1, "feed_forward_proj": "gated-gelu", "gradient_checkpointing": false, "initializer_factor": 1.0, "is_encoder_decoder": true, "is_gated_act": true, "layer_norm_epsilon": 1e-06, "model_type": "t5", "num_decoder_layers": 2, "num_heads": 6, "num_layers": 2, "pad_token_id": 0, "relative_attention_max_distance": 128, "relative_attention_num_buckets": 32, "scale_decoder_outputs": false, "tokenizer_class": "ByT5Tokenizer", "transformers_version": "4.57.6", "use_cache": false, "vocab_size": 384}123456{ "decoder_start_token_id": 0, "eos_token_id": 1, "pad_token_id": 0, "transformers_version": "4.57.6"}123version https://git-lfs.github.com/spec/v1oid sha256:2d89883abe07082cfb291203c1e5609f8974e71ca04d6c3e73bf2d32f8b715cfsize 322757761{"fallback":"preserve_negara_v7_output","matching":"exact_normalized_surface_and_exact_raw_repr1","overlay_sha256":"0759f09ef057eb6cc5fe64d7f5c3e589b577d3c6ecea9b8002809488ed7aad62","provenance":{"gemini_model":"google/gemini-3.6-flash","gemini_use":"admit a learned rule only when frozen Gemini phones exactly match the human phones","human_authoritative":true,"manual_canonical_rule_count":6,"votes_path":"gooya5-authoritative470-with-gemini.jsonl","votes_sha256":"9e897dfdc1e96dc521801f1dce43b64373fdf6c381813bc270eea2b7fb92b117"},"rules":[{"card_ids":["8f822288977092df91ec49e76073f9c47f2a16b1b7f61d99f4a2b176e4560eab"],"raw":"AghAyAn","source":"exact_human_gemini36_agreement","support":1,"surface":"آقایان","target":"AqAyAn"},{"card_ids":["1b2d8f9aa0d9ebba16e9385a5bbd6b887102bd1a21a0d7c6f839665192bf8f99","66c9bf5f9bf4b2970e897bbd3fc4c12731978314a69fccc0bc39e29169bf9caa"],"raw":"ama","source":"exact_human_gemini36_agreement","support":2,"surface":"اما","target":"amA"},{"card_ids":["45df52f659869151f7d9c677d2ac8ae714f4d2d76f42ffff7d5c76bc600351a2","a2b77f327c7e5a70d55966908579a1205c36617f5bc452f1b44030ec86a2c36a","a8c5a82843e124c9ea885e795502a38320c975e4791176c0d67aba8e0f2b7324"],"raw":"breil","source":"exact_human_gemini36_agreement","support":3,"surface":"بریل","target":"bereil"},{"card_ids":["627dfa3407bb5778e22ea7d61b61a48c28f5060a2c5505ce3ea217f6614989e6","baa2cd9a1bb5cb0150ec60cef7bbf1084184cdb784e2010d17fbe20ea5cc8afb"],"raw":"breile","source":"exact_human_gemini36_agreement","support":2,"surface":"بریل","target":"bereile"},{"card_ids":["d5089df4fd3e9eaf6ffeceb31d0e8bb83d05b45a53a57713453c866033b625b1"],"raw":"teleskopip","source":"exact_human_gemini36_agreement","support":1,"surface":"تلسکوپی","target":"teleskopi"},{"card_ids":["3f142b8596470886d7bb641b437fa575303e987917ba38491d472ea17f12a350"],"raw":"xorm","source":"exact_human_gemini36_agreement","support":1,"surface":"خرم","target":"xorram"},{"card_ids":["338bf447f6857caf048d0cce3313e56b99464343966db04c786dd7e528d2d87c"],"raw":"darbAreyeye","source":"exact_human_gemini36_agreement","support":1,"surface":"دربارۀ","target":"darbAreye"},{"card_ids":["a02f20288f8f60053e89343c35db96ffebdf95bc8e9aefbdc84ebecef0080d44"],"raw":"darangi","source":"exact_human_gemini36_agreement","support":1,"surface":"درنگی","target":"derangi"},{"card_ids":["4aef44d4d7bdae3beb403e418b045863f6cc3a5ed774da383d35e06000167f7e"],"raw":"dah","source":"exact_human_gemini36_agreement","support":1,"surface":"ده","target":"deh"},{"card_ids":["8df7f8a894595e53bb6f511db09487315444c8e1f8373d258da73f0e01b75efd"],"raw":"davist","source":"exact_human_gemini36_agreement","support":1,"surface":"دویست","target":"divist"},{"card_ids":["bd26d55116162127a948af4e8d5887ff4e07aedf1c38f030e08f37908a223ac1"],"raw":"rasidi","source":"exact_human_gemini36_agreement","support":1,"surface":"رسیدی","target":"residi"},{"card_ids":["579861c9c2cc88069e2f0fbe18c62f5541eda6dffdbb204040dedf2624cda1f5"],"raw":"sabb","source":"exact_human_gemini36_agreement","support":1,"surface":"سبب","target":"sabab"},{"card_ids":["a4ac7672f9217013f757554e506309af97f81c71baac11a1b1f8daaba5bda07e"],"raw":"send","source":"exact_human_gemini36_agreement","support":1,"surface":"سند","target":"sanad"},{"card_ids":["a9ba820e7c2bad36f23a4ed858f37fbe4fb10acd581238433218c1723dee3607"],"raw":"Sakiban","source":"exact_human_gemini36_agreement","support":1,"surface":"شکیبا","target":"SakibA"},{"card_ids":["068586a1fe3ade39e7fb88ff5b92387cfb0dd37c4f90eafa3da662e519ec8846"],"raw":"faaliyAthA","source":"exact_human_gemini36_agreement","support":1,"surface":"فعالیتها","target":"faAliyathA"},{"card_ids":["918787327d852669b476c294f9a7e2953e1c60c383df26350173364f642333ed"],"raw":"qoSqAyi","source":"exact_human_gemini36_agreement","support":1,"surface":"قشقایی","target":"qaSqAyi"},{"card_ids":["34fadc403460da8480ffe93e2ebd611cbb91a561b83b5ad275f37bc766835d52"],"raw":"qate","source":"exact_human_gemini36_agreement","support":1,"surface":"قطعه","target":"qetQe"},{"card_ids":["9e83b4c5aa60d49dcecb7b257c7cb7e60227d646528232791ee838e30954ab35"],"raw":"mAlkine","source":"exact_human_gemini36_agreement","support":1,"surface":"مالکین","target":"mAlekine"},{"card_ids":["8022af96bff5295c4fcdc3e33c3859274a33ed99bf295e9e5d3938e5a7547110"],"raw":"mAneyeye","source":"exact_human_gemini36_agreement","support":1,"surface":"مانع","target":"mAneQe"},{"card_ids":["34e6a7f9d75c00a0f7aca13ba549c47a8c60482939746ad2a54c04d24690e0b3"],"raw":"mAnandeye","source":"exact_human_gemini36_agreement","support":1,"surface":"مانند","target":"mAnande"},{"card_ids":["9e76f8d19c5e76a3607b88bdb4c72ddd2221dc55e08a3cef3cc09991f977f6d3"],"raw":"mAykrusAfat","source":"exact_human_gemini36_agreement","support":1,"surface":"مایکروسافت","target":"mAykrosAft"},{"card_ids":["2f3ac3e3827d04eee84aed082a1927e4eb023bdcac8cba4ee16372b017e7e8aa"],"raw":"navisexAne","source":"exact_human_gemini36_agreement","support":1,"surface":"نویسهخوان","target":"nevisexAne"},{"card_ids":["eaab528d56903607937aad088d043c5b58f51233d3938e9a87b0f50956ac592b"],"raw":"nakanid","source":"exact_human_gemini36_agreement","support":1,"surface":"نکنید","target":"nakonid"},{"card_ids":["463b8f7b90da42a258de2ecb8483de99a3cd6914f44140adbd7220bae9f435e5"],"raw":"negAye","source":"exact_human_gemini36_agreement","support":1,"surface":"نگاه","target":"negAhe"},{"card_ids":["d7142a09ccc8b220290695e0127fcbe2d5ceeaa4899eb4ec7260fd431390bfbc"],"raw":"viziat","source":"exact_human_gemini36_agreement","support":1,"surface":"ویزیت","target":"vizit"},{"card_ids":["984987c18e58e118eae9dc8463f36788bf2fefcf11d488e7150574ed49db5b34"],"raw":"parnur","source":"exact_human_gemini36_agreement","support":1,"surface":"پرنور","target":"pornur"},{"card_ids":["4c029e3894c59e7850fdd31ed09decc8bfc1022984d56e4278a4251330569a68"],"raw":"past","source":"exact_human_gemini36_agreement","support":1,"surface":"پست","target":"post"},{"card_ids":["96693d68ea30c10a3f2aabfe4501dc9d93f85cc25816ef188bfe078ef9762844"],"raw":"CaSme","source":"exact_human_gemini36_agreement","support":1,"surface":"چشم","target":"CeSme"},{"card_ids":["c1c3cf0b826768caf994af32f4c26912cb2b0a5e84342e9609be2caffa610d1f"],"raw":"kuseSaS","source":"exact_human_gemini36_agreement","support":1,"surface":"کوشش","target":"kuSeS"},{"raw":"alAq","source":"user_canonical_example","surface":"الاغ","target":"olAq"},{"raw":"alAqe","source":"user_canonical_example","surface":"الاغ","target":"olAqe"},{"raw":"salAme","source":"user_canonical_example","surface":"سلام","target":"salAm"},{"raw":"hAlat","source":"user_canonical_example","surface":"حالت","target":"hAlet"},{"raw":"Cetore","source":"user_canonical_example","surface":"چطوره","target":"Cetoreh"},{"raw":"ahvAlat","source":"user_canonical_example","surface":"احوالت","target":"ahvAlet"}],"schema_version":"negara.v7.1-human-gemini-overlay/v1"}1234567891011121314151617181920212223{ "eos_token": { "content": "</s>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }, "pad_token": { "content": "<pad>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }, "unk_token": { "content": "<unk>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040{ "added_tokens_decoder": { "0": { "content": "<pad>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": true }, "1": { "content": "</s>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": true }, "2": { "content": "<unk>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": true }, "259": { "content": "<extra_id_0>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "260": { "content": "<extra_id_1>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "261": { "content": "<extra_id_2>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "262": { "content": "<extra_id_3>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "263": { "content": "<extra_id_4>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "264": { "content": "<extra_id_5>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "265": { "content": "<extra_id_6>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "266": { "content": "<extra_id_7>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "267": { "content": "<extra_id_8>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "268": { "content": "<extra_id_9>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "269": { "content": "<extra_id_10>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "270": { "content": "<extra_id_11>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "271": { "content": "<extra_id_12>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "272": { "content": "<extra_id_13>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "273": { "content": "<extra_id_14>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "274": { "content": "<extra_id_15>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "275": { "content": "<extra_id_16>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "276": { "content": "<extra_id_17>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "277": { "content": "<extra_id_18>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "278": { "content": "<extra_id_19>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "279": { "content": "<extra_id_20>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "280": { "content": "<extra_id_21>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "281": { "content": "<extra_id_22>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "282": { "content": "<extra_id_23>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "283": { "content": "<extra_id_24>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "284": { "content": "<extra_id_25>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "285": { "content": "<extra_id_26>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "286": { "content": "<extra_id_27>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "287": { "content": "<extra_id_28>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "288": { "content": "<extra_id_29>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "289": { "content": "<extra_id_30>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "290": { "content": "<extra_id_31>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "291": { "content": "<extra_id_32>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "292": { "content": "<extra_id_33>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "293": { "content": "<extra_id_34>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "294": { "content": "<extra_id_35>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "295": { "content": "<extra_id_36>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "296": { "content": "<extra_id_37>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "297": { "content": "<extra_id_38>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "298": { "content": "<extra_id_39>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "299": { "content": "<extra_id_40>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "300": { "content": "<extra_id_41>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "301": { "content": "<extra_id_42>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "302": { "content": "<extra_id_43>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "303": { "content": "<extra_id_44>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "304": { "content": "<extra_id_45>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "305": { "content": "<extra_id_46>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "306": { "content": "<extra_id_47>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "307": { "content": "<extra_id_48>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "308": { "content": "<extra_id_49>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "309": { "content": "<extra_id_50>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "310": { "content": "<extra_id_51>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "311": { "content": "<extra_id_52>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "312": { "content": "<extra_id_53>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "313": { "content": "<extra_id_54>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "314": { "content": "<extra_id_55>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "315": { "content": "<extra_id_56>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "316": { "content": "<extra_id_57>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "317": { "content": "<extra_id_58>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "318": { "content": "<extra_id_59>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "319": { "content": "<extra_id_60>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "320": { "content": "<extra_id_61>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "321": { "content": "<extra_id_62>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "322": { "content": "<extra_id_63>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "323": { "content": "<extra_id_64>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "324": { "content": "<extra_id_65>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "325": { "content": "<extra_id_66>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "326": { "content": "<extra_id_67>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "327": { "content": "<extra_id_68>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "328": { "content": "<extra_id_69>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "329": { "content": "<extra_id_70>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "330": { "content": "<extra_id_71>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "331": { "content": "<extra_id_72>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "332": { "content": "<extra_id_73>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "333": { "content": "<extra_id_74>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "334": { "content": "<extra_id_75>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "335": { "content": "<extra_id_76>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "336": { "content": "<extra_id_77>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "337": { "content": "<extra_id_78>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "338": { "content": "<extra_id_79>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "339": { "content": "<extra_id_80>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "340": { "content": "<extra_id_81>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "341": { "content": "<extra_id_82>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "342": { "content": "<extra_id_83>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "343": { "content": "<extra_id_84>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "344": { "content": "<extra_id_85>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "345": { "content": "<extra_id_86>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "346": { "content": "<extra_id_87>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "347": { "content": "<extra_id_88>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "348": { "content": "<extra_id_89>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "349": { "content": "<extra_id_90>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "350": { "content": "<extra_id_91>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "351": { "content": "<extra_id_92>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "352": { "content": "<extra_id_93>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "353": { "content": "<extra_id_94>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "354": { "content": "<extra_id_95>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "355": { "content": "<extra_id_96>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "356": { "content": "<extra_id_97>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "357": { "content": "<extra_id_98>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "358": { "content": "<extra_id_99>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "359": { "content": "<extra_id_100>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "360": { "content": "<extra_id_101>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "361": { "content": "<extra_id_102>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "362": { "content": "<extra_id_103>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "363": { "content": "<extra_id_104>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "364": { "content": "<extra_id_105>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "365": { "content": "<extra_id_106>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "366": { "content": "<extra_id_107>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "367": { "content": "<extra_id_108>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "368": { "content": "<extra_id_109>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "369": { "content": "<extra_id_110>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "370": { "content": "<extra_id_111>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "371": { "content": "<extra_id_112>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "372": { "content": "<extra_id_113>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "373": { "content": "<extra_id_114>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "374": { "content": "<extra_id_115>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "375": { "content": "<extra_id_116>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "376": { "content": "<extra_id_117>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "377": { "content": "<extra_id_118>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "378": { "content": "<extra_id_119>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "379": { "content": "<extra_id_120>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "380": { "content": "<extra_id_121>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "381": { "content": "<extra_id_122>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "382": { "content": "<extra_id_123>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "383": { "content": "<extra_id_124>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "additional_special_tokens": [], "backend": "custom", "clean_up_tokenization_spaces": false, "eos_token": "</s>", "extra_ids": 0, "extra_special_tokens": {}, "is_local": false, "local_files_only": false, "model_max_length": 1000000000000000019884624838656, "pad_token": "<pad>", "tokenizer_class": "ByT5Tokenizer", "unk_token": "<unk>"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234{ "name": "Gooya-RizehPizeh-v2-exp", "sample_rate": 24000, "n_mels": 100, "hop_length": 256, "parameters": { "total": 9451575, "acoustic": 437685, "vocoder": 946434, "g2p": 8067456 }, "frontend": { "num_beams": 5, "max_new_tokens": 512, "overlay": true }, "vocabulary": { "<pad>": 0, "A": 1, "C": 2, "Q": 3, "S": 4, "Z": 5, "a": 6, "b": 7, "c": 8, "d": 9, "e": 10, "f": 11, "g": 12, "h": 13, "i": 14, "j": 15, "k": 16, "l": 17, "m": 18, "n": 19, "o": 20, "p": 21, "q": 22, "r": 23, "s": 24, "t": 25, "u": 26, "v": 27, "x": 28, "y": 29, "z": 30, "<sil>": 31, "<wb>": 32, "<comma>": 33, "<stop>": 34 }, "stats": { "pitch": [ -4.268602197682544, 9.7447582834536, 236.40021959281708, 55.38117834478943 ], "energy": [ -1.383905377099731, 15.066260915460015, 19.318673053037664, 13.959533196932918 ], "mel_mean": [ -1.2599120962399815, -1.0706863130203852, -1.3486225483807173, -1.7726936082089029, -2.041859880321682, -1.712638320035706, -1.0914770279327108, -0.3807035679628814, 0.07982043833775036, 0.22480345288187137, -0.055095117517642914, -0.44897131882475627, -0.6456663869845404, -0.757075913214885, -0.6418275830384098, -0.6876451645425007, -0.5022434700565953, -0.5589231758789743, -0.7308565946682717, -0.6738371803222432, -0.6591148241863097, -0.5883852729898147, -0.5639190191526563, -0.7877885209264643, -0.8651297569802631, -0.9135138596372251, -0.9160686679274491, -1.0026051861303737, -1.1595387866912998, -1.3463762292503894, -1.433785481625953, -1.509796948289812, -1.5532702188077707, -1.58031571677792, -1.5848189295037685, -1.53389185687708, -1.6147262252995764, -1.5244208106009025, -1.5246441635814538, -1.404755357976768, -1.2746636397949307, -1.2552575190198396, -1.2390230013675123, -1.2408969273842558, -1.2593803586363268, -1.2886173993373498, -1.3755037817316689, -1.489770602358068, -1.5264167721939668, -1.5668277704132214, -1.485083786356484, -1.3851185974497089, -1.3471519688882847, -1.355141926671464, -1.366675977216914, -1.378138861126079, -1.426072925184457, -1.4807474690972087, -1.5874296346188488, -1.7006418388046916, -1.8353564094266106, -1.9317527992801704, -1.9428357752375198, -1.883040283595134, -1.7377132245251883, -1.5972257115773942, -1.4810687983142867, -1.444813686563024, -1.4722089856505978, -1.50291586943949, -1.5512569720723524, -1.6538890198503444, -1.817821647804874, -2.0399388252424093, -2.2701647154375406, -2.5035088520641633, -2.6186066993318593, -2.6823086870228656, -2.682087813068936, -2.7183459479868217, -2.5509733317896353, -2.1603005679802307, -1.8111598191860174, -1.621251966300455, -1.6408059785839708, -1.9298176242428915, -2.4191385805562073, -2.9964079875197016, -2.9862544853959996, -3.2133091665313294, -3.915077464403742, -5.339607711801079, -6.822064941222431, -7.397338695634322, -7.699124545520323, -7.589487886694324, -7.834026533757323, -7.592484212990957, -7.787868553571219, -7.700824718443493 ] }, "vocoder_config": { "resblock": "1", "num_gpus": 0, "batch_size": 16, "learning_rate": 0.0002, "adam_b1": 0.8, "adam_b2": 0.99, "lr_decay": 0.999, "seed": 1234, "upsample_rates": [ 8, 8, 2, 2 ], "upsample_kernel_sizes": [ 16, 16, 4, 4 ], "upsample_initial_channel": 128, "resblock_kernel_sizes": [ 3, 7, 11 ], "resblock_dilation_sizes": [ [ 1, 3, 5 ], [ 1, 3, 5 ], [ 1, 3, 5 ] ], "resblock_initial_channel": 64, "segment_size": 8192, "num_mels": 100, "num_freq": 1025, "n_fft": 1024, "hop_size": 256, "win_size": 1024, "sampling_rate": 24000, "fmin": 0, "fmax": 12000, "fmax_loss": null, "num_workers": 4, "dist_config": { "dist_backend": "nccl", "dist_url": "tcp://localhost:54321", "world_size": 1 } }, "comma_gap_seconds": 0.15, "sentence_gap_seconds": 0.3}12from .runtime import GooyaTTS__all__ = ["GooyaTTS"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
#from utils import init_weights, get_padding
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(mean, std)
def get_padding(kernel_size, dilation=1):
return int((kernel_size * dilation - dilation) / 2)
LRELU_SLOPE = 0.1
class ResBlock1(torch.nn.Module):
def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)):
super(ResBlock1, self).__init__()
self.h = h
self.convs1 = nn.ModuleList([
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
padding=get_padding(kernel_size, dilation[0]))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
padding=get_padding(kernel_size, dilation[1]))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
padding=get_padding(kernel_size, dilation[2])))
])
self.convs1.apply(init_weights)
self.convs2 = nn.ModuleList([
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
padding=get_padding(kernel_size, 1))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
padding=get_padding(kernel_size, 1))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
padding=get_padding(kernel_size, 1)))
])
self.convs2.apply(init_weights)
def forward(self, x):
for c1, c2 in zip(self.convs1, self.convs2):
xt = F.leaky_relu(x, LRELU_SLOPE)
xt = c1(xt)
xt = F.leaky_relu(xt, LRELU_SLOPE)
xt = c2(xt)
x = xt + x
return x
def remove_weight_norm(self):
for l in self.convs1:
remove_weight_norm(l)
for l in self.convs2:
remove_weight_norm(l)
class ResBlock2(torch.nn.Module):
def __init__(self, h, channels, kernel_size=3, dilation=(1, 3)):
super(ResBlock2, self).__init__()
self.h = h
self.convs = nn.ModuleList([
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
padding=get_padding(kernel_size, dilation[0]))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
padding=get_padding(kernel_size, dilation[1])))
])
self.convs.apply(init_weights)
def forward(self, x):
for c in self.convs:
xt = F.leaky_relu(x, LRELU_SLOPE)
xt = c(xt)
x = xt + x
return x
def remove_weight_norm(self):
for l in self.convs:
remove_weight_norm(l)
class Generator(torch.nn.Module):
def __init__(self, h):
super(Generator, self).__init__()
self.h = h
self.num_kernels = len(h.resblock_kernel_sizes)
self.num_upsamples = len(h.upsample_rates)
self.conv_pre = weight_norm(Conv1d(80, h.upsample_initial_channel, 7, 1, padding=3))
resblock = ResBlock1 if h.resblock == '1' else ResBlock2
self.ups = nn.ModuleList()
for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)):
self.ups.append(weight_norm(
ConvTranspose1d(h.upsample_initial_channel//(2**i), h.upsample_initial_channel//(2**(i+1)),
k, u, padding=(k-u)//2)))
self.resblocks = nn.ModuleList()
for i in range(len(self.ups)):
ch = h.upsample_initial_channel//(2**(i+1))
for j, (k, d) in enumerate(zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes)):
self.resblocks.append(resblock(h, ch, k, d))
self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3))
self.ups.apply(init_weights)
self.conv_post.apply(init_weights)
def forward(self, x):
x = self.conv_pre(x)
for i in range(self.num_upsamples):
x = F.leaky_relu(x, LRELU_SLOPE)
x = self.ups[i](x)
xs = None
for j in range(self.num_kernels):
if xs is None:
xs = self.resblocks[i*self.num_kernels+j](x)
else:
xs += self.resblocks[i*self.num_kernels+j](x)
x = xs / self.num_kernels
x = F.leaky_relu(x)
x = self.conv_post(x)
x = torch.tanh(x)
return x
def remove_weight_norm(self):
print('Removing weight norm...')
for l in self.ups:
remove_weight_norm(l)
for l in self.resblocks:
l.remove_weight_norm()
remove_weight_norm(self.conv_pre)
remove_weight_norm(self.conv_post)
class DiscriminatorP(torch.nn.Module):
def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
super(DiscriminatorP, self).__init__()
self.period = period
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
self.convs = nn.ModuleList([
norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(2, 0))),
])
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
def forward(self, x):
fmap = []
# 1d to 2d
b, c, t = x.shape
if t % self.period != 0: # pad first
n_pad = self.period - (t % self.period)
x = F.pad(x, (0, n_pad), "reflect")
t = t + n_pad
x = x.view(b, c, t // self.period, self.period)
for l in self.convs:
x = l(x)
x = F.leaky_relu(x, LRELU_SLOPE)
fmap.append(x)
x = self.conv_post(x)
fmap.append(x)
x = torch.flatten(x, 1, -1)
return x, fmap
class MultiPeriodDiscriminator(torch.nn.Module):
def __init__(self):
super(MultiPeriodDiscriminator, self).__init__()
self.discriminators = nn.ModuleList([
DiscriminatorP(2),
DiscriminatorP(3),
DiscriminatorP(5),
DiscriminatorP(7),
DiscriminatorP(11),
])
def forward(self, y, y_hat):
y_d_rs = []
y_d_gs = []
fmap_rs = []
fmap_gs = []
for i, d in enumerate(self.discriminators):
y_d_r, fmap_r = d(y)
y_d_g, fmap_g = d(y_hat)
y_d_rs.append(y_d_r)
fmap_rs.append(fmap_r)
y_d_gs.append(y_d_g)
fmap_gs.append(fmap_g)
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
class DiscriminatorS(torch.nn.Module):
def __init__(self, use_spectral_norm=False):
super(DiscriminatorS, self).__init__()
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
self.convs = nn.ModuleList([
norm_f(Conv1d(1, 128, 15, 1, padding=7)),
norm_f(Conv1d(128, 128, 41, 2, groups=4, padding=20)),
norm_f(Conv1d(128, 256, 41, 2, groups=16, padding=20)),
norm_f(Conv1d(256, 512, 41, 4, groups=16, padding=20)),
norm_f(Conv1d(512, 1024, 41, 4, groups=16, padding=20)),
norm_f(Conv1d(1024, 1024, 41, 1, groups=16, padding=20)),
norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
])
self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
def forward(self, x):
fmap = []
for l in self.convs:
x = l(x)
x = F.leaky_relu(x, LRELU_SLOPE)
fmap.append(x)
x = self.conv_post(x)
fmap.append(x)
x = torch.flatten(x, 1, -1)
return x, fmap
class MultiScaleDiscriminator(torch.nn.Module):
def __init__(self):
super(MultiScaleDiscriminator, self).__init__()
self.discriminators = nn.ModuleList([
DiscriminatorS(use_spectral_norm=True),
DiscriminatorS(),
DiscriminatorS(),
])
self.meanpools = nn.ModuleList([
AvgPool1d(4, 2, padding=2),
AvgPool1d(4, 2, padding=2)
])
def forward(self, y, y_hat):
y_d_rs = []
y_d_gs = []
fmap_rs = []
fmap_gs = []
for i, d in enumerate(self.discriminators):
if i != 0:
y = self.meanpools[i-1](y)
y_hat = self.meanpools[i-1](y_hat)
y_d_r, fmap_r = d(y)
y_d_g, fmap_g = d(y_hat)
y_d_rs.append(y_d_r)
fmap_rs.append(fmap_r)
y_d_gs.append(y_d_g)
fmap_gs.append(fmap_g)
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
def feature_loss(fmap_r, fmap_g):
loss = 0
for dr, dg in zip(fmap_r, fmap_g):
for rl, gl in zip(dr, dg):
loss += torch.mean(torch.abs(rl - gl))
return loss*2
def discriminator_loss(disc_real_outputs, disc_generated_outputs):
loss = 0
r_losses = []
g_losses = []
for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
r_loss = torch.mean((1-dr)**2)
g_loss = torch.mean(dg**2)
loss += (r_loss + g_loss)
r_losses.append(r_loss.item())
g_losses.append(g_loss.item())
return loss, r_losses, g_losses
def generator_loss(disc_outputs):
loss = 0
gen_losses = []
for dg in disc_outputs:
l = torch.mean((1-dg)**2)
gen_losses.append(l)
loss += l
return loss, gen_losses
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469'''EfficientSpeech: An On-Device Text to Speech Modelhttps://ieeexplore.ieee.org/abstract/document/10094639Rowel AtienzaApache 2.0 License2023'''
import torchimport torch.nn.functional as Ffrom torch import nnsymbols = [] # Replaced by the packaged Persian vocabulary during construction.from einops import repeat
class DynamicTanh(nn.Module): def __init__( self, normalized_shape, channels_last=True, alpha_init_value=0.5, activation="tanh", ): super().__init__() self.normalized_shape = normalized_shape self.alpha_init_value = alpha_init_value self.channels_last = channels_last self.activation = activation
self.alpha = nn.Parameter(torch.ones(1) * alpha_init_value) self.weight = nn.Parameter(torch.ones(normalized_shape)) self.bias = nn.Parameter(torch.zeros(normalized_shape))
def splitanh(self, x): a = 0.75 B = 1.25
z = self.alpha * x u = torch.abs(z) sign = torch.sign(z)
t = (u - a) / (B - a) y_turn = a + (1 - a) * (2 * t - t * t)
y_abs = torch.where(u <= a, u, y_turn) y_abs = torch.where(u >= B, torch.ones_like(u), y_abs)
return sign * y_abs
def forward(self, x): if self.activation == "splitanh": x = self.splitanh(x) else: x = torch.tanh(self.alpha * x) if self.channels_last: x = x * self.weight + self.bias else: x = x * self.weight[:, None, None] + self.bias[:, None, None] return x
class Encoder(nn.Module): """ Phoneme Encoder """
def __init__(self): super().__init__()
embed_dim=80 kernel_size=5 dim_out = 32 self.embed = nn.Embedding(len(symbols) + 1, embed_dim, padding_idx=0) self.b1_conv1 = nn.Conv1d(embed_dim, embed_dim, kernel_size=kernel_size, padding=kernel_size // 2) self.b1_dyt1 = DynamicTanh(embed_dim) self.b1_conv2 = nn.Conv1d(embed_dim, embed_dim, kernel_size=kernel_size, padding=kernel_size // 2) self.b1_dyt2 = DynamicTanh(embed_dim) self.b2_conv1 = nn.Conv1d(embed_dim, embed_dim, kernel_size=kernel_size, padding=kernel_size // 2) self.b2_dyt1 = DynamicTanh(embed_dim) self.b2_conv2 = nn.Conv1d(embed_dim, embed_dim, kernel_size=kernel_size, padding=kernel_size // 2) self.b2_dyt2 = DynamicTanh(embed_dim) self.linear = nn.Linear(embed_dim, dim_out)
def forward(self, phoneme, mask=None):
skip = self.embed(phoneme)
x = skip.permute(0, 2, 1) x = self.b1_conv1(x) x = x.permute(0, 2, 1) x = self.b1_dyt1(x) x = x.permute(0, 2, 1) x = self.b1_conv2(x) x = x.permute(0, 2, 1) x = self.b1_dyt2(x+skip)
skip = x x = skip.permute(0, 2, 1) x = self.b2_conv1(x) x = x.permute(0, 2, 1) x = self.b2_dyt1(x) x = x.permute(0, 2, 1) x = self.b2_conv2(x) x = x.permute(0, 2, 1) x = self.b2_dyt2(x+skip) x_32 = self.linear(x)
return x_32
class AcousticDecoder(nn.Module): """ Pitch, Duration, Energy Predictor """
def __init__(self, pitch_stats=None, energy_stats=None, duration_stats=None, duration=False): super().__init__() dim=32 self.conv1 = nn.Conv1d(dim, dim, kernel_size=3, padding=1) self.dyt1 = DynamicTanh(dim) self.conv2 = nn.Conv1d(dim, dim, kernel_size=3, padding=1) self.dyt2 = DynamicTanh(dim) self.linear = nn.Linear(dim, 1) self.duration = duration if pitch_stats is not None: pitch_min, pitch_max = pitch_stats self.pitch_bins = nn.Parameter(torch.linspace(pitch_min, pitch_max, dim - 1),\ requires_grad=False,) self.pitch_embedding = nn.Embedding(dim, dim) else: self.pitch_bins = None self.pitch_embedding = None
if energy_stats is not None: energy_min, energy_max = energy_stats self.energy_bins = nn.Parameter(torch.linspace(energy_min, energy_max, dim - 1), \ requires_grad=False,) self.energy_embedding = nn.Embedding(dim, dim) else: self.energy_bins = None self.energy_embedding = None
if duration_stats is not None: duration_min, duration_max = duration_stats self.duration_bins = nn.Parameter(torch.linspace(duration_min, duration_max, dim - 1), \ requires_grad=False,) self.duration_embedding = nn.Embedding(dim, dim) else: self.duration_bins = None self.duration_embedding = None
def get_pitch_embedding(self, pred, target, mask, control=1.): if target is not None: embedding = self.pitch_embedding(torch.bucketize(target, self.pitch_bins)) else: #pred = pred * control embedding = self.pitch_embedding(torch.bucketize(pred, self.pitch_bins)) return embedding
def get_energy_embedding(self, pred, target, mask, control=1.): if target is not None: embedding = self.energy_embedding(torch.bucketize(target, self.energy_bins)) else: #pred = pred * control embedding = self.energy_embedding(torch.bucketize(pred, self.energy_bins)) return embedding
def get_duration_embedding(self, pred, target, mask, control=1.): if target is not None: embedding = self.duration_embedding(torch.bucketize(target.float(), self.duration_bins)) else: embedding = self.duration_embedding(torch.bucketize(pred.float(), self.duration_bins)) return embedding
def get_embedding(self, pred, target, mask, control=1.): if self.pitch_embedding is not None: return self.get_pitch_embedding(pred, target, mask, control) elif self.energy_embedding is not None: return self.get_energy_embedding(pred, target, mask, control) elif self.duration_embedding is not None: return self.get_duration_embedding(pred, target, mask, control) return None
def forward(self, features):
y = features.permute(0, 2, 1) y = self.conv1(y) y = y.permute(0, 2, 1) y = self.dyt1(y) y = y.permute(0, 2, 1) y = self.conv2(y) y = y.permute(0, 2, 1) y = self.dyt2(y) y = self.linear(y) if self.duration: y = nn.ReLU()(y)+1 return y
class FeatureUpsampler(nn.Module): """ Upsample fused features using target or predicted duration"""
def __init__(self): super().__init__()
def forward(self, fused_features, fused_masks, duration, max_mel_len=None): mel_len = list() features = list() masks = list()
for feature, mask, repetition in zip(fused_features, fused_masks, duration): repetition = repetition.squeeze().int() feature = feature.repeat_interleave(repetition, dim=0) mask = mask.repeat_interleave(repetition, dim=0) mel_len.append(feature.shape[0]) if max_mel_len is not None: feature = F.pad(feature, (0, 0, 0, max_mel_len - feature.shape[0]), "constant", 0.0) mask = F.pad(mask, (0, 0, 0, max_mel_len - mask.shape[0]), "constant", True) features.append(feature) masks.append(mask)
if max_mel_len is None: max_mel_len = max(mel_len) features = [F.pad(feature, (0, 0, 0, max_mel_len - feature.shape[0]), "constant", 0.0) for feature in features] masks = [F.pad(mask, (0, 0, 0, max_mel_len - mask.shape[0]), "constant", True) for mask in masks]
features = torch.stack(features) masks = torch.stack(masks) len_pred = torch.IntTensor(mel_len).to(features.device) #len_pred = torch.LongTensor(mel_len).to(features.device)
return features, masks, len_pred
class MelDecoder(nn.Module): """ Mel Spectrogram Decoder """
def __init__(self): super().__init__()
dim_mel=80
self.proj = nn.Conv1d(dim_mel, dim_mel, kernel_size=9, padding=4, dilation=1, groups=dim_mel)
self.block1_dyt1 = DynamicTanh(dim_mel) self.block1_conv1_dw = nn.Conv1d(dim_mel, dim_mel, kernel_size=3, padding=1, dilation=1, groups=dim_mel) self.block1_conv1_pw = nn.Conv1d(dim_mel, dim_mel, kernel_size=1) self.block1_dyt2 = DynamicTanh(dim_mel) self.block1_conv2_dw = nn.Conv1d(dim_mel, dim_mel, kernel_size=3, padding=1, dilation=1, groups=dim_mel) self.block1_conv2_pw = nn.Conv1d(dim_mel, dim_mel, kernel_size=1) self.block2_dyt1 = DynamicTanh(dim_mel) self.block2_conv1_dw = nn.Conv1d(dim_mel, dim_mel, kernel_size=3, padding=3, dilation=3, groups=dim_mel) self.block2_conv1_pw = nn.Conv1d(dim_mel, dim_mel, kernel_size=1) self.block2_dyt2 = DynamicTanh(dim_mel) self.block2_conv2_dw = nn.Conv1d(dim_mel, dim_mel, kernel_size=3, padding=1, dilation=1, groups=dim_mel) self.block2_conv2_pw = nn.Conv1d(dim_mel, dim_mel, kernel_size=1)
self.block3_dyt1 = DynamicTanh(dim_mel) self.block3_conv1_dw = nn.Conv1d(dim_mel, dim_mel, kernel_size=3, padding=5, dilation=5, groups=dim_mel) self.block3_conv1_pw = nn.Conv1d(dim_mel, dim_mel, kernel_size=1) self.block3_dyt2 = DynamicTanh(dim_mel) self.block3_conv2_dw = nn.Conv1d(dim_mel, dim_mel, kernel_size=3, padding=1, dilation=1, groups=dim_mel) self.block3_conv2_pw = nn.Conv1d(dim_mel, dim_mel, kernel_size=1)
self.mel_linear_up = nn.Linear(dim_mel, 4*dim_mel) self.mel_dyt = DynamicTanh(4*dim_mel) self.mel_linear_down = nn.Linear(4*dim_mel, dim_mel)
def forward(self, features): x = features x = x.permute(0, 2, 1) x = self.proj(x) x = x.permute(0, 2, 1) skip = x x = self.block1_dyt1(skip) x = x.permute(0, 2, 1) x = self.block1_conv1_dw(x) x = self.block1_conv1_pw(x) x = x.permute(0, 2, 1) x = self.block1_dyt2(x) x = x.permute(0, 2, 1) x = self.block1_conv2_dw(x) x = self.block1_conv2_pw(x) x = x.permute(0, 2, 1)
skip = x + skip x = self.block2_dyt1(skip) x = x.permute(0, 2, 1) x = self.block2_conv1_dw(x) x = self.block2_conv1_pw(x) x = x.permute(0, 2, 1) x = self.block2_dyt2(x) x = x.permute(0, 2, 1) x = self.block2_conv2_dw(x) x = self.block2_conv2_pw(x) x = x.permute(0, 2, 1)
skip = x + skip x = self.block3_dyt1(skip) x = x.permute(0, 2, 1) x = self.block3_conv1_dw(x) x = self.block3_conv1_pw(x) x = x.permute(0, 2, 1) x = self.block3_dyt2(x) x = x.permute(0, 2, 1) x = self.block3_conv2_dw(x) x = self.block3_conv2_pw(x) x = x.permute(0, 2, 1) mel = self.mel_linear_up(x + skip) mel = self.mel_dyt(mel) mel = self.mel_linear_down(mel)
return mel
class PhonemeEncoder(nn.Module): """ Encodes phonemes to acoustic features """
def __init__(self, pitch_stats=None, energy_stats=None): super().__init__()
self.encoder = Encoder() self.feature_upsampler = FeatureUpsampler() self.pitch_decoder = AcousticDecoder(pitch_stats=pitch_stats) self.energy_decoder = AcousticDecoder(energy_stats=energy_stats) self.duration_decoder = AcousticDecoder(duration=True, duration_stats=(2, 34))
self.fusion_linear = nn.Linear(32*4, 80)
def forward(self, x, train=False): phoneme = x["phoneme"] phoneme_mask = x["phoneme_mask"] if phoneme.shape[0] > 1 else None
pitch_target = x["pitch"] if train else None energy_target = x["energy"] if train else None duration_target = x["duration"] if train else None mel_len = x["mel_len"] if train else None max_mel_len = torch.max(mel_len).item() if train else None
features = self.encoder(phoneme)
mask = None if phoneme_mask is not None: mask = repeat(phoneme_mask, 'b n -> b n a', a=features.shape[-1]) features = features.masked_fill(mask, 0) pitch_pred = self.pitch_decoder(features) pitch_features = self.pitch_decoder.get_embedding(pitch_pred, pitch_target, mask) pitch_features = pitch_features.squeeze() if mask is not None: pitch_features = pitch_features.masked_fill(mask, 0) elif pitch_features.dim() != 3: pitch_features = pitch_features.unsqueeze(0)
energy_pred = self.energy_decoder(features) energy_features = self.energy_decoder.get_embedding(energy_pred, energy_target, mask) energy_features = energy_features.squeeze()
if mask is not None: energy_features = energy_features.masked_fill(mask, 0) elif energy_features.dim() != 3: energy_features = energy_features.unsqueeze(0)
duration_pred = self.duration_decoder(features) # Persian boundary tokens may have zero acoustic duration; speech phones retain >=1. if hasattr(self, "boundary_token_ids"): boundary = torch.zeros_like(phoneme, dtype=torch.bool) for token_id in self.boundary_token_ids: boundary |= phoneme == token_id duration_pred = torch.where(boundary.unsqueeze(-1), (duration_pred - 1.0).clamp(min=0), duration_pred) duration_features = self.duration_decoder.get_embedding(duration_pred, duration_target, mask) duration_features = duration_features.squeeze() if mask is not None: duration_features = duration_features.masked_fill(mask, 0) elif duration_features.dim() != 3: duration_features = duration_features.unsqueeze(0) fused_features = torch.cat([features, pitch_features, \ energy_features, duration_features], dim=-1)
fused_features = self.fusion_linear(fused_features)
if phoneme_mask is not None: fused_masks = repeat(phoneme_mask, 'b n -> b n a', a=fused_features.shape[-1]) fused_features = fused_features.masked_fill(fused_masks, 0) else: fused_masks = torch.zeros_like(fused_features).bool() if duration_target is None: duration_target = torch.round(duration_pred).squeeze() if phoneme_mask is not None: duration_target = duration_target.masked_fill(phoneme_mask, 0).clamp(min=0) else: duration_target = duration_target.unsqueeze(0)
features, masks, mel_len_pred = self.feature_upsampler(fused_features, fused_masks, duration=duration_target, max_mel_len=max_mel_len,) if mask is None: masks = None
y = {"pitch": pitch_pred, "energy": energy_pred, "duration": duration_pred, "mel_len": mel_len_pred, "features": features, "masks": masks, }
return y
class Phoneme2Mel(nn.Module): """ From Phoneme Sequence to Mel Spectrogram """
def __init__(self, encoder, decoder): super().__init__()
self.encoder = encoder self.decoder = decoder
def forward(self, x, train=False): # Dirty trick to enable ONNX compilation. # Else, the torch.to_onnx complains about missing input in the forward method. if isinstance(x, list): x = x[0] pred = self.encoder(x, train=train) mel = self.decoder(pred["features"]) mask = pred["masks"] if mask is not None and mel.size(0) > 1: mask = mask[:, :, :1].expand(-1, -1, mel.shape[-1]) mel = mel.masked_fill(mask, 0) pred["mel"] = mel
if train: return pred
return mel, pred["mel_len"], pred["duration"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Deterministic Persian text normalization before G2P.
The G2P model should predict pronunciation, not perform arithmetic. This moduleexpands the number forms that previously caused structural decoder failures whileleaving punctuation available to the pacing layer."""
from __future__ import annotations
import re
_DIGIT_TRANSLATION = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789")_ONES = ("صفر", "یک", "دو", "سه", "چهار", "پنج", "شش", "هفت", "هشت", "نه")_TEENS = { 10: "ده", 11: "یازده", 12: "دوازده", 13: "سیزده", 14: "چهارده", 15: "پانزده", 16: "شانزده", 17: "هفده", 18: "هجده", 19: "نوزده",}_TENS = {20: "بیست", 30: "سی", 40: "چهل", 50: "پنجاه", 60: "شصت", 70: "هفتاد", 80: "هشتاد", 90: "نود"}_HUNDREDS = {100: "صد", 200: "دویست", 300: "سیصد", 400: "چهارصد", 500: "پانصد", 600: "ششصد", 700: "هفتصد", 800: "هشتصد", 900: "نهصد"}_SCALES = ((10**12, "تریلیون"), (10**9, "میلیارد"), (10**6, "میلیون"), (10**3, "هزار"))_NUMBER = re.compile( r"(?<![\w])(?P<sign>[+\-−]?)(?P<int>[0-9]+(?:[٬,][0-9]{3})*)(?:(?P<decimal>[٫.])(?P<fraction>[0-9]+))?(?P<percent>[٪%])?(?![\w])")
def integer_to_persian(number: int) -> str: if number < 0: return "منفی " + integer_to_persian(-number) if number < 10: return _ONES[number] if number < 20: return _TEENS[number] if number < 100: tens, rest = divmod(number, 10) parts = [_TENS[tens * 10]] if rest: parts.append(_ONES[rest]) return " و ".join(parts) if number < 1000: hundreds, rest = divmod(number, 100) parts = [_HUNDREDS[hundreds * 100]] if rest: parts.append(integer_to_persian(rest)) return " و ".join(parts) for scale, label in _SCALES: if number >= scale: count, rest = divmod(number, scale) parts = [f"{integer_to_persian(count)} {label}"] if rest: parts.append(integer_to_persian(rest)) return " و ".join(parts) raise ValueError(f"number is outside the supported range: {number}")
def _expand_number(match: re.Match[str]) -> str: integer_digits = match.group("int").replace("٬", "").replace(",", "") parts: list[str] = [] sign = match.group("sign") if sign in {"-", "−"}: parts.append("منفی") elif sign == "+": parts.append("مثبت") parts.append(integer_to_persian(int(integer_digits))) fraction = match.group("fraction") if fraction is not None: parts.append("ممیز") parts.append(" ".join(_ONES[int(digit)] for digit in fraction)) if match.group("percent"): parts.append("درصد") return " ".join(parts)
def normalize_persian_for_g2p(text: str) -> str: """Expand Persian/Arabic/ASCII numerals and retain authored punctuation.""" ascii_digits = str(text).translate(_DIGIT_TRANSLATION) return _NUMBER.sub(_expand_number, ascii_digits)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""Self-contained inference for Gooya v2 experimental releases."""from pathlib import Pathimport json,re,warningsimport numpy as npimport torchfrom torch import nnfrom torch.nn import functional as Ffrom torch.nn.utils.rnn import pack_padded_sequence,pad_packed_sequencefrom torch.nn.utils import weight_normfrom safetensors.torch import load_filefrom transformers import AutoTokenizer,AutoModelForSeq2SeqLMfrom .networks import PhonemeEncoder,MelDecoder,Phoneme2Melfrom .hifigan import Generatorfrom .normalize import normalize_persian_for_g2pfrom .words import surface_words
class ContextEncoder(nn.Module): def __init__(self,local): super().__init__(); self.local=local; self.context=nn.GRU(80,128,batch_first=True,bidirectional=True); self.project=nn.Linear(256,32); self.dropout=nn.Dropout(.1) def forward(self,phones): x=self.local.embed(phones); lengths=(phones!=0).sum(-1).cpu() packed=pack_padded_sequence(x,lengths,batch_first=True,enforce_sorted=False) y,_=self.context(packed); y,_=pad_packed_sequence(y,batch_first=True,total_length=phones.shape[1]) return self.local(phones)+self.project(self.dropout(y))
class SmoothDuration(nn.Module): def __init__(self,original): super().__init__(); self.original=original; self.original.duration=False def forward(self,x): return F.softplus(self.original(x))+1 def get_embedding(self,*args,**kwargs): return self.original.get_embedding(*args,**kwargs)
class AttrDict(dict): __getattr__=dict.__getitem__
class GooyaTTS: """Loads all model weights locally. CPU is the default; CUDA is optional.""" def __init__(self,model_dir,device='cpu',num_threads=4): self.root=Path(model_dir); self.device=torch.device(device) if num_threads: torch.set_num_threads(num_threads) self.config=json.loads((self.root/'gooya_config.json').read_text()); self.sample_rate=self.config['sample_rate']; self.ids=self.config['vocabulary'] self.tokenizer=AutoTokenizer.from_pretrained(self.root/'frontend',local_files_only=True) self.g2p=AutoModelForSeq2SeqLM.from_pretrained(self.root/'frontend',local_files_only=True).to(self.device).eval() stats=self.config['stats']; encoder=PhonemeEncoder(pitch_stats=stats['pitch'][:2],energy_stats=stats['energy'][:2]); decoder=MelDecoder() encoder.encoder.embed=nn.Embedding(len(self.ids),80,padding_idx=0) encoder.boundary_token_ids=[i for s,i in self.ids.items() if s.startswith('<')] encoder.encoder=ContextEncoder(encoder.encoder); encoder.duration_decoder=SmoothDuration(encoder.duration_decoder) decoder.mel_linear_down=nn.Linear(320,100); self.acoustic=Phoneme2Mel(encoder,decoder) self.acoustic.load_state_dict(load_file(str(self.root/'acoustic.safetensors')),strict=True); self.acoustic.to(self.device).eval() self.vocoder=Generator(AttrDict(self.config['vocoder_config'])); self.vocoder.conv_pre=weight_norm(nn.Conv1d(100,128,7,1,padding=3)) self.vocoder.load_state_dict(load_file(str(self.root/'vocoder.safetensors')),strict=True); self.vocoder.to(self.device).eval() self.overlay={} if self.config['frontend']['overlay']: data=json.loads((self.root/'frontend/overlay.json').read_text()); self.overlay={(r['surface'],r['raw']):r['target'] for r in data['rules']} count=sum(p.numel() for m in [self.g2p,self.acoustic,self.vocoder] for p in m.parameters()) if count!=self.config['parameters']['total']: raise ValueError(f'Parameter count mismatch: {count}') @classmethod def from_pretrained(cls,repo_id,revision=None,**kwargs): from huggingface_hub import snapshot_download return cls(snapshot_download(repo_id,revision=revision),**kwargs) @torch.inference_mode() def synthesize(self,text,return_details=False): if not isinstance(text,str) or not text.strip(): raise ValueError('Text must be a nonempty string.') chunks=re.findall(r'[^،,؟?\.\n]+[،,؟?\.]?',text); waves=[]; records=[] for chunk in chunks: chunk=chunk.strip() if not chunk: continue normalized=normalize_persian_for_g2p(chunk) x=self.tokenizer(normalized,return_tensors='pt',add_special_tokens=False).to(self.device) if x['input_ids'].shape[1]>1024: raise ValueError('Clause exceeds 1024 input tokens; use shorter sentences or punctuation.') output=self.g2p.generate(**x,max_new_tokens=self.config['frontend']['max_new_tokens'],num_beams=self.config['frontend']['num_beams']) if self.tokenizer.eos_token_id not in output[0,1:].tolist(): raise RuntimeError('G2P did not terminate. Split this clause into shorter phrases; no incomplete audio was returned.') phones=self.tokenizer.decode(output[0],skip_special_tokens=True).strip().replace('?','Q') words=surface_words(normalized); pw=phones.split(); matched=len(words)==len(pw) if self.overlay and matched: phones=' '.join(self.overlay.get((a,b),b) for a,b in zip(words,pw)) if not matched: warnings.warn('G2P word count differs from input; inspect pronunciation in returned details.',RuntimeWarning) if not phones: raise RuntimeError('G2P returned an empty pronunciation.') tokens=['<sil>']+['<wb>' if c==' ' else c for c in phones]+['<comma>' if chunk[-1] in '،,' else '<stop>'] unknown=set(tokens)-set(self.ids) if unknown: raise ValueError(f'Unsupported G2P symbols: {sorted(unknown)}') encoded=torch.tensor([[self.ids[t] for t in tokens]],device=self.device) pred=self.acoustic.encoder({'phoneme':encoded},train=False); mel=self.acoustic.decoder(pred['features']) if mel.shape[1]>24000//256*120: raise RuntimeError('Predicted clause duration exceeds 120 seconds.') wave=self.vocoder(F.pad(mel.transpose(1,2),(4,4),mode='replicate'))[:,:,1024:-1024].squeeze().cpu().numpy() if not np.isfinite(wave).all(): raise RuntimeError('Nonfinite audio output.') waves.append(wave); gap=self.config['comma_gap_seconds'] if chunk[-1] in '،,' else self.config['sentence_gap_seconds']; waves.append(np.zeros(round(gap*self.sample_rate),dtype=np.float32)) records.append({'text':chunk,'normalized':normalized,'phonemes':phones,'word_count_matches':matched,'duration_seconds':len(wave)/self.sample_rate}) if not waves: raise ValueError('No speakable text found.') result=np.concatenate(waves[:-1]); details={'text':text,'model':self.config['name'],'parameters':self.config['parameters'],'sample_rate':self.sample_rate,'segments':records,'duration_seconds':len(result)/self.sample_rate} return (result,details) if return_details else result123456789101112131415161718192021import unicodedata
def surface_words(text: str) -> list[str]: """Dependency-free equivalent of Gooya's ZWNJ-preserving word scan.""" result: list[str] = [] cursor = 0 while cursor < len(text): if text[cursor].isspace(): cursor += 1 continue is_word = text[cursor] == "\u200c" or unicodedata.category(text[cursor])[0] in {"L", "M", "N"} if not is_word: cursor += 1 continue start = cursor cursor += 1 while cursor < len(text) and (text[cursor] == "\u200c" or unicodedata.category(text[cursor])[0] in {"L", "M", "N"}): cursor += 1 result.append(text[start:cursor]) return result
12345678910111213from pathlib import Pathimport argparse,jsonimport soundfile as sffrom gooya_tts import GooyaTTS
def main(): parser=argparse.ArgumentParser(description='Standalone Persian text-to-speech; all weights loaded from this package.') source=parser.add_mutually_exclusive_group(required=True);source.add_argument('--text');source.add_argument('--text-file',type=Path) parser.add_argument('--model-dir',type=Path,default=Path(__file__).resolve().parent);parser.add_argument('--output',type=Path,default=Path('output.wav'));parser.add_argument('--device',default='cpu');parser.add_argument('--threads',type=int,default=4) args=parser.parse_args();text=args.text if args.text is not None else args.text_file.read_text(encoding='utf-8') model=GooyaTTS(args.model_dir,device=args.device,num_threads=args.threads);wave,details=model.synthesize(text,return_details=True) args.output.parent.mkdir(parents=True,exist_ok=True);sf.write(args.output,wave,model.sample_rate,subtype='FLOAT');args.output.with_suffix('.json').write_text(json.dumps(details,ensure_ascii=False,indent=2),encoding='utf-8');print(f'Wrote {args.output} ({details["duration_seconds"]:.2f} seconds, {model.sample_rate} Hz)')if __name__=='__main__':main()123456789101112131415161718192021MIT License
Copyright (c) 2020 Jungil Kong
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.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.123456789101112131415161718192021222324252627{ "acoustic_checkpoint_sha256": "e237160c1c2a8afc7a1f44ae323cd0a4d87fdba13826879139d546c4b7bfa472", "vocoder_checkpoint_sha256": "9c007b9b4f58fa65d29b947e8ce09f3564638c0aca1bc60e0d02e182c81892b0", "acoustic_step": 10413, "vocoder_step": 29000, "acoustic_training": { "train_rows": 9255, "dev_rows": 2337, "train_hours": 19.09963390625, "dev_hours": 5.477470677083333, "held_rows": 4502, "source_rows": 16094, "label_field": "label", "split": "parent recording SHA256 disjoint", "epochs": 100, "batch_size": 8, "device": "cuda", "initialization": "upstream warm weights; new Persian embedding and native 100-mel projection", "vocoder": "frozen charactr/vocos-mel-24khz" }, "grain_speech_commit": "8b38829809a6f86a9699371adc487c1efb875b05", "acoustic_dataset": "Reza2kn/nasle-mana-clean-chunked-30s-avasanj", "dataset_revision": "606ecdc1d93a77c6f3a452ab5721774248cdf587", "g2p_source": "Negara v7.1 with overlay", "waveform_training": "50,000 updates; generator selected on 96 dev excerpts; discriminators excluded", "frontend_evaluation": null}123456789101112[build-system]requires = ["setuptools>=68"]build-backend = "setuptools.build_meta"[project]name = "gooya-tts-experimental"version = "2.0.0"requires-python = ">=3.10"dynamic = ["dependencies"][tool.setuptools.dynamic]dependencies = {file = ["requirements.txt"]}[tool.setuptools.packages.find]include = ["gooya_tts*"]1234567torch>=2.6,<3transformers>=4.57,<6safetensors>=0.5huggingface_hub>=0.34numpy>=1.26soundfile>=0.12einops>=0.812345678910111213141516171819202122232425{ "status": "passed", "environment": "clean isolated Python venv; package copied into a temporary directory; empty HF cache; offline env flags; CPU inference", "python": "3.13.11", "sample_seconds": 17.412666666666667, "sample_rate": 24000, "sample_max_abs_delta_against_listened_reference": 0.0, "sample_segments": 6, "numeric_smoke_text": "\u0627\u0645\u0631\u0648\u0632 \u06f2\u06f4 \u0646\u0641\u0631 \u0622\u0645\u062f\u0646\u062f. \u0633\u0627\u0639\u062a \u06f3 \u0627\u0633\u062a.", "numeric_smoke_seconds": 3.3186666666666667, "checks": [ "strict safetensors state loading", "exact architecture parameter count", "nonempty finite audio", "all G2P segments emitted EOS", "requested sample waveform parity <1e-4", "separate number-normalization inference" ], "not_tested": [ "human accuracy of numeral sample", "Windows/macOS/mobile runtime", "FP16 or quantized inference", "old-device latency" ]}123version https://git-lfs.github.com/spec/v1oid sha256:081fb32646d70590e52926115b13481753c6d846647111a502cc93c3295a0a67size 3807768.gitattributes+2
LICENSEAdded+201
NOTICEAdded+6
README.mdAdded+111
SHA256SUMS.jsonAdded+126
acoustic.safetensorsAdded+3
environment.jsonAdded+13
examples/example.txtAdded+2
examples/reference.wavAdded+3
examples/standalone.jsonAdded+56
examples/standalone.wavAdded+3
frontend/added_tokens.jsonAdded+127
frontend/config.jsonAdded+32
frontend/generation_config.jsonAdded+6
frontend/model.safetensorsAdded+3
frontend/overlay.jsonAdded+1
frontend/special_tokens_map.jsonAdded+23
frontend/tokenizer_config.jsonAdded+1040
gooya_config.jsonAdded+234
gooya_tts/__init__.pyAdded+2
gooya_tts/hifigan.pyAdded+292
gooya_tts/networks.pyAdded+469
gooya_tts/normalize.pyAdded+77
gooya_tts/runtime.pyAdded+89
gooya_tts/words.pyAdded+21
infer.pyAdded+13
licenses/HiFi-GAN-MIT.txtAdded+21
licenses/Negara-Apache-2.0.txtAdded+202
provenance.jsonAdded+27
pyproject.tomlAdded+12
requirements.txtAdded+7
verification.jsonAdded+25
vocoder.safetensorsAdded+3