Renderlib-dev vanshp123 commited on
Commit
bccbc5b
·
0 Parent(s):

Duplicate from bharatgenai/sooktam2

Browse files

Co-authored-by: Vansh Pundir <vanshp123@users.noreply.huggingface.co>

Files changed (46) hide show
  1. .gitattributes +36 -0
  2. .gitignore +217 -0
  3. LICENSE +50 -0
  4. README.md +174 -0
  5. config.json +13 -0
  6. hf_auto.py +18 -0
  7. model_1250000.pt +3 -0
  8. poetry.lock +0 -0
  9. pyproject.toml +74 -0
  10. ref.wav +3 -0
  11. setup-cls.sh +32 -0
  12. sooktam.safetensors +3 -0
  13. src/f5_tts/api.py +174 -0
  14. src/f5_tts/configs/E2TTS_Base.yaml +22 -0
  15. src/f5_tts/configs/E2TTS_Small.yaml +22 -0
  16. src/f5_tts/configs/F5TTS_Base.yaml +27 -0
  17. src/f5_tts/configs/F5TTS_Small.yaml +27 -0
  18. src/f5_tts/configs/F5TTS_v1_Base.yaml +28 -0
  19. src/f5_tts/configs/F5TTS_v1_Base_frame.yaml +28 -0
  20. src/f5_tts/hf_auto.py +228 -0
  21. src/f5_tts/infer/README.md +177 -0
  22. src/f5_tts/infer/SHARED.md +193 -0
  23. src/f5_tts/infer/cls_tokenizer_v2.py +181 -0
  24. src/f5_tts/infer/examples/basic/basic.toml +11 -0
  25. src/f5_tts/infer/examples/multi/story.toml +20 -0
  26. src/f5_tts/infer/examples/multi/story.txt +1 -0
  27. src/f5_tts/infer/examples/vocab.txt +2545 -0
  28. src/f5_tts/infer/hf_infer.py +98 -0
  29. src/f5_tts/infer/infer_api.py +367 -0
  30. src/f5_tts/infer/infer_cli.py +383 -0
  31. src/f5_tts/infer/infer_cli_resized_vocab.py +521 -0
  32. src/f5_tts/infer/infer_gradio.py +1121 -0
  33. src/f5_tts/infer/speech_edit.py +205 -0
  34. src/f5_tts/infer/utils_infer.py +765 -0
  35. src/f5_tts/model/__init__.py +5 -0
  36. src/f5_tts/model/backbones/README.md +20 -0
  37. src/f5_tts/model/backbones/dit.py +318 -0
  38. src/f5_tts/model/backbones/mmdit.py +212 -0
  39. src/f5_tts/model/backbones/unett.py +279 -0
  40. src/f5_tts/model/cfm.py +320 -0
  41. src/f5_tts/model/modules.py +790 -0
  42. src/f5_tts/model/utils.py +318 -0
  43. src/f5_tts/socket_client.py +63 -0
  44. src/f5_tts/socket_server.py +268 -0
  45. test.py +34 -0
  46. vocab.txt +543 -0
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ ref.wav filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Customed
2
+ .vscode/
3
+ tests/
4
+ runs/
5
+ data
6
+ data/
7
+ ckpts/
8
+ wandb/
9
+ results/
10
+ packaged_results/
11
+ packaged_results_backup/
12
+ outputs/
13
+ data/
14
+ data
15
+ ray_results/
16
+ hindi_models.zip
17
+ hindi_models
18
+ pretrained_model.safetensors
19
+ awscliv2.zip
20
+ sukumo28.wav-preview-2.6.0 (1).vsix
21
+
22
+ hf_inference_models/
23
+ # Byte-compiled / optimized / DLL files
24
+ __pycache__/
25
+ *.py[cod]
26
+ *$py.class
27
+
28
+ ckpts/
29
+ data/
30
+
31
+
32
+ # C extensions
33
+ *.so
34
+ .cursor
35
+ # Distribution / packaging
36
+ .Python
37
+ build/
38
+ develop-eggs/
39
+ dist/
40
+ downloads/
41
+ eggs/
42
+ .eggs/
43
+ lib/
44
+ lib64/
45
+ parts/
46
+ sdist/
47
+ var/
48
+ wheels/
49
+ share/python-wheels/
50
+ *.egg-info/
51
+ .installed.cfg
52
+ *.egg
53
+ MANIFEST
54
+
55
+ # PyInstaller
56
+ # Usually these files are written by a python script from a template
57
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
58
+ *.manifest
59
+ *.spec
60
+
61
+ # Installer logs
62
+ pip-log.txt
63
+ pip-delete-this-directory.txt
64
+
65
+ # Unit test / coverage reports
66
+ htmlcov/
67
+ .tox/
68
+ .nox/
69
+ .coverage
70
+ .coverage.*
71
+ .cache
72
+ nosetests.xml
73
+ coverage.xml
74
+ *.cover
75
+ *.py,cover
76
+ .hypothesis/
77
+ .pytest_cache/
78
+ cover/
79
+
80
+ # Translations
81
+ *.mo
82
+ *.pot
83
+
84
+ # Django stuff:
85
+ *.log
86
+ local_settings.py
87
+ db.sqlite3
88
+ db.sqlite3-journal
89
+
90
+ # Flask stuff:
91
+ instance/
92
+ .webassets-cache
93
+
94
+ # Scrapy stuff:
95
+ .scrapy
96
+
97
+ # Sphinx documentation
98
+ docs/_build/
99
+
100
+ # PyBuilder
101
+ .pybuilder/
102
+ target/
103
+ results/
104
+ # Jupyter Notebook
105
+ .ipynb_checkpoints
106
+
107
+ # IPython
108
+ profile_default/
109
+ ipython_config.py
110
+
111
+ # pyenv
112
+ # For a library or package, you might want to ignore these files since the code is
113
+ # intended to run in multiple environments; otherwise, check them in:
114
+ # .python-version
115
+
116
+ # pipenv
117
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
118
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
119
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
120
+ # install all needed dependencies.
121
+ #Pipfile.lock
122
+
123
+ # poetry
124
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
125
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
126
+ # commonly ignored for libraries.
127
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
128
+ #poetry.lock
129
+
130
+ # pdm
131
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
132
+ #pdm.lock
133
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
134
+ # in version control.
135
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
136
+ .pdm.toml
137
+ .pdm-python
138
+ .pdm-build/
139
+
140
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
141
+ __pypackages__/
142
+
143
+ # Celery stuff
144
+ celerybeat-schedule
145
+ celerybeat.pid
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .venv
153
+ env/
154
+ venv/
155
+ ENV/
156
+ env.bak/
157
+ venv.bak/
158
+
159
+ # Spyder project settings
160
+ .spyderproject
161
+ .spyproject
162
+
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ #.idea/
190
+ 5066549580888614_chunk_5_0000076.wav
191
+
192
+ hindi_models.zip
193
+ hindi_models/whisper-large-hi-noldcil/pytorch_model.bin
194
+ hindi_models/whisper-medium-hi_alldata_multigpu/pytorch_model.bin
195
+ pretrained_model.safetensors
196
+ awscliv2.zip
197
+ src/third_party/BigVGAN/filelists/LibriTTS/train-full.txt
198
+ src/third_party/BigVGAN/demo/examples/megalovania_24k.wav
199
+ hindi_models/whisper-large-hi-noldcil/vocab.json
200
+ src/third_party/BigVGAN/demo/examples/musdbhq_44k.wav
201
+ src/third_party/BigVGAN/demo/examples/musiccaps1_44k.wav
202
+ src/third_party/BigVGAN/demo/examples/musiccaps2_44k.wav
203
+ (1).vsix
204
+ src/third_party/BigVGAN/demo/examples/hifitts_44k.wav
205
+ hindi_models/whisper-large-hi-noldcil/merges.txt
206
+ src/third_party/BigVGAN/demo/examples/jensen_24k.wav
207
+ src/third_party/BigVGAN/demo/examples/dance_24k.wav
208
+ src/third_party/BigVGAN/demo/examples/queen_24k.wav
209
+ hindi_models/whisper-large-hi-noldcil/trainer_state.json
210
+ src/f5_tts/infer/examples/basic/basic_ref_zh.wav
211
+ hindi_models/whisper-medium-hi_alldata_multigpu/trainer_state.json
212
+ src/third_party/BigVGAN/demo/examples/libritts_24k.wav
213
+ src/f5_tts/infer/examples/multi/main.flac
214
+ src/f5_tts/infer/examples/basic/basic_ref_en.wav
215
+ src/f5_tts/infer/examples/multi/town.flac
216
+ hindi_models/whisper-large-hi-noldcil/preprocessor_config.json
217
+ src/f5_tts/infer/examples/multi/country.flac
LICENSE ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BharatGen Research License (BRL)
2
+ Last Updated: August 7, 2025
3
+ Note: This license is subject to change. Please refer to the latest version before using any BharatGen resource.
4
+
5
+ 1. Scope and Acceptance
6
+ - This license applies to any use, modification, or distribution of BharatGen Models, Derivatives, or Outputs.
7
+ - By accessing, using, modifying, or distributing a BharatGen Model or its Derivatives, or by creating Outputs from them, you agree to be bound by this License.
8
+ - If you accept on behalf of an organization, you represent that you have authority to do so.
9
+
10
+ 2. Permitted Use
11
+ - You are granted a non-exclusive, non-transferable, royalty-free license to use, modify, and distribute BharatGen Models and Derivatives strictly for non-commercial research and academic purposes.
12
+ - You must retain the following notice in all copies and distributions:
13
+
14
+ "Licensed by BharatGen under the BharatGen Research License."
15
+ - If you create Derivatives, you must clearly indicate that modifications were made by you.
16
+ - You must not use BharatGen Models, Derivatives, or Outputs for any commercial purposes without prior written permission from the BharatGen legal team.
17
+
18
+ 3. Commercial Use & Modifications
19
+ - Commercial use is strictly prohibited unless you obtain explicit written permission from the BharatGen legal team.
20
+ - If you wish to release, share, publish, fine-tune, or deploy any BharatGen Models or Derivatives (including Outputs) publicly, you must request and receive written approval from the BharatGen team.
21
+ Please reach out via our contact form or designated email.
22
+
23
+ 4. Limitations
24
+ - You must not claim that your modifications, Derivatives, or Outputs are official BharatGen products.
25
+ - You may not use BharatGen resources for any unlawful or unethical purposes.
26
+ - Redistribution of BharatGen resources through SaaS, APIs, or any hosted service—even for free—requires permission.
27
+
28
+ 5. Outputs
29
+ - You own the content (Outputs) you generate using BharatGen models, subject to the non-commercial restriction.
30
+ - You are fully responsible for the Outputs you generate and their usage.
31
+
32
+ 6. Disclaimer & Liability
33
+ - BharatGen resources are provided "AS IS", without warranties of any kind.
34
+ - The BharatGen team are not liable for any damages arising from the use of BharatGen Models, Derivatives, or Outputs.
35
+
36
+ 7. Termination
37
+ - This license is valid until terminated.
38
+ - It will terminate immediately if you breach any of its terms. Upon termination, you must stop using and delete all copies of the Models and Derivatives.
39
+
40
+ 8. Jurisdiction
41
+ This License is governed by the laws of India. Any disputes shall be subject to the courts of India.
42
+
43
+ Definitions
44
+ BharatGen Model: Any model, code, data, or related resource released under this license.
45
+ Derivative: Any modification, fine-tuning, or adaptation of a BharatGen Model.
46
+ Output: Any result generated by running a BharatGen Model.
47
+ You: Any individual or organization using BharatGen resources.
48
+ Non-commercial research: Use in academic, personal, or scientific contexts not intended to generate revenue.
49
+
50
+ If you have questions or require a commercial license, please contact the BharatGen team.
README.md ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ - hi
5
+ - mr
6
+ - gu
7
+ - ta
8
+ - te
9
+ - kn
10
+ - bn
11
+ - ml
12
+ - or
13
+ - ur
14
+ - pa
15
+ pipeline_tag: text-to-speech
16
+ library_name: transformers
17
+ tags:
18
+ - text-to-speech
19
+ - tts
20
+ - multilingual
21
+ - indic
22
+ - f5-tts
23
+ - sooktam2
24
+ ---
25
+
26
+ <p align="center">
27
+ <img src="https://cdn-avatars.huggingface.co/v1/production/uploads/67b462a1f4f414c2b3e2bc2f/EnVeNWEIeZ6yF6ueZ7E3Y.jpeg" width="140" alt="BharatGen Logo"/>
28
+ </p>
29
+
30
+ <h1 align="center">Sooktam-2 🇮🇳</h1>
31
+ <p align="center"><em>"विविधता में ही भारत की शक्ति है, और हर भाषा उस शक्ति की आवाज़ है।"</em></p>
32
+ <p align="center"><b>Sovereign AI · Built in Bharat · For Bharat</b></p>
33
+
34
+ ---
35
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1YvgkOL7mM7vcOE8IHOhHD9PprYUh5bvb)
36
+
37
+ ## The Story
38
+
39
+ India is not one voice - it is a symphony. Tamil, Bengali, Urdu, Hindi, Kannada - each a living civilisation, spoken daily by hundreds of millions. Yet for too long, AI treated them as afterthoughts. Models built elsewhere, for someone else, leaving Bharat to make do with approximations of its own languages.
40
+
41
+ **BharatGen was built to end that.** We are India's sovereign AI initiative - weaving the country's languages, cultures, and voices into technology that is truly Indian. Not adapted. Not translated. *Built from the ground up, for Bharat.*
42
+
43
+ **Sooktam-2** is our answer to India's need for a voice. A Text-to-Speech model that speaks 12 languages (11 indian languages + 1 indian english) with the phonetic precision, prosody, and cultural soul they deserve - so that every Indian, in every state, can hear AI speak *their* language, in *their* accent, and feel at home.
44
+
45
+ This is **GenAI for Bharat, by Bharat.**
46
+
47
+ ---
48
+
49
+ ## What is Sooktam-2?
50
+
51
+ Sooktam-2 is a sovereign multilingual Text-to-Speech model built by BharatGen. It synthesises natural, expressive speech across India's major languages using reference-guided voice conditioning - preserving the speaker's voice, accent, and cultural cadence.
52
+
53
+ **Represented Languages - 12**
54
+
55
+ `Hindi` · `Marathi` · `Gujarati` · `Tamil` · `Telugu` · `Kannada` · `Bengali` · `Malayalam` · `Odia` · `Urdu` · `Punjabi` · `Indian English`
56
+
57
+ **Key Capabilities**
58
+ - Reference-guided voice cloning
59
+ - Multilingual Indic speech synthesis
60
+ - Natural prosody and expressive delivery
61
+ - Language-aware CLS tokenization for accurate Indic phonetics
62
+ - Production-quality audio output, deployment-ready at scale
63
+
64
+ ---
65
+
66
+ ## Quickstart
67
+
68
+ - Python version = 3.10
69
+
70
+ ```bash
71
+ git clone https://huggingface.co/bharatgenai/sooktam2
72
+ cd sooktam2
73
+ sh setup-cls.sh
74
+ ```
75
+
76
+ ---
77
+
78
+ ## Python Inference
79
+
80
+ ```python
81
+ import os
82
+ from transformers import AutoModel
83
+
84
+ # --- Model ID ---
85
+ MODEL_ID = "bharatgenai/sooktam2"
86
+
87
+ # --- Your reference audio and target text ---
88
+ REF_AUDIO = "reference.wav" # A short, clean voice clip (3–10 sec)
89
+ REF_TEXT = "सर, मैं तब से यह कह रहा हूँ कि मैंने अपना टिकट कैंसल कर दिया है, लेकिन अब तक मेरे पैसे वापस नहीं आए हैं। आप इस मामले को देखेंगे भी या नहीं?"
90
+ GEN_TEXT = "यह एक टेस्ट वाक्य है जिसे आवाज़ में बदलना है।"
91
+
92
+ # --- Output ---
93
+ OUT_DIR = "outputs"
94
+ OUT_WAV = os.path.join(OUT_DIR, "sooktam_cls.wav")
95
+
96
+ # --- Load model (auto-downloads checkpoint + vocab from HuggingFace) ---
97
+ model = AutoModel.from_pretrained(
98
+ MODEL_ID,
99
+ trust_remote_code=True,
100
+ )
101
+
102
+ os.makedirs(OUT_DIR, exist_ok=True)
103
+
104
+ # CLS tokenization is handled inside utils_infer via cls_tokenizer_v2
105
+ wav, sr, _ = model.infer(
106
+ ref_file=REF_AUDIO,
107
+ ref_text=REF_TEXT,
108
+ gen_text=GEN_TEXT,
109
+ tokenizer="cls",
110
+ cls_language="hindi",
111
+ file_wave=OUT_WAV,
112
+ )
113
+
114
+ print("Saved:", OUT_WAV, "sample_rate:", sr, "samples:", len(wav))
115
+ ```
116
+
117
+ > The model and vocab download automatically from HuggingFace on first run. No manual checkpoint hunting required.
118
+
119
+ ---
120
+
121
+ ## Hugging Face AutoModel
122
+
123
+ ```python
124
+ from transformers import AutoModel
125
+
126
+ model = AutoModel.from_pretrained(
127
+ "bharatgenai/sooktam2",
128
+ trust_remote_code=True,
129
+ )
130
+
131
+ wav, sr, _ = model.infer(
132
+ ref_file="ref.wav",
133
+ ref_text="Your reference transcript.",
134
+ gen_text="Text you want to synthesise.",
135
+ tokenizer="cls",
136
+ cls_language="hindi",
137
+ )
138
+ ```
139
+
140
+ ---
141
+
142
+ ## License
143
+ This post-trained checkpoint is released under the BharatGen non-commercial license.
144
+
145
+ Please refer to the [LICENSE](./LICENSE) file for detailed terms and conditions.
146
+
147
+ ---
148
+
149
+ ## Contributors
150
+ - Yash
151
+ - Supreet
152
+ - Isha
153
+ - Vansh
154
+ - Pranav
155
+
156
+ For any questions or feedback, please contact: contact@bharatgen.com
157
+
158
+ ---
159
+
160
+ ## BharatGen - Sovereign AI for a Sovereign Nation
161
+
162
+ BharatGen is India's initiative to build AI that is Indian in its roots, inclusive in its reach, and sovereign in its design. We believe that a nation of India's civilisational depth - of Sanskrit and Tamil, of Tagore and Kabir, of a billion daily conversations - should not have to borrow its voice from elsewhere.
163
+
164
+ India's languages are not a niche. They are the world's richest linguistic heritage. And now, they have a model built for them.
165
+
166
+ We are just getting started.
167
+
168
+ ---
169
+
170
+ <p align="center">
171
+ <a href="https://bharatgen.com">bharatgen.com</a> · <a href="https://huggingface.co/bharatgenai/sooktam2">HuggingFace ↗</a>
172
+ <br/><br/>
173
+ <b>जय हिन्द · जय भारत 🇮🇳</b>
174
+ </p>
config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "f5_tts",
3
+ "model_name": "F5TTS_v1_Base",
4
+ "ckpt_file": "model_1250000.pt",
5
+ "vocab_file": "vocab.txt",
6
+ "ode_method": "euler",
7
+ "use_ema": true,
8
+ "auto_map": {
9
+ "AutoConfig": "hf_auto.F5TTSConfig",
10
+ "AutoModel": "hf_auto.F5TTSAutoModel",
11
+ "AutoTokenizer": "hf_auto.F5TTSTokenizer"
12
+ }
13
+ }
hf_auto.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HF Auto classes entrypoint for remote loading (used by AutoModel/AutoTokenizer)."""
2
+
3
+ import os
4
+ import sys
5
+
6
+ _ROOT = os.path.dirname(os.path.abspath(__file__))
7
+ _SRC = os.path.join(_ROOT, "src")
8
+ if _SRC not in sys.path:
9
+ sys.path.insert(0, _SRC)
10
+
11
+ from f5_tts.hf_auto import ( # noqa: E402
12
+ F5TTSConfig,
13
+ F5TTSAutoModel,
14
+ F5TTSTokenizer,
15
+ register_f5tts_auto,
16
+ )
17
+
18
+ __all__ = ["F5TTSConfig", "F5TTSAutoModel", "F5TTSTokenizer", "register_f5tts_auto"]
model_1250000.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:53ade74b27c43e3bd6947d25a0450964c3eaa76c133378c011e6b3fcb33bc772
3
+ size 5377795177
poetry.lock ADDED
The diff for this file is too large to render. See raw diff
 
pyproject.toml ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools >= 61.0", "setuptools-scm>=8.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "f5-tts"
7
+ version = "1.1.9"
8
+ description = "F5-TTS: A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching"
9
+ readme = "README.md"
10
+ license = {text = "MIT License"}
11
+ classifiers = [
12
+ "License :: OSI Approved :: MIT License",
13
+ "Operating System :: OS Independent",
14
+ "Programming Language :: Python :: 3",
15
+
16
+ ]
17
+ requires-python = ">=3.9,<3.12"
18
+ dependencies = [
19
+ "accelerate>=0.33.0",
20
+ "bitsandbytes>0.37.0; platform_machine!='arm64' and platform_system!='Darwin'",
21
+ "cached_path",
22
+ "click",
23
+ "datasets",
24
+ "ema-pytorch==0.7.9",
25
+ "gradio>=5.0.0",
26
+ "hydra-core>=1.3.0",
27
+ "jiwer",
28
+ "jieba",
29
+ "zhon",
30
+ "pytorch-wpe==0.0.1",
31
+ "torch-complex==0.4.4",
32
+ "torchcodec==0.9.1",
33
+ "librosa",
34
+ "matplotlib",
35
+ "numpy<=1.26.4; python_version<='3.10'",
36
+ "pydantic<=2.10.6",
37
+ "pydub",
38
+ "pypinyin",
39
+ "safetensors",
40
+ "soundfile",
41
+ "tomli",
42
+ "torch==2.6.0",
43
+ "torchaudio==2.6.0",
44
+ "torchdiffeq==0.2.5",
45
+ "torchelastic==0.2.2",
46
+ "torchvision==0.21.0",
47
+ "tqdm>=4.65.0",
48
+ "transformers",
49
+ "transformers_stream_generator",
50
+ "unidecode",
51
+ "vocos",
52
+ "wandb",
53
+ "x_transformers>=1.31.14",
54
+ ]
55
+
56
+ [project.optional-dependencies]
57
+ eval = [
58
+ "faster_whisper==1.2.1",
59
+ "funasr",
60
+ "jiwer",
61
+ "modelscope",
62
+ "s3prl",
63
+ "zhconv",
64
+ "zhon",
65
+ ]
66
+
67
+ [project.urls]
68
+ Homepage = "https://github.com/SWivid/F5-TTS"
69
+
70
+ [project.scripts]
71
+ "f5-tts_infer-cli" = "f5_tts.infer.infer_cli:main"
72
+ "f5-tts_infer-gradio" = "f5_tts.infer.infer_gradio:main"
73
+ "f5-tts_finetune-cli" = "f5_tts.train.finetune_cli:main"
74
+ "f5-tts_finetune-gradio" = "f5_tts.train.finetune_gradio:main"
ref.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e4d4e7df7bc1c11c746b7ea78fa3247740244212b99de5f82cddd5801cb212ec
3
+ size 504398
setup-cls.sh ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+
4
+
5
+ # apt update
6
+ # apt-get install libavformat-dev libavdevice-dev -y
7
+ # if gpu is available
8
+ if [ -n "$(lspci | grep NVIDIA)" ]; then
9
+ apt-get install libcudnn9-cuda-12 -y
10
+ fi
11
+ pip install torch==2.6.0 torchaudio==2.6.0 torchvision==0.21.0 transformers==4.41.2 huggingface-hub==0.24.7 indic-nlp-library==0.92
12
+
13
+
14
+ echo "Installing dependencies for prepare_cls_version.py..."
15
+ pip install \
16
+ datasets==4.5.0 \
17
+ tqdm \
18
+ indo-arabic-transliteration==0.1.5 \
19
+ indic-unified-parser==1.0.6 \
20
+ indic-numtowords==1.1.0 \
21
+ indic-nlp-library==0.92 \
22
+ git+https://github.com/libindic/indic-trans.git@0287fa62289968f0ce06cbe2df61cfadf4088c75 \
23
+ urduhack==1.1.1 \
24
+ keras==2.15.0 \
25
+ tensorflow==2.15.0 \
26
+ tensorflow-addons==0.23.0 \
27
+ fastapi==0.128.7 \
28
+ uvicorn==0.40.0
29
+
30
+ pip install indic_unified_parser==1.0.6 indo-arabic-transliteration==0.1.5 indic-numtowords==1.1.0
31
+ pip install click==8.0.1
32
+ pip install -e . --no-cache-dir
sooktam.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5d7cbda57c6748a88a59d3893af3738e4f97aa31fc946fbdd6e93f4e7f37fe7
3
+ size 1344331880
src/f5_tts/api.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import sys
3
+ from importlib.resources import files
4
+
5
+ import soundfile as sf
6
+ import tqdm
7
+ from cached_path import cached_path
8
+ from hydra.utils import get_class
9
+ from omegaconf import OmegaConf
10
+
11
+ from f5_tts.infer.utils_infer import (
12
+ infer_process,
13
+ load_model,
14
+ load_vocoder,
15
+ preprocess_ref_audio_text,
16
+ remove_silence_for_generated_wav,
17
+ save_spectrogram,
18
+ transcribe,
19
+ )
20
+ from f5_tts.model.utils import seed_everything
21
+
22
+
23
+ class F5TTS:
24
+ def __init__(
25
+ self,
26
+ model="F5TTS_v1_Base",
27
+ ckpt_file="",
28
+ vocab_file="",
29
+ ode_method="euler",
30
+ use_ema=True,
31
+ vocoder_local_path=None,
32
+ device=None,
33
+ hf_cache_dir=None,
34
+ ):
35
+ model_cfg = OmegaConf.load(str(files("f5_tts").joinpath(f"configs/{model}.yaml")))
36
+ model_cls = get_class(f"f5_tts.model.{model_cfg.model.backbone}")
37
+ model_arc = model_cfg.model.arch
38
+
39
+ self.mel_spec_type = model_cfg.model.mel_spec.mel_spec_type
40
+ self.target_sample_rate = model_cfg.model.mel_spec.target_sample_rate
41
+
42
+ self.ode_method = ode_method
43
+ self.use_ema = use_ema
44
+
45
+ if device is not None:
46
+ self.device = device
47
+ else:
48
+ import torch
49
+
50
+ self.device = (
51
+ "cuda"
52
+ if torch.cuda.is_available()
53
+ else "xpu"
54
+ if torch.xpu.is_available()
55
+ else "mps"
56
+ if torch.backends.mps.is_available()
57
+ else "cpu"
58
+ )
59
+
60
+ # Load models
61
+ self.vocoder = load_vocoder(
62
+ self.mel_spec_type, vocoder_local_path is not None, vocoder_local_path, self.device, hf_cache_dir
63
+ )
64
+
65
+ repo_name, ckpt_step, ckpt_type = "F5-TTS", 1250000, "safetensors"
66
+
67
+ # override for previous models
68
+ if model == "F5TTS_Base":
69
+ if self.mel_spec_type == "vocos":
70
+ ckpt_step = 1200000
71
+ elif self.mel_spec_type == "bigvgan":
72
+ model = "F5TTS_Base_bigvgan"
73
+ ckpt_type = "pt"
74
+ elif model == "E2TTS_Base":
75
+ repo_name = "E2-TTS"
76
+ ckpt_step = 1200000
77
+
78
+ if not ckpt_file:
79
+ ckpt_file = str(
80
+ cached_path(f"hf://SWivid/{repo_name}/{model}/model_{ckpt_step}.{ckpt_type}", cache_dir=hf_cache_dir)
81
+ )
82
+ self.ema_model = load_model(
83
+ model_cls, model_arc, ckpt_file, self.mel_spec_type, vocab_file, self.ode_method, self.use_ema, self.device
84
+ )
85
+
86
+ def transcribe(self, ref_audio, language=None):
87
+ return transcribe(ref_audio, language)
88
+
89
+ def export_wav(self, wav, file_wave, remove_silence=False):
90
+ sf.write(file_wave, wav, self.target_sample_rate)
91
+
92
+ if remove_silence:
93
+ remove_silence_for_generated_wav(file_wave)
94
+
95
+ def export_spectrogram(self, spec, file_spec):
96
+ save_spectrogram(spec, file_spec)
97
+
98
+ def infer(
99
+ self,
100
+ ref_file,
101
+ ref_text,
102
+ gen_text,
103
+ show_info=print,
104
+ progress=tqdm,
105
+ target_rms=0.1,
106
+ cross_fade_duration=0.15,
107
+ sway_sampling_coef=-1,
108
+ cfg_strength=2,
109
+ nfe_step=32,
110
+ speed=1.0,
111
+ fix_duration=None,
112
+ remove_silence=False,
113
+ file_wave=None,
114
+ file_spec=None,
115
+ seed=None,
116
+ tokenizer="pinyin",
117
+ cls_language=None,
118
+ cls_server_url=None,
119
+ cls_timeout=5.0,
120
+ cls_tokenizer_fn=None,
121
+ ):
122
+ if seed is None:
123
+ seed = random.randint(0, sys.maxsize)
124
+ seed_everything(seed)
125
+ self.seed = seed
126
+
127
+ ref_file, ref_text = preprocess_ref_audio_text(ref_file, ref_text)
128
+
129
+ wav, sr, spec = infer_process(
130
+ ref_file,
131
+ ref_text,
132
+ gen_text,
133
+ self.ema_model,
134
+ self.vocoder,
135
+ self.mel_spec_type,
136
+ show_info=show_info,
137
+ progress=progress,
138
+ target_rms=target_rms,
139
+ cross_fade_duration=cross_fade_duration,
140
+ nfe_step=nfe_step,
141
+ cfg_strength=cfg_strength,
142
+ sway_sampling_coef=sway_sampling_coef,
143
+ speed=speed,
144
+ fix_duration=fix_duration,
145
+ device=self.device,
146
+ tokenizer=tokenizer,
147
+ cls_language=cls_language,
148
+ cls_server_url=cls_server_url,
149
+ cls_timeout=cls_timeout,
150
+ cls_tokenizer_fn=cls_tokenizer_fn,
151
+ )
152
+
153
+ if file_wave is not None:
154
+ self.export_wav(wav, file_wave, remove_silence)
155
+
156
+ if file_spec is not None:
157
+ self.export_spectrogram(spec, file_spec)
158
+
159
+ return wav, sr, spec
160
+
161
+
162
+ if __name__ == "__main__":
163
+ f5tts = F5TTS()
164
+
165
+ wav, sr, spec = f5tts.infer(
166
+ ref_file=str(files("f5_tts").joinpath("infer/examples/basic/basic_ref_en.wav")),
167
+ ref_text="some call me nature, others call me mother nature.",
168
+ gen_text="""I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring. Respect me and I'll nurture you; ignore me and you shall face the consequences.""",
169
+ file_wave=str(files("f5_tts").joinpath("../../tests/api_out.wav")),
170
+ file_spec=str(files("f5_tts").joinpath("../../tests/api_out.png")),
171
+ seed=None,
172
+ )
173
+
174
+ print("seed :", f5tts.seed)
src/f5_tts/configs/E2TTS_Base.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ name: E2TTS_Base
3
+ tokenizer: pinyin
4
+ tokenizer_path: null
5
+ backbone: UNetT
6
+ arch:
7
+ dim: 1024
8
+ depth: 24
9
+ heads: 16
10
+ ff_mult: 4
11
+ text_mask_padding: False
12
+ pe_attn_head: 1
13
+ mel_spec:
14
+ target_sample_rate: 24000
15
+ n_mel_channels: 100
16
+ hop_length: 256
17
+ win_length: 1024
18
+ n_fft: 1024
19
+ mel_spec_type: vocos
20
+ vocoder:
21
+ is_local: False
22
+ local_path: null
src/f5_tts/configs/E2TTS_Small.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ name: E2TTS_Small
3
+ tokenizer: pinyin
4
+ tokenizer_path: null
5
+ backbone: UNetT
6
+ arch:
7
+ dim: 768
8
+ depth: 18
9
+ heads: 12
10
+ ff_mult: 4
11
+ text_mask_padding: False
12
+ pe_attn_head: 1
13
+ mel_spec:
14
+ target_sample_rate: 24000
15
+ n_mel_channels: 100
16
+ hop_length: 256
17
+ win_length: 1024
18
+ n_fft: 1024
19
+ mel_spec_type: vocos
20
+ vocoder:
21
+ is_local: False
22
+ local_path: null
src/f5_tts/configs/F5TTS_Base.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ name: F5TTS_Base
3
+ tokenizer: pinyin
4
+ tokenizer_path: null
5
+ backbone: DiT
6
+ arch:
7
+ dim: 1024
8
+ depth: 22
9
+ heads: 16
10
+ ff_mult: 2
11
+ text_dim: 512
12
+ text_mask_padding: False
13
+ conv_layers: 4
14
+ pe_attn_head: 1
15
+ attn_backend: torch
16
+ attn_mask_enabled: False
17
+ checkpoint_activations: False
18
+ mel_spec:
19
+ target_sample_rate: 24000
20
+ n_mel_channels: 100
21
+ hop_length: 256
22
+ win_length: 1024
23
+ n_fft: 1024
24
+ mel_spec_type: vocos
25
+ vocoder:
26
+ is_local: False
27
+ local_path: null
src/f5_tts/configs/F5TTS_Small.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ name: F5TTS_Small
3
+ tokenizer: pinyin
4
+ tokenizer_path: null
5
+ backbone: DiT
6
+ arch:
7
+ dim: 768
8
+ depth: 18
9
+ heads: 12
10
+ ff_mult: 2
11
+ text_dim: 512
12
+ text_mask_padding: False
13
+ conv_layers: 4
14
+ pe_attn_head: 1
15
+ attn_backend: torch
16
+ attn_mask_enabled: False
17
+ checkpoint_activations: False
18
+ mel_spec:
19
+ target_sample_rate: 24000
20
+ n_mel_channels: 100
21
+ hop_length: 256
22
+ win_length: 1024
23
+ n_fft: 1024
24
+ mel_spec_type: vocos
25
+ vocoder:
26
+ is_local: False
27
+ local_path: null
src/f5_tts/configs/F5TTS_v1_Base.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ name: F5TTS_v1_Base
3
+ tokenizer: pinyin
4
+ tokenizer_path: null
5
+ backbone: DiT
6
+ arch:
7
+ dim: 1024
8
+ depth: 22
9
+ heads: 16
10
+ ff_mult: 2
11
+ text_dim: 512
12
+ text_mask_padding: True
13
+ qk_norm: null
14
+ conv_layers: 4
15
+ pe_attn_head: null
16
+ attn_backend: torch
17
+ attn_mask_enabled: False
18
+ checkpoint_activations: False
19
+ mel_spec:
20
+ target_sample_rate: 24000
21
+ n_mel_channels: 100
22
+ hop_length: 256
23
+ win_length: 1024
24
+ n_fft: 1024
25
+ mel_spec_type: vocos
26
+ vocoder:
27
+ is_local: False
28
+ local_path: null
src/f5_tts/configs/F5TTS_v1_Base_frame.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ name: F5TTS_v1_Base
3
+ tokenizer: char
4
+ tokenizer_path: null
5
+ backbone: DiT
6
+ arch:
7
+ dim: 1024
8
+ depth: 22
9
+ heads: 16
10
+ ff_mult: 2
11
+ text_dim: 512
12
+ text_mask_padding: True
13
+ qk_norm: null
14
+ conv_layers: 4
15
+ pe_attn_head: null
16
+ attn_backend: torch
17
+ attn_mask_enabled: False
18
+ checkpoint_activations: False
19
+ mel_spec:
20
+ target_sample_rate: 24000
21
+ n_mel_channels: 100
22
+ hop_length: 256
23
+ win_length: 1024
24
+ n_fft: 1024
25
+ mel_spec_type: vocos
26
+ vocoder:
27
+ is_local: False
28
+ local_path: null
src/f5_tts/hf_auto.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hugging Face AutoModel integration for F5-TTS (inference-only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any, List, Optional
7
+
8
+ import torch
9
+ from huggingface_hub import hf_hub_download
10
+ from transformers import AutoConfig, AutoModel, AutoTokenizer
11
+ from transformers.configuration_utils import PretrainedConfig
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.tokenization_utils import PreTrainedTokenizer
14
+ from transformers.utils import logging
15
+
16
+ from f5_tts.api import F5TTS
17
+
18
+ logger = logging.get_logger(__name__)
19
+
20
+
21
+ class F5TTSConfig(PretrainedConfig):
22
+ model_type = "f5_tts"
23
+
24
+ def __init__(
25
+ self,
26
+ model_name: str = "F5TTS_v1_Base",
27
+ ckpt_file: str = "",
28
+ vocab_file: str = "",
29
+ ode_method: str = "euler",
30
+ use_ema: bool = True,
31
+ vocoder_local_path: Optional[str] = None,
32
+ device: Optional[str] = None,
33
+ hf_cache_dir: Optional[str] = None,
34
+ **kwargs,
35
+ ) -> None:
36
+ super().__init__(**kwargs)
37
+ self.model_name = model_name
38
+ self.ckpt_file = ckpt_file
39
+ self.vocab_file = vocab_file
40
+ self.ode_method = ode_method
41
+ self.use_ema = use_ema
42
+ self.vocoder_local_path = vocoder_local_path
43
+ self.device = device
44
+ self.hf_cache_dir = hf_cache_dir
45
+
46
+ if "auto_map" not in kwargs:
47
+ # Keep AutoTokenizer as a string to satisfy Hub config validators.
48
+ self.auto_map = {
49
+ "AutoConfig": "hf_auto.F5TTSConfig",
50
+ "AutoModel": "hf_auto.F5TTSAutoModel",
51
+ "AutoTokenizer": "hf_auto.F5TTSTokenizer",
52
+ }
53
+
54
+
55
+ class F5TTSTokenizer(PreTrainedTokenizer):
56
+ """Minimal character-level tokenizer backed by vocab.txt (inference helper)."""
57
+
58
+ vocab_files_names = {"vocab_file": "vocab.txt"}
59
+ model_input_names = ["input_ids", "attention_mask"]
60
+
61
+ def __init__(self, vocab_file: str, **kwargs) -> None:
62
+ self.vocab_file = vocab_file
63
+ tokens = self._load_vocab_tokens(vocab_file)
64
+ self.vocab = {tok: idx for idx, tok in enumerate(tokens)}
65
+ self.ids_to_tokens = {idx: tok for tok, idx in self.vocab.items()}
66
+
67
+ if kwargs.get("unk_token") is None:
68
+ kwargs["unk_token"] = "<unk>"
69
+ super().__init__(**kwargs)
70
+
71
+ if self.unk_token not in self.vocab:
72
+ unk_id = len(self.vocab)
73
+ self.vocab[self.unk_token] = unk_id
74
+ self.ids_to_tokens[unk_id] = self.unk_token
75
+
76
+ @staticmethod
77
+ def _load_vocab_tokens(path: str) -> List[str]:
78
+ with open(path, "r", encoding="utf-8") as handle:
79
+ return [line.rstrip("\n") for line in handle]
80
+
81
+ def get_vocab(self) -> dict:
82
+ return dict(self.vocab)
83
+
84
+ def _tokenize(self, text: str) -> List[str]:
85
+ return list(text)
86
+
87
+ def _convert_token_to_id(self, token: str) -> int:
88
+ return self.vocab.get(token, self.vocab[self.unk_token])
89
+
90
+ def _convert_id_to_token(self, index: int) -> str:
91
+ return self.ids_to_tokens.get(index, self.unk_token)
92
+
93
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None):
94
+ os.makedirs(save_directory, exist_ok=True)
95
+ filename = (filename_prefix + "-" if filename_prefix else "") + "vocab.txt"
96
+ path = os.path.join(save_directory, filename)
97
+ with open(path, "w", encoding="utf-8") as handle:
98
+ for idx in range(len(self.ids_to_tokens)):
99
+ handle.write(f"{self.ids_to_tokens[idx]}\n")
100
+ return (path,)
101
+
102
+
103
+ def load_tokenizer(
104
+ repo_or_path: str = "bharatgenai/sooktam2",
105
+ vocab_file: str = "vocab.txt",
106
+ cache_dir: Optional[str] = None,
107
+ revision: Optional[str] = None,
108
+ token: Optional[str] = None,
109
+ local_files_only: bool = False,
110
+ ) -> F5TTSTokenizer:
111
+ """Load the character-level tokenizer from a local folder or Hugging Face."""
112
+ resolved = F5TTSAutoModel._resolve_file(
113
+ vocab_file,
114
+ repo_or_path,
115
+ cache_dir,
116
+ revision,
117
+ token,
118
+ local_files_only,
119
+ )
120
+ return F5TTSTokenizer(resolved)
121
+
122
+
123
+ class F5TTSAutoModel(PreTrainedModel):
124
+ config_class = F5TTSConfig
125
+
126
+ def __init__(self, config: F5TTSConfig, ckpt_file: str = "", vocab_file: str = "", **kwargs) -> None:
127
+ super().__init__(config)
128
+ self._dummy = torch.nn.Parameter(torch.zeros(1), requires_grad=False)
129
+
130
+ self.tts = F5TTS(
131
+ model=config.model_name,
132
+ ckpt_file=ckpt_file or config.ckpt_file,
133
+ vocab_file=vocab_file or config.vocab_file,
134
+ ode_method=config.ode_method,
135
+ use_ema=config.use_ema,
136
+ vocoder_local_path=config.vocoder_local_path,
137
+ device=config.device,
138
+ hf_cache_dir=config.hf_cache_dir,
139
+ )
140
+
141
+ @staticmethod
142
+ def _resolve_file(
143
+ filename: str,
144
+ repo_or_path: Optional[str],
145
+ cache_dir: Optional[str],
146
+ revision: Optional[str],
147
+ token: Optional[str],
148
+ local_files_only: bool,
149
+ ) -> str:
150
+ if not filename:
151
+ return ""
152
+ if os.path.isfile(filename):
153
+ return filename
154
+ if repo_or_path and os.path.isdir(repo_or_path):
155
+ candidate = os.path.join(repo_or_path, filename)
156
+ if os.path.isfile(candidate):
157
+ return candidate
158
+ if not repo_or_path:
159
+ return filename
160
+ return hf_hub_download(
161
+ repo_id=repo_or_path,
162
+ filename=filename,
163
+ cache_dir=cache_dir,
164
+ revision=revision,
165
+ token=token,
166
+ local_files_only=local_files_only,
167
+ )
168
+
169
+ @classmethod
170
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[str], *model_args, **kwargs):
171
+ config = kwargs.pop("config", None)
172
+ if config is None:
173
+ config_kwargs = {
174
+ "cache_dir": kwargs.get("cache_dir"),
175
+ "revision": kwargs.get("revision"),
176
+ "token": kwargs.get("token"),
177
+ "local_files_only": kwargs.get("local_files_only", False),
178
+ "trust_remote_code": kwargs.get("trust_remote_code"),
179
+ }
180
+ try:
181
+ config = F5TTSConfig.from_pretrained(pretrained_model_name_or_path, **config_kwargs)
182
+ except Exception: # noqa: BLE001
183
+ logger.warning("F5TTSConfig not found, using defaults.")
184
+ config = F5TTSConfig()
185
+
186
+ ckpt_file = kwargs.pop("ckpt_file", None) or config.ckpt_file
187
+ vocab_file = kwargs.pop("vocab_file", None) or config.vocab_file
188
+
189
+ cache_dir = kwargs.get("cache_dir") or config.hf_cache_dir
190
+ revision = kwargs.get("revision")
191
+ token = kwargs.get("token")
192
+ local_files_only = kwargs.get("local_files_only", False)
193
+
194
+ ckpt_file = cls._resolve_file(
195
+ ckpt_file,
196
+ pretrained_model_name_or_path,
197
+ cache_dir,
198
+ revision,
199
+ token,
200
+ local_files_only,
201
+ )
202
+ vocab_file = cls._resolve_file(
203
+ vocab_file,
204
+ pretrained_model_name_or_path,
205
+ cache_dir,
206
+ revision,
207
+ token,
208
+ local_files_only,
209
+ )
210
+
211
+ return cls(config, ckpt_file=ckpt_file, vocab_file=vocab_file)
212
+
213
+ def forward(self, *args, **kwargs): # noqa: D401
214
+ raise NotImplementedError("Use .infer(...) or .tts.infer(...) for generation.")
215
+
216
+ def infer(self, *args, **kwargs):
217
+ return self.tts.infer(*args, **kwargs)
218
+
219
+ def save_pretrained(self, save_directory: str, **kwargs):
220
+ os.makedirs(save_directory, exist_ok=True)
221
+ self.config.save_pretrained(save_directory)
222
+
223
+
224
+ def register_f5tts_auto() -> None:
225
+ """Register F5-TTS with Hugging Face AutoConfig/AutoModel/AutoTokenizer (local usage)."""
226
+ AutoConfig.register(F5TTSConfig.model_type, F5TTSConfig)
227
+ AutoModel.register(F5TTSConfig, F5TTSAutoModel)
228
+ AutoTokenizer.register(F5TTSConfig, F5TTSTokenizer)
src/f5_tts/infer/README.md ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference
2
+
3
+ The pretrained model checkpoints can be reached at [🤗 Hugging Face](https://huggingface.co/SWivid/F5-TTS) and [🤖 Model Scope](https://www.modelscope.cn/models/SWivid/F5-TTS_Emilia-ZH-EN), or will be automatically downloaded when running inference scripts.
4
+
5
+ **More checkpoints with whole community efforts can be found in [SHARED.md](SHARED.md), supporting more languages.**
6
+
7
+ Currently support **30s for a single** generation, which is the **total length** (same logic if `fix_duration`) including both prompt and output audio. However, `infer_cli` and `infer_gradio` will automatically do chunk generation for longer text. Long reference audio will be **clip short to ~12s**.
8
+
9
+ To avoid possible inference failures, make sure you have seen through the following instructions.
10
+
11
+ - Use reference audio <12s and leave proper silence space (e.g. 1s) at the end. Otherwise there is a risk of truncating in the middle of word, leading to suboptimal generation.
12
+ - <ins>Uppercased letters</ins> (best with form like K.F.C.) will be uttered letter by letter, and lowercased letters used for common words.
13
+ - Add some spaces (blank: " ") or punctuations (e.g. "," ".") <ins>to explicitly introduce some pauses</ins>.
14
+ - If English punctuation marks the end of a sentence, make sure there is a space " " after it. Otherwise not regarded as when chunk.
15
+ - <ins>Preprocess numbers</ins> to Chinese letters if you want to have them read in Chinese, otherwise in English.
16
+ - If the generation output is blank (pure silence), <ins>check for FFmpeg installation</ins>.
17
+ - Try <ins>turn off `use_ema` if using an early-stage</ins> finetuned checkpoint (which goes just few updates).
18
+
19
+
20
+ ## Gradio App
21
+
22
+ Currently supported features:
23
+
24
+ - Basic TTS with Chunk Inference
25
+ - Multi-Style / Multi-Speaker Generation
26
+ - Voice Chat powered by Qwen2.5-3B-Instruct
27
+ - [Custom inference with more language support](SHARED.md)
28
+
29
+ The cli command `f5-tts_infer-gradio` equals to `python src/f5_tts/infer/infer_gradio.py`, which launches a Gradio APP (web interface) for inference.
30
+
31
+ The script will load model checkpoints from Huggingface. You can also manually download files and update the path to `load_model()` in `infer_gradio.py`. Currently only load TTS models first, will load ASR model to do transcription if `ref_text` not provided, will load LLM model if use Voice Chat.
32
+
33
+ More flags options:
34
+
35
+ ```bash
36
+ # Automatically launch the interface in the default web browser
37
+ f5-tts_infer-gradio --inbrowser
38
+
39
+ # Set the root path of the application, if it's not served from the root ("/") of the domain
40
+ # For example, if the application is served at "https://example.com/myapp"
41
+ f5-tts_infer-gradio --root_path "/myapp"
42
+ ```
43
+
44
+ Could also be used as a component for larger application:
45
+ ```python
46
+ import gradio as gr
47
+ from f5_tts.infer.infer_gradio import app
48
+
49
+ with gr.Blocks() as main_app:
50
+ gr.Markdown("# This is an example of using F5-TTS within a bigger Gradio app")
51
+
52
+ # ... other Gradio components
53
+
54
+ app.render()
55
+
56
+ main_app.launch()
57
+ ```
58
+
59
+
60
+ ## CLI Inference
61
+
62
+ The cli command `f5-tts_infer-cli` equals to `python src/f5_tts/infer/infer_cli.py`, which is a command line tool for inference.
63
+
64
+ The script will load model checkpoints from Huggingface. You can also manually download files and use `--ckpt_file` to specify the model you want to load, or directly update in `infer_cli.py`.
65
+
66
+ For change vocab.txt use `--vocab_file` to provide your `vocab.txt` file.
67
+
68
+ Basically you can inference with flags:
69
+ ```bash
70
+ # Leave --ref_text "" will have ASR model transcribe (extra GPU memory usage)
71
+ f5-tts_infer-cli \
72
+ --model F5TTS_v1_Base \
73
+ --ref_audio "ref_audio.wav" \
74
+ --ref_text "The content, subtitle or transcription of reference audio." \
75
+ --gen_text "Some text you want TTS model generate for you."
76
+
77
+ # Use BigVGAN as vocoder. Currently only support F5TTS_Base.
78
+ f5-tts_infer-cli --model F5TTS_Base --vocoder_name bigvgan --load_vocoder_from_local
79
+
80
+ # Use custom path checkpoint, e.g.
81
+ f5-tts_infer-cli --ckpt_file ckpts/F5TTS_v1_Base/model_1250000.safetensors
82
+
83
+ # More instructions
84
+ f5-tts_infer-cli --help
85
+ ```
86
+
87
+ And a `.toml` file would help with more flexible usage.
88
+
89
+ ```bash
90
+ f5-tts_infer-cli -c custom.toml
91
+ ```
92
+
93
+ For example, you can use `.toml` to pass in variables, refer to `src/f5_tts/infer/examples/basic/basic.toml`:
94
+
95
+ ```toml
96
+ # F5TTS_v1_Base | E2TTS_Base
97
+ model = "F5TTS_v1_Base"
98
+ ref_audio = "infer/examples/basic/basic_ref_en.wav"
99
+ # If an empty "", transcribes the reference audio automatically.
100
+ ref_text = "Some call me nature, others call me mother nature."
101
+ gen_text = "I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring."
102
+ # File with text to generate. Ignores the text above.
103
+ gen_file = ""
104
+ remove_silence = false
105
+ output_dir = "tests"
106
+ ```
107
+
108
+ You can also leverage `.toml` file to do multi-style generation, refer to `src/f5_tts/infer/examples/multi/story.toml`.
109
+
110
+ ```toml
111
+ # F5TTS_v1_Base | E2TTS_Base
112
+ model = "F5TTS_v1_Base"
113
+ ref_audio = "infer/examples/multi/main.flac"
114
+ # If an empty "", transcribes the reference audio automatically.
115
+ ref_text = ""
116
+ gen_text = ""
117
+ # File with text to generate. Ignores the text above.
118
+ gen_file = "infer/examples/multi/story.txt"
119
+ remove_silence = true
120
+ output_dir = "tests"
121
+
122
+ [voices.town]
123
+ ref_audio = "infer/examples/multi/town.flac"
124
+ ref_text = ""
125
+
126
+ [voices.country]
127
+ ref_audio = "infer/examples/multi/country.flac"
128
+ ref_text = ""
129
+ ```
130
+ You should mark the voice with `[main]` `[town]` `[country]` whenever you want to change voice, refer to `src/f5_tts/infer/examples/multi/story.txt`.
131
+
132
+ ## API Usage
133
+
134
+ ```python
135
+ from importlib.resources import files
136
+ from f5_tts.api import F5TTS
137
+
138
+ f5tts = F5TTS()
139
+ wav, sr, spec = f5tts.infer(
140
+ ref_file=str(files("f5_tts").joinpath("infer/examples/basic/basic_ref_en.wav")),
141
+ ref_text="some call me nature, others call me mother nature.",
142
+ gen_text="""I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring. Respect me and I'll nurture you; ignore me and you shall face the consequences.""",
143
+ file_wave=str(files("f5_tts").joinpath("../../tests/api_out.wav")),
144
+ file_spec=str(files("f5_tts").joinpath("../../tests/api_out.png")),
145
+ seed=None,
146
+ )
147
+ ```
148
+ Check [api.py](../api.py) for more details.
149
+
150
+ ## TensorRT-LLM Deployment
151
+
152
+ See [detailed instructions](../runtime/triton_trtllm/README.md) for more information.
153
+
154
+ ## Socket Real-time Service
155
+
156
+ Real-time voice output with chunk stream:
157
+
158
+ ```bash
159
+ # Start socket server
160
+ python src/f5_tts/socket_server.py
161
+
162
+ # If PyAudio not installed
163
+ sudo apt-get install portaudio19-dev
164
+ pip install pyaudio
165
+
166
+ # Communicate with socket client
167
+ python src/f5_tts/socket_client.py
168
+ ```
169
+
170
+ ## Speech Editing
171
+
172
+ To test speech editing capabilities, use the following command:
173
+
174
+ ```bash
175
+ python src/f5_tts/infer/speech_edit.py
176
+ ```
177
+
src/f5_tts/infer/SHARED.md ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- omit in toc -->
2
+ # Shared Model Cards
3
+
4
+ <!-- omit in toc -->
5
+ ### **Prerequisites of using**
6
+ - This document is serving as a quick lookup table for the community training/finetuning result, with various language support.
7
+ - The models in this repository are open source and are based on voluntary contributions from contributors.
8
+ - The use of models must be conditioned on respect for the respective creators. The convenience brought comes from their efforts.
9
+
10
+ <!-- omit in toc -->
11
+ ### **Welcome to share here**
12
+ - Have a pretrained/finetuned result: model checkpoint (pruned best to facilitate inference, i.e. leave only `ema_model_state_dict`) and corresponding vocab file (for tokenization).
13
+ - Host a public [huggingface model repository](https://huggingface.co/new) and upload the model related files.
14
+ - Make a pull request adding a model card to the current page, i.e. `src\f5_tts\infer\SHARED.md`.
15
+
16
+ <!-- omit in toc -->
17
+ ### Supported Languages
18
+ - [Multilingual](#multilingual)
19
+ - [F5-TTS v1 v0 Base @ zh \& en @ F5-TTS](#f5-tts-v1-v0-base--zh--en--f5-tts)
20
+ - [English](#english)
21
+ - [Finnish](#finnish)
22
+ - [F5-TTS Base @ fi @ AsmoKoskinen](#f5-tts-base--fi--asmokoskinen)
23
+ - [French](#french)
24
+ - [F5-TTS Base @ fr @ RASPIAUDIO](#f5-tts-base--fr--raspiaudio)
25
+ - [German](#german)
26
+ - [F5-TTS Base @ de @ hvoss-techfak](#f5-tts-base--de--hvoss-techfak)
27
+ - [Hindi](#hindi)
28
+ - [F5-TTS Small @ hi @ SPRINGLab](#f5-tts-small--hi--springlab)
29
+ - [Italian](#italian)
30
+ - [F5-TTS Base @ it @ alien79](#f5-tts-base--it--alien79)
31
+ - [Japanese](#japanese)
32
+ - [F5-TTS Base @ ja @ Jmica](#f5-tts-base--ja--jmica)
33
+ - [Mandarin](#mandarin)
34
+ - [Russian](#russian)
35
+ - [F5-TTS Base @ ru @ HotDro4illa](#f5-tts-base--ru--hotdro4illa)
36
+ - [Spanish](#spanish)
37
+ - [F5-TTS Base @ es @ jpgallegoar](#f5-tts-base--es--jpgallegoar)
38
+
39
+
40
+ ## Multilingual
41
+
42
+ #### F5-TTS v1 v0 Base @ zh & en @ F5-TTS
43
+ |Model|🤗Hugging Face|Data (Hours)|Model License|
44
+ |:---:|:------------:|:-----------:|:-------------:|
45
+ |F5-TTS v1 Base|[ckpt & vocab](https://huggingface.co/SWivid/F5-TTS/tree/main/F5TTS_v1_Base)|[Emilia 95K zh&en](https://huggingface.co/datasets/amphion/Emilia-Dataset/tree/fc71e07)|cc-by-nc-4.0|
46
+
47
+ ```bash
48
+ Model: hf://SWivid/F5-TTS/F5TTS_v1_Base/model_1250000.safetensors
49
+ # A Variant Model: hf://SWivid/F5-TTS/F5TTS_v1_Base_no_zero_init/model_1250000.safetensors
50
+ Vocab: hf://SWivid/F5-TTS/F5TTS_v1_Base/vocab.txt
51
+ Config: {"dim": 1024, "depth": 22, "heads": 16, "ff_mult": 2, "text_dim": 512, "conv_layers": 4}
52
+ ```
53
+
54
+ |Model|🤗Hugging Face|Data (Hours)|Model License|
55
+ |:---:|:------------:|:-----------:|:-------------:|
56
+ |F5-TTS Base|[ckpt & vocab](https://huggingface.co/SWivid/F5-TTS/tree/main/F5TTS_Base)|[Emilia 95K zh&en](https://huggingface.co/datasets/amphion/Emilia-Dataset/tree/fc71e07)|cc-by-nc-4.0|
57
+
58
+ ```bash
59
+ Model: hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors
60
+ Vocab: hf://SWivid/F5-TTS/F5TTS_Base/vocab.txt
61
+ Config: {"dim": 1024, "depth": 22, "heads": 16, "ff_mult": 2, "text_dim": 512, "text_mask_padding": False, "conv_layers": 4, "pe_attn_head": 1}
62
+ ```
63
+
64
+ *Other infos, e.g. Author info, Github repo, Link to some sampled results, Usage instruction, Tutorial (Blog, Video, etc.) ...*
65
+
66
+
67
+ ## English
68
+
69
+
70
+ ## Finnish
71
+
72
+ #### F5-TTS Base @ fi @ AsmoKoskinen
73
+ |Model|🤗Hugging Face|Data|Model License|
74
+ |:---:|:------------:|:-----------:|:-------------:|
75
+ |F5-TTS Base|[ckpt & vocab](https://huggingface.co/AsmoKoskinen/F5-TTS_Finnish_Model)|[Common Voice](https://huggingface.co/datasets/mozilla-foundation/common_voice_17_0), [Vox Populi](https://huggingface.co/datasets/facebook/voxpopuli)|cc-by-nc-4.0|
76
+
77
+ ```bash
78
+ Model: hf://AsmoKoskinen/F5-TTS_Finnish_Model/model_common_voice_fi_vox_populi_fi_20241206.safetensors
79
+ Vocab: hf://AsmoKoskinen/F5-TTS_Finnish_Model/vocab.txt
80
+ Config: {"dim": 1024, "depth": 22, "heads": 16, "ff_mult": 2, "text_dim": 512, "text_mask_padding": False, "conv_layers": 4, "pe_attn_head": 1}
81
+ ```
82
+
83
+
84
+ ## French
85
+
86
+ #### F5-TTS Base @ fr @ RASPIAUDIO
87
+ |Model|🤗Hugging Face|Data (Hours)|Model License|
88
+ |:---:|:------------:|:-----------:|:-------------:|
89
+ |F5-TTS Base|[ckpt & vocab](https://huggingface.co/RASPIAUDIO/F5-French-MixedSpeakers-reduced)|[LibriVox](https://librivox.org/)|cc-by-nc-4.0|
90
+
91
+ ```bash
92
+ Model: hf://RASPIAUDIO/F5-French-MixedSpeakers-reduced/model_last_reduced.pt
93
+ Vocab: hf://RASPIAUDIO/F5-French-MixedSpeakers-reduced/vocab.txt
94
+ Config: {"dim": 1024, "depth": 22, "heads": 16, "ff_mult": 2, "text_dim": 512, "text_mask_padding": False, "conv_layers": 4, "pe_attn_head": 1}
95
+ ```
96
+
97
+ - [Online Inference with Hugging Face Space](https://huggingface.co/spaces/RASPIAUDIO/f5-tts_french).
98
+ - [Tutorial video to train a new language model](https://www.youtube.com/watch?v=UO4usaOojys).
99
+ - [Discussion about this training can be found here](https://github.com/SWivid/F5-TTS/issues/434).
100
+
101
+
102
+ ## German
103
+
104
+ #### F5-TTS Base @ de @ hvoss-techfak
105
+ |Model|🤗Hugging Face|Data (Hours)|Model License|
106
+ |:---:|:------------:|:-----------:|:-------------:|
107
+ |F5-TTS Base|[ckpt & vocab](https://huggingface.co/hvoss-techfak/F5-TTS-German)|[Mozilla Common Voice 19.0](https://commonvoice.mozilla.org/en/datasets) & 800 hours Crowdsourced |cc-by-nc-4.0|
108
+
109
+ ```bash
110
+ Model: hf://hvoss-techfak/F5-TTS-German/model_f5tts_german.pt
111
+ Vocab: hf://hvoss-techfak/F5-TTS-German/vocab.txt
112
+ Config: {"dim": 1024, "depth": 22, "heads": 16, "ff_mult": 2, "text_dim": 512, "text_mask_padding": False, "conv_layers": 4, "pe_attn_head": 1}
113
+ ```
114
+
115
+ - Finetuned by [@hvoss-techfak](https://github.com/hvoss-techfak)
116
+
117
+
118
+ ## Hindi
119
+
120
+ #### F5-TTS Small @ hi @ SPRINGLab
121
+ |Model|🤗Hugging Face|Data (Hours)|Model License|
122
+ |:---:|:------------:|:-----------:|:-------------:|
123
+ |F5-TTS Small|[ckpt & vocab](https://huggingface.co/SPRINGLab/F5-Hindi-24KHz)|[IndicTTS Hi](https://huggingface.co/datasets/SPRINGLab/IndicTTS-Hindi) & [IndicVoices-R Hi](https://huggingface.co/datasets/SPRINGLab/IndicVoices-R_Hindi) |cc-by-4.0|
124
+
125
+ ```bash
126
+ Model: hf://SPRINGLab/F5-Hindi-24KHz/model_2500000.safetensors
127
+ Vocab: hf://SPRINGLab/F5-Hindi-24KHz/vocab.txt
128
+ Config: {"dim": 768, "depth": 18, "heads": 12, "ff_mult": 2, "text_dim": 512, "text_mask_padding": False, "conv_layers": 4, "pe_attn_head": 1}
129
+ ```
130
+
131
+ - Authors: SPRING Lab, Indian Institute of Technology, Madras
132
+ - Website: https://asr.iitm.ac.in/
133
+
134
+
135
+ ## Italian
136
+
137
+ #### F5-TTS Base @ it @ alien79
138
+ |Model|🤗Hugging Face|Data|Model License|
139
+ |:---:|:------------:|:-----------:|:-------------:|
140
+ |F5-TTS Base|[ckpt & vocab](https://huggingface.co/alien79/F5-TTS-italian)|[ylacombe/cml-tts](https://huggingface.co/datasets/ylacombe/cml-tts) |cc-by-nc-4.0|
141
+
142
+ ```bash
143
+ Model: hf://alien79/F5-TTS-italian/model_159600.safetensors
144
+ Vocab: hf://alien79/F5-TTS-italian/vocab.txt
145
+ Config: {"dim": 1024, "depth": 22, "heads": 16, "ff_mult": 2, "text_dim": 512, "text_mask_padding": False, "conv_layers": 4, "pe_attn_head": 1}
146
+ ```
147
+
148
+ - Trained by [Mithril Man](https://github.com/MithrilMan)
149
+ - Model details on [hf project home](https://huggingface.co/alien79/F5-TTS-italian)
150
+ - Open to collaborations to further improve the model
151
+
152
+
153
+ ## Japanese
154
+
155
+ #### F5-TTS Base @ ja @ Jmica
156
+ |Model|🤗Hugging Face|Data (Hours)|Model License|
157
+ |:---:|:------------:|:-----------:|:-------------:|
158
+ |F5-TTS Base|[ckpt & vocab](https://huggingface.co/Jmica/F5TTS/tree/main/JA_21999120)|[Emilia 1.7k JA](https://huggingface.co/datasets/amphion/Emilia-Dataset/tree/fc71e07) & [Galgame Dataset 5.4k](https://huggingface.co/datasets/OOPPEENN/Galgame_Dataset)|cc-by-nc-4.0|
159
+
160
+ ```bash
161
+ Model: hf://Jmica/F5TTS/JA_21999120/model_21999120.pt
162
+ Vocab: hf://Jmica/F5TTS/JA_21999120/vocab_japanese.txt
163
+ Config: {"dim": 1024, "depth": 22, "heads": 16, "ff_mult": 2, "text_dim": 512, "text_mask_padding": False, "conv_layers": 4, "pe_attn_head": 1}
164
+ ```
165
+
166
+
167
+ ## Mandarin
168
+
169
+
170
+ ## Russian
171
+
172
+ #### F5-TTS Base @ ru @ HotDro4illa
173
+ |Model|🤗Hugging Face|Data (Hours)|Model License|
174
+ |:---:|:------------:|:-----------:|:-------------:|
175
+ |F5-TTS Base|[ckpt & vocab](https://huggingface.co/hotstone228/F5-TTS-Russian)|[Common voice](https://huggingface.co/datasets/mozilla-foundation/common_voice_17_0)|cc-by-nc-4.0|
176
+
177
+ ```bash
178
+ Model: hf://hotstone228/F5-TTS-Russian/model_last.safetensors
179
+ Vocab: hf://hotstone228/F5-TTS-Russian/vocab.txt
180
+ Config: {"dim": 1024, "depth": 22, "heads": 16, "ff_mult": 2, "text_dim": 512, "text_mask_padding": False, "conv_layers": 4, "pe_attn_head": 1}
181
+ ```
182
+ - Finetuned by [HotDro4illa](https://github.com/HotDro4illa)
183
+ - Any improvements are welcome
184
+
185
+
186
+ ## Spanish
187
+
188
+ #### F5-TTS Base @ es @ jpgallegoar
189
+ |Model|🤗Hugging Face|Data (Hours)|Model License|
190
+ |:---:|:------------:|:-----------:|:-------------:|
191
+ |F5-TTS Base|[ckpt & vocab](https://huggingface.co/jpgallegoar/F5-Spanish)|[Voxpopuli](https://huggingface.co/datasets/facebook/voxpopuli) & Crowdsourced & TEDx, 218 hours|cc0-1.0|
192
+
193
+ - @jpgallegoar [GitHub repo](https://github.com/jpgallegoar/Spanish-F5), Jupyter Notebook and Gradio usage for Spanish model.
src/f5_tts/infer/cls_tokenizer_v2.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import string
3
+
4
+ try:
5
+ from indic_unified_parser.uparser import wordparse
6
+ except Exception: # noqa: BLE001
7
+ wordparse = None
8
+
9
+ script_ranges = {
10
+ # Indo-Aryan
11
+ "devanagari": [("\u0900", "\u097F")], # Hindi, Marathi
12
+ "arabic": [("\u0600", "\u06FF")], # Urdu
13
+ "gurmukhi": [("\u0A00", "\u0A7F")], # Punjabi
14
+ "gujarati": [("\u0A80", "\u0AFF")], # Gujarati
15
+ "bengali": [("\u0980", "\u09FF")], # Bengali
16
+ "odia": [("\u0B00", "\u0B7F")], # Odia
17
+
18
+ # Dravidian
19
+ "tamil": [("\u0B80", "\u0BFF")], # Tamil
20
+ "telugu": [("\u0C00", "\u0C7F")], # Telugu
21
+ "kannada": [("\u0C80", "\u0CFF")], # Kannada
22
+ "malayalam": [("\u0D00", "\u0D7F")], # Malayalam
23
+
24
+ # English + digits + common punctuation
25
+ "latin_basic": [("\u0020", "\u007E")] # English letters, digits, ASCII symbols
26
+ }
27
+
28
+ def has_non_indic_script(text):
29
+ """
30
+ Check if text contains any other characters from the specified Indic/Urdu scripts.
31
+
32
+ Returns True if any character falls in the Unicode ranges outside of Hindi/Marathi (Devanagari),
33
+ Gujarati, Punjabi (Gurmukhi), Urdu (Arabic), English (Latin) False otherwise.
34
+ """
35
+ for char in text:
36
+ for lang, ranges in script_ranges.items():
37
+ for start, end in ranges:
38
+ if start <= char <= end:
39
+ return False
40
+ return True
41
+
42
+ non_problematic_chars = set()
43
+
44
+ for lang, ranges in script_ranges.items():
45
+ for start, end in ranges:
46
+ for char in range(ord(start), ord(end)+1):
47
+ parsed = None
48
+ try:
49
+ parsed = wordparse(chr(char), 0, 0, 1)
50
+ except Exception as e:
51
+ pass
52
+ if parsed is not None and isinstance(parsed, str) and parsed.strip() != "":
53
+ non_problematic_chars.add(chr(char))
54
+
55
+ def get_transliteration(text, language):
56
+ if language.lower() == "urdu":
57
+ # We will not add bias with transliteration as of now
58
+ # text = ml_transliterate(text, from_script="ur-PK", to_script="hi-IN")
59
+ pass
60
+ elif language.lower() == "punjabi":
61
+ # GURUMUKHI TO DEVNAGRI IS NOT THERE - SKIPPING FOR NOW, WILL REVIST IF CLS SHOWS EVIDENCE OF IMPROVEMENT
62
+ # text = script_convert(text, from_script="pa-IN", to_script="hi-IN")
63
+ pass
64
+ return text
65
+
66
+ def normalize_indic_nasals(text):
67
+ # Combined pattern and replacement using capturing groups for script-specific anusvara and consonant groups
68
+ pattern = (
69
+ r'(ं|ং|ં|ਂ|ಂ|ം|ଂ|ం|ஂ)' # anusvara chars for Devanagari, Bengali, Gujarati, Punjabi, Kannada, Malayalam, Odia, Telugu, Tamil
70
+ r'([कखगघङचछजझञटठडढणतथदधनपफबभम'
71
+ r'কখগঘঙচছজঝঞটঠডঢণতথদধনপফবভম'
72
+ r'કખગઘઙચછજઝઞટઠડઢણતથદધનપફબભમ'
73
+ r'ਕਖਗਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮ'
74
+ r'ಕಖಗಘಙಚಛಜಝಞಟಠಡಢಣತಥದಧನಪಫಬಭಮ'
75
+ r'കഖഗഘങചഛജഝഞടഠഡഢണതഥദധനപഫബഭമ'
76
+ r'କଖଗଘଙଚଛଜଝଞଟଠଡଢଣତଥଦଧନପଫବଭମ'
77
+ r'కఖగఘఙచఛజఝఞటఠడఢణతథదధనపఫబభమ'
78
+ r'கஙசஜஞடணதநபம])'
79
+ )
80
+
81
+ replacement = lambda m: {
82
+ # Mapping anusvara to conjunct nasal for each script block
83
+ 'ं': {'क': 'ङ्', 'ख': 'ङ्', 'ग': 'ङ्', 'घ': 'ङ्', 'ङ': 'ङ्',
84
+ 'च': 'ञ्', 'छ': 'ञ्', 'ज': 'ञ्', 'झ': 'ञ्', 'ञ': 'ञ्',
85
+ 'ट': 'ण्', 'ठ': 'ण्', 'ड': 'ण्', 'ढ': 'ण्', 'ण': 'ण्',
86
+ 'त': 'न्', 'थ': 'न्', 'द': 'न्', 'ध': 'न्', 'न': 'न्',
87
+ 'प': 'म्', 'फ': 'म्', 'ब': 'म्', 'भ': 'म्', 'म': 'म्'},
88
+ 'ং': {'ক': 'ঙ্', 'খ': 'ঙ্', 'গ': 'ঙ্', 'ঘ': 'ঙ্', 'ঙ': 'ঙ্',
89
+ 'চ': 'ঞ্', 'ছ': 'ঞ্', 'জ': 'ঞ্', 'ঝ': 'ঞ্', 'ঞ': 'ঞ্',
90
+ 'ট': 'ণ্', 'ঠ': 'ণ্', 'ড': 'ণ্', 'ঢ': 'ণ্', 'ণ': 'ণ্',
91
+ 'ত': 'ন্', 'থ': 'ন্', 'দ': 'ন্', 'ধ': 'ন্', 'ন': 'ন্',
92
+ 'প': 'ম্', 'ফ': 'ম্', 'ব': 'ম্', 'ভ': 'ম্', 'ম': 'ম্'},
93
+ 'ં': {'ક': 'ઙ્', 'ખ': 'ઙ્', 'ગ': 'ઙ્', 'ઘ': 'ઙ્', 'ઙ': 'ઙ્',
94
+ 'ચ': 'ઞ્', 'છ': 'ઞ્', 'જ': 'ઞ્', 'ઝ': 'ઞ્', 'ઞ': 'ઞ્',
95
+ 'ટ': 'ણ્', 'ઠ': 'ણ્', 'ડ': 'ણ્', 'ઢ': 'ણ્', 'ણ': 'ણ્',
96
+ 'ત': 'ન્', 'થ': 'ન્', 'દ': 'ન્', 'ધ': 'ન્', 'ન': 'ન્',
97
+ 'પ': 'મ્', 'ફ': 'મ્', 'બ': 'મ્', 'ભ': 'મ્', 'મ': 'મ્'},
98
+ 'ਂ': {'ਕ': 'ਙ੍', 'ਖ': 'ਙ੍', 'ਗ': 'ਙ੍', 'ਘ': 'ਙ੍', 'ਙ': 'ਙ੍',
99
+ 'ਚ': 'ਞ੍', 'ਛ': 'ਞ੍', 'ਜ': 'ਞ੍', 'ਝ': 'ਞ੍', 'ਞ': 'ਞ੍',
100
+ 'ਟ': 'ਣ੍', 'ਠ': 'ਣ੍', 'ਡ': 'ਣ੍', 'ਢ': 'ਣ੍', 'ਣ': 'ਣ੍',
101
+ 'ਤ': 'ਨ੍', 'ਥ': 'ਨ੍', 'ਦ': 'ਨ੍', 'ਧ': 'ਨ੍', 'ਨ': 'ਨ੍',
102
+ 'ਪ': 'ਮ੍', 'ਫ': 'ਮ੍', 'ਬ': 'ਮ੍', 'ਭ': 'ਮ੍', 'ਮ': 'ਮ੍'},
103
+ 'ಂ': {'ಕ': 'ಙ್', 'ಖ': 'ಙ್', 'ಗ': 'ಙ್', 'ಘ': 'ಙ್', 'ಙ': 'ಙ್',
104
+ 'ಚ': 'ಞ್', 'ಛ': 'ಞ್', 'ಜ': 'ಞ್', 'ಝ': 'ಞ್', 'ಞ': 'ಞ್',
105
+ 'ಟ': 'ಣ್', 'ಠ': 'ಣ್', 'ಡ': 'ಣ್', 'ಢ': 'ಣ್', 'ಣ': 'ಣ್',
106
+ 'ತ': 'ನ್', 'ಥ': 'ನ್', 'ದ': 'ನ್', 'ಧ': 'ನ್', 'ನ': 'ನ್',
107
+ 'ಪ': 'ಮ್', 'ಫ': 'ಮ್', 'ಬ': 'ಮ್', 'ಭ': 'ಮ್', 'ಮ': 'ಮ್'},
108
+ 'ം': {'ക': 'ങ്', 'ഖ': 'ങ്', 'ഗ': 'ങ്', 'ഘ': 'ങ്', 'ങ': 'ങ്',
109
+ 'ച': 'ഞ്', 'ഛ': 'ഞ്', 'ജ': 'ഞ്', 'ഝ': 'ഞ്', 'ഞ': 'ഞ്',
110
+ 'ട': 'ണ്', 'ഠ': 'ണ്', 'ഡ': 'ണ്', 'ഢ': 'ണ്', 'ണ': 'ണ',
111
+ 'ത': 'ന്', 'ഥ': 'ന്', 'ദ': 'ന്', 'ധ': 'ന്', 'ന': 'ന്',
112
+ 'പ': 'മ്', 'ഫ': 'മ്', 'ബ': 'മ്', 'ഭ': 'മ്', 'മ': 'മ്'},
113
+ 'ଂ': {'କ': 'ଙ୍', 'ଖ': 'ଙ୍', 'ଗ': 'ଙ୍', 'ଘ': 'ଙ୍', 'ଙ': 'ଙ୍',
114
+ 'ଚ': 'ଞ୍', 'ଛ': 'ଞ୍', 'ଜ': 'ଞ୍', 'ଝ': 'ଞ୍', 'ଞ': 'ଞ୍',
115
+ 'ଟ': 'ଣ୍', 'ଠ': 'ଣ୍', 'ଡ': 'ଣ୍', 'ଢ': 'ଣ୍', 'ଣ': 'ଣ୍',
116
+ 'ତ': 'ନ୍', 'ଥ': 'ନ୍', 'ଦ': 'ନ୍', 'ଧ': 'ନ୍', 'ନ': 'ନ୍',
117
+ 'ପ': 'ମ୍', 'ଫ': 'ମ୍', 'ବ': 'ମ୍', 'ଭ': 'ମ୍', 'ମ': 'ମ୍'},
118
+ 'ం': {'క': 'ఙ్', 'ఖ': 'ఙ్', 'గ': 'ఙ్', 'ఘ': 'ఙ్', 'ఙ': 'ఙ్',
119
+ 'చ': 'ఞ్', 'ఛ': 'ఞ్', 'జ': 'ఞ్', 'ఝ': 'ఞ్', 'ఞ': 'ఞ్',
120
+ 'ట': 'ణ్', 'ఠ': 'ణ్', 'డ': 'ణ్', 'ఢ': 'ణ్', 'ణ': 'ణ్',
121
+ 'త': 'న్', 'థ': 'న్', 'ద': 'న్', 'ధ': 'న్', 'న': 'న్',
122
+ 'ప': 'మ్', 'ఫ': 'మ్', 'బ': 'మ్', 'భ': 'మ్', 'మ': 'మ్'},
123
+ 'ஂ': {'க': 'ங்', 'ங': 'ங்',
124
+ 'ச': 'ஞ்', 'ஜ': 'ஞ்', 'ஞ': 'ஞ்',
125
+ 'ட': 'ண்', 'ண': 'ண்',
126
+ 'த': 'ந்', 'ந': 'ந்',
127
+ 'ப': 'ம்', 'ம': 'ம்'}
128
+ }[m.group(1)][m.group(2)] + m.group(2)
129
+
130
+ return re.sub(pattern, replacement, text)
131
+
132
+ def process_segment(segment, state, language):
133
+ if state == "problematic":
134
+ return list(segment)
135
+ elif state == "english":
136
+ return [f"en_{char}" for char in segment]
137
+ else:
138
+ try:
139
+ return wordparse(segment, 0, 0, 1).split()
140
+ except Exception as e:
141
+ return list(segment)
142
+
143
+ def get_cls_token_list(text, language):
144
+ cls_token_list = []
145
+ state = "text"
146
+ if has_non_indic_script(text):
147
+ raise Exception("Non-indic script found in text.")
148
+ for word in text.split():
149
+ segment = ""
150
+ for char in word:
151
+ if char in string.ascii_letters:
152
+ curr_state = "english"
153
+ elif char in non_problematic_chars:
154
+ curr_state = "text"
155
+ else:
156
+ curr_state = "problematic"
157
+ if state != curr_state:
158
+ cls_token_list.extend(process_segment(segment, state, language))
159
+ segment = ""
160
+ segment += char
161
+ state = curr_state
162
+ if segment:
163
+ cls_token_list.extend(process_segment(segment, state, language))
164
+ cls_token_list.append(" ")
165
+ return cls_token_list[:-1]
166
+
167
+ def get_cls_for_out_of_mapping(text):
168
+ cls_token_list = []
169
+ for word in text.split():
170
+ for char in word:
171
+ processed_char = char
172
+ if char in string.ascii_letters:
173
+ processed_char = f"en_{char}"
174
+ cls_token_list.append(processed_char)
175
+ cls_token_list.append(" ")
176
+ return cls_token_list[:-1]
177
+
178
+ def cls_tokenize_text(text: str, language: str):
179
+ if wordparse is None:
180
+ raise RuntimeError("indic_unified_parser is required for CLS tokenization but is not installed.")
181
+ return get_cls_token_list(normalize_indic_nasals(get_transliteration(text.lower(), language)), language)
src/f5_tts/infer/examples/basic/basic.toml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # F5TTS_v1_Base | E2TTS_Base
2
+ model = "F5TTS_v1_Base"
3
+ ref_audio = "infer/examples/basic/basic_ref_en.wav"
4
+ # If an empty "", transcribes the reference audio automatically.
5
+ ref_text = "Some call me nature, others call me mother nature."
6
+ gen_text = "I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring."
7
+ # File with text to generate. Ignores the text above.
8
+ gen_file = ""
9
+ remove_silence = false
10
+ output_dir = "tests"
11
+ output_file = "infer_cli_basic.wav"
src/f5_tts/infer/examples/multi/story.toml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # F5TTS_v1_Base | E2TTS_Base
2
+ model = "F5TTS_v1_Base"
3
+ ref_audio = "infer/examples/multi/main.flac"
4
+ # If an empty "", transcribes the reference audio automatically.
5
+ ref_text = ""
6
+ gen_text = ""
7
+ # File with text to generate. Ignores the text above.
8
+ gen_file = "infer/examples/multi/story.txt"
9
+ remove_silence = true
10
+ output_dir = "tests"
11
+ output_file = "infer_cli_story.wav"
12
+
13
+ [voices.town]
14
+ ref_audio = "infer/examples/multi/town.flac"
15
+ ref_text = ""
16
+ speed = 0.8 # will ignore global speed
17
+
18
+ [voices.country]
19
+ ref_audio = "infer/examples/multi/country.flac"
20
+ ref_text = ""
src/f5_tts/infer/examples/multi/story.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A Town Mouse and a Country Mouse were acquaintances, and the Country Mouse one day invited his friend to come and see him at his home in the fields. The Town Mouse came, and they sat down to a dinner of barleycorns and roots, the latter of which had a distinctly earthy flavour. The fare was not much to the taste of the guest, and presently he broke out with [town] "My poor dear friend, you live here no better than the ants! Now, you should just see how I fare! My larder is a regular horn of plenty. You must come and stay with me, and I promise you you shall live on the fat of the land." [main] So when he returned to town he took the Country Mouse with him, and showed him into a larder containing flour and oatmeal and figs and honey and dates. The Country Mouse had never seen anything like it, and sat down to enjoy the luxuries his friend provided: but before they had well begun, the door of the larder opened and someone came in. The two Mice scampered off and hid themselves in a narrow and exceedingly uncomfortable hole. Presently, when all was quiet, they ventured out again; but someone else came in, and off they scuttled again. This was too much for the visitor. [country] "Goodbye," [main] said he, [country] "I'm off. You live in the lap of luxury, I can see, but you are surrounded by dangers; whereas at home I can enjoy my simple dinner of roots and corn in peace."
src/f5_tts/infer/examples/vocab.txt ADDED
@@ -0,0 +1,2545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ !
3
+ "
4
+ #
5
+ $
6
+ %
7
+ &
8
+ '
9
+ (
10
+ )
11
+ *
12
+ +
13
+ ,
14
+ -
15
+ .
16
+ /
17
+ 0
18
+ 1
19
+ 2
20
+ 3
21
+ 4
22
+ 5
23
+ 6
24
+ 7
25
+ 8
26
+ 9
27
+ :
28
+ ;
29
+ =
30
+ >
31
+ ?
32
+ @
33
+ A
34
+ B
35
+ C
36
+ D
37
+ E
38
+ F
39
+ G
40
+ H
41
+ I
42
+ J
43
+ K
44
+ L
45
+ M
46
+ N
47
+ O
48
+ P
49
+ Q
50
+ R
51
+ S
52
+ T
53
+ U
54
+ V
55
+ W
56
+ X
57
+ Y
58
+ Z
59
+ [
60
+ \
61
+ ]
62
+ _
63
+ a
64
+ a1
65
+ ai1
66
+ ai2
67
+ ai3
68
+ ai4
69
+ an1
70
+ an3
71
+ an4
72
+ ang1
73
+ ang2
74
+ ang4
75
+ ao1
76
+ ao2
77
+ ao3
78
+ ao4
79
+ b
80
+ ba
81
+ ba1
82
+ ba2
83
+ ba3
84
+ ba4
85
+ bai1
86
+ bai2
87
+ bai3
88
+ bai4
89
+ ban1
90
+ ban2
91
+ ban3
92
+ ban4
93
+ bang1
94
+ bang2
95
+ bang3
96
+ bang4
97
+ bao1
98
+ bao2
99
+ bao3
100
+ bao4
101
+ bei
102
+ bei1
103
+ bei2
104
+ bei3
105
+ bei4
106
+ ben1
107
+ ben2
108
+ ben3
109
+ ben4
110
+ beng
111
+ beng1
112
+ beng2
113
+ beng3
114
+ beng4
115
+ bi1
116
+ bi2
117
+ bi3
118
+ bi4
119
+ bian1
120
+ bian2
121
+ bian3
122
+ bian4
123
+ biao1
124
+ biao2
125
+ biao3
126
+ bie1
127
+ bie2
128
+ bie3
129
+ bie4
130
+ bin1
131
+ bin4
132
+ bing1
133
+ bing2
134
+ bing3
135
+ bing4
136
+ bo
137
+ bo1
138
+ bo2
139
+ bo3
140
+ bo4
141
+ bu2
142
+ bu3
143
+ bu4
144
+ c
145
+ ca1
146
+ cai1
147
+ cai2
148
+ cai3
149
+ cai4
150
+ can1
151
+ can2
152
+ can3
153
+ can4
154
+ cang1
155
+ cang2
156
+ cao1
157
+ cao2
158
+ cao3
159
+ ce4
160
+ cen1
161
+ cen2
162
+ ceng1
163
+ ceng2
164
+ ceng4
165
+ cha1
166
+ cha2
167
+ cha3
168
+ cha4
169
+ chai1
170
+ chai2
171
+ chan1
172
+ chan2
173
+ chan3
174
+ chan4
175
+ chang1
176
+ chang2
177
+ chang3
178
+ chang4
179
+ chao1
180
+ chao2
181
+ chao3
182
+ che1
183
+ che2
184
+ che3
185
+ che4
186
+ chen1
187
+ chen2
188
+ chen3
189
+ chen4
190
+ cheng1
191
+ cheng2
192
+ cheng3
193
+ cheng4
194
+ chi1
195
+ chi2
196
+ chi3
197
+ chi4
198
+ chong1
199
+ chong2
200
+ chong3
201
+ chong4
202
+ chou1
203
+ chou2
204
+ chou3
205
+ chou4
206
+ chu1
207
+ chu2
208
+ chu3
209
+ chu4
210
+ chua1
211
+ chuai1
212
+ chuai2
213
+ chuai3
214
+ chuai4
215
+ chuan1
216
+ chuan2
217
+ chuan3
218
+ chuan4
219
+ chuang1
220
+ chuang2
221
+ chuang3
222
+ chuang4
223
+ chui1
224
+ chui2
225
+ chun1
226
+ chun2
227
+ chun3
228
+ chuo1
229
+ chuo4
230
+ ci1
231
+ ci2
232
+ ci3
233
+ ci4
234
+ cong1
235
+ cong2
236
+ cou4
237
+ cu1
238
+ cu4
239
+ cuan1
240
+ cuan2
241
+ cuan4
242
+ cui1
243
+ cui3
244
+ cui4
245
+ cun1
246
+ cun2
247
+ cun4
248
+ cuo1
249
+ cuo2
250
+ cuo4
251
+ d
252
+ da
253
+ da1
254
+ da2
255
+ da3
256
+ da4
257
+ dai1
258
+ dai2
259
+ dai3
260
+ dai4
261
+ dan1
262
+ dan2
263
+ dan3
264
+ dan4
265
+ dang1
266
+ dang2
267
+ dang3
268
+ dang4
269
+ dao1
270
+ dao2
271
+ dao3
272
+ dao4
273
+ de
274
+ de1
275
+ de2
276
+ dei3
277
+ den4
278
+ deng1
279
+ deng2
280
+ deng3
281
+ deng4
282
+ di1
283
+ di2
284
+ di3
285
+ di4
286
+ dia3
287
+ dian1
288
+ dian2
289
+ dian3
290
+ dian4
291
+ diao1
292
+ diao3
293
+ diao4
294
+ die1
295
+ die2
296
+ die4
297
+ ding1
298
+ ding2
299
+ ding3
300
+ ding4
301
+ diu1
302
+ dong1
303
+ dong3
304
+ dong4
305
+ dou1
306
+ dou2
307
+ dou3
308
+ dou4
309
+ du1
310
+ du2
311
+ du3
312
+ du4
313
+ duan1
314
+ duan2
315
+ duan3
316
+ duan4
317
+ dui1
318
+ dui4
319
+ dun1
320
+ dun3
321
+ dun4
322
+ duo1
323
+ duo2
324
+ duo3
325
+ duo4
326
+ e
327
+ e1
328
+ e2
329
+ e3
330
+ e4
331
+ ei2
332
+ en1
333
+ en4
334
+ er
335
+ er2
336
+ er3
337
+ er4
338
+ f
339
+ fa1
340
+ fa2
341
+ fa3
342
+ fa4
343
+ fan1
344
+ fan2
345
+ fan3
346
+ fan4
347
+ fang1
348
+ fang2
349
+ fang3
350
+ fang4
351
+ fei1
352
+ fei2
353
+ fei3
354
+ fei4
355
+ fen1
356
+ fen2
357
+ fen3
358
+ fen4
359
+ feng1
360
+ feng2
361
+ feng3
362
+ feng4
363
+ fo2
364
+ fou2
365
+ fou3
366
+ fu1
367
+ fu2
368
+ fu3
369
+ fu4
370
+ g
371
+ ga1
372
+ ga2
373
+ ga3
374
+ ga4
375
+ gai1
376
+ gai2
377
+ gai3
378
+ gai4
379
+ gan1
380
+ gan2
381
+ gan3
382
+ gan4
383
+ gang1
384
+ gang2
385
+ gang3
386
+ gang4
387
+ gao1
388
+ gao2
389
+ gao3
390
+ gao4
391
+ ge1
392
+ ge2
393
+ ge3
394
+ ge4
395
+ gei2
396
+ gei3
397
+ gen1
398
+ gen2
399
+ gen3
400
+ gen4
401
+ geng1
402
+ geng3
403
+ geng4
404
+ gong1
405
+ gong3
406
+ gong4
407
+ gou1
408
+ gou2
409
+ gou3
410
+ gou4
411
+ gu
412
+ gu1
413
+ gu2
414
+ gu3
415
+ gu4
416
+ gua1
417
+ gua2
418
+ gua3
419
+ gua4
420
+ guai1
421
+ guai2
422
+ guai3
423
+ guai4
424
+ guan1
425
+ guan2
426
+ guan3
427
+ guan4
428
+ guang1
429
+ guang2
430
+ guang3
431
+ guang4
432
+ gui1
433
+ gui2
434
+ gui3
435
+ gui4
436
+ gun3
437
+ gun4
438
+ guo1
439
+ guo2
440
+ guo3
441
+ guo4
442
+ h
443
+ ha1
444
+ ha2
445
+ ha3
446
+ hai1
447
+ hai2
448
+ hai3
449
+ hai4
450
+ han1
451
+ han2
452
+ han3
453
+ han4
454
+ hang1
455
+ hang2
456
+ hang4
457
+ hao1
458
+ hao2
459
+ hao3
460
+ hao4
461
+ he1
462
+ he2
463
+ he4
464
+ hei1
465
+ hen2
466
+ hen3
467
+ hen4
468
+ heng1
469
+ heng2
470
+ heng4
471
+ hong1
472
+ hong2
473
+ hong3
474
+ hong4
475
+ hou1
476
+ hou2
477
+ hou3
478
+ hou4
479
+ hu1
480
+ hu2
481
+ hu3
482
+ hu4
483
+ hua1
484
+ hua2
485
+ hua4
486
+ huai2
487
+ huai4
488
+ huan1
489
+ huan2
490
+ huan3
491
+ huan4
492
+ huang1
493
+ huang2
494
+ huang3
495
+ huang4
496
+ hui1
497
+ hui2
498
+ hui3
499
+ hui4
500
+ hun1
501
+ hun2
502
+ hun4
503
+ huo
504
+ huo1
505
+ huo2
506
+ huo3
507
+ huo4
508
+ i
509
+ j
510
+ ji1
511
+ ji2
512
+ ji3
513
+ ji4
514
+ jia
515
+ jia1
516
+ jia2
517
+ jia3
518
+ jia4
519
+ jian1
520
+ jian2
521
+ jian3
522
+ jian4
523
+ jiang1
524
+ jiang2
525
+ jiang3
526
+ jiang4
527
+ jiao1
528
+ jiao2
529
+ jiao3
530
+ jiao4
531
+ jie1
532
+ jie2
533
+ jie3
534
+ jie4
535
+ jin1
536
+ jin2
537
+ jin3
538
+ jin4
539
+ jing1
540
+ jing2
541
+ jing3
542
+ jing4
543
+ jiong3
544
+ jiu1
545
+ jiu2
546
+ jiu3
547
+ jiu4
548
+ ju1
549
+ ju2
550
+ ju3
551
+ ju4
552
+ juan1
553
+ juan2
554
+ juan3
555
+ juan4
556
+ jue1
557
+ jue2
558
+ jue4
559
+ jun1
560
+ jun4
561
+ k
562
+ ka1
563
+ ka2
564
+ ka3
565
+ kai1
566
+ kai2
567
+ kai3
568
+ kai4
569
+ kan1
570
+ kan2
571
+ kan3
572
+ kan4
573
+ kang1
574
+ kang2
575
+ kang4
576
+ kao1
577
+ kao2
578
+ kao3
579
+ kao4
580
+ ke1
581
+ ke2
582
+ ke3
583
+ ke4
584
+ ken3
585
+ keng1
586
+ kong1
587
+ kong3
588
+ kong4
589
+ kou1
590
+ kou2
591
+ kou3
592
+ kou4
593
+ ku1
594
+ ku2
595
+ ku3
596
+ ku4
597
+ kua1
598
+ kua3
599
+ kua4
600
+ kuai3
601
+ kuai4
602
+ kuan1
603
+ kuan2
604
+ kuan3
605
+ kuang1
606
+ kuang2
607
+ kuang4
608
+ kui1
609
+ kui2
610
+ kui3
611
+ kui4
612
+ kun1
613
+ kun3
614
+ kun4
615
+ kuo4
616
+ l
617
+ la
618
+ la1
619
+ la2
620
+ la3
621
+ la4
622
+ lai2
623
+ lai4
624
+ lan2
625
+ lan3
626
+ lan4
627
+ lang1
628
+ lang2
629
+ lang3
630
+ lang4
631
+ lao1
632
+ lao2
633
+ lao3
634
+ lao4
635
+ le
636
+ le1
637
+ le4
638
+ lei
639
+ lei1
640
+ lei2
641
+ lei3
642
+ lei4
643
+ leng1
644
+ leng2
645
+ leng3
646
+ leng4
647
+ li
648
+ li1
649
+ li2
650
+ li3
651
+ li4
652
+ lia3
653
+ lian2
654
+ lian3
655
+ lian4
656
+ liang2
657
+ liang3
658
+ liang4
659
+ liao1
660
+ liao2
661
+ liao3
662
+ liao4
663
+ lie1
664
+ lie2
665
+ lie3
666
+ lie4
667
+ lin1
668
+ lin2
669
+ lin3
670
+ lin4
671
+ ling2
672
+ ling3
673
+ ling4
674
+ liu1
675
+ liu2
676
+ liu3
677
+ liu4
678
+ long1
679
+ long2
680
+ long3
681
+ long4
682
+ lou1
683
+ lou2
684
+ lou3
685
+ lou4
686
+ lu1
687
+ lu2
688
+ lu3
689
+ lu4
690
+ luan2
691
+ luan3
692
+ luan4
693
+ lun1
694
+ lun2
695
+ lun4
696
+ luo1
697
+ luo2
698
+ luo3
699
+ luo4
700
+ lv2
701
+ lv3
702
+ lv4
703
+ lve3
704
+ lve4
705
+ m
706
+ ma
707
+ ma1
708
+ ma2
709
+ ma3
710
+ ma4
711
+ mai2
712
+ mai3
713
+ mai4
714
+ man1
715
+ man2
716
+ man3
717
+ man4
718
+ mang2
719
+ mang3
720
+ mao1
721
+ mao2
722
+ mao3
723
+ mao4
724
+ me
725
+ mei2
726
+ mei3
727
+ mei4
728
+ men
729
+ men1
730
+ men2
731
+ men4
732
+ meng
733
+ meng1
734
+ meng2
735
+ meng3
736
+ meng4
737
+ mi1
738
+ mi2
739
+ mi3
740
+ mi4
741
+ mian2
742
+ mian3
743
+ mian4
744
+ miao1
745
+ miao2
746
+ miao3
747
+ miao4
748
+ mie1
749
+ mie4
750
+ min2
751
+ min3
752
+ ming2
753
+ ming3
754
+ ming4
755
+ miu4
756
+ mo1
757
+ mo2
758
+ mo3
759
+ mo4
760
+ mou1
761
+ mou2
762
+ mou3
763
+ mu2
764
+ mu3
765
+ mu4
766
+ n
767
+ n2
768
+ na1
769
+ na2
770
+ na3
771
+ na4
772
+ nai2
773
+ nai3
774
+ nai4
775
+ nan1
776
+ nan2
777
+ nan3
778
+ nan4
779
+ nang1
780
+ nang2
781
+ nang3
782
+ nao1
783
+ nao2
784
+ nao3
785
+ nao4
786
+ ne
787
+ ne2
788
+ ne4
789
+ nei3
790
+ nei4
791
+ nen4
792
+ neng2
793
+ ni1
794
+ ni2
795
+ ni3
796
+ ni4
797
+ nian1
798
+ nian2
799
+ nian3
800
+ nian4
801
+ niang2
802
+ niang4
803
+ niao2
804
+ niao3
805
+ niao4
806
+ nie1
807
+ nie4
808
+ nin2
809
+ ning2
810
+ ning3
811
+ ning4
812
+ niu1
813
+ niu2
814
+ niu3
815
+ niu4
816
+ nong2
817
+ nong4
818
+ nou4
819
+ nu2
820
+ nu3
821
+ nu4
822
+ nuan3
823
+ nuo2
824
+ nuo4
825
+ nv2
826
+ nv3
827
+ nve4
828
+ o
829
+ o1
830
+ o2
831
+ ou1
832
+ ou2
833
+ ou3
834
+ ou4
835
+ p
836
+ pa1
837
+ pa2
838
+ pa4
839
+ pai1
840
+ pai2
841
+ pai3
842
+ pai4
843
+ pan1
844
+ pan2
845
+ pan4
846
+ pang1
847
+ pang2
848
+ pang4
849
+ pao1
850
+ pao2
851
+ pao3
852
+ pao4
853
+ pei1
854
+ pei2
855
+ pei4
856
+ pen1
857
+ pen2
858
+ pen4
859
+ peng1
860
+ peng2
861
+ peng3
862
+ peng4
863
+ pi1
864
+ pi2
865
+ pi3
866
+ pi4
867
+ pian1
868
+ pian2
869
+ pian4
870
+ piao1
871
+ piao2
872
+ piao3
873
+ piao4
874
+ pie1
875
+ pie2
876
+ pie3
877
+ pin1
878
+ pin2
879
+ pin3
880
+ pin4
881
+ ping1
882
+ ping2
883
+ po1
884
+ po2
885
+ po3
886
+ po4
887
+ pou1
888
+ pu1
889
+ pu2
890
+ pu3
891
+ pu4
892
+ q
893
+ qi1
894
+ qi2
895
+ qi3
896
+ qi4
897
+ qia1
898
+ qia3
899
+ qia4
900
+ qian1
901
+ qian2
902
+ qian3
903
+ qian4
904
+ qiang1
905
+ qiang2
906
+ qiang3
907
+ qiang4
908
+ qiao1
909
+ qiao2
910
+ qiao3
911
+ qiao4
912
+ qie1
913
+ qie2
914
+ qie3
915
+ qie4
916
+ qin1
917
+ qin2
918
+ qin3
919
+ qin4
920
+ qing1
921
+ qing2
922
+ qing3
923
+ qing4
924
+ qiong1
925
+ qiong2
926
+ qiu1
927
+ qiu2
928
+ qiu3
929
+ qu1
930
+ qu2
931
+ qu3
932
+ qu4
933
+ quan1
934
+ quan2
935
+ quan3
936
+ quan4
937
+ que1
938
+ que2
939
+ que4
940
+ qun2
941
+ r
942
+ ran2
943
+ ran3
944
+ rang1
945
+ rang2
946
+ rang3
947
+ rang4
948
+ rao2
949
+ rao3
950
+ rao4
951
+ re2
952
+ re3
953
+ re4
954
+ ren2
955
+ ren3
956
+ ren4
957
+ reng1
958
+ reng2
959
+ ri4
960
+ rong1
961
+ rong2
962
+ rong3
963
+ rou2
964
+ rou4
965
+ ru2
966
+ ru3
967
+ ru4
968
+ ruan2
969
+ ruan3
970
+ rui3
971
+ rui4
972
+ run4
973
+ ruo4
974
+ s
975
+ sa1
976
+ sa2
977
+ sa3
978
+ sa4
979
+ sai1
980
+ sai4
981
+ san1
982
+ san2
983
+ san3
984
+ san4
985
+ sang1
986
+ sang3
987
+ sang4
988
+ sao1
989
+ sao2
990
+ sao3
991
+ sao4
992
+ se4
993
+ sen1
994
+ seng1
995
+ sha1
996
+ sha2
997
+ sha3
998
+ sha4
999
+ shai1
1000
+ shai2
1001
+ shai3
1002
+ shai4
1003
+ shan1
1004
+ shan3
1005
+ shan4
1006
+ shang
1007
+ shang1
1008
+ shang3
1009
+ shang4
1010
+ shao1
1011
+ shao2
1012
+ shao3
1013
+ shao4
1014
+ she1
1015
+ she2
1016
+ she3
1017
+ she4
1018
+ shei2
1019
+ shen1
1020
+ shen2
1021
+ shen3
1022
+ shen4
1023
+ sheng1
1024
+ sheng2
1025
+ sheng3
1026
+ sheng4
1027
+ shi
1028
+ shi1
1029
+ shi2
1030
+ shi3
1031
+ shi4
1032
+ shou1
1033
+ shou2
1034
+ shou3
1035
+ shou4
1036
+ shu1
1037
+ shu2
1038
+ shu3
1039
+ shu4
1040
+ shua1
1041
+ shua2
1042
+ shua3
1043
+ shua4
1044
+ shuai1
1045
+ shuai3
1046
+ shuai4
1047
+ shuan1
1048
+ shuan4
1049
+ shuang1
1050
+ shuang3
1051
+ shui2
1052
+ shui3
1053
+ shui4
1054
+ shun3
1055
+ shun4
1056
+ shuo1
1057
+ shuo4
1058
+ si1
1059
+ si2
1060
+ si3
1061
+ si4
1062
+ song1
1063
+ song3
1064
+ song4
1065
+ sou1
1066
+ sou3
1067
+ sou4
1068
+ su1
1069
+ su2
1070
+ su4
1071
+ suan1
1072
+ suan4
1073
+ sui1
1074
+ sui2
1075
+ sui3
1076
+ sui4
1077
+ sun1
1078
+ sun3
1079
+ suo
1080
+ suo1
1081
+ suo2
1082
+ suo3
1083
+ t
1084
+ ta1
1085
+ ta2
1086
+ ta3
1087
+ ta4
1088
+ tai1
1089
+ tai2
1090
+ tai4
1091
+ tan1
1092
+ tan2
1093
+ tan3
1094
+ tan4
1095
+ tang1
1096
+ tang2
1097
+ tang3
1098
+ tang4
1099
+ tao1
1100
+ tao2
1101
+ tao3
1102
+ tao4
1103
+ te4
1104
+ teng2
1105
+ ti1
1106
+ ti2
1107
+ ti3
1108
+ ti4
1109
+ tian1
1110
+ tian2
1111
+ tian3
1112
+ tiao1
1113
+ tiao2
1114
+ tiao3
1115
+ tiao4
1116
+ tie1
1117
+ tie2
1118
+ tie3
1119
+ tie4
1120
+ ting1
1121
+ ting2
1122
+ ting3
1123
+ tong1
1124
+ tong2
1125
+ tong3
1126
+ tong4
1127
+ tou
1128
+ tou1
1129
+ tou2
1130
+ tou4
1131
+ tu1
1132
+ tu2
1133
+ tu3
1134
+ tu4
1135
+ tuan1
1136
+ tuan2
1137
+ tui1
1138
+ tui2
1139
+ tui3
1140
+ tui4
1141
+ tun1
1142
+ tun2
1143
+ tun4
1144
+ tuo1
1145
+ tuo2
1146
+ tuo3
1147
+ tuo4
1148
+ u
1149
+ v
1150
+ w
1151
+ wa
1152
+ wa1
1153
+ wa2
1154
+ wa3
1155
+ wa4
1156
+ wai1
1157
+ wai3
1158
+ wai4
1159
+ wan1
1160
+ wan2
1161
+ wan3
1162
+ wan4
1163
+ wang1
1164
+ wang2
1165
+ wang3
1166
+ wang4
1167
+ wei1
1168
+ wei2
1169
+ wei3
1170
+ wei4
1171
+ wen1
1172
+ wen2
1173
+ wen3
1174
+ wen4
1175
+ weng1
1176
+ weng4
1177
+ wo1
1178
+ wo2
1179
+ wo3
1180
+ wo4
1181
+ wu1
1182
+ wu2
1183
+ wu3
1184
+ wu4
1185
+ x
1186
+ xi1
1187
+ xi2
1188
+ xi3
1189
+ xi4
1190
+ xia1
1191
+ xia2
1192
+ xia4
1193
+ xian1
1194
+ xian2
1195
+ xian3
1196
+ xian4
1197
+ xiang1
1198
+ xiang2
1199
+ xiang3
1200
+ xiang4
1201
+ xiao1
1202
+ xiao2
1203
+ xiao3
1204
+ xiao4
1205
+ xie1
1206
+ xie2
1207
+ xie3
1208
+ xie4
1209
+ xin1
1210
+ xin2
1211
+ xin4
1212
+ xing1
1213
+ xing2
1214
+ xing3
1215
+ xing4
1216
+ xiong1
1217
+ xiong2
1218
+ xiu1
1219
+ xiu3
1220
+ xiu4
1221
+ xu
1222
+ xu1
1223
+ xu2
1224
+ xu3
1225
+ xu4
1226
+ xuan1
1227
+ xuan2
1228
+ xuan3
1229
+ xuan4
1230
+ xue1
1231
+ xue2
1232
+ xue3
1233
+ xue4
1234
+ xun1
1235
+ xun2
1236
+ xun4
1237
+ y
1238
+ ya
1239
+ ya1
1240
+ ya2
1241
+ ya3
1242
+ ya4
1243
+ yan1
1244
+ yan2
1245
+ yan3
1246
+ yan4
1247
+ yang1
1248
+ yang2
1249
+ yang3
1250
+ yang4
1251
+ yao1
1252
+ yao2
1253
+ yao3
1254
+ yao4
1255
+ ye1
1256
+ ye2
1257
+ ye3
1258
+ ye4
1259
+ yi
1260
+ yi1
1261
+ yi2
1262
+ yi3
1263
+ yi4
1264
+ yin1
1265
+ yin2
1266
+ yin3
1267
+ yin4
1268
+ ying1
1269
+ ying2
1270
+ ying3
1271
+ ying4
1272
+ yo1
1273
+ yong1
1274
+ yong2
1275
+ yong3
1276
+ yong4
1277
+ you1
1278
+ you2
1279
+ you3
1280
+ you4
1281
+ yu1
1282
+ yu2
1283
+ yu3
1284
+ yu4
1285
+ yuan1
1286
+ yuan2
1287
+ yuan3
1288
+ yuan4
1289
+ yue1
1290
+ yue4
1291
+ yun1
1292
+ yun2
1293
+ yun3
1294
+ yun4
1295
+ z
1296
+ za1
1297
+ za2
1298
+ za3
1299
+ zai1
1300
+ zai3
1301
+ zai4
1302
+ zan1
1303
+ zan2
1304
+ zan3
1305
+ zan4
1306
+ zang1
1307
+ zang4
1308
+ zao1
1309
+ zao2
1310
+ zao3
1311
+ zao4
1312
+ ze2
1313
+ ze4
1314
+ zei2
1315
+ zen3
1316
+ zeng1
1317
+ zeng4
1318
+ zha1
1319
+ zha2
1320
+ zha3
1321
+ zha4
1322
+ zhai1
1323
+ zhai2
1324
+ zhai3
1325
+ zhai4
1326
+ zhan1
1327
+ zhan2
1328
+ zhan3
1329
+ zhan4
1330
+ zhang1
1331
+ zhang2
1332
+ zhang3
1333
+ zhang4
1334
+ zhao1
1335
+ zhao2
1336
+ zhao3
1337
+ zhao4
1338
+ zhe
1339
+ zhe1
1340
+ zhe2
1341
+ zhe3
1342
+ zhe4
1343
+ zhen1
1344
+ zhen2
1345
+ zhen3
1346
+ zhen4
1347
+ zheng1
1348
+ zheng2
1349
+ zheng3
1350
+ zheng4
1351
+ zhi1
1352
+ zhi2
1353
+ zhi3
1354
+ zhi4
1355
+ zhong1
1356
+ zhong2
1357
+ zhong3
1358
+ zhong4
1359
+ zhou1
1360
+ zhou2
1361
+ zhou3
1362
+ zhou4
1363
+ zhu1
1364
+ zhu2
1365
+ zhu3
1366
+ zhu4
1367
+ zhua1
1368
+ zhua2
1369
+ zhua3
1370
+ zhuai1
1371
+ zhuai3
1372
+ zhuai4
1373
+ zhuan1
1374
+ zhuan2
1375
+ zhuan3
1376
+ zhuan4
1377
+ zhuang1
1378
+ zhuang4
1379
+ zhui1
1380
+ zhui4
1381
+ zhun1
1382
+ zhun2
1383
+ zhun3
1384
+ zhuo1
1385
+ zhuo2
1386
+ zi
1387
+ zi1
1388
+ zi2
1389
+ zi3
1390
+ zi4
1391
+ zong1
1392
+ zong2
1393
+ zong3
1394
+ zong4
1395
+ zou1
1396
+ zou2
1397
+ zou3
1398
+ zou4
1399
+ zu1
1400
+ zu2
1401
+ zu3
1402
+ zuan1
1403
+ zuan3
1404
+ zuan4
1405
+ zui2
1406
+ zui3
1407
+ zui4
1408
+ zun1
1409
+ zuo
1410
+ zuo1
1411
+ zuo2
1412
+ zuo3
1413
+ zuo4
1414
+ {
1415
+ ~
1416
+ ¡
1417
+ ¢
1418
+ £
1419
+ ¥
1420
+ §
1421
+ ¨
1422
+ ©
1423
+ «
1424
+ ®
1425
+ ¯
1426
+ °
1427
+ ±
1428
+ ²
1429
+ ³
1430
+ ´
1431
+ µ
1432
+ ·
1433
+ ¹
1434
+ º
1435
+ »
1436
+ ¼
1437
+ ½
1438
+ ¾
1439
+ ¿
1440
+ À
1441
+ Á
1442
+ Â
1443
+ Ã
1444
+ Ä
1445
+ Å
1446
+ Æ
1447
+ Ç
1448
+ È
1449
+ É
1450
+ Ê
1451
+ Í
1452
+ Î
1453
+ Ñ
1454
+ Ó
1455
+ Ö
1456
+ ×
1457
+ Ø
1458
+ Ú
1459
+ Ü
1460
+ Ý
1461
+ Þ
1462
+ ß
1463
+ à
1464
+ á
1465
+ â
1466
+ ã
1467
+ ä
1468
+ å
1469
+ æ
1470
+ ç
1471
+ è
1472
+ é
1473
+ ê
1474
+ ë
1475
+ ì
1476
+ í
1477
+ î
1478
+ ï
1479
+ ð
1480
+ ñ
1481
+ ò
1482
+ ó
1483
+ ô
1484
+ õ
1485
+ ö
1486
+ ø
1487
+ ù
1488
+ ú
1489
+ û
1490
+ ü
1491
+ ý
1492
+ Ā
1493
+ ā
1494
+ ă
1495
+ ą
1496
+ ć
1497
+ Č
1498
+ č
1499
+ Đ
1500
+ đ
1501
+ ē
1502
+ ė
1503
+ ę
1504
+ ě
1505
+ ĝ
1506
+ ğ
1507
+ ħ
1508
+ ī
1509
+ į
1510
+ İ
1511
+ ı
1512
+ Ł
1513
+ ł
1514
+ ń
1515
+ ņ
1516
+ ň
1517
+ ŋ
1518
+ Ō
1519
+ ō
1520
+ ő
1521
+ œ
1522
+ ř
1523
+ Ś
1524
+ ś
1525
+ Ş
1526
+ ş
1527
+ Š
1528
+ š
1529
+ Ť
1530
+ ť
1531
+ ũ
1532
+ ū
1533
+ ź
1534
+ Ż
1535
+ ż
1536
+ Ž
1537
+ ž
1538
+ ơ
1539
+ ư
1540
+ ǎ
1541
+ ǐ
1542
+ ǒ
1543
+ ǔ
1544
+ ǚ
1545
+ ș
1546
+ ț
1547
+ ɑ
1548
+ ɔ
1549
+ ɕ
1550
+ ə
1551
+ ɛ
1552
+ ɜ
1553
+ ɡ
1554
+ ɣ
1555
+ ɪ
1556
+ ɫ
1557
+ ɴ
1558
+ ɹ
1559
+ ɾ
1560
+ ʃ
1561
+ ʊ
1562
+ ʌ
1563
+ ʒ
1564
+ ʔ
1565
+ ʰ
1566
+ ʷ
1567
+ ʻ
1568
+ ʾ
1569
+ ʿ
1570
+ ˈ
1571
+ ː
1572
+ ˙
1573
+ ˜
1574
+ ˢ
1575
+ ́
1576
+ ̅
1577
+ Α
1578
+ Β
1579
+ Δ
1580
+ Ε
1581
+ Θ
1582
+ Κ
1583
+ Λ
1584
+ Μ
1585
+ Ξ
1586
+ Π
1587
+ Σ
1588
+ Τ
1589
+ Φ
1590
+ Χ
1591
+ Ψ
1592
+ Ω
1593
+ ά
1594
+ έ
1595
+ ή
1596
+ ί
1597
+ α
1598
+ β
1599
+ γ
1600
+ δ
1601
+ ε
1602
+ ζ
1603
+ η
1604
+ θ
1605
+ ι
1606
+ κ
1607
+ λ
1608
+ μ
1609
+ ν
1610
+ ξ
1611
+ ο
1612
+ π
1613
+ ρ
1614
+ ς
1615
+ σ
1616
+ τ
1617
+ υ
1618
+ φ
1619
+ χ
1620
+ ψ
1621
+ ω
1622
+ ϊ
1623
+ ό
1624
+ ύ
1625
+ ώ
1626
+ ϕ
1627
+ ϵ
1628
+ Ё
1629
+ А
1630
+ Б
1631
+ В
1632
+ Г
1633
+ Д
1634
+ Е
1635
+ Ж
1636
+ З
1637
+ И
1638
+ Й
1639
+ К
1640
+ Л
1641
+ М
1642
+ Н
1643
+ О
1644
+ П
1645
+ Р
1646
+ С
1647
+ Т
1648
+ У
1649
+ Ф
1650
+ Х
1651
+ Ц
1652
+ Ч
1653
+ Ш
1654
+ Щ
1655
+ Ы
1656
+ Ь
1657
+ Э
1658
+ Ю
1659
+ Я
1660
+ а
1661
+ б
1662
+ в
1663
+ г
1664
+ д
1665
+ е
1666
+ ж
1667
+ з
1668
+ и
1669
+ й
1670
+ к
1671
+ л
1672
+ м
1673
+ н
1674
+ о
1675
+ п
1676
+ р
1677
+ с
1678
+ т
1679
+ у
1680
+ ф
1681
+ х
1682
+ ц
1683
+ ч
1684
+ ш
1685
+ щ
1686
+ ъ
1687
+ ы
1688
+ ь
1689
+ э
1690
+ ю
1691
+ я
1692
+ ё
1693
+ і
1694
+ ְ
1695
+ ִ
1696
+ ֵ
1697
+ ֶ
1698
+ ַ
1699
+ ָ
1700
+ ֹ
1701
+ ּ
1702
+ ־
1703
+ ׁ
1704
+ א
1705
+ ב
1706
+ ג
1707
+ ד
1708
+ ה
1709
+ ו
1710
+ ז
1711
+ ח
1712
+ ט
1713
+ י
1714
+ כ
1715
+ ל
1716
+ ם
1717
+ מ
1718
+ ן
1719
+ נ
1720
+ ס
1721
+ ע
1722
+ פ
1723
+ ק
1724
+ ר
1725
+ ש
1726
+ ת
1727
+ أ
1728
+ ب
1729
+ ة
1730
+ ت
1731
+ ج
1732
+ ح
1733
+ د
1734
+ ر
1735
+ ز
1736
+ س
1737
+ ص
1738
+ ط
1739
+ ع
1740
+ ق
1741
+ ك
1742
+ ل
1743
+ م
1744
+ ن
1745
+ ه
1746
+ و
1747
+ ي
1748
+ َ
1749
+ ُ
1750
+ ِ
1751
+ ْ
1752
+
1753
+
1754
+
1755
+
1756
+
1757
+
1758
+
1759
+
1760
+
1761
+
1762
+
1763
+
1764
+
1765
+
1766
+
1767
+
1768
+
1769
+
1770
+
1771
+
1772
+
1773
+
1774
+
1775
+
1776
+
1777
+
1778
+
1779
+
1780
+
1781
+
1782
+
1783
+
1784
+
1785
+
1786
+
1787
+
1788
+
1789
+
1790
+
1791
+
1792
+
1793
+
1794
+
1795
+
1796
+
1797
+
1798
+
1799
+
1800
+ ế
1801
+
1802
+
1803
+
1804
+
1805
+
1806
+
1807
+
1808
+
1809
+
1810
+
1811
+
1812
+
1813
+
1814
+
1815
+
1816
+
1817
+
1818
+
1819
+
1820
+
1821
+
1822
+
1823
+
1824
+
1825
+
1826
+
1827
+
1828
+
1829
+
1830
+ ���
1831
+
1832
+
1833
+
1834
+
1835
+
1836
+
1837
+
1838
+
1839
+
1840
+
1841
+
1842
+
1843
+
1844
+
1845
+
1846
+
1847
+
1848
+
1849
+
1850
+
1851
+
1852
+
1853
+
1854
+
1855
+
1856
+
1857
+
1858
+
1859
+
1860
+
1861
+
1862
+
1863
+
1864
+
1865
+
1866
+
1867
+
1868
+
1869
+
1870
+
1871
+
1872
+
1873
+
1874
+
1875
+
1876
+
1877
+
1878
+
1879
+
1880
+
1881
+
1882
+
1883
+
1884
+
1885
+
1886
+
1887
+
1888
+
1889
+
1890
+
1891
+
1892
+
1893
+
1894
+
1895
+
1896
+
1897
+
1898
+
1899
+
1900
+
1901
+
1902
+
1903
+
1904
+
1905
+
1906
+
1907
+
1908
+
1909
+
1910
+
1911
+
1912
+
1913
+
1914
+
1915
+
1916
+
1917
+
1918
+
1919
+
1920
+
1921
+
1922
+
1923
+
1924
+
1925
+
1926
+
1927
+
1928
+
1929
+
1930
+
1931
+
1932
+
1933
+
1934
+
1935
+
1936
+
1937
+
1938
+
1939
+
1940
+
1941
+
1942
+
1943
+
1944
+
1945
+
1946
+
1947
+
1948
+
1949
+
1950
+
1951
+
1952
+
1953
+
1954
+
1955
+
1956
+
1957
+
1958
+
1959
+
1960
+
1961
+
1962
+
1963
+
1964
+
1965
+
1966
+
1967
+
1968
+
1969
+
1970
+
1971
+
1972
+
1973
+
1974
+
1975
+
1976
+
1977
+
1978
+
1979
+
1980
+
1981
+
1982
+
1983
+
1984
+
1985
+
1986
+
1987
+
1988
+
1989
+
1990
+
1991
+
1992
+
1993
+
1994
+
1995
+
1996
+
1997
+
1998
+
1999
+
2000
+
2001
+
2002
+
2003
+
2004
+
2005
+
2006
+
2007
+
2008
+
2009
+
2010
+
2011
+
2012
+
2013
+
2014
+
2015
+
2016
+
2017
+
2018
+
2019
+
2020
+
2021
+
2022
+
2023
+
2024
+
2025
+
2026
+
2027
+
2028
+
2029
+
2030
+
2031
+
2032
+
2033
+
2034
+
2035
+
2036
+
2037
+
2038
+
2039
+
2040
+
2041
+
2042
+
2043
+
2044
+
2045
+
2046
+
2047
+
2048
+
2049
+
2050
+
2051
+
2052
+
2053
+
2054
+
2055
+
2056
+
2057
+
2058
+
2059
+
2060
+
2061
+
2062
+
2063
+
2064
+
2065
+
2066
+
2067
+
2068
+
2069
+
2070
+
2071
+
2072
+
2073
+
2074
+
2075
+
2076
+
2077
+
2078
+
2079
+
2080
+
2081
+
2082
+
2083
+
2084
+
2085
+
2086
+
2087
+
2088
+
2089
+
2090
+
2091
+
2092
+
2093
+
2094
+
2095
+
2096
+
2097
+
2098
+
2099
+
2100
+
2101
+
2102
+
2103
+
2104
+
2105
+
2106
+
2107
+
2108
+
2109
+
2110
+
2111
+
2112
+
2113
+
2114
+
2115
+
2116
+
2117
+
2118
+
2119
+
2120
+
2121
+
2122
+
2123
+
2124
+
2125
+
2126
+
2127
+
2128
+
2129
+
2130
+
2131
+
2132
+
2133
+
2134
+
2135
+
2136
+
2137
+
2138
+
2139
+
2140
+
2141
+
2142
+
2143
+
2144
+
2145
+
2146
+
2147
+
2148
+
2149
+
2150
+
2151
+
2152
+
2153
+
2154
+
2155
+
2156
+
2157
+
2158
+
2159
+
2160
+
2161
+
2162
+
2163
+
2164
+
2165
+
2166
+
2167
+
2168
+
2169
+
2170
+
2171
+
2172
+
2173
+
2174
+
2175
+
2176
+
2177
+
2178
+
2179
+
2180
+
2181
+
2182
+
2183
+
2184
+
2185
+
2186
+
2187
+
2188
+
2189
+
2190
+
2191
+
2192
+
2193
+
2194
+
2195
+
2196
+
2197
+
2198
+
2199
+
2200
+
2201
+
2202
+
2203
+
2204
+
2205
+
2206
+
2207
+
2208
+
2209
+
2210
+
2211
+
2212
+
2213
+
2214
+
2215
+
2216
+
2217
+
2218
+
2219
+
2220
+
2221
+
2222
+
2223
+
2224
+
2225
+
2226
+
2227
+
2228
+
2229
+
2230
+
2231
+
2232
+
2233
+
2234
+
2235
+
2236
+
2237
+
2238
+
2239
+
2240
+
2241
+
2242
+
2243
+
2244
+
2245
+
2246
+
2247
+
2248
+
2249
+
2250
+
2251
+
2252
+
2253
+
2254
+
2255
+
2256
+
2257
+
2258
+
2259
+
2260
+
2261
+
2262
+
2263
+
2264
+
2265
+
2266
+
2267
+
2268
+
2269
+
2270
+
2271
+
2272
+
2273
+
2274
+
2275
+
2276
+
2277
+
2278
+
2279
+
2280
+
2281
+
2282
+
2283
+
2284
+
2285
+
2286
+
2287
+
2288
+
2289
+
2290
+
2291
+
2292
+
2293
+
2294
+
2295
+
2296
+
2297
+
2298
+
2299
+
2300
+
2301
+
2302
+
2303
+
2304
+
2305
+
2306
+
2307
+
2308
+
2309
+
2310
+
2311
+
2312
+
2313
+
2314
+
2315
+
2316
+
2317
+
2318
+
2319
+
2320
+
2321
+
2322
+
2323
+
2324
+
2325
+
2326
+
2327
+
2328
+
2329
+
2330
+
2331
+
2332
+
2333
+
2334
+
2335
+
2336
+
2337
+
2338
+
2339
+
2340
+
2341
+
2342
+
2343
+
2344
+
2345
+
2346
+
2347
+
2348
+
2349
+
2350
+
2351
+
2352
+
2353
+
2354
+
2355
+
2356
+
2357
+
2358
+
2359
+
2360
+
2361
+
2362
+
2363
+
2364
+
2365
+
2366
+
2367
+
2368
+
2369
+
2370
+
2371
+
2372
+
2373
+
2374
+
2375
+
2376
+
2377
+
2378
+
2379
+
2380
+
2381
+
2382
+
2383
+
2384
+
2385
+
2386
+
2387
+
2388
+
2389
+
2390
+
2391
+
2392
+
2393
+
2394
+
2395
+
2396
+
2397
+
2398
+
2399
+
2400
+
2401
+
2402
+
2403
+
2404
+
2405
+
2406
+
2407
+
2408
+
2409
+
2410
+
2411
+
2412
+
2413
+
2414
+
2415
+
2416
+
2417
+
2418
+
2419
+
2420
+
2421
+
2422
+
2423
+
2424
+
2425
+
2426
+
2427
+
2428
+
2429
+
2430
+
2431
+
2432
+
2433
+
2434
+
2435
+
2436
+
2437
+
2438
+
2439
+
2440
+
2441
+
2442
+
2443
+
2444
+
2445
+
2446
+
2447
+
2448
+
2449
+
2450
+
2451
+
2452
+
2453
+
2454
+
2455
+
2456
+
2457
+
2458
+
2459
+
2460
+
2461
+
2462
+
2463
+
2464
+
2465
+
2466
+
2467
+
2468
+
2469
+
2470
+
2471
+
2472
+
2473
+
2474
+
2475
+
2476
+
2477
+
2478
+
2479
+
2480
+
2481
+
2482
+
2483
+
2484
+
2485
+
2486
+
2487
+
2488
+
2489
+
2490
+
2491
+
2492
+
2493
+
2494
+
2495
+
2496
+
2497
+
2498
+
2499
+
2500
+
2501
+
2502
+
2503
+
2504
+
2505
+
2506
+
2507
+
2508
+
2509
+
2510
+
2511
+
2512
+
2513
+
2514
+
2515
+
2516
+
2517
+
2518
+
2519
+
2520
+
2521
+
2522
+
2523
+
2524
+
2525
+
2526
+
2527
+
2528
+
2529
+
2530
+
2531
+
2532
+
2533
+
2534
+
2535
+
2536
+
2537
+
2538
+
2539
+
2540
+
2541
+
2542
+
2543
+
2544
+
2545
+ 𠮶
src/f5_tts/infer/hf_infer.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inference helpers intended for Hugging Face usage (no HTTP server required)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from functools import lru_cache
7
+ from typing import Any, Callable, Optional, Tuple
8
+
9
+ from f5_tts.api import F5TTS
10
+
11
+ ENV_DEFAULTS = {
12
+ "model": os.environ.get("F5TTS_MODEL", "F5TTS_v1_Base"),
13
+ "ckpt_file": os.environ.get("F5TTS_CKPT", ""),
14
+ "vocab_file": os.environ.get("F5TTS_VOCAB", ""),
15
+ "ode_method": os.environ.get("F5TTS_ODE_METHOD", "euler"),
16
+ "use_ema": os.environ.get("F5TTS_USE_EMA", "true").lower() != "false",
17
+ "vocoder_local_path": os.environ.get("F5TTS_VOCODER_PATH"),
18
+ "device": os.environ.get("F5TTS_DEVICE"),
19
+ "hf_cache_dir": os.environ.get("F5TTS_HF_CACHE_DIR"),
20
+ }
21
+
22
+
23
+ @lru_cache(maxsize=2)
24
+ def load_tts(
25
+ model: str = ENV_DEFAULTS["model"],
26
+ ckpt_file: str = ENV_DEFAULTS["ckpt_file"],
27
+ vocab_file: str = ENV_DEFAULTS["vocab_file"],
28
+ ode_method: str = ENV_DEFAULTS["ode_method"],
29
+ use_ema: bool = ENV_DEFAULTS["use_ema"],
30
+ vocoder_local_path: Optional[str] = ENV_DEFAULTS["vocoder_local_path"],
31
+ device: Optional[str] = ENV_DEFAULTS["device"],
32
+ hf_cache_dir: Optional[str] = ENV_DEFAULTS["hf_cache_dir"],
33
+ ) -> F5TTS:
34
+ """Load and cache an F5TTS model for inference."""
35
+ return F5TTS(
36
+ model=model,
37
+ ckpt_file=ckpt_file,
38
+ vocab_file=vocab_file,
39
+ ode_method=ode_method,
40
+ use_ema=use_ema,
41
+ vocoder_local_path=vocoder_local_path,
42
+ device=device,
43
+ hf_cache_dir=hf_cache_dir,
44
+ )
45
+
46
+
47
+ def synthesize(
48
+ tts: F5TTS,
49
+ ref_audio_path: str,
50
+ ref_text: str,
51
+ gen_text: str,
52
+ *,
53
+ target_rms: float = 0.1,
54
+ cross_fade_duration: float = 0.15,
55
+ sway_sampling_coef: float = -1.0,
56
+ cfg_strength: float = 2.0,
57
+ nfe_step: int = 32,
58
+ speed: float = 1.0,
59
+ fix_duration: Optional[float] = None,
60
+ remove_silence: bool = False,
61
+ seed: Optional[int] = None,
62
+ tokenizer: str = "pinyin",
63
+ cls_language: Optional[str] = None,
64
+ cls_tokenizer_fn: Optional[Callable[[str, str], list]] = None,
65
+ cls_server_url: Optional[str] = None,
66
+ cls_timeout: float = 5.0,
67
+ file_wave: Optional[str] = None,
68
+ file_spec: Optional[str] = None,
69
+ show_info=None,
70
+ progress=None,
71
+ ) -> Tuple[Any, int, Optional[Any]]:
72
+ """Run inference and return (wav, sample_rate, spectrogram)."""
73
+ if show_info is None:
74
+ show_info = lambda *args, **kwargs: None
75
+
76
+ return tts.infer(
77
+ ref_file=ref_audio_path,
78
+ ref_text=ref_text,
79
+ gen_text=gen_text,
80
+ show_info=show_info,
81
+ progress=progress,
82
+ target_rms=target_rms,
83
+ cross_fade_duration=cross_fade_duration,
84
+ sway_sampling_coef=sway_sampling_coef,
85
+ cfg_strength=cfg_strength,
86
+ nfe_step=nfe_step,
87
+ speed=speed,
88
+ fix_duration=fix_duration,
89
+ remove_silence=remove_silence,
90
+ file_wave=file_wave,
91
+ file_spec=file_spec,
92
+ seed=seed,
93
+ tokenizer=tokenizer,
94
+ cls_language=cls_language,
95
+ cls_tokenizer_fn=cls_tokenizer_fn,
96
+ cls_server_url=cls_server_url,
97
+ cls_timeout=cls_timeout,
98
+ )
src/f5_tts/infer/infer_api.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI server for F5-TTS inference.
2
+
3
+ Launch with a custom checkpoint:
4
+ python src/f5_tts/infer/infer_api.py --ckpt-file ckpts/my_model.safetensors --vocab-file ckpts/vocab.txt
5
+
6
+ The API exposes:
7
+ - GET /health -> basic readiness info
8
+ - POST /v1/tts -> synthesize speech (JSON body)
9
+ """
10
+
11
+ import base64
12
+ import io
13
+ import os
14
+ import tempfile
15
+ import threading
16
+ from functools import lru_cache
17
+ from typing import Optional
18
+
19
+ import click
20
+ import soundfile as sf
21
+ import uvicorn
22
+ from fastapi import FastAPI, HTTPException, Query
23
+ from fastapi.middleware.cors import CORSMiddleware
24
+ from pydantic import BaseModel, Field, model_validator
25
+
26
+ from f5_tts.api import F5TTS
27
+ from f5_tts.infer.utils_infer import save_spectrogram
28
+
29
+ # Allow configuration through environment variables for quick overrides
30
+ ENV_DEFAULTS = {
31
+ "model": os.environ.get("F5TTS_API_MODEL", "F5TTS_v1_Base"),
32
+ "ckpt_file": os.environ.get(
33
+ "F5TTS_API_CKPT",
34
+ "/workspace/personal/team_folders/F5-TTS-common/ckpts/F5TTS_v1_Base_vocos_cls_speech_db_wer_filtered_12_langs_train_finetune_cls/"
35
+ "model_1250000.pt",
36
+ ),
37
+ "vocab_file": os.environ.get(
38
+ "F5TTS_API_VOCAB",
39
+ "/workspace/personal/team_folders/F5-TTS-common/ckpts/F5TTS_v1_Base_vocos_cls_speech_db_wer_filtered_12_langs_train_finetune_cls/"
40
+ "vocab.txt",
41
+ ),
42
+ "ode_method": os.environ.get("F5TTS_API_ODE_METHOD", "euler"),
43
+ "use_ema": os.environ.get("F5TTS_API_USE_EMA", "true").lower() != "false",
44
+ "vocoder_local_path": os.environ.get("F5TTS_API_VOCODER_PATH"),
45
+ "device": os.environ.get("F5TTS_API_DEVICE"),
46
+ "hf_cache_dir": os.environ.get("F5TTS_API_HF_CACHE_DIR"),
47
+ "en_model": os.environ.get("F5TTS_API_EN_MODEL", os.environ.get("F5TTS_API_MODEL", "F5TTS_v1_Base")),
48
+ "en_ckpt_file": os.environ.get(
49
+ "F5TTS_API_EN_CKPT",
50
+ "/workspace/personal/team_folders/vansh.pundir/F5-TTS/ckpts/"
51
+ "F5TTS_v1_Base_12_lang_vocos_char_speech_db_only_TTS_12_langs_eval_v3_char_dedup_validation/"
52
+ "model_550000.pt",
53
+ ),
54
+ "en_vocab_file": os.environ.get(
55
+ "F5TTS_API_EN_VOCAB",
56
+ "/workspace/personal/team_folders/vansh.pundir/F5-TTS/ckpts/"
57
+ "F5TTS_v1_Base_12_lang_vocos_char_speech_db_only_TTS_12_langs_eval_v3_char_dedup_validation/"
58
+ "vocab.txt",
59
+ ),
60
+ "cls_url": os.environ.get("F5TTS_CLS_URL", "http://localhost:8061/process"),
61
+ "cls_timeout": float(os.environ.get("F5TTS_CLS_TIMEOUT", "5.0")),
62
+ }
63
+
64
+
65
+ class InferenceRequest(BaseModel):
66
+ ref_audio_path: Optional[str] = Field(
67
+ default=None, description="Path to reference audio reachable by the server."
68
+ )
69
+ ref_audio_base64: Optional[str] = Field(
70
+ default=None, description="Base64-encoded reference audio (recommended: WAV/FLAC)."
71
+ )
72
+ ref_text: str = Field(
73
+ default="",
74
+ description="Transcript of the reference audio. Leave blank to auto-transcribe (requires ASR).",
75
+ )
76
+ gen_text: str = Field(..., description="Text to synthesize.")
77
+ target_rms: float = Field(default=0.1, description="Minimum RMS applied to reference audio.")
78
+ cross_fade_duration: float = Field(default=0.15, description="Seconds to overlap between chunks.")
79
+ sway_sampling_coef: float = Field(default=-1.0, description="Sway sampling coefficient.")
80
+ cfg_strength: float = Field(default=2.0, description="Classifier-free guidance strength.")
81
+ nfe_step: int = Field(default=32, description="Number of function evaluations.")
82
+ speed: float = Field(default=1.0, description="Generation speed multiplier.")
83
+ fix_duration: Optional[float] = Field(
84
+ default=None, description="Force output duration (seconds). Leave None for automatic."
85
+ )
86
+ remove_silence: bool = Field(default=False, description="Remove leading/trailing silence from output.")
87
+ seed: Optional[int] = Field(default=None, description="Set for deterministic output.")
88
+ return_spectrogram: bool = Field(default=False, description="Also return spectrogram as base64 PNG.")
89
+ tokenizer: Optional[str] = Field(
90
+ default=None,
91
+ description="Optional tokenizer override: char | cls | pinyin. If omitted, uses legacy pinyin behavior.",
92
+ )
93
+ cls_language: Optional[str] = Field(
94
+ default=None,
95
+ description="CLS language name (e.g., hindi, english). Used only when tokenizer=cls.",
96
+ )
97
+
98
+ @model_validator(mode="after")
99
+ def ensure_audio_source(self):
100
+ if not self.ref_audio_path and not self.ref_audio_base64:
101
+ raise ValueError("Provide either ref_audio_path or ref_audio_base64.")
102
+ if not self.gen_text or not self.gen_text.strip():
103
+ raise ValueError("gen_text cannot be empty.")
104
+ return self
105
+
106
+
107
+ def _encode_wav_base64(wav, sample_rate: int) -> str:
108
+ """Encode waveform to a base64 WAV string."""
109
+ with io.BytesIO() as buffer:
110
+ sf.write(buffer, wav, sample_rate, format="WAV")
111
+ return base64.b64encode(buffer.getvalue()).decode("ascii")
112
+
113
+
114
+ def _encode_spec_base64(spec) -> str:
115
+ """Save spectrogram to a temp file and encode it as base64 PNG."""
116
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
117
+ tmp_path = tmp.name
118
+ try:
119
+ save_spectrogram(spec, tmp_path)
120
+ with open(tmp_path, "rb") as img:
121
+ return base64.b64encode(img.read()).decode("ascii")
122
+ finally:
123
+ os.remove(tmp_path)
124
+
125
+
126
+ def _write_temp_audio(data: bytes) -> str:
127
+ """Persist uploaded audio bytes to a temp file for downstream processing."""
128
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
129
+ tmp.write(data)
130
+ return tmp.name
131
+
132
+
133
+ @lru_cache(maxsize=4)
134
+ def _load_model(
135
+ model: str = ENV_DEFAULTS["model"],
136
+ ckpt_file: str = ENV_DEFAULTS["ckpt_file"],
137
+ vocab_file: str = ENV_DEFAULTS["vocab_file"],
138
+ ode_method: str = ENV_DEFAULTS["ode_method"],
139
+ use_ema: bool = ENV_DEFAULTS["use_ema"],
140
+ vocoder_local_path: Optional[str] = ENV_DEFAULTS["vocoder_local_path"],
141
+ device: Optional[str] = ENV_DEFAULTS["device"],
142
+ hf_cache_dir: Optional[str] = ENV_DEFAULTS["hf_cache_dir"],
143
+ ):
144
+ """Cache TTS models by configuration to avoid reloading across requests."""
145
+ return F5TTS(
146
+ model=model,
147
+ ckpt_file=ckpt_file,
148
+ vocab_file=vocab_file,
149
+ ode_method=ode_method,
150
+ use_ema=use_ema,
151
+ vocoder_local_path=vocoder_local_path,
152
+ device=device,
153
+ hf_cache_dir=hf_cache_dir,
154
+ )
155
+
156
+
157
+ def create_app(
158
+ model: str = ENV_DEFAULTS["model"],
159
+ ckpt_file: str = ENV_DEFAULTS["ckpt_file"],
160
+ vocab_file: str = ENV_DEFAULTS["vocab_file"],
161
+ en_model: str = ENV_DEFAULTS["en_model"],
162
+ en_ckpt_file: str = ENV_DEFAULTS["en_ckpt_file"],
163
+ en_vocab_file: str = ENV_DEFAULTS["en_vocab_file"],
164
+ ode_method: str = ENV_DEFAULTS["ode_method"],
165
+ use_ema: bool = ENV_DEFAULTS["use_ema"],
166
+ vocoder_local_path: Optional[str] = ENV_DEFAULTS["vocoder_local_path"],
167
+ device: Optional[str] = ENV_DEFAULTS["device"],
168
+ hf_cache_dir: Optional[str] = ENV_DEFAULTS["hf_cache_dir"],
169
+ ):
170
+ """Build a FastAPI app wired to a single F5TTS instance."""
171
+ tts_hi = _load_model(
172
+ model=model,
173
+ ckpt_file=ckpt_file,
174
+ vocab_file=vocab_file,
175
+ ode_method=ode_method,
176
+ use_ema=use_ema,
177
+ vocoder_local_path=vocoder_local_path,
178
+ device=device,
179
+ hf_cache_dir=hf_cache_dir,
180
+ )
181
+ infer_lock_hi = threading.Lock()
182
+ infer_lock_en = threading.Lock()
183
+
184
+ app = FastAPI(title="F5-TTS API", version="1.0")
185
+ app.add_middleware(
186
+ CORSMiddleware,
187
+ allow_origins=["*"],
188
+ allow_credentials=True,
189
+ allow_methods=["*"],
190
+ allow_headers=["*"],
191
+ )
192
+
193
+ @app.get("/health")
194
+ def health():
195
+ return {
196
+ "status": "ok",
197
+ "device": tts_hi.device,
198
+ "mel_spec_type": tts_hi.mel_spec_type,
199
+ "use_ema": tts_hi.use_ema,
200
+ "supported_langs": ["hi", "en"],
201
+ }
202
+
203
+ @app.post("/v1/tts")
204
+ def infer(payload: InferenceRequest, lang: str = Query("hi", description="Language code: hi|en")):
205
+ lang_key = (lang or "hi").strip().lower()
206
+ if lang_key == "hi":
207
+ tts = tts_hi
208
+ infer_lock = infer_lock_hi
209
+ elif lang_key == "en":
210
+ tts = _load_model(
211
+ model=en_model,
212
+ ckpt_file=en_ckpt_file,
213
+ vocab_file=en_vocab_file,
214
+ ode_method=ode_method,
215
+ use_ema=use_ema,
216
+ vocoder_local_path=vocoder_local_path,
217
+ device=device,
218
+ hf_cache_dir=hf_cache_dir,
219
+ )
220
+ infer_lock = infer_lock_en
221
+ else:
222
+ raise HTTPException(
223
+ status_code=400,
224
+ detail=f"Unsupported lang '{lang}'. Use 'hi' for Hindi or 'en' for English.",
225
+ )
226
+
227
+ if lang_key == "hi":
228
+ tokenizer_used = "cls"
229
+ elif lang_key == "en":
230
+ tokenizer_used = "char"
231
+ else:
232
+ raise HTTPException(
233
+ status_code=400,
234
+ detail="Unsupported lang for hard-coded tokenizer. Use 'hi' or 'en'.",
235
+ )
236
+
237
+ cls_language = None
238
+ if tokenizer_used == "cls":
239
+ if payload.cls_language and payload.cls_language.strip():
240
+ cls_language = payload.cls_language.strip().lower()
241
+ else:
242
+ cls_language = "hindi" if lang_key == "hi" else "english" if lang_key == "en" else None
243
+ if not cls_language:
244
+ raise HTTPException(
245
+ status_code=400,
246
+ detail="cls_language is required when tokenizer=cls and lang is not hi/en.",
247
+ )
248
+
249
+ cleanup_path = None
250
+ if payload.ref_audio_path:
251
+ ref_audio = payload.ref_audio_path
252
+ if not os.path.exists(ref_audio):
253
+ raise HTTPException(status_code=400, detail=f"ref_audio_path not found: {ref_audio}")
254
+ else:
255
+ try:
256
+ audio_bytes = base64.b64decode(payload.ref_audio_base64)
257
+ except Exception as exc: # noqa: BLE001
258
+ raise HTTPException(status_code=400, detail=f"Invalid ref_audio_base64: {exc}") from exc
259
+ ref_audio = _write_temp_audio(audio_bytes)
260
+ cleanup_path = ref_audio
261
+
262
+ try:
263
+ with infer_lock:
264
+ try:
265
+ wav, sr, spec = tts.infer(
266
+ ref_file=ref_audio,
267
+ ref_text=payload.ref_text,
268
+ gen_text=payload.gen_text,
269
+ show_info=lambda *args, **kwargs: None,
270
+ progress=None,
271
+ target_rms=payload.target_rms,
272
+ cross_fade_duration=payload.cross_fade_duration,
273
+ sway_sampling_coef=payload.sway_sampling_coef,
274
+ cfg_strength=payload.cfg_strength,
275
+ nfe_step=payload.nfe_step,
276
+ speed=payload.speed,
277
+ fix_duration=payload.fix_duration,
278
+ remove_silence=payload.remove_silence,
279
+ seed=payload.seed,
280
+ tokenizer=tokenizer_used,
281
+ cls_language=cls_language,
282
+ cls_server_url=ENV_DEFAULTS["cls_url"],
283
+ cls_timeout=ENV_DEFAULTS["cls_timeout"],
284
+ )
285
+ except Exception as exc: # noqa: BLE001
286
+ if tokenizer_used == "cls":
287
+ raise HTTPException(
288
+ status_code=502,
289
+ detail=f"CLS tokenization failed: {exc}",
290
+ ) from exc
291
+ raise
292
+ finally:
293
+ if cleanup_path and os.path.exists(cleanup_path):
294
+ os.remove(cleanup_path)
295
+
296
+ response = {
297
+ "audio_base64": _encode_wav_base64(wav, sr),
298
+ "sample_rate": sr,
299
+ "seed": getattr(tts, "seed", payload.seed),
300
+ }
301
+ if payload.return_spectrogram and spec is not None:
302
+ response["spectrogram_base64"] = _encode_spec_base64(spec)
303
+
304
+ return response
305
+
306
+ return app
307
+
308
+
309
+ app = create_app()
310
+
311
+
312
+ @click.command()
313
+ @click.option("--model", default=ENV_DEFAULTS["model"], show_default=True, help="Model config name to load.")
314
+ @click.option("--ckpt-file", default=ENV_DEFAULTS["ckpt_file"], show_default=True, help="Checkpoint file path.")
315
+ @click.option("--vocab-file", default=ENV_DEFAULTS["vocab_file"], show_default=True, help="Custom vocab file path.")
316
+ @click.option("--ode-method", default=ENV_DEFAULTS["ode_method"], show_default=True, help="ODE method for sampler.")
317
+ @click.option(
318
+ "--use-ema/--no-use-ema",
319
+ default=ENV_DEFAULTS["use_ema"],
320
+ show_default=True,
321
+ help="Load EMA weights from checkpoint.",
322
+ )
323
+ @click.option(
324
+ "--vocoder-local-path",
325
+ default=ENV_DEFAULTS["vocoder_local_path"],
326
+ show_default=True,
327
+ help="Local vocoder directory (skips HF download).",
328
+ )
329
+ @click.option("--device", default=ENV_DEFAULTS["device"], show_default=True, help="Force device: cpu|cuda|mps|xpu.")
330
+ @click.option(
331
+ "--hf-cache-dir",
332
+ default=ENV_DEFAULTS["hf_cache_dir"],
333
+ show_default=True,
334
+ help="HuggingFace cache directory override.",
335
+ )
336
+ @click.option("--host", default="0.0.0.0", show_default=True, help="API host.")
337
+ @click.option("--port", default=8060, show_default=True, help="API port.", type=int)
338
+ @click.option("--root-path", default="", show_default=True, help="Set FastAPI root_path when behind a proxy.")
339
+ def main(
340
+ model,
341
+ ckpt_file,
342
+ vocab_file,
343
+ ode_method,
344
+ use_ema,
345
+ vocoder_local_path,
346
+ device,
347
+ hf_cache_dir,
348
+ host,
349
+ port,
350
+ root_path,
351
+ ):
352
+ """Run the FastAPI server for HTTP inference."""
353
+ api_app = create_app(
354
+ model=model,
355
+ ckpt_file=ckpt_file,
356
+ vocab_file=vocab_file,
357
+ ode_method=ode_method,
358
+ use_ema=use_ema,
359
+ vocoder_local_path=vocoder_local_path,
360
+ device=device,
361
+ hf_cache_dir=hf_cache_dir,
362
+ )
363
+ uvicorn.run(api_app, host=host, port=port, root_path=root_path)
364
+
365
+
366
+ if __name__ == "__main__":
367
+ main()
src/f5_tts/infer/infer_cli.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import codecs
3
+ import os
4
+ import re
5
+ from datetime import datetime
6
+ from importlib.resources import files
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ import soundfile as sf
11
+ import tomli
12
+ from cached_path import cached_path
13
+ from hydra.utils import get_class
14
+ from omegaconf import OmegaConf
15
+ from unidecode import unidecode
16
+
17
+ from f5_tts.infer.utils_infer import (
18
+ cfg_strength,
19
+ cross_fade_duration,
20
+ device,
21
+ fix_duration,
22
+ infer_process,
23
+ load_model,
24
+ load_vocoder,
25
+ mel_spec_type,
26
+ nfe_step,
27
+ preprocess_ref_audio_text,
28
+ remove_silence_for_generated_wav,
29
+ speed,
30
+ sway_sampling_coef,
31
+ target_rms,
32
+ )
33
+
34
+
35
+ parser = argparse.ArgumentParser(
36
+ prog="python3 infer-cli.py",
37
+ description="Commandline interface for E2/F5 TTS with Advanced Batch Processing.",
38
+ epilog="Specify options above to override one or more settings from config.",
39
+ )
40
+ parser.add_argument(
41
+ "-c",
42
+ "--config",
43
+ type=str,
44
+ default=os.path.join(files("f5_tts").joinpath("infer/examples/basic"), "basic.toml"),
45
+ help="The configuration file, default see infer/examples/basic/basic.toml",
46
+ )
47
+
48
+
49
+ # Note. Not to provide default value here in order to read default from config file
50
+
51
+ parser.add_argument(
52
+ "-m",
53
+ "--model",
54
+ type=str,
55
+ help="The model name: F5TTS_v1_Base | F5TTS_Base | E2TTS_Base | etc.",
56
+ )
57
+ parser.add_argument(
58
+ "-mc",
59
+ "--model_cfg",
60
+ type=str,
61
+ help="The path to F5-TTS model config file .yaml",
62
+ )
63
+ parser.add_argument(
64
+ "-p",
65
+ "--ckpt_file",
66
+ type=str,
67
+ help="The path to model checkpoint .pt, leave blank to use default",
68
+ )
69
+ parser.add_argument(
70
+ "-v",
71
+ "--vocab_file",
72
+ type=str,
73
+ help="The path to vocab file .txt, leave blank to use default",
74
+ )
75
+ parser.add_argument(
76
+ "-r",
77
+ "--ref_audio",
78
+ type=str,
79
+ help="The reference audio file.",
80
+ )
81
+ parser.add_argument(
82
+ "-s",
83
+ "--ref_text",
84
+ type=str,
85
+ help="The transcript/subtitle for the reference audio",
86
+ )
87
+ parser.add_argument(
88
+ "-t",
89
+ "--gen_text",
90
+ type=str,
91
+ help="The text to make model synthesize a speech",
92
+ )
93
+ parser.add_argument(
94
+ "-f",
95
+ "--gen_file",
96
+ type=str,
97
+ help="The file with text to generate, will ignore --gen_text",
98
+ )
99
+ parser.add_argument(
100
+ "-o",
101
+ "--output_dir",
102
+ type=str,
103
+ help="The path to output folder",
104
+ )
105
+ parser.add_argument(
106
+ "-w",
107
+ "--output_file",
108
+ type=str,
109
+ help="The name of output file",
110
+ )
111
+ parser.add_argument(
112
+ "--save_chunk",
113
+ action="store_true",
114
+ help="To save each audio chunks during inference",
115
+ )
116
+ parser.add_argument(
117
+ "--no_legacy_text",
118
+ action="store_false",
119
+ help="Not to use lossy ASCII transliterations of unicode text in saved file names.",
120
+ )
121
+ parser.add_argument(
122
+ "--remove_silence",
123
+ action="store_true",
124
+ help="To remove long silence found in ouput",
125
+ )
126
+ parser.add_argument(
127
+ "--load_vocoder_from_local",
128
+ action="store_true",
129
+ help="To load vocoder from local dir, default to ../checkpoints/vocos-mel-24khz",
130
+ )
131
+ parser.add_argument(
132
+ "--vocoder_name",
133
+ type=str,
134
+ choices=["vocos", "bigvgan"],
135
+ help=f"Used vocoder name: vocos | bigvgan, default {mel_spec_type}",
136
+ )
137
+ parser.add_argument(
138
+ "--target_rms",
139
+ type=float,
140
+ help=f"Target output speech loudness normalization value, default {target_rms}",
141
+ )
142
+ parser.add_argument(
143
+ "--cross_fade_duration",
144
+ type=float,
145
+ help=f"Duration of cross-fade between audio segments in seconds, default {cross_fade_duration}",
146
+ )
147
+ parser.add_argument(
148
+ "--nfe_step",
149
+ type=int,
150
+ help=f"The number of function evaluation (denoising steps), default {nfe_step}",
151
+ )
152
+ parser.add_argument(
153
+ "--cfg_strength",
154
+ type=float,
155
+ help=f"Classifier-free guidance strength, default {cfg_strength}",
156
+ )
157
+ parser.add_argument(
158
+ "--sway_sampling_coef",
159
+ type=float,
160
+ help=f"Sway Sampling coefficient, default {sway_sampling_coef}",
161
+ )
162
+ parser.add_argument(
163
+ "--speed",
164
+ type=float,
165
+ help=f"The speed of the generated audio, default {speed}",
166
+ )
167
+ parser.add_argument(
168
+ "--fix_duration",
169
+ type=float,
170
+ help=f"Fix the total duration (ref and gen audios) in seconds, default {fix_duration}",
171
+ )
172
+ parser.add_argument(
173
+ "--device",
174
+ type=str,
175
+ help="Specify the device to run on",
176
+ )
177
+ args = parser.parse_args()
178
+
179
+
180
+ # config file
181
+
182
+ config = tomli.load(open(args.config, "rb"))
183
+
184
+
185
+ # command-line interface parameters
186
+
187
+ model = args.model or config.get("model", "F5TTS_v1_Base")
188
+ ckpt_file = args.ckpt_file or config.get("ckpt_file", "")
189
+ vocab_file = args.vocab_file or config.get("vocab_file", "")
190
+
191
+ ref_audio = args.ref_audio or config.get("ref_audio", "infer/examples/basic/basic_ref_en.wav")
192
+ ref_text = (
193
+ args.ref_text
194
+ if args.ref_text is not None
195
+ else config.get("ref_text", "Some call me nature, others call me mother nature.")
196
+ )
197
+ gen_text = args.gen_text or config.get("gen_text", "Here we generate something just for test.")
198
+ gen_file = args.gen_file or config.get("gen_file", "")
199
+
200
+ output_dir = args.output_dir or config.get("output_dir", "tests")
201
+ output_file = args.output_file or config.get(
202
+ "output_file", f"infer_cli_{datetime.now().strftime(r'%Y%m%d_%H%M%S')}.wav"
203
+ )
204
+
205
+ save_chunk = args.save_chunk or config.get("save_chunk", False)
206
+ use_legacy_text = args.no_legacy_text or config.get("no_legacy_text", False) # no_legacy_text is a store_false arg
207
+ if save_chunk and use_legacy_text:
208
+ print(
209
+ "\nWarning to --save_chunk: lossy ASCII transliterations of unicode text for legacy (.wav) file names, --no_legacy_text to disable.\n"
210
+ )
211
+
212
+ remove_silence = args.remove_silence or config.get("remove_silence", False)
213
+ load_vocoder_from_local = args.load_vocoder_from_local or config.get("load_vocoder_from_local", False)
214
+
215
+ vocoder_name = args.vocoder_name or config.get("vocoder_name", mel_spec_type)
216
+ target_rms = args.target_rms or config.get("target_rms", target_rms)
217
+ cross_fade_duration = args.cross_fade_duration or config.get("cross_fade_duration", cross_fade_duration)
218
+ nfe_step = args.nfe_step or config.get("nfe_step", nfe_step)
219
+ cfg_strength = args.cfg_strength or config.get("cfg_strength", cfg_strength)
220
+ sway_sampling_coef = args.sway_sampling_coef or config.get("sway_sampling_coef", sway_sampling_coef)
221
+ speed = args.speed or config.get("speed", speed)
222
+ fix_duration = args.fix_duration or config.get("fix_duration", fix_duration)
223
+ device = args.device or config.get("device", device)
224
+
225
+
226
+ # patches for pip pkg user
227
+ if "infer/examples/" in ref_audio:
228
+ ref_audio = str(files("f5_tts").joinpath(f"{ref_audio}"))
229
+ if "infer/examples/" in gen_file:
230
+ gen_file = str(files("f5_tts").joinpath(f"{gen_file}"))
231
+ if "voices" in config:
232
+ for voice in config["voices"]:
233
+ voice_ref_audio = config["voices"][voice]["ref_audio"]
234
+ if "infer/examples/" in voice_ref_audio:
235
+ config["voices"][voice]["ref_audio"] = str(files("f5_tts").joinpath(f"{voice_ref_audio}"))
236
+
237
+
238
+ # ignore gen_text if gen_file provided
239
+
240
+ if gen_file:
241
+ gen_text = codecs.open(gen_file, "r", "utf-8").read()
242
+
243
+
244
+ # output path
245
+
246
+ wave_path = Path(output_dir) / output_file
247
+ # spectrogram_path = Path(output_dir) / "infer_cli_out.png"
248
+ if save_chunk:
249
+ output_chunk_dir = os.path.join(output_dir, f"{Path(output_file).stem}_chunks")
250
+ if not os.path.exists(output_chunk_dir):
251
+ os.makedirs(output_chunk_dir)
252
+
253
+
254
+ # load vocoder
255
+
256
+ if vocoder_name == "vocos":
257
+ vocoder_local_path = "../checkpoints/vocos-mel-24khz"
258
+ elif vocoder_name == "bigvgan":
259
+ vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x"
260
+
261
+ vocoder = load_vocoder(
262
+ vocoder_name=vocoder_name, is_local=load_vocoder_from_local, local_path=vocoder_local_path, device=device
263
+ )
264
+
265
+
266
+ # load TTS model
267
+
268
+ model_cfg = OmegaConf.load(
269
+ args.model_cfg or config.get("model_cfg", str(files("f5_tts").joinpath(f"configs/{model}.yaml")))
270
+ )
271
+ model_cls = get_class(f"f5_tts.model.{model_cfg.model.backbone}")
272
+ model_arc = model_cfg.model.arch
273
+
274
+ repo_name, ckpt_step, ckpt_type = "F5-TTS", 1250000, "safetensors"
275
+
276
+ if model != "F5TTS_Base":
277
+ assert vocoder_name == model_cfg.model.mel_spec.mel_spec_type
278
+
279
+ # override for previous models
280
+ if model == "F5TTS_Base":
281
+ if vocoder_name == "vocos":
282
+ ckpt_step = 1200000
283
+ elif vocoder_name == "bigvgan":
284
+ model = "F5TTS_Base_bigvgan"
285
+ ckpt_type = "pt"
286
+ elif model == "E2TTS_Base":
287
+ repo_name = "E2-TTS"
288
+ ckpt_step = 1200000
289
+
290
+ if not ckpt_file:
291
+ ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{model}/model_{ckpt_step}.{ckpt_type}"))
292
+
293
+ print(f"Using {model}...")
294
+ ema_model = load_model(
295
+ model_cls, model_arc, ckpt_file, mel_spec_type=vocoder_name, vocab_file=vocab_file, device=device
296
+ )
297
+
298
+
299
+ # inference process
300
+
301
+
302
+ def main():
303
+ main_voice = {"ref_audio": ref_audio, "ref_text": ref_text}
304
+ if "voices" not in config:
305
+ voices = {"main": main_voice}
306
+ else:
307
+ voices = config["voices"]
308
+ voices["main"] = main_voice
309
+ for voice in voices:
310
+ print("Voice:", voice)
311
+ print("ref_audio ", voices[voice]["ref_audio"])
312
+ voices[voice]["ref_audio"], voices[voice]["ref_text"] = preprocess_ref_audio_text(
313
+ voices[voice]["ref_audio"], voices[voice]["ref_text"]
314
+ )
315
+ print("ref_audio_", voices[voice]["ref_audio"], "\n\n")
316
+
317
+ generated_audio_segments = []
318
+ reg1 = r"(?=\[\w+\])"
319
+ chunks = re.split(reg1, gen_text)
320
+ reg2 = r"\[(\w+)\]"
321
+ for text in chunks:
322
+ if not text.strip():
323
+ continue
324
+ match = re.match(reg2, text)
325
+ if match:
326
+ voice = match[1]
327
+ else:
328
+ print("No voice tag found, using main.")
329
+ voice = "main"
330
+ if voice not in voices:
331
+ print(f"Voice {voice} not found, using main.")
332
+ voice = "main"
333
+ text = re.sub(reg2, "", text)
334
+ ref_audio_ = voices[voice]["ref_audio"]
335
+ ref_text_ = voices[voice]["ref_text"]
336
+ local_speed = voices[voice].get("speed", speed)
337
+ gen_text_ = text.strip()
338
+ print(f"Voice: {voice}")
339
+ audio_segment, final_sample_rate, spectrogram = infer_process(
340
+ ref_audio_,
341
+ ref_text_,
342
+ gen_text_,
343
+ ema_model,
344
+ vocoder,
345
+ mel_spec_type=vocoder_name,
346
+ target_rms=target_rms,
347
+ cross_fade_duration=cross_fade_duration,
348
+ nfe_step=nfe_step,
349
+ cfg_strength=cfg_strength,
350
+ sway_sampling_coef=sway_sampling_coef,
351
+ speed=local_speed,
352
+ fix_duration=fix_duration,
353
+ device=device,
354
+ )
355
+ generated_audio_segments.append(audio_segment)
356
+
357
+ if save_chunk:
358
+ if len(gen_text_) > 200:
359
+ gen_text_ = gen_text_[:200] + " ... "
360
+ if use_legacy_text:
361
+ gen_text_ = unidecode(gen_text_)
362
+ sf.write(
363
+ os.path.join(output_chunk_dir, f"{len(generated_audio_segments) - 1}_{gen_text_}.wav"),
364
+ audio_segment,
365
+ final_sample_rate,
366
+ )
367
+
368
+ if generated_audio_segments:
369
+ final_wave = np.concatenate(generated_audio_segments)
370
+
371
+ if not os.path.exists(output_dir):
372
+ os.makedirs(output_dir)
373
+
374
+ with open(wave_path, "wb") as f:
375
+ sf.write(f.name, final_wave, final_sample_rate)
376
+ # Remove silence
377
+ if remove_silence:
378
+ remove_silence_for_generated_wav(f.name)
379
+ print(f.name)
380
+
381
+
382
+ if __name__ == "__main__":
383
+ main()
src/f5_tts/infer/infer_cli_resized_vocab.py ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import codecs
3
+ import os
4
+ import re
5
+ import torch
6
+ from datetime import datetime
7
+ from importlib.resources import files
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import soundfile as sf
12
+ import tomli
13
+ from cached_path import cached_path
14
+ from hydra.utils import get_class
15
+ from omegaconf import OmegaConf
16
+ from unidecode import unidecode
17
+
18
+ from f5_tts.infer.utils_infer import (
19
+ cfg_strength,
20
+ cross_fade_duration,
21
+ device,
22
+ fix_duration,
23
+ infer_process,
24
+ load_vocoder,
25
+ mel_spec_type,
26
+ nfe_step,
27
+ preprocess_ref_audio_text,
28
+ remove_silence_for_generated_wav,
29
+ speed,
30
+ sway_sampling_coef,
31
+ target_rms,
32
+ )
33
+ from f5_tts.model import CFM
34
+
35
+
36
+ # -------------------------- Patch load_model with vocab resize -------------------------- #
37
+
38
+ def load_model_with_vocab_resize(
39
+ model_cls,
40
+ model_cfg,
41
+ ckpt_path,
42
+ mel_spec_type="vocos",
43
+ vocab_file="",
44
+ use_ema=True,
45
+ device=None,
46
+ ):
47
+ """Load model with vocab size mismatch handling"""
48
+ if device is None:
49
+ device = "cuda" if torch.cuda.is_available() else "cpu"
50
+
51
+ print(f"\nLoading F5-TTS model:")
52
+ print(f" Checkpoint: {ckpt_path}")
53
+ print(f" Vocab file: {vocab_file}")
54
+ print(f" Device: {device}")
55
+
56
+ # Load vocab
57
+ vocab_char_map = None
58
+ vocab_size = None
59
+
60
+ if vocab_file:
61
+ with open(vocab_file, "r", encoding="utf-8") as f:
62
+ vocab_char_map = {}
63
+ for i, char in enumerate(f):
64
+ char = char.rstrip('\n')
65
+ vocab_char_map[char] = i
66
+ vocab_size = len(vocab_char_map)
67
+ print(f" Vocab size: {vocab_size}")
68
+
69
+ # Setup mel spec kwargs
70
+ if mel_spec_type == "vocos":
71
+ mel_spec_kwargs = dict(
72
+ n_fft=1024,
73
+ hop_length=256,
74
+ win_length=1024,
75
+ n_mel_channels=100,
76
+ target_sample_rate=24000,
77
+ mel_spec_type="vocos",
78
+ )
79
+ elif mel_spec_type == "bigvgan":
80
+ mel_spec_kwargs = dict(
81
+ n_fft=1024,
82
+ hop_length=256,
83
+ win_length=1024,
84
+ n_mel_channels=100,
85
+ target_sample_rate=24000,
86
+ mel_spec_type="bigvgan",
87
+ )
88
+ else:
89
+ raise ValueError(f"Unknown mel_spec_type: {mel_spec_type}")
90
+
91
+ # Update model config with vocab size
92
+ if vocab_size is not None:
93
+ model_cfg = dict(model_cfg) # Make a copy
94
+ model_cfg["text_num_embeds"] = vocab_size
95
+ model_cfg["mel_dim"] = mel_spec_kwargs["n_mel_channels"]
96
+
97
+ # Initialize model
98
+ model = CFM(
99
+ transformer=model_cls(**model_cfg),
100
+ mel_spec_kwargs=mel_spec_kwargs,
101
+ vocab_char_map=vocab_char_map,
102
+ )
103
+
104
+ model = model.to(device)
105
+
106
+ # Load checkpoint with vocab resize support
107
+ print(f"\nLoading checkpoint: {ckpt_path}")
108
+
109
+ # Handle different checkpoint formats
110
+ if ckpt_path.endswith('.safetensors'):
111
+ from safetensors.torch import load_file
112
+ state_dict = load_file(ckpt_path)
113
+ else:
114
+ checkpoint = torch.load(ckpt_path, map_location=device)
115
+
116
+ # Get state dict
117
+ if use_ema and "ema_model_state_dict" in checkpoint:
118
+ state_dict = checkpoint["ema_model_state_dict"]
119
+ elif "model_state_dict" in checkpoint:
120
+ state_dict = checkpoint["model_state_dict"]
121
+ else:
122
+ state_dict = checkpoint
123
+
124
+ # Remove ema_model prefix if exists
125
+ if any(k.startswith("ema_model.") for k in state_dict.keys()):
126
+ state_dict = {
127
+ k.replace("ema_model.", ""): v
128
+ for k, v in state_dict.items()
129
+ if k not in ["initted", "step"]
130
+ }
131
+
132
+ # Handle vocab size mismatch
133
+ embed_key = 'transformer.text_embed.text_embed.weight'
134
+ if embed_key in state_dict:
135
+ current_embed_weight = model.transformer.text_embed.text_embed.weight
136
+ new_vocab_size, embed_dim = current_embed_weight.shape
137
+ old_weight = state_dict[embed_key]
138
+ old_vocab_size = old_weight.shape[0]
139
+
140
+ if old_vocab_size != new_vocab_size:
141
+ print(f"\n⚠️ Vocab size mismatch detected!")
142
+ print(f" Checkpoint vocab: {old_vocab_size}")
143
+ print(f" Current vocab: {new_vocab_size}")
144
+ print(f" Resizing embedding layer...")
145
+
146
+ # Create new embedding weight
147
+ new_weight = torch.zeros(
148
+ new_vocab_size, embed_dim,
149
+ device=old_weight.device,
150
+ dtype=old_weight.dtype
151
+ )
152
+
153
+ # Copy overlapping weights
154
+ min_vocab_size = min(old_vocab_size, new_vocab_size)
155
+ new_weight[:min_vocab_size, :] = old_weight[:min_vocab_size, :]
156
+
157
+ # Handle different cases
158
+ if new_vocab_size > old_vocab_size:
159
+ # More tokens - initialize new ones
160
+ num_new_tokens = new_vocab_size - old_vocab_size
161
+ sample_indices = torch.randint(1, old_vocab_size, (num_new_tokens,))
162
+ new_weight[old_vocab_size:, :] = old_weight[sample_indices, :]
163
+ print(f" ✓ Initialized {num_new_tokens} new embeddings")
164
+ else:
165
+ # Fewer tokens - just use subset
166
+ num_missing = old_vocab_size - new_vocab_size
167
+ print(f" ✓ Using subset of embeddings ({new_vocab_size}/{old_vocab_size}, {num_missing} tokens dropped)")
168
+
169
+ state_dict[embed_key] = new_weight
170
+
171
+ # Load with strict=False
172
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
173
+
174
+ if missing_keys:
175
+ print(f"⚠️ Missing keys: {missing_keys}")
176
+ if unexpected_keys:
177
+ print(f"⚠️ Unexpected keys: {unexpected_keys}")
178
+
179
+ print("✓ Model loaded successfully\n")
180
+
181
+ model.eval()
182
+ return model
183
+
184
+
185
+
186
+ # -------------------------- Argument Parsing -------------------------- #
187
+
188
+ parser = argparse.ArgumentParser(
189
+ prog="python3 infer-cli.py",
190
+ description="Commandline interface for E2/F5 TTS with Advanced Batch Processing.",
191
+ epilog="Specify options above to override one or more settings from config.",
192
+ )
193
+ parser.add_argument(
194
+ "-c",
195
+ "--config",
196
+ type=str,
197
+ default=os.path.join(files("f5_tts").joinpath("infer/examples/basic"), "basic.toml"),
198
+ help="The configuration file, default see infer/examples/basic/basic.toml",
199
+ )
200
+
201
+ parser.add_argument(
202
+ "-m",
203
+ "--model",
204
+ type=str,
205
+ help="The model name: F5TTS_v1_Base | F5TTS_Base | E2TTS_Base | etc.",
206
+ )
207
+ parser.add_argument(
208
+ "-mc",
209
+ "--model_cfg",
210
+ type=str,
211
+ help="The path to F5-TTS model config file .yaml",
212
+ )
213
+ parser.add_argument(
214
+ "-p",
215
+ "--ckpt_file",
216
+ type=str,
217
+ help="The path to model checkpoint .pt, leave blank to use default",
218
+ )
219
+ parser.add_argument(
220
+ "-v",
221
+ "--vocab_file",
222
+ type=str,
223
+ help="The path to vocab file .txt, leave blank to use default",
224
+ )
225
+ parser.add_argument(
226
+ "-r",
227
+ "--ref_audio",
228
+ type=str,
229
+ help="The reference audio file.",
230
+ )
231
+ parser.add_argument(
232
+ "-s",
233
+ "--ref_text",
234
+ type=str,
235
+ help="The transcript/subtitle for the reference audio",
236
+ )
237
+ parser.add_argument(
238
+ "-t",
239
+ "--gen_text",
240
+ type=str,
241
+ help="The text to make model synthesize a speech",
242
+ )
243
+ parser.add_argument(
244
+ "-f",
245
+ "--gen_file",
246
+ type=str,
247
+ help="The file with text to generate, will ignore --gen_text",
248
+ )
249
+ parser.add_argument(
250
+ "-o",
251
+ "--output_dir",
252
+ type=str,
253
+ help="The path to output folder",
254
+ )
255
+ parser.add_argument(
256
+ "-w",
257
+ "--output_file",
258
+ type=str,
259
+ help="The name of output file",
260
+ )
261
+ parser.add_argument(
262
+ "--save_chunk",
263
+ action="store_true",
264
+ help="To save each audio chunks during inference",
265
+ )
266
+ parser.add_argument(
267
+ "--no_legacy_text",
268
+ action="store_false",
269
+ help="Not to use lossy ASCII transliterations of unicode text in saved file names.",
270
+ )
271
+ parser.add_argument(
272
+ "--remove_silence",
273
+ action="store_true",
274
+ help="To remove long silence found in ouput",
275
+ )
276
+ parser.add_argument(
277
+ "--load_vocoder_from_local",
278
+ action="store_true",
279
+ help="To load vocoder from local dir, default to ../checkpoints/vocos-mel-24khz",
280
+ )
281
+ parser.add_argument(
282
+ "--vocoder_name",
283
+ type=str,
284
+ choices=["vocos", "bigvgan"],
285
+ help=f"Used vocoder name: vocos | bigvgan, default {mel_spec_type}",
286
+ )
287
+ parser.add_argument(
288
+ "--target_rms",
289
+ type=float,
290
+ help=f"Target output speech loudness normalization value, default {target_rms}",
291
+ )
292
+ parser.add_argument(
293
+ "--cross_fade_duration",
294
+ type=float,
295
+ help=f"Duration of cross-fade between audio segments in seconds, default {cross_fade_duration}",
296
+ )
297
+ parser.add_argument(
298
+ "--nfe_step",
299
+ type=int,
300
+ help=f"The number of function evaluation (denoising steps), default {nfe_step}",
301
+ )
302
+ parser.add_argument(
303
+ "--cfg_strength",
304
+ type=float,
305
+ help=f"Classifier-free guidance strength, default {cfg_strength}",
306
+ )
307
+ parser.add_argument(
308
+ "--sway_sampling_coef",
309
+ type=float,
310
+ help=f"Sway Sampling coefficient, default {sway_sampling_coef}",
311
+ )
312
+ parser.add_argument(
313
+ "--speed",
314
+ type=float,
315
+ help=f"The speed of the generated audio, default {speed}",
316
+ )
317
+ parser.add_argument(
318
+ "--fix_duration",
319
+ type=float,
320
+ help=f"Fix the total duration (ref and gen audios) in seconds, default {fix_duration}",
321
+ )
322
+ parser.add_argument(
323
+ "--device",
324
+ type=str,
325
+ help="Specify the device to run on",
326
+ )
327
+ args = parser.parse_args()
328
+
329
+ # config file
330
+ config = tomli.load(open(args.config, "rb"))
331
+
332
+ # command-line interface parameters
333
+ model = args.model or config.get("model", "F5TTS_v1_Base")
334
+ ckpt_file = args.ckpt_file or config.get("ckpt_file", "")
335
+ vocab_file = args.vocab_file or config.get("vocab_file", "")
336
+
337
+ ref_audio = args.ref_audio or config.get("ref_audio", "infer/examples/basic/basic_ref_en.wav")
338
+ ref_text = (
339
+ args.ref_text
340
+ if args.ref_text is not None
341
+ else config.get("ref_text", "Some call me nature, others call me mother nature.")
342
+ )
343
+ gen_text = args.gen_text or config.get("gen_text", "Here we generate something just for test.")
344
+ gen_file = args.gen_file or config.get("gen_file", "")
345
+
346
+ output_dir = args.output_dir or config.get("output_dir", "tests")
347
+ output_file = args.output_file or config.get(
348
+ "output_file", f"infer_cli_{datetime.now().strftime(r'%Y%m%d_%H%M%S')}.wav"
349
+ )
350
+
351
+ save_chunk = args.save_chunk or config.get("save_chunk", False)
352
+ use_legacy_text = args.no_legacy_text or config.get("no_legacy_text", False)
353
+ if save_chunk and use_legacy_text:
354
+ print(
355
+ "\nWarning to --save_chunk: lossy ASCII transliterations of unicode text for legacy (.wav) file names, --no_legacy_text to disable.\n"
356
+ )
357
+
358
+ remove_silence = args.remove_silence or config.get("remove_silence", False)
359
+ load_vocoder_from_local = args.load_vocoder_from_local or config.get("load_vocoder_from_local", False)
360
+
361
+ vocoder_name = args.vocoder_name or config.get("vocoder_name", mel_spec_type)
362
+ target_rms = args.target_rms or config.get("target_rms", target_rms)
363
+ cross_fade_duration = args.cross_fade_duration or config.get("cross_fade_duration", cross_fade_duration)
364
+ nfe_step = args.nfe_step or config.get("nfe_step", nfe_step)
365
+ cfg_strength = args.cfg_strength or config.get("cfg_strength", cfg_strength)
366
+ sway_sampling_coef = args.sway_sampling_coef or config.get("sway_sampling_coef", sway_sampling_coef)
367
+ speed = args.speed or config.get("speed", speed)
368
+ fix_duration = args.fix_duration or config.get("fix_duration", fix_duration)
369
+ device = args.device or config.get("device", device)
370
+
371
+ # patches for pip pkg user
372
+ if "infer/examples/" in ref_audio:
373
+ ref_audio = str(files("f5_tts").joinpath(f"{ref_audio}"))
374
+ if "infer/examples/" in gen_file:
375
+ gen_file = str(files("f5_tts").joinpath(f"{gen_file}"))
376
+ if "voices" in config:
377
+ for voice in config["voices"]:
378
+ voice_ref_audio = config["voices"][voice]["ref_audio"]
379
+ if "infer/examples/" in voice_ref_audio:
380
+ config["voices"][voice]["ref_audio"] = str(files("f5_tts").joinpath(f"{voice_ref_audio}"))
381
+
382
+ # ignore gen_text if gen_file provided
383
+ if gen_file:
384
+ gen_text = codecs.open(gen_file, "r", "utf-8").read()
385
+
386
+ # output path
387
+ wave_path = Path(output_dir) / output_file
388
+ if save_chunk:
389
+ output_chunk_dir = os.path.join(output_dir, f"{Path(output_file).stem}_chunks")
390
+ if not os.path.exists(output_chunk_dir):
391
+ os.makedirs(output_chunk_dir)
392
+
393
+ # load vocoder
394
+ if vocoder_name == "vocos":
395
+ vocoder_local_path = "../checkpoints/vocos-mel-24khz"
396
+ elif vocoder_name == "bigvgan":
397
+ vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x"
398
+
399
+ vocoder = load_vocoder(
400
+ vocoder_name=vocoder_name, is_local=load_vocoder_from_local, local_path=vocoder_local_path, device=device
401
+ )
402
+
403
+ # load TTS model
404
+ model_cfg = OmegaConf.load(
405
+ args.model_cfg or config.get("model_cfg", str(files("f5_tts").joinpath(f"configs/{model}.yaml")))
406
+ )
407
+ model_cls = get_class(f"f5_tts.model.{model_cfg.model.backbone}")
408
+ model_arc = model_cfg.model.arch
409
+
410
+ repo_name, ckpt_step, ckpt_type = "F5-TTS", 1250000, "safetensors"
411
+
412
+ if model != "F5TTS_Base":
413
+ assert vocoder_name == model_cfg.model.mel_spec.mel_spec_type
414
+
415
+ # override for previous models
416
+ if model == "F5TTS_Base":
417
+ if vocoder_name == "vocos":
418
+ ckpt_step = 1200000
419
+ elif vocoder_name == "bigvgan":
420
+ model = "F5TTS_Base_bigvgan"
421
+ ckpt_type = "pt"
422
+ elif model == "E2TTS_Base":
423
+ repo_name = "E2-TTS"
424
+ ckpt_step = 1200000
425
+
426
+ if not ckpt_file:
427
+ ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{model}/model_{ckpt_step}.{ckpt_type}"))
428
+
429
+ print(f"Using {model}...")
430
+
431
+ # Use patched load function with vocab resize support
432
+ ema_model = load_model_with_vocab_resize(
433
+ model_cls, model_arc, ckpt_file, mel_spec_type=vocoder_name, vocab_file=vocab_file, device=device
434
+ )
435
+
436
+
437
+ # inference process
438
+ def main():
439
+ main_voice = {"ref_audio": ref_audio, "ref_text": ref_text}
440
+ if "voices" not in config:
441
+ voices = {"main": main_voice}
442
+ else:
443
+ voices = config["voices"]
444
+ voices["main"] = main_voice
445
+
446
+ for voice in voices:
447
+ print("Voice:", voice)
448
+ print("ref_audio ", voices[voice]["ref_audio"])
449
+ voices[voice]["ref_audio"], voices[voice]["ref_text"] = preprocess_ref_audio_text(
450
+ voices[voice]["ref_audio"], voices[voice]["ref_text"]
451
+ )
452
+ print("ref_audio_", voices[voice]["ref_audio"], "\n\n")
453
+
454
+ generated_audio_segments = []
455
+ reg1 = r"(?=\[\w+\])"
456
+ chunks = re.split(reg1, gen_text)
457
+ reg2 = r"\[(\w+)\]"
458
+
459
+ for text in chunks:
460
+ if not text.strip():
461
+ continue
462
+ match = re.match(reg2, text)
463
+ if match:
464
+ voice = match[1]
465
+ else:
466
+ print("No voice tag found, using main.")
467
+ voice = "main"
468
+ if voice not in voices:
469
+ print(f"Voice {voice} not found, using main.")
470
+ voice = "main"
471
+ text = re.sub(reg2, "", text)
472
+ ref_audio_ = voices[voice]["ref_audio"]
473
+ ref_text_ = voices[voice]["ref_text"]
474
+ local_speed = voices[voice].get("speed", speed)
475
+ gen_text_ = text.strip()
476
+ print(f"Voice: {voice}")
477
+
478
+ audio_segment, final_sample_rate, spectrogram = infer_process(
479
+ ref_audio_,
480
+ ref_text_,
481
+ gen_text_,
482
+ ema_model,
483
+ vocoder,
484
+ mel_spec_type=vocoder_name,
485
+ target_rms=target_rms,
486
+ cross_fade_duration=cross_fade_duration,
487
+ nfe_step=nfe_step,
488
+ cfg_strength=cfg_strength,
489
+ sway_sampling_coef=sway_sampling_coef,
490
+ speed=local_speed,
491
+ fix_duration=fix_duration,
492
+ device=device,
493
+ )
494
+ generated_audio_segments.append(audio_segment)
495
+
496
+ if save_chunk:
497
+ if len(gen_text_) > 200:
498
+ gen_text_ = gen_text_[:200] + " ... "
499
+ if use_legacy_text:
500
+ gen_text_ = unidecode(gen_text_)
501
+ sf.write(
502
+ os.path.join(output_chunk_dir, f"{len(generated_audio_segments) - 1}_{gen_text_}.wav"),
503
+ audio_segment,
504
+ final_sample_rate,
505
+ )
506
+
507
+ if generated_audio_segments:
508
+ final_wave = np.concatenate(generated_audio_segments)
509
+
510
+ if not os.path.exists(output_dir):
511
+ os.makedirs(output_dir)
512
+
513
+ with open(wave_path, "wb") as f:
514
+ sf.write(f.name, final_wave, final_sample_rate)
515
+ # Remove silence
516
+ if remove_silence:
517
+ remove_silence_for_generated_wav(f.name)
518
+ print(f.name)
519
+
520
+ if __name__ == "__main__":
521
+ main()
src/f5_tts/infer/infer_gradio.py ADDED
@@ -0,0 +1,1121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ruff: noqa: E402
2
+ # Above allows ruff to ignore E402: module level import not at top of file
3
+
4
+ import gc
5
+ import json
6
+ import os
7
+ import re
8
+ import tempfile
9
+ from collections import OrderedDict
10
+ from functools import lru_cache
11
+ from importlib.resources import files
12
+
13
+ import click
14
+ import gradio as gr
15
+ import numpy as np
16
+ import soundfile as sf
17
+ import torch
18
+ import torchaudio
19
+ from cached_path import cached_path
20
+ from transformers import AutoModelForCausalLM, AutoTokenizer
21
+
22
+
23
+ try:
24
+ import spaces
25
+
26
+ USING_SPACES = True
27
+ except ImportError:
28
+ USING_SPACES = False
29
+
30
+
31
+ def gpu_decorator(func):
32
+ if USING_SPACES:
33
+ return spaces.GPU(func)
34
+ else:
35
+ return func
36
+
37
+
38
+ from f5_tts.infer.utils_infer import (
39
+ infer_process,
40
+ load_model,
41
+ load_vocoder,
42
+ preprocess_ref_audio_text,
43
+ remove_silence_for_generated_wav,
44
+ save_spectrogram,
45
+ tempfile_kwargs,
46
+ )
47
+ from f5_tts.model import DiT, UNetT
48
+
49
+
50
+ DEFAULT_TTS_MODEL = "F5-TTS_v1"
51
+ tts_model_choice = DEFAULT_TTS_MODEL
52
+
53
+ DEFAULT_TTS_MODEL_CFG = [
54
+ "hf://SWivid/F5-TTS/F5TTS_v1_Base/model_1250000.safetensors",
55
+ "hf://SWivid/F5-TTS/F5TTS_v1_Base/vocab.txt",
56
+ json.dumps(dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)),
57
+ ]
58
+
59
+
60
+ # load models
61
+
62
+ vocoder = load_vocoder()
63
+
64
+
65
+ def load_f5tts():
66
+ ckpt_path = str(cached_path(DEFAULT_TTS_MODEL_CFG[0]))
67
+ F5TTS_model_cfg = json.loads(DEFAULT_TTS_MODEL_CFG[2])
68
+ return load_model(DiT, F5TTS_model_cfg, ckpt_path)
69
+
70
+
71
+ def load_e2tts():
72
+ ckpt_path = str(cached_path("hf://SWivid/E2-TTS/E2TTS_Base/model_1200000.safetensors"))
73
+ E2TTS_model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4, text_mask_padding=False, pe_attn_head=1)
74
+ return load_model(UNetT, E2TTS_model_cfg, ckpt_path)
75
+
76
+
77
+ def load_custom(ckpt_path: str, vocab_path="", model_cfg=None):
78
+ ckpt_path, vocab_path = ckpt_path.strip(), vocab_path.strip()
79
+ if ckpt_path.startswith("hf://"):
80
+ ckpt_path = str(cached_path(ckpt_path))
81
+ if vocab_path.startswith("hf://"):
82
+ vocab_path = str(cached_path(vocab_path))
83
+ if model_cfg is None:
84
+ model_cfg = json.loads(DEFAULT_TTS_MODEL_CFG[2])
85
+ elif isinstance(model_cfg, str):
86
+ model_cfg = json.loads(model_cfg)
87
+ return load_model(DiT, model_cfg, ckpt_path, vocab_file=vocab_path)
88
+
89
+
90
+ F5TTS_ema_model = load_f5tts()
91
+ E2TTS_ema_model = load_e2tts() if USING_SPACES else None
92
+ custom_ema_model, pre_custom_path = None, ""
93
+
94
+ chat_model_state = None
95
+ chat_tokenizer_state = None
96
+
97
+
98
+ @gpu_decorator
99
+ def chat_model_inference(messages, model, tokenizer):
100
+ """Generate response using Qwen"""
101
+ text = tokenizer.apply_chat_template(
102
+ messages,
103
+ tokenize=False,
104
+ add_generation_prompt=True,
105
+ )
106
+
107
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
108
+ generated_ids = model.generate(
109
+ **model_inputs,
110
+ max_new_tokens=512,
111
+ temperature=0.7,
112
+ top_p=0.95,
113
+ )
114
+
115
+ generated_ids = [
116
+ output_ids[len(input_ids) :] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
117
+ ]
118
+ return tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
119
+
120
+
121
+ @gpu_decorator
122
+ def load_text_from_file(file):
123
+ if file:
124
+ with open(file, "r", encoding="utf-8") as f:
125
+ text = f.read().strip()
126
+ else:
127
+ text = ""
128
+ return gr.update(value=text)
129
+
130
+
131
+ @lru_cache(maxsize=1000) # NOTE. need to ensure params of infer() hashable
132
+ @gpu_decorator
133
+ def infer(
134
+ ref_audio_orig,
135
+ ref_text,
136
+ gen_text,
137
+ model,
138
+ remove_silence,
139
+ seed,
140
+ cross_fade_duration=0.15,
141
+ nfe_step=32,
142
+ speed=1,
143
+ show_info=gr.Info,
144
+ ):
145
+ if not ref_audio_orig:
146
+ gr.Warning("Please provide reference audio.")
147
+ return gr.update(), gr.update(), ref_text
148
+
149
+ # Set inference seed
150
+ if seed < 0 or seed > 2**31 - 1:
151
+ gr.Warning("Seed must in range 0 ~ 2147483647. Using random seed instead.")
152
+ seed = np.random.randint(0, 2**31 - 1)
153
+ torch.manual_seed(seed)
154
+ used_seed = seed
155
+
156
+ if not gen_text.strip():
157
+ gr.Warning("Please enter text to generate or upload a text file.")
158
+ return gr.update(), gr.update(), ref_text
159
+
160
+ ref_audio, ref_text = preprocess_ref_audio_text(ref_audio_orig, ref_text, show_info=show_info)
161
+
162
+ if model == DEFAULT_TTS_MODEL:
163
+ ema_model = F5TTS_ema_model
164
+ elif model == "E2-TTS":
165
+ global E2TTS_ema_model
166
+ if E2TTS_ema_model is None:
167
+ show_info("Loading E2-TTS model...")
168
+ E2TTS_ema_model = load_e2tts()
169
+ ema_model = E2TTS_ema_model
170
+ elif isinstance(model, tuple) and model[0] == "Custom":
171
+ assert not USING_SPACES, "Only official checkpoints allowed in Spaces."
172
+ global custom_ema_model, pre_custom_path
173
+ if pre_custom_path != model[1]:
174
+ show_info("Loading Custom TTS model...")
175
+ custom_ema_model = load_custom(model[1], vocab_path=model[2], model_cfg=model[3])
176
+ pre_custom_path = model[1]
177
+ ema_model = custom_ema_model
178
+
179
+ final_wave, final_sample_rate, combined_spectrogram = infer_process(
180
+ ref_audio,
181
+ ref_text,
182
+ gen_text,
183
+ ema_model,
184
+ vocoder,
185
+ cross_fade_duration=cross_fade_duration,
186
+ nfe_step=nfe_step,
187
+ speed=speed,
188
+ show_info=show_info,
189
+ progress=gr.Progress(),
190
+ )
191
+
192
+ # Remove silence
193
+ if remove_silence:
194
+ with tempfile.NamedTemporaryFile(suffix=".wav", **tempfile_kwargs) as f:
195
+ temp_path = f.name
196
+ try:
197
+ sf.write(temp_path, final_wave, final_sample_rate)
198
+ remove_silence_for_generated_wav(f.name)
199
+ final_wave, _ = torchaudio.load(f.name)
200
+ finally:
201
+ os.unlink(temp_path)
202
+ final_wave = final_wave.squeeze().cpu().numpy()
203
+
204
+ # Save the spectrogram
205
+ with tempfile.NamedTemporaryFile(suffix=".png", **tempfile_kwargs) as tmp_spectrogram:
206
+ spectrogram_path = tmp_spectrogram.name
207
+ save_spectrogram(combined_spectrogram, spectrogram_path)
208
+
209
+ return (final_sample_rate, final_wave), spectrogram_path, ref_text, used_seed
210
+
211
+
212
+ with gr.Blocks() as app_tts:
213
+ gr.Markdown("# Batched TTS")
214
+ ref_audio_input = gr.Audio(label="Reference Audio", type="filepath")
215
+ with gr.Row():
216
+ gen_text_input = gr.Textbox(
217
+ label="Text to Generate",
218
+ lines=10,
219
+ max_lines=40,
220
+ scale=4,
221
+ )
222
+ gen_text_file = gr.File(label="Load Text to Generate from File (.txt)", file_types=[".txt"], scale=1)
223
+ generate_btn = gr.Button("Synthesize", variant="primary")
224
+ with gr.Accordion("Advanced Settings", open=False):
225
+ with gr.Row():
226
+ ref_text_input = gr.Textbox(
227
+ label="Reference Text",
228
+ info="Leave blank to automatically transcribe the reference audio. If you enter text or upload a file, it will override automatic transcription.",
229
+ lines=2,
230
+ scale=4,
231
+ )
232
+ ref_text_file = gr.File(label="Load Reference Text from File (.txt)", file_types=[".txt"], scale=1)
233
+ with gr.Row():
234
+ randomize_seed = gr.Checkbox(
235
+ label="Randomize Seed",
236
+ info="Check to use a random seed for each generation. Uncheck to use the seed specified.",
237
+ value=True,
238
+ scale=3,
239
+ )
240
+ seed_input = gr.Number(show_label=False, value=0, precision=0, scale=1)
241
+ with gr.Column(scale=4):
242
+ remove_silence = gr.Checkbox(
243
+ label="Remove Silences",
244
+ info="If undesired long silence(s) produced, turn on to automatically detect and crop.",
245
+ value=False,
246
+ )
247
+ speed_slider = gr.Slider(
248
+ label="Speed",
249
+ minimum=0.3,
250
+ maximum=2.0,
251
+ value=1.0,
252
+ step=0.1,
253
+ info="Adjust the speed of the audio.",
254
+ )
255
+ nfe_slider = gr.Slider(
256
+ label="NFE Steps",
257
+ minimum=4,
258
+ maximum=64,
259
+ value=32,
260
+ step=2,
261
+ info="Set the number of denoising steps.",
262
+ )
263
+ cross_fade_duration_slider = gr.Slider(
264
+ label="Cross-Fade Duration (s)",
265
+ minimum=0.0,
266
+ maximum=1.0,
267
+ value=0.15,
268
+ step=0.01,
269
+ info="Set the duration of the cross-fade between audio clips.",
270
+ )
271
+
272
+ audio_output = gr.Audio(label="Synthesized Audio")
273
+ spectrogram_output = gr.Image(label="Spectrogram")
274
+
275
+ @gpu_decorator
276
+ def basic_tts(
277
+ ref_audio_input,
278
+ ref_text_input,
279
+ gen_text_input,
280
+ remove_silence,
281
+ randomize_seed,
282
+ seed_input,
283
+ cross_fade_duration_slider,
284
+ nfe_slider,
285
+ speed_slider,
286
+ ):
287
+ if randomize_seed:
288
+ seed_input = np.random.randint(0, 2**31 - 1)
289
+
290
+ audio_out, spectrogram_path, ref_text_out, used_seed = infer(
291
+ ref_audio_input,
292
+ ref_text_input,
293
+ gen_text_input,
294
+ tts_model_choice,
295
+ remove_silence,
296
+ seed=seed_input,
297
+ cross_fade_duration=cross_fade_duration_slider,
298
+ nfe_step=nfe_slider,
299
+ speed=speed_slider,
300
+ )
301
+ return audio_out, spectrogram_path, ref_text_out, used_seed
302
+
303
+ gen_text_file.upload(
304
+ load_text_from_file,
305
+ inputs=[gen_text_file],
306
+ outputs=[gen_text_input],
307
+ )
308
+
309
+ ref_text_file.upload(
310
+ load_text_from_file,
311
+ inputs=[ref_text_file],
312
+ outputs=[ref_text_input],
313
+ )
314
+
315
+ ref_audio_input.clear(
316
+ lambda: [None, None],
317
+ None,
318
+ [ref_text_input, ref_text_file],
319
+ )
320
+
321
+ generate_btn.click(
322
+ basic_tts,
323
+ inputs=[
324
+ ref_audio_input,
325
+ ref_text_input,
326
+ gen_text_input,
327
+ remove_silence,
328
+ randomize_seed,
329
+ seed_input,
330
+ cross_fade_duration_slider,
331
+ nfe_slider,
332
+ speed_slider,
333
+ ],
334
+ outputs=[audio_output, spectrogram_output, ref_text_input, seed_input],
335
+ )
336
+
337
+
338
+ def parse_speechtypes_text(gen_text):
339
+ # Pattern to find {str} or {"name": str, "seed": int, "speed": float}
340
+ pattern = r"(\{.*?\})"
341
+
342
+ # Split the text by the pattern
343
+ tokens = re.split(pattern, gen_text)
344
+
345
+ segments = []
346
+
347
+ current_type_dict = {
348
+ "name": "Regular",
349
+ "seed": -1,
350
+ "speed": 1.0,
351
+ }
352
+
353
+ for i in range(len(tokens)):
354
+ if i % 2 == 0:
355
+ # This is text
356
+ text = tokens[i].strip()
357
+ if text:
358
+ current_type_dict["text"] = text
359
+ segments.append(current_type_dict)
360
+ else:
361
+ # This is type
362
+ type_str = tokens[i].strip()
363
+ try: # if type dict
364
+ current_type_dict = json.loads(type_str)
365
+ except json.decoder.JSONDecodeError:
366
+ type_str = type_str[1:-1] # remove brace {}
367
+ current_type_dict = {"name": type_str, "seed": -1, "speed": 1.0}
368
+
369
+ return segments
370
+
371
+
372
+ with gr.Blocks() as app_multistyle:
373
+ # New section for multistyle generation
374
+ gr.Markdown(
375
+ """
376
+ # Multiple Speech-Type Generation
377
+
378
+ This section allows you to generate multiple speech types or multiple people's voices. Enter your text in the format shown below, or upload a .txt file with the same format. The system will generate speech using the appropriate type. If unspecified, the model will use the regular speech type. The current speech type will be used until the next speech type is specified.
379
+ """
380
+ )
381
+
382
+ with gr.Row():
383
+ gr.Markdown(
384
+ """
385
+ **Example Input:** <br>
386
+ {Regular} Hello, I'd like to order a sandwich please. <br>
387
+ {Surprised} What do you mean you're out of bread? <br>
388
+ {Sad} I really wanted a sandwich though... <br>
389
+ {Angry} You know what, darn you and your little shop! <br>
390
+ {Whisper} I'll just go back home and cry now. <br>
391
+ {Shouting} Why me?!
392
+ """
393
+ )
394
+
395
+ gr.Markdown(
396
+ """
397
+ **Example Input 2:** <br>
398
+ {"name": "Speaker1_Happy", "seed": -1, "speed": 1} Hello, I'd like to order a sandwich please. <br>
399
+ {"name": "Speaker2_Regular", "seed": -1, "speed": 1} Sorry, we're out of bread. <br>
400
+ {"name": "Speaker1_Sad", "seed": -1, "speed": 1} I really wanted a sandwich though... <br>
401
+ {"name": "Speaker2_Whisper", "seed": -1, "speed": 1} I'll give you the last one I was hiding.
402
+ """
403
+ )
404
+
405
+ gr.Markdown(
406
+ 'Upload different audio clips for each speech type. The first speech type is mandatory. You can add additional speech types by clicking the "Add Speech Type" button.'
407
+ )
408
+
409
+ # Regular speech type (mandatory)
410
+ with gr.Row(variant="compact") as regular_row:
411
+ with gr.Column(scale=1, min_width=160):
412
+ regular_name = gr.Textbox(value="Regular", label="Speech Type Name")
413
+ regular_insert = gr.Button("Insert Label", variant="secondary")
414
+ with gr.Column(scale=3):
415
+ regular_audio = gr.Audio(label="Regular Reference Audio", type="filepath")
416
+ with gr.Column(scale=3):
417
+ regular_ref_text = gr.Textbox(label="Reference Text (Regular)", lines=4)
418
+ with gr.Row():
419
+ regular_seed_slider = gr.Slider(
420
+ show_label=False, minimum=-1, maximum=999, value=-1, step=1, info="Seed, -1 for random"
421
+ )
422
+ regular_speed_slider = gr.Slider(
423
+ show_label=False, minimum=0.3, maximum=2.0, value=1.0, step=0.1, info="Adjust the speed"
424
+ )
425
+ with gr.Column(scale=1, min_width=160):
426
+ regular_ref_text_file = gr.File(label="Load Reference Text from File (.txt)", file_types=[".txt"])
427
+
428
+ # Regular speech type (max 100)
429
+ max_speech_types = 100
430
+ speech_type_rows = [regular_row]
431
+ speech_type_names = [regular_name]
432
+ speech_type_audios = [regular_audio]
433
+ speech_type_ref_texts = [regular_ref_text]
434
+ speech_type_ref_text_files = [regular_ref_text_file]
435
+ speech_type_seeds = [regular_seed_slider]
436
+ speech_type_speeds = [regular_speed_slider]
437
+ speech_type_delete_btns = [None]
438
+ speech_type_insert_btns = [regular_insert]
439
+
440
+ # Additional speech types (99 more)
441
+ for i in range(max_speech_types - 1):
442
+ with gr.Row(variant="compact", visible=False) as row:
443
+ with gr.Column(scale=1, min_width=160):
444
+ name_input = gr.Textbox(label="Speech Type Name")
445
+ insert_btn = gr.Button("Insert Label", variant="secondary")
446
+ delete_btn = gr.Button("Delete Type", variant="stop")
447
+ with gr.Column(scale=3):
448
+ audio_input = gr.Audio(label="Reference Audio", type="filepath")
449
+ with gr.Column(scale=3):
450
+ ref_text_input = gr.Textbox(label="Reference Text", lines=4)
451
+ with gr.Row():
452
+ seed_input = gr.Slider(
453
+ show_label=False, minimum=-1, maximum=999, value=-1, step=1, info="Seed. -1 for random"
454
+ )
455
+ speed_input = gr.Slider(
456
+ show_label=False, minimum=0.3, maximum=2.0, value=1.0, step=0.1, info="Adjust the speed"
457
+ )
458
+ with gr.Column(scale=1, min_width=160):
459
+ ref_text_file_input = gr.File(label="Load Reference Text from File (.txt)", file_types=[".txt"])
460
+ speech_type_rows.append(row)
461
+ speech_type_names.append(name_input)
462
+ speech_type_audios.append(audio_input)
463
+ speech_type_ref_texts.append(ref_text_input)
464
+ speech_type_ref_text_files.append(ref_text_file_input)
465
+ speech_type_seeds.append(seed_input)
466
+ speech_type_speeds.append(speed_input)
467
+ speech_type_delete_btns.append(delete_btn)
468
+ speech_type_insert_btns.append(insert_btn)
469
+
470
+ # Global logic for all speech types
471
+ for i in range(max_speech_types):
472
+ speech_type_audios[i].clear(
473
+ lambda: [None, None],
474
+ None,
475
+ [speech_type_ref_texts[i], speech_type_ref_text_files[i]],
476
+ )
477
+ speech_type_ref_text_files[i].upload(
478
+ load_text_from_file,
479
+ inputs=[speech_type_ref_text_files[i]],
480
+ outputs=[speech_type_ref_texts[i]],
481
+ )
482
+
483
+ # Button to add speech type
484
+ add_speech_type_btn = gr.Button("Add Speech Type")
485
+
486
+ # Keep track of autoincrement of speech types, no roll back
487
+ speech_type_count = 1
488
+
489
+ # Function to add a speech type
490
+ def add_speech_type_fn():
491
+ row_updates = [gr.update() for _ in range(max_speech_types)]
492
+ global speech_type_count
493
+ if speech_type_count < max_speech_types:
494
+ row_updates[speech_type_count] = gr.update(visible=True)
495
+ speech_type_count += 1
496
+ else:
497
+ gr.Warning("Exhausted maximum number of speech types. Consider restart the app.")
498
+ return row_updates
499
+
500
+ add_speech_type_btn.click(add_speech_type_fn, outputs=speech_type_rows)
501
+
502
+ # Function to delete a speech type
503
+ def delete_speech_type_fn():
504
+ return gr.update(visible=False), None, None, None, None
505
+
506
+ # Update delete button clicks and ref text file changes
507
+ for i in range(1, len(speech_type_delete_btns)):
508
+ speech_type_delete_btns[i].click(
509
+ delete_speech_type_fn,
510
+ outputs=[
511
+ speech_type_rows[i],
512
+ speech_type_names[i],
513
+ speech_type_audios[i],
514
+ speech_type_ref_texts[i],
515
+ speech_type_ref_text_files[i],
516
+ ],
517
+ )
518
+
519
+ # Text input for the prompt
520
+ with gr.Row():
521
+ gen_text_input_multistyle = gr.Textbox(
522
+ label="Text to Generate",
523
+ lines=10,
524
+ max_lines=40,
525
+ scale=4,
526
+ placeholder="Enter the script with speaker names (or emotion types) at the start of each block, e.g.:\n\n{Regular} Hello, I'd like to order a sandwich please.\n{Surprised} What do you mean you're out of bread?\n{Sad} I really wanted a sandwich though...\n{Angry} You know what, darn you and your little shop!\n{Whisper} I'll just go back home and cry now.\n{Shouting} Why me?!",
527
+ )
528
+ gen_text_file_multistyle = gr.File(label="Load Text to Generate from File (.txt)", file_types=[".txt"], scale=1)
529
+
530
+ def make_insert_speech_type_fn(index):
531
+ def insert_speech_type_fn(current_text, speech_type_name, speech_type_seed, speech_type_speed):
532
+ current_text = current_text or ""
533
+ if not speech_type_name:
534
+ gr.Warning("Please enter speech type name before insert.")
535
+ return current_text
536
+ speech_type_dict = {
537
+ "name": speech_type_name,
538
+ "seed": speech_type_seed,
539
+ "speed": speech_type_speed,
540
+ }
541
+ updated_text = current_text + json.dumps(speech_type_dict) + " "
542
+ return updated_text
543
+
544
+ return insert_speech_type_fn
545
+
546
+ for i, insert_btn in enumerate(speech_type_insert_btns):
547
+ insert_fn = make_insert_speech_type_fn(i)
548
+ insert_btn.click(
549
+ insert_fn,
550
+ inputs=[gen_text_input_multistyle, speech_type_names[i], speech_type_seeds[i], speech_type_speeds[i]],
551
+ outputs=gen_text_input_multistyle,
552
+ )
553
+
554
+ with gr.Accordion("Advanced Settings", open=True):
555
+ with gr.Row():
556
+ with gr.Column():
557
+ show_cherrypick_multistyle = gr.Checkbox(
558
+ label="Show Cherry-pick Interface",
559
+ info="Turn on to show interface, picking seeds from previous generations.",
560
+ value=False,
561
+ )
562
+ with gr.Column():
563
+ remove_silence_multistyle = gr.Checkbox(
564
+ label="Remove Silences",
565
+ info="Turn on to automatically detect and crop long silences.",
566
+ value=True,
567
+ )
568
+
569
+ # Generate button
570
+ generate_multistyle_btn = gr.Button("Generate Multi-Style Speech", variant="primary")
571
+
572
+ # Output audio
573
+ audio_output_multistyle = gr.Audio(label="Synthesized Audio")
574
+
575
+ # Used seed gallery
576
+ cherrypick_interface_multistyle = gr.Textbox(
577
+ label="Cherry-pick Interface",
578
+ lines=10,
579
+ max_lines=40,
580
+ show_copy_button=True,
581
+ interactive=False,
582
+ visible=False,
583
+ )
584
+
585
+ # Logic control to show/hide the cherrypick interface
586
+ show_cherrypick_multistyle.change(
587
+ lambda is_visible: gr.update(visible=is_visible),
588
+ show_cherrypick_multistyle,
589
+ cherrypick_interface_multistyle,
590
+ )
591
+
592
+ # Function to load text to generate from file
593
+ gen_text_file_multistyle.upload(
594
+ load_text_from_file,
595
+ inputs=[gen_text_file_multistyle],
596
+ outputs=[gen_text_input_multistyle],
597
+ )
598
+
599
+ @gpu_decorator
600
+ def generate_multistyle_speech(
601
+ gen_text,
602
+ *args,
603
+ ):
604
+ speech_type_names_list = args[:max_speech_types]
605
+ speech_type_audios_list = args[max_speech_types : 2 * max_speech_types]
606
+ speech_type_ref_texts_list = args[2 * max_speech_types : 3 * max_speech_types]
607
+ remove_silence = args[3 * max_speech_types]
608
+ # Collect the speech types and their audios into a dict
609
+ speech_types = OrderedDict()
610
+
611
+ ref_text_idx = 0
612
+ for name_input, audio_input, ref_text_input in zip(
613
+ speech_type_names_list, speech_type_audios_list, speech_type_ref_texts_list
614
+ ):
615
+ if name_input and audio_input:
616
+ speech_types[name_input] = {"audio": audio_input, "ref_text": ref_text_input}
617
+ else:
618
+ speech_types[f"@{ref_text_idx}@"] = {"audio": "", "ref_text": ""}
619
+ ref_text_idx += 1
620
+
621
+ # Parse the gen_text into segments
622
+ segments = parse_speechtypes_text(gen_text)
623
+
624
+ # For each segment, generate speech
625
+ generated_audio_segments = []
626
+ current_type_name = "Regular"
627
+ inference_meta_data = ""
628
+
629
+ for segment in segments:
630
+ name = segment["name"]
631
+ seed_input = segment["seed"]
632
+ speed = segment["speed"]
633
+ text = segment["text"]
634
+
635
+ if name in speech_types:
636
+ current_type_name = name
637
+ else:
638
+ gr.Warning(f"Type {name} is not available, will use Regular as default.")
639
+ current_type_name = "Regular"
640
+
641
+ try:
642
+ ref_audio = speech_types[current_type_name]["audio"]
643
+ except KeyError:
644
+ gr.Warning(f"Please provide reference audio for type {current_type_name}.")
645
+ return [None] + [speech_types[name]["ref_text"] for name in speech_types] + [None]
646
+ ref_text = speech_types[current_type_name].get("ref_text", "")
647
+
648
+ if seed_input == -1:
649
+ seed_input = np.random.randint(0, 2**31 - 1)
650
+
651
+ # Generate or retrieve speech for this segment
652
+ audio_out, _, ref_text_out, used_seed = infer(
653
+ ref_audio,
654
+ ref_text,
655
+ text,
656
+ tts_model_choice,
657
+ remove_silence,
658
+ seed=seed_input,
659
+ cross_fade_duration=0,
660
+ speed=speed,
661
+ show_info=print, # no pull to top when generating
662
+ )
663
+ sr, audio_data = audio_out
664
+
665
+ generated_audio_segments.append(audio_data)
666
+ speech_types[current_type_name]["ref_text"] = ref_text_out
667
+ inference_meta_data += json.dumps(dict(name=name, seed=used_seed, speed=speed)) + f" {text}\n"
668
+
669
+ # Concatenate all audio segments
670
+ if generated_audio_segments:
671
+ final_audio_data = np.concatenate(generated_audio_segments)
672
+ return (
673
+ [(sr, final_audio_data)]
674
+ + [speech_types[name]["ref_text"] for name in speech_types]
675
+ + [inference_meta_data]
676
+ )
677
+ else:
678
+ gr.Warning("No audio generated.")
679
+ return [None] + [speech_types[name]["ref_text"] for name in speech_types] + [None]
680
+
681
+ generate_multistyle_btn.click(
682
+ generate_multistyle_speech,
683
+ inputs=[
684
+ gen_text_input_multistyle,
685
+ ]
686
+ + speech_type_names
687
+ + speech_type_audios
688
+ + speech_type_ref_texts
689
+ + [
690
+ remove_silence_multistyle,
691
+ ],
692
+ outputs=[audio_output_multistyle] + speech_type_ref_texts + [cherrypick_interface_multistyle],
693
+ )
694
+
695
+ # Validation function to disable Generate button if speech types are missing
696
+ def validate_speech_types(gen_text, regular_name, *args):
697
+ speech_type_names_list = args
698
+
699
+ # Collect the speech types names
700
+ speech_types_available = set()
701
+ if regular_name:
702
+ speech_types_available.add(regular_name)
703
+ for name_input in speech_type_names_list:
704
+ if name_input:
705
+ speech_types_available.add(name_input)
706
+
707
+ # Parse the gen_text to get the speech types used
708
+ segments = parse_speechtypes_text(gen_text)
709
+ speech_types_in_text = set(segment["name"] for segment in segments)
710
+
711
+ # Check if all speech types in text are available
712
+ missing_speech_types = speech_types_in_text - speech_types_available
713
+
714
+ if missing_speech_types:
715
+ # Disable the generate button
716
+ return gr.update(interactive=False)
717
+ else:
718
+ # Enable the generate button
719
+ return gr.update(interactive=True)
720
+
721
+ gen_text_input_multistyle.change(
722
+ validate_speech_types,
723
+ inputs=[gen_text_input_multistyle, regular_name] + speech_type_names,
724
+ outputs=generate_multistyle_btn,
725
+ )
726
+
727
+
728
+ with gr.Blocks() as app_chat:
729
+ gr.Markdown(
730
+ """
731
+ # Voice Chat
732
+ Have a conversation with an AI using your reference voice!
733
+ 1. Upload a reference audio clip and optionally its transcript (via text or .txt file).
734
+ 2. Load the chat model.
735
+ 3. Record your message through your microphone or type it.
736
+ 4. The AI will respond using the reference voice.
737
+ """
738
+ )
739
+
740
+ chat_model_name_list = [
741
+ "Qwen/Qwen2.5-3B-Instruct",
742
+ "microsoft/Phi-4-mini-instruct",
743
+ ]
744
+
745
+ @gpu_decorator
746
+ def load_chat_model(chat_model_name):
747
+ show_info = gr.Info
748
+ global chat_model_state, chat_tokenizer_state
749
+ if chat_model_state is not None:
750
+ chat_model_state = None
751
+ chat_tokenizer_state = None
752
+ gc.collect()
753
+ torch.cuda.empty_cache()
754
+
755
+ show_info(f"Loading chat model: {chat_model_name}")
756
+ chat_model_state = AutoModelForCausalLM.from_pretrained(chat_model_name, torch_dtype="auto", device_map="auto")
757
+ chat_tokenizer_state = AutoTokenizer.from_pretrained(chat_model_name)
758
+ show_info(f"Chat model {chat_model_name} loaded successfully!")
759
+
760
+ return gr.update(visible=False), gr.update(visible=True)
761
+
762
+ if USING_SPACES:
763
+ load_chat_model(chat_model_name_list[0])
764
+
765
+ chat_model_name_input = gr.Dropdown(
766
+ choices=chat_model_name_list,
767
+ value=chat_model_name_list[0],
768
+ label="Chat Model Name",
769
+ info="Enter the name of a HuggingFace chat model",
770
+ allow_custom_value=not USING_SPACES,
771
+ )
772
+ load_chat_model_btn = gr.Button("Load Chat Model", variant="primary", visible=not USING_SPACES)
773
+ chat_interface_container = gr.Column(visible=USING_SPACES)
774
+
775
+ chat_model_name_input.change(
776
+ lambda: gr.update(visible=True),
777
+ None,
778
+ load_chat_model_btn,
779
+ show_progress="hidden",
780
+ )
781
+ load_chat_model_btn.click(
782
+ load_chat_model, inputs=[chat_model_name_input], outputs=[load_chat_model_btn, chat_interface_container]
783
+ )
784
+
785
+ with chat_interface_container:
786
+ with gr.Row():
787
+ with gr.Column():
788
+ ref_audio_chat = gr.Audio(label="Reference Audio", type="filepath")
789
+ with gr.Column():
790
+ with gr.Accordion("Advanced Settings", open=False):
791
+ with gr.Row():
792
+ ref_text_chat = gr.Textbox(
793
+ label="Reference Text",
794
+ info="Optional: Leave blank to auto-transcribe",
795
+ lines=2,
796
+ scale=3,
797
+ )
798
+ ref_text_file_chat = gr.File(
799
+ label="Load Reference Text from File (.txt)", file_types=[".txt"], scale=1
800
+ )
801
+ with gr.Row():
802
+ randomize_seed_chat = gr.Checkbox(
803
+ label="Randomize Seed",
804
+ value=True,
805
+ info="Uncheck to use the seed specified.",
806
+ scale=3,
807
+ )
808
+ seed_input_chat = gr.Number(show_label=False, value=0, precision=0, scale=1)
809
+ remove_silence_chat = gr.Checkbox(
810
+ label="Remove Silences",
811
+ value=True,
812
+ )
813
+ system_prompt_chat = gr.Textbox(
814
+ label="System Prompt",
815
+ value="You are not an AI assistant, you are whoever the user says you are. You must stay in character. Keep your responses concise since they will be spoken out loud.",
816
+ lines=2,
817
+ )
818
+
819
+ chatbot_interface = gr.Chatbot(label="Conversation", type="messages")
820
+
821
+ with gr.Row():
822
+ with gr.Column():
823
+ audio_input_chat = gr.Microphone(
824
+ label="Speak your message",
825
+ type="filepath",
826
+ )
827
+ audio_output_chat = gr.Audio(autoplay=True)
828
+ with gr.Column():
829
+ text_input_chat = gr.Textbox(
830
+ label="Type your message",
831
+ lines=1,
832
+ )
833
+ send_btn_chat = gr.Button("Send Message")
834
+ clear_btn_chat = gr.Button("Clear Conversation")
835
+
836
+ # Modify process_audio_input to generate user input
837
+ @gpu_decorator
838
+ def process_audio_input(conv_state, audio_path, text):
839
+ """Handle audio or text input from user"""
840
+
841
+ if not audio_path and not text.strip():
842
+ return conv_state
843
+
844
+ if audio_path:
845
+ text = preprocess_ref_audio_text(audio_path, text)[1]
846
+ if not text.strip():
847
+ return conv_state
848
+
849
+ conv_state.append({"role": "user", "content": text})
850
+ return conv_state
851
+
852
+ # Use model and tokenizer from state to get text response
853
+ @gpu_decorator
854
+ def generate_text_response(conv_state, system_prompt):
855
+ """Generate text response from AI"""
856
+
857
+ system_prompt_state = [{"role": "system", "content": system_prompt}]
858
+ response = chat_model_inference(system_prompt_state + conv_state, chat_model_state, chat_tokenizer_state)
859
+
860
+ conv_state.append({"role": "assistant", "content": response})
861
+ return conv_state
862
+
863
+ @gpu_decorator
864
+ def generate_audio_response(conv_state, ref_audio, ref_text, remove_silence, randomize_seed, seed_input):
865
+ """Generate TTS audio for AI response"""
866
+ if not conv_state or not ref_audio:
867
+ return None, ref_text, seed_input
868
+
869
+ last_ai_response = conv_state[-1]["content"]
870
+ if not last_ai_response or conv_state[-1]["role"] != "assistant":
871
+ return None, ref_text, seed_input
872
+
873
+ if randomize_seed:
874
+ seed_input = np.random.randint(0, 2**31 - 1)
875
+
876
+ audio_result, _, ref_text_out, used_seed = infer(
877
+ ref_audio,
878
+ ref_text,
879
+ last_ai_response,
880
+ tts_model_choice,
881
+ remove_silence,
882
+ seed=seed_input,
883
+ cross_fade_duration=0.15,
884
+ speed=1.0,
885
+ show_info=print, # show_info=print no pull to top when generating
886
+ )
887
+ return audio_result, ref_text_out, used_seed
888
+
889
+ def clear_conversation():
890
+ """Reset the conversation"""
891
+ return [], None
892
+
893
+ ref_text_file_chat.upload(
894
+ load_text_from_file,
895
+ inputs=[ref_text_file_chat],
896
+ outputs=[ref_text_chat],
897
+ )
898
+
899
+ for user_operation in [audio_input_chat.stop_recording, text_input_chat.submit, send_btn_chat.click]:
900
+ user_operation(
901
+ process_audio_input,
902
+ inputs=[chatbot_interface, audio_input_chat, text_input_chat],
903
+ outputs=[chatbot_interface],
904
+ ).then(
905
+ generate_text_response,
906
+ inputs=[chatbot_interface, system_prompt_chat],
907
+ outputs=[chatbot_interface],
908
+ ).then(
909
+ generate_audio_response,
910
+ inputs=[
911
+ chatbot_interface,
912
+ ref_audio_chat,
913
+ ref_text_chat,
914
+ remove_silence_chat,
915
+ randomize_seed_chat,
916
+ seed_input_chat,
917
+ ],
918
+ outputs=[audio_output_chat, ref_text_chat, seed_input_chat],
919
+ ).then(
920
+ lambda: [None, None],
921
+ None,
922
+ [audio_input_chat, text_input_chat],
923
+ )
924
+
925
+ # Handle clear button or system prompt change and reset conversation
926
+ for user_operation in [clear_btn_chat.click, system_prompt_chat.change, chatbot_interface.clear]:
927
+ user_operation(
928
+ clear_conversation,
929
+ outputs=[chatbot_interface, audio_output_chat],
930
+ )
931
+
932
+
933
+ with gr.Blocks() as app_credits:
934
+ gr.Markdown("""
935
+ # Credits
936
+
937
+ * [mrfakename](https://github.com/fakerybakery) for the original [online demo](https://huggingface.co/spaces/mrfakename/E2-F5-TTS)
938
+ * [RootingInLoad](https://github.com/RootingInLoad) for initial chunk generation and podcast app exploration
939
+ * [jpgallegoar](https://github.com/jpgallegoar) for multiple speech-type generation & voice chat
940
+ """)
941
+
942
+
943
+ with gr.Blocks() as app:
944
+ gr.Markdown(
945
+ f"""
946
+ # F5-TTS Demo Space
947
+
948
+ This is {"a local web UI for [F5-TTS](https://github.com/SWivid/F5-TTS)" if not USING_SPACES else "an online demo for [F5-TTS](https://github.com/SWivid/F5-TTS)"} with advanced batch processing support. This app supports the following TTS models:
949
+
950
+ * [F5-TTS](https://arxiv.org/abs/2410.06885) (A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching)
951
+ * [E2 TTS](https://arxiv.org/abs/2406.18009) (Embarrassingly Easy Fully Non-Autoregressive Zero-Shot TTS)
952
+
953
+ The checkpoints currently support English and Chinese.
954
+
955
+ If you're having issues, try converting your reference audio to WAV or MP3, clipping it to 12s with ✂ in the bottom right corner (otherwise might have non-optimal auto-trimmed result).
956
+
957
+ **NOTE: Reference text will be automatically transcribed with Whisper if not provided. For best results, keep your reference clips short (<12s). Ensure the audio is fully uploaded before generating.**
958
+ """
959
+ )
960
+
961
+ last_used_custom = files("f5_tts").joinpath("infer/.cache/last_used_custom_model_info_v1.txt")
962
+
963
+ def load_last_used_custom():
964
+ try:
965
+ custom = []
966
+ with open(last_used_custom, "r", encoding="utf-8") as f:
967
+ for line in f:
968
+ custom.append(line.strip())
969
+ return custom
970
+ except FileNotFoundError:
971
+ last_used_custom.parent.mkdir(parents=True, exist_ok=True)
972
+ return DEFAULT_TTS_MODEL_CFG
973
+
974
+ def switch_tts_model(new_choice):
975
+ global tts_model_choice
976
+ if new_choice == "Custom": # override in case webpage is refreshed
977
+ custom_ckpt_path, custom_vocab_path, custom_model_cfg = load_last_used_custom()
978
+ tts_model_choice = ("Custom", custom_ckpt_path, custom_vocab_path, custom_model_cfg)
979
+ return (
980
+ gr.update(visible=True, value=custom_ckpt_path),
981
+ gr.update(visible=True, value=custom_vocab_path),
982
+ gr.update(visible=True, value=custom_model_cfg),
983
+ )
984
+ else:
985
+ tts_model_choice = new_choice
986
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
987
+
988
+ def set_custom_model(custom_ckpt_path, custom_vocab_path, custom_model_cfg):
989
+ global tts_model_choice
990
+ tts_model_choice = ("Custom", custom_ckpt_path, custom_vocab_path, custom_model_cfg)
991
+ with open(last_used_custom, "w", encoding="utf-8") as f:
992
+ f.write(custom_ckpt_path + "\n" + custom_vocab_path + "\n" + custom_model_cfg + "\n")
993
+
994
+ with gr.Row():
995
+ if not USING_SPACES:
996
+ choose_tts_model = gr.Radio(
997
+ choices=[DEFAULT_TTS_MODEL, "E2-TTS", "Custom"], label="Choose TTS Model", value=DEFAULT_TTS_MODEL
998
+ )
999
+ else:
1000
+ choose_tts_model = gr.Radio(
1001
+ choices=[DEFAULT_TTS_MODEL, "E2-TTS"], label="Choose TTS Model", value=DEFAULT_TTS_MODEL
1002
+ )
1003
+ custom_ckpt_path = gr.Dropdown(
1004
+ choices=[DEFAULT_TTS_MODEL_CFG[0]],
1005
+ value=load_last_used_custom()[0],
1006
+ allow_custom_value=True,
1007
+ label="Model: local_path | hf://user_id/repo_id/model_ckpt",
1008
+ visible=False,
1009
+ )
1010
+ custom_vocab_path = gr.Dropdown(
1011
+ choices=[DEFAULT_TTS_MODEL_CFG[1]],
1012
+ value=load_last_used_custom()[1],
1013
+ allow_custom_value=True,
1014
+ label="Vocab: local_path | hf://user_id/repo_id/vocab_file",
1015
+ visible=False,
1016
+ )
1017
+ custom_model_cfg = gr.Dropdown(
1018
+ choices=[
1019
+ DEFAULT_TTS_MODEL_CFG[2],
1020
+ json.dumps(
1021
+ dict(
1022
+ dim=1024,
1023
+ depth=22,
1024
+ heads=16,
1025
+ ff_mult=2,
1026
+ text_dim=512,
1027
+ text_mask_padding=False,
1028
+ conv_layers=4,
1029
+ pe_attn_head=1,
1030
+ )
1031
+ ),
1032
+ json.dumps(
1033
+ dict(
1034
+ dim=768,
1035
+ depth=18,
1036
+ heads=12,
1037
+ ff_mult=2,
1038
+ text_dim=512,
1039
+ text_mask_padding=False,
1040
+ conv_layers=4,
1041
+ pe_attn_head=1,
1042
+ )
1043
+ ),
1044
+ ],
1045
+ value=load_last_used_custom()[2],
1046
+ allow_custom_value=True,
1047
+ label="Config: in a dictionary form",
1048
+ visible=False,
1049
+ )
1050
+
1051
+ choose_tts_model.change(
1052
+ switch_tts_model,
1053
+ inputs=[choose_tts_model],
1054
+ outputs=[custom_ckpt_path, custom_vocab_path, custom_model_cfg],
1055
+ show_progress="hidden",
1056
+ )
1057
+ custom_ckpt_path.change(
1058
+ set_custom_model,
1059
+ inputs=[custom_ckpt_path, custom_vocab_path, custom_model_cfg],
1060
+ show_progress="hidden",
1061
+ )
1062
+ custom_vocab_path.change(
1063
+ set_custom_model,
1064
+ inputs=[custom_ckpt_path, custom_vocab_path, custom_model_cfg],
1065
+ show_progress="hidden",
1066
+ )
1067
+ custom_model_cfg.change(
1068
+ set_custom_model,
1069
+ inputs=[custom_ckpt_path, custom_vocab_path, custom_model_cfg],
1070
+ show_progress="hidden",
1071
+ )
1072
+
1073
+ gr.TabbedInterface(
1074
+ [app_tts, app_multistyle, app_chat, app_credits],
1075
+ ["Basic-TTS", "Multi-Speech", "Voice-Chat", "Credits"],
1076
+ )
1077
+
1078
+
1079
+ @click.command()
1080
+ @click.option("--port", "-p", default=None, type=int, help="Port to run the app on")
1081
+ @click.option("--host", "-H", default=None, help="Host to run the app on")
1082
+ @click.option(
1083
+ "--share",
1084
+ "-s",
1085
+ default=False,
1086
+ is_flag=True,
1087
+ help="Share the app via Gradio share link",
1088
+ )
1089
+ @click.option("--api", "-a", default=True, is_flag=True, help="Allow API access")
1090
+ @click.option(
1091
+ "--root_path",
1092
+ "-r",
1093
+ default=None,
1094
+ type=str,
1095
+ help='The root path (or "mount point") of the application, if it\'s not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application, e.g. set "/myapp" or full URL for application served at "https://example.com/myapp".',
1096
+ )
1097
+ @click.option(
1098
+ "--inbrowser",
1099
+ "-i",
1100
+ is_flag=True,
1101
+ default=False,
1102
+ help="Automatically launch the interface in the default web browser",
1103
+ )
1104
+ def main(port, host, share, api, root_path, inbrowser):
1105
+ global app
1106
+ print("Starting app...")
1107
+ app.queue(api_open=api).launch(
1108
+ server_name=host,
1109
+ server_port=port,
1110
+ share=share,
1111
+ show_api=api,
1112
+ root_path=root_path,
1113
+ inbrowser=inbrowser,
1114
+ )
1115
+
1116
+
1117
+ if __name__ == "__main__":
1118
+ if not USING_SPACES:
1119
+ main()
1120
+ else:
1121
+ app.queue().launch()
src/f5_tts/infer/speech_edit.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+
4
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" # for MPS device compatibility
5
+
6
+ from importlib.resources import files
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torchaudio
11
+ from cached_path import cached_path
12
+ from hydra.utils import get_class
13
+ from omegaconf import OmegaConf
14
+
15
+ from f5_tts.infer.utils_infer import load_checkpoint, load_vocoder, save_spectrogram
16
+ from f5_tts.model import CFM
17
+ from f5_tts.model.utils import convert_char_to_pinyin, get_tokenizer
18
+
19
+
20
+ device = (
21
+ "cuda"
22
+ if torch.cuda.is_available()
23
+ else "xpu"
24
+ if torch.xpu.is_available()
25
+ else "mps"
26
+ if torch.backends.mps.is_available()
27
+ else "cpu"
28
+ )
29
+
30
+
31
+ # ---------------------- infer setting ---------------------- #
32
+
33
+ seed = None # int | None
34
+
35
+ exp_name = "F5TTS_v1_Base" # F5TTS_v1_Base | E2TTS_Base
36
+ ckpt_step = 1250000
37
+
38
+ nfe_step = 32 # 16, 32
39
+ cfg_strength = 2.0
40
+ ode_method = "euler" # euler | midpoint
41
+ sway_sampling_coef = -1.0
42
+ speed = 1.0
43
+ target_rms = 0.1
44
+
45
+
46
+ model_cfg = OmegaConf.load(str(files("f5_tts").joinpath(f"configs/{exp_name}.yaml")))
47
+ model_cls = get_class(f"f5_tts.model.{model_cfg.model.backbone}")
48
+ model_arc = model_cfg.model.arch
49
+
50
+ dataset_name = model_cfg.datasets.name
51
+ tokenizer = model_cfg.model.tokenizer
52
+
53
+ mel_spec_type = model_cfg.model.mel_spec.mel_spec_type
54
+ target_sample_rate = model_cfg.model.mel_spec.target_sample_rate
55
+ n_mel_channels = model_cfg.model.mel_spec.n_mel_channels
56
+ hop_length = model_cfg.model.mel_spec.hop_length
57
+ win_length = model_cfg.model.mel_spec.win_length
58
+ n_fft = model_cfg.model.mel_spec.n_fft
59
+
60
+
61
+ # ckpt_path = str(files("f5_tts").joinpath("../../")) + f"/ckpts/{exp_name}/model_{ckpt_step}.safetensors"
62
+ ckpt_path = str(cached_path(f"hf://SWivid/F5-TTS/{exp_name}/model_{ckpt_step}.safetensors"))
63
+ output_dir = "tests"
64
+
65
+
66
+ # [leverage https://github.com/MahmoudAshraf97/ctc-forced-aligner to get char level alignment]
67
+ # pip install git+https://github.com/MahmoudAshraf97/ctc-forced-aligner.git
68
+ # [write the origin_text into a file, e.g. tests/test_edit.txt]
69
+ # ctc-forced-aligner --audio_path "src/f5_tts/infer/examples/basic/basic_ref_en.wav" --text_path "tests/test_edit.txt" --language "zho" --romanize --split_size "char"
70
+ # [result will be saved at same path of audio file]
71
+ # [--language "zho" for Chinese, "eng" for English]
72
+ # [if local ckpt, set --alignment_model "../checkpoints/mms-300m-1130-forced-aligner"]
73
+
74
+ audio_to_edit = str(files("f5_tts").joinpath("infer/examples/basic/basic_ref_en.wav"))
75
+ origin_text = "Some call me nature, others call me mother nature."
76
+ target_text = "Some call me optimist, others call me realist."
77
+ parts_to_edit = [
78
+ [1.42, 2.44],
79
+ [4.04, 4.9],
80
+ ] # stard_ends of "nature" & "mother nature", in seconds
81
+ fix_duration = [
82
+ 1.2,
83
+ 1,
84
+ ] # fix duration for "optimist" & "realist", in seconds
85
+
86
+ # audio_to_edit = "src/f5_tts/infer/examples/basic/basic_ref_zh.wav"
87
+ # origin_text = "对,这就是我,万人敬仰的太乙真人。"
88
+ # target_text = "对,那就是你,万人敬仰的太白金星。"
89
+ # parts_to_edit = [[0.84, 1.4], [1.92, 2.4], [4.26, 6.26], ]
90
+ # fix_duration = None # use origin text duration
91
+
92
+
93
+ # -------------------------------------------------#
94
+
95
+ use_ema = True
96
+
97
+ if not os.path.exists(output_dir):
98
+ os.makedirs(output_dir)
99
+
100
+ # Vocoder model
101
+ local = False
102
+ if mel_spec_type == "vocos":
103
+ vocoder_local_path = "../checkpoints/charactr/vocos-mel-24khz"
104
+ elif mel_spec_type == "bigvgan":
105
+ vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x"
106
+ vocoder = load_vocoder(vocoder_name=mel_spec_type, is_local=local, local_path=vocoder_local_path)
107
+
108
+ # Tokenizer
109
+ vocab_char_map, vocab_size = get_tokenizer(dataset_name, tokenizer)
110
+
111
+ # Model
112
+ model = CFM(
113
+ transformer=model_cls(**model_arc, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
114
+ mel_spec_kwargs=dict(
115
+ n_fft=n_fft,
116
+ hop_length=hop_length,
117
+ win_length=win_length,
118
+ n_mel_channels=n_mel_channels,
119
+ target_sample_rate=target_sample_rate,
120
+ mel_spec_type=mel_spec_type,
121
+ ),
122
+ odeint_kwargs=dict(
123
+ method=ode_method,
124
+ ),
125
+ vocab_char_map=vocab_char_map,
126
+ ).to(device)
127
+
128
+ dtype = torch.float32 if mel_spec_type == "bigvgan" else None
129
+ model = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
130
+
131
+ # Audio
132
+ audio, sr = torchaudio.load(audio_to_edit)
133
+ if audio.shape[0] > 1:
134
+ audio = torch.mean(audio, dim=0, keepdim=True)
135
+ rms = torch.sqrt(torch.mean(torch.square(audio)))
136
+ if rms < target_rms:
137
+ audio = audio * target_rms / rms
138
+ if sr != target_sample_rate:
139
+ resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
140
+ audio = resampler(audio)
141
+ offset = 0
142
+ audio_ = torch.zeros(1, 0)
143
+ edit_mask = torch.zeros(1, 0, dtype=torch.bool)
144
+ for part in parts_to_edit:
145
+ start, end = part
146
+ part_dur = end - start if fix_duration is None else fix_duration.pop(0)
147
+ part_dur = part_dur * target_sample_rate
148
+ start = start * target_sample_rate
149
+ audio_ = torch.cat((audio_, audio[:, round(offset) : round(start)], torch.zeros(1, round(part_dur))), dim=-1)
150
+ edit_mask = torch.cat(
151
+ (
152
+ edit_mask,
153
+ torch.ones(1, round((start - offset) / hop_length), dtype=torch.bool),
154
+ torch.zeros(1, round(part_dur / hop_length), dtype=torch.bool),
155
+ ),
156
+ dim=-1,
157
+ )
158
+ offset = end * target_sample_rate
159
+ audio = torch.cat((audio_, audio[:, round(offset) :]), dim=-1)
160
+ edit_mask = F.pad(edit_mask, (0, audio.shape[-1] // hop_length - edit_mask.shape[-1] + 1), value=True)
161
+ audio = audio.to(device)
162
+ edit_mask = edit_mask.to(device)
163
+
164
+ # Text
165
+ text_list = [target_text]
166
+ if tokenizer == "pinyin":
167
+ final_text_list = convert_char_to_pinyin(text_list)
168
+ else:
169
+ final_text_list = [text_list]
170
+ print(f"text : {text_list}")
171
+ print(f"pinyin: {final_text_list}")
172
+
173
+ # Duration
174
+ ref_audio_len = 0
175
+ duration = audio.shape[-1] // hop_length
176
+
177
+ # Inference
178
+ with torch.inference_mode():
179
+ generated, trajectory = model.sample(
180
+ cond=audio,
181
+ text=final_text_list,
182
+ duration=duration,
183
+ steps=nfe_step,
184
+ cfg_strength=cfg_strength,
185
+ sway_sampling_coef=sway_sampling_coef,
186
+ seed=seed,
187
+ edit_mask=edit_mask,
188
+ )
189
+ print(f"Generated mel: {generated.shape}")
190
+
191
+ # Final result
192
+ generated = generated.to(torch.float32)
193
+ generated = generated[:, ref_audio_len:, :]
194
+ gen_mel_spec = generated.permute(0, 2, 1)
195
+ if mel_spec_type == "vocos":
196
+ generated_wave = vocoder.decode(gen_mel_spec).cpu()
197
+ elif mel_spec_type == "bigvgan":
198
+ generated_wave = vocoder(gen_mel_spec).squeeze(0).cpu()
199
+
200
+ if rms < target_rms:
201
+ generated_wave = generated_wave * rms / target_rms
202
+
203
+ save_spectrogram(gen_mel_spec[0].cpu().numpy(), f"{output_dir}/speech_edit_out.png")
204
+ torchaudio.save(f"{output_dir}/speech_edit_out.wav", generated_wave, target_sample_rate)
205
+ print(f"Generated wav: {generated_wave.shape}")
src/f5_tts/infer/utils_infer.py ADDED
@@ -0,0 +1,765 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A unified script for inference process
2
+ # Make adjustments inside functions, and consider both gradio and cli scripts if need to change func output format
3
+ import os
4
+ import sys
5
+ from concurrent.futures import ThreadPoolExecutor
6
+
7
+
8
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" # for MPS device compatibility
9
+ sys.path.append(f"{os.path.dirname(os.path.abspath(__file__))}/../../third_party/BigVGAN/")
10
+
11
+ import hashlib
12
+ import re
13
+ import tempfile
14
+ from importlib.resources import files
15
+
16
+ import matplotlib
17
+
18
+
19
+ matplotlib.use("Agg")
20
+
21
+ import matplotlib.pylab as plt
22
+ import numpy as np
23
+ import torch
24
+ import torchaudio
25
+ import tqdm
26
+ import requests
27
+ from huggingface_hub import hf_hub_download
28
+ from pydub import AudioSegment, silence
29
+ from transformers import pipeline
30
+ from vocos import Vocos
31
+
32
+ from f5_tts.model import CFM
33
+ from f5_tts.model.modules import MelSpec
34
+ from f5_tts.model.utils import convert_char_to_pinyin, get_tokenizer
35
+ from f5_tts.infer.cls_tokenizer_v2 import cls_tokenize_text
36
+
37
+
38
+ _ref_audio_cache = {}
39
+ _ref_text_cache = {}
40
+
41
+
42
+ def _load_state_dict_resilient(model: torch.nn.Module, state_dict: dict):
43
+ """
44
+ Load a state_dict while tolerating shape mismatches (e.g. when switching vocabularies).
45
+ Any parameters whose shapes do not match the current model will be skipped so that
46
+ those layers keep their freshly initialized weights instead of raising.
47
+ """
48
+ model_state = model.state_dict()
49
+ filtered_state = {}
50
+ mismatched = {}
51
+
52
+ for key, weight in state_dict.items():
53
+ target = model_state.get(key)
54
+ if target is None:
55
+ continue
56
+ if hasattr(target, "shape") and hasattr(weight, "shape") and target.shape != weight.shape:
57
+ # If only the vocab size dimension differs, align by slicing/padding so embeddings still load.
58
+ if (
59
+ len(target.shape) == len(weight.shape)
60
+ and target.shape[1:] == weight.shape[1:]
61
+ and key.endswith("text_embed.weight")
62
+ ):
63
+ new_weight = target.clone()
64
+ rows = min(target.shape[0], weight.shape[0])
65
+ new_weight[:rows] = weight[:rows]
66
+ filtered_state[key] = new_weight
67
+ if target.shape[0] != weight.shape[0]:
68
+ print(
69
+ f"Info: resized {key} from {tuple(weight.shape)} to {tuple(target.shape)} "
70
+ f"(copied {rows} rows)."
71
+ )
72
+ continue
73
+ mismatched[key] = (tuple(weight.shape), tuple(target.shape))
74
+ continue
75
+ filtered_state[key] = weight
76
+
77
+ missing, unexpected = model.load_state_dict(filtered_state, strict=False)
78
+ if mismatched:
79
+ mismatch_info = ", ".join(f"{k}: {src} -> {dst}" for k, (src, dst) in mismatched.items())
80
+ print(f"Warning: skipped loading parameters with shape mismatch ({mismatch_info}).")
81
+ if missing:
82
+ print(f"Warning: missing parameters not loaded from checkpoint: {missing}")
83
+ if unexpected:
84
+ print(f"Warning: unexpected parameters in checkpoint were ignored: {unexpected}")
85
+
86
+ device = (
87
+ "cuda"
88
+ if torch.cuda.is_available()
89
+ else "xpu"
90
+ if torch.xpu.is_available()
91
+ else "mps"
92
+ if torch.backends.mps.is_available()
93
+ else "cpu"
94
+ )
95
+
96
+ tempfile_kwargs = {"delete_on_close": False} if sys.version_info >= (3, 12) else {"delete": False}
97
+
98
+ # -----------------------------------------
99
+
100
+ target_sample_rate = 24000
101
+ n_mel_channels = 100
102
+ hop_length = 256
103
+ win_length = 1024
104
+ n_fft = 1024
105
+ mel_spec_type = "vocos"
106
+ target_rms = 0.1
107
+ cross_fade_duration = 0.15
108
+ ode_method = "euler"
109
+ nfe_step = 32 # 16, 32
110
+ cfg_strength = 2.0
111
+ sway_sampling_coef = -1.0
112
+ speed = 1.0
113
+ fix_duration = None
114
+
115
+ # -----------------------------------------
116
+
117
+
118
+ # chunk text into smaller pieces
119
+
120
+
121
+ def chunk_text(text, max_chars=135):
122
+ """
123
+ Splits the input text into chunks, each with a maximum number of characters.
124
+
125
+ Args:
126
+ text (str): The text to be split.
127
+ max_chars (int): The maximum number of characters per chunk.
128
+
129
+ Returns:
130
+ List[str]: A list of text chunks.
131
+ """
132
+ chunks = []
133
+ current_chunk = ""
134
+ # Split the text into sentences based on punctuation followed by whitespace
135
+ sentences = re.split(r"(?<=[;:,.!?])\s+|(?<=[;:,。!?])", text)
136
+
137
+ for sentence in sentences:
138
+ if len(current_chunk.encode("utf-8")) + len(sentence.encode("utf-8")) <= max_chars:
139
+ current_chunk += sentence + " " if sentence and len(sentence[-1].encode("utf-8")) == 1 else sentence
140
+ else:
141
+ if current_chunk:
142
+ chunks.append(current_chunk.strip())
143
+ current_chunk = sentence + " " if sentence and len(sentence[-1].encode("utf-8")) == 1 else sentence
144
+
145
+ if current_chunk:
146
+ chunks.append(current_chunk.strip())
147
+
148
+ return chunks
149
+
150
+
151
+ def tokenize_texts(
152
+ text_list,
153
+ tokenizer="pinyin",
154
+ cls_language=None,
155
+ cls_server_url=None,
156
+ cls_timeout=5.0,
157
+ cls_tokenizer_fn=None,
158
+ ):
159
+ tokenizer = (tokenizer or "pinyin").strip().lower()
160
+ if tokenizer == "pinyin":
161
+ return convert_char_to_pinyin(text_list)
162
+ if tokenizer == "char":
163
+ return [list(t) for t in text_list]
164
+ if tokenizer == "cls":
165
+ if not cls_language:
166
+ raise ValueError("cls_language must be set when tokenizer='cls'.")
167
+ if cls_tokenizer_fn is not None:
168
+ results = []
169
+ for text in text_list:
170
+ cls_tokens = cls_tokenizer_fn(text, cls_language)
171
+ if not isinstance(cls_tokens, list) or len(cls_tokens) == 0:
172
+ raise RuntimeError("CLS tokenizer function returned empty tokens.")
173
+ results.append(cls_tokens)
174
+ return results
175
+ if cls_server_url:
176
+ results = []
177
+ for text in text_list:
178
+ try:
179
+ resp = requests.post(
180
+ cls_server_url,
181
+ json={"text": text, "language": cls_language},
182
+ timeout=cls_timeout,
183
+ )
184
+ except Exception as exc: # noqa: BLE001
185
+ raise RuntimeError(f"CLS server request failed: {exc}") from exc
186
+ if resp.status_code != 200:
187
+ raise RuntimeError(f"CLS server error {resp.status_code}: {resp.text}")
188
+ try:
189
+ data = resp.json()
190
+ except Exception as exc: # noqa: BLE001
191
+ raise RuntimeError(f"CLS server returned non-JSON response: {exc}") from exc
192
+ cls_tokens = data.get("cls")
193
+ if not isinstance(cls_tokens, list) or len(cls_tokens) == 0:
194
+ raise RuntimeError("CLS server returned empty tokens.")
195
+ results.append(cls_tokens)
196
+ return results
197
+ results = []
198
+ for text in text_list:
199
+ cls_tokens = cls_tokenize_text(text, cls_language)
200
+ if not isinstance(cls_tokens, list) or len(cls_tokens) == 0:
201
+ raise RuntimeError("CLS tokenizer returned empty tokens.")
202
+ results.append(cls_tokens)
203
+ return results
204
+ raise ValueError(f"Unsupported tokenizer: {tokenizer}")
205
+
206
+
207
+ # load vocoder
208
+ def load_vocoder(vocoder_name="vocos", is_local=False, local_path="", device=device, hf_cache_dir=None):
209
+ if vocoder_name == "vocos":
210
+ # vocoder = Vocos.from_pretrained("charactr/vocos-mel-24khz").to(device)
211
+ if is_local:
212
+ print(f"Load vocos from local path {local_path}")
213
+ config_path = f"{local_path}/config.yaml"
214
+ model_path = f"{local_path}/pytorch_model.bin"
215
+ else:
216
+ print("Download Vocos from huggingface charactr/vocos-mel-24khz")
217
+ repo_id = "charactr/vocos-mel-24khz"
218
+ config_path = hf_hub_download(repo_id=repo_id, cache_dir=hf_cache_dir, filename="config.yaml")
219
+ model_path = hf_hub_download(repo_id=repo_id, cache_dir=hf_cache_dir, filename="pytorch_model.bin")
220
+ vocoder = Vocos.from_hparams(config_path)
221
+ state_dict = torch.load(model_path, map_location="cpu", weights_only=True)
222
+ from vocos.feature_extractors import EncodecFeatures
223
+
224
+ if isinstance(vocoder.feature_extractor, EncodecFeatures):
225
+ encodec_parameters = {
226
+ "feature_extractor.encodec." + key: value
227
+ for key, value in vocoder.feature_extractor.encodec.state_dict().items()
228
+ }
229
+ state_dict.update(encodec_parameters)
230
+ vocoder.load_state_dict(state_dict)
231
+ vocoder = vocoder.eval().to(device)
232
+ elif vocoder_name == "bigvgan":
233
+ try:
234
+ from third_party.BigVGAN import bigvgan
235
+ except ImportError:
236
+ print("You need to follow the README to init submodule and change the BigVGAN source code.")
237
+ if is_local:
238
+ # download generator from https://huggingface.co/nvidia/bigvgan_v2_24khz_100band_256x/tree/main
239
+ vocoder = bigvgan.BigVGAN.from_pretrained(local_path, use_cuda_kernel=False)
240
+ else:
241
+ vocoder = bigvgan.BigVGAN.from_pretrained(
242
+ "nvidia/bigvgan_v2_24khz_100band_256x", use_cuda_kernel=False, cache_dir=hf_cache_dir
243
+ )
244
+
245
+ vocoder.remove_weight_norm()
246
+ vocoder = vocoder.eval().to(device)
247
+ return vocoder
248
+
249
+
250
+ # load asr pipeline
251
+
252
+ asr_pipe = None
253
+
254
+
255
+ def initialize_asr_pipeline(device: str = device, dtype=None):
256
+ if dtype is None:
257
+ dtype = (
258
+ torch.float16
259
+ if "cuda" in device
260
+ and torch.cuda.get_device_properties(device).major >= 7
261
+ and not torch.cuda.get_device_name().endswith("[ZLUDA]")
262
+ else torch.float32
263
+ )
264
+ global asr_pipe
265
+ asr_pipe = pipeline(
266
+ "automatic-speech-recognition",
267
+ model="openai/whisper-large-v3-turbo",
268
+ torch_dtype=dtype,
269
+ device=device,
270
+ )
271
+
272
+
273
+ # transcribe
274
+
275
+
276
+ def transcribe(ref_audio, language=None):
277
+ global asr_pipe
278
+ if asr_pipe is None:
279
+ initialize_asr_pipeline(device=device)
280
+ return asr_pipe(
281
+ ref_audio,
282
+ chunk_length_s=30,
283
+ batch_size=128,
284
+ generate_kwargs={"task": "transcribe", "language": language} if language else {"task": "transcribe"},
285
+ return_timestamps=False,
286
+ )["text"].strip()
287
+
288
+
289
+ # load model checkpoint for inference
290
+
291
+
292
+ def load_checkpoint(model, ckpt_path, device: str, dtype=None, use_ema=True):
293
+ if dtype is None:
294
+ dtype = torch.float32
295
+ # dtype = (
296
+ # torch.float16
297
+ # if "cuda" in device
298
+ # and torch.cuda.get_device_properties(device).major >= 6
299
+ # and not torch.cuda.get_device_name().endswith("[ZLUDA]")
300
+ # else torch.float32
301
+ # )
302
+ model = model.to(dtype)
303
+
304
+ ckpt_type = ckpt_path.split(".")[-1]
305
+ if ckpt_type == "safetensors":
306
+ from safetensors.torch import load_file
307
+
308
+ checkpoint = load_file(ckpt_path, device=device)
309
+ else:
310
+ checkpoint = torch.load(ckpt_path, map_location=device, weights_only=True)
311
+
312
+ if use_ema:
313
+ if ckpt_type == "safetensors":
314
+ checkpoint = {"ema_model_state_dict": checkpoint}
315
+ checkpoint["model_state_dict"] = {
316
+ k.replace("ema_model.", ""): v
317
+ for k, v in checkpoint["ema_model_state_dict"].items()
318
+ if k not in ["initted", "step"]
319
+ }
320
+
321
+ # patch for backward compatibility, 305e3ea
322
+ for key in ["mel_spec.mel_stft.mel_scale.fb", "mel_spec.mel_stft.spectrogram.window"]:
323
+ if key in checkpoint["model_state_dict"]:
324
+ del checkpoint["model_state_dict"][key]
325
+
326
+ _load_state_dict_resilient(model, checkpoint["model_state_dict"])
327
+ else:
328
+ if ckpt_type == "safetensors":
329
+ checkpoint = {"model_state_dict": checkpoint}
330
+ _load_state_dict_resilient(model, checkpoint["model_state_dict"])
331
+
332
+ del checkpoint
333
+ torch.cuda.empty_cache()
334
+
335
+ return model.to(device)
336
+
337
+
338
+ # load model for inference
339
+
340
+
341
+ def load_model(
342
+ model_cls,
343
+ model_cfg,
344
+ ckpt_path,
345
+ mel_spec_type=mel_spec_type,
346
+ vocab_file="",
347
+ ode_method=ode_method,
348
+ use_ema=True,
349
+ device=device,
350
+ ):
351
+ if vocab_file == "":
352
+ vocab_file = str(files("f5_tts").joinpath("infer/examples/vocab.txt"))
353
+ tokenizer = "custom"
354
+
355
+ print("\nvocab : ", vocab_file)
356
+ print("token : ", tokenizer)
357
+ print("model : ", ckpt_path, "\n")
358
+
359
+ vocab_char_map, vocab_size = get_tokenizer(vocab_file, tokenizer)
360
+ model = CFM(
361
+ transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
362
+ mel_spec_kwargs=dict(
363
+ n_fft=n_fft,
364
+ hop_length=hop_length,
365
+ win_length=win_length,
366
+ n_mel_channels=n_mel_channels,
367
+ target_sample_rate=target_sample_rate,
368
+ mel_spec_type=mel_spec_type,
369
+ ),
370
+ odeint_kwargs=dict(
371
+ method=ode_method,
372
+ ),
373
+ vocab_char_map=vocab_char_map,
374
+ ).to(device)
375
+
376
+ dtype = torch.float32 if mel_spec_type == "bigvgan" else None
377
+ model = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
378
+
379
+ return model
380
+
381
+
382
+ def remove_silence_edges(audio, silence_threshold=-42):
383
+ # Remove silence from the start
384
+ non_silent_start_idx = silence.detect_leading_silence(audio, silence_threshold=silence_threshold)
385
+ audio = audio[non_silent_start_idx:]
386
+
387
+ # Remove silence from the end
388
+ non_silent_end_duration = audio.duration_seconds
389
+ for ms in reversed(audio):
390
+ if ms.dBFS > silence_threshold:
391
+ break
392
+ non_silent_end_duration -= 0.001
393
+ trimmed_audio = audio[: int(non_silent_end_duration * 1000)]
394
+
395
+ return trimmed_audio
396
+
397
+
398
+ # preprocess reference audio and text
399
+
400
+
401
+ def preprocess_ref_audio_text(ref_audio_orig, ref_text, show_info=print):
402
+ show_info("Converting audio...")
403
+
404
+ # Compute a hash of the reference audio file
405
+ with open(ref_audio_orig, "rb") as audio_file:
406
+ audio_data = audio_file.read()
407
+ audio_hash = hashlib.md5(audio_data).hexdigest()
408
+
409
+ global _ref_audio_cache
410
+
411
+ if audio_hash in _ref_audio_cache:
412
+ show_info("Using cached preprocessed reference audio...")
413
+ ref_audio = _ref_audio_cache[audio_hash]
414
+
415
+ else: # first pass, do preprocess
416
+ with tempfile.NamedTemporaryFile(suffix=".wav", **tempfile_kwargs) as f:
417
+ temp_path = f.name
418
+
419
+ aseg = AudioSegment.from_file(ref_audio_orig)
420
+
421
+ # 1. try to find long silence for clipping
422
+ non_silent_segs = silence.split_on_silence(
423
+ aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=1000, seek_step=10
424
+ )
425
+ non_silent_wave = AudioSegment.silent(duration=0)
426
+ for non_silent_seg in non_silent_segs:
427
+ if len(non_silent_wave) > 6000 and len(non_silent_wave + non_silent_seg) > 12000:
428
+ show_info("Audio is over 12s, clipping short. (1)")
429
+ break
430
+ non_silent_wave += non_silent_seg
431
+
432
+ # 2. try to find short silence for clipping if 1. failed
433
+ if len(non_silent_wave) > 12000:
434
+ non_silent_segs = silence.split_on_silence(
435
+ aseg, min_silence_len=100, silence_thresh=-40, keep_silence=1000, seek_step=10
436
+ )
437
+ non_silent_wave = AudioSegment.silent(duration=0)
438
+ for non_silent_seg in non_silent_segs:
439
+ if len(non_silent_wave) > 6000 and len(non_silent_wave + non_silent_seg) > 12000:
440
+ show_info("Audio is over 12s, clipping short. (2)")
441
+ break
442
+ non_silent_wave += non_silent_seg
443
+
444
+ aseg = non_silent_wave
445
+
446
+ # 3. if no proper silence found for clipping
447
+ if len(aseg) > 12000:
448
+ aseg = aseg[:12000]
449
+ show_info("Audio is over 12s, clipping short. (3)")
450
+
451
+ aseg = remove_silence_edges(aseg) + AudioSegment.silent(duration=50)
452
+ aseg.export(temp_path, format="wav")
453
+ ref_audio = temp_path
454
+
455
+ # Cache the processed reference audio
456
+ _ref_audio_cache[audio_hash] = ref_audio
457
+
458
+ if not ref_text.strip():
459
+ global _ref_text_cache
460
+ if audio_hash in _ref_text_cache:
461
+ # Use cached asr transcription
462
+ show_info("Using cached reference text...")
463
+ ref_text = _ref_text_cache[audio_hash]
464
+ else:
465
+ show_info("No reference text provided, transcribing reference audio...")
466
+ ref_text = transcribe(ref_audio)
467
+ # Cache the transcribed text (not caching custom ref_text, enabling users to do manual tweak)
468
+ _ref_text_cache[audio_hash] = ref_text
469
+ else:
470
+ show_info("Using custom reference text...")
471
+
472
+ # Ensure ref_text ends with a proper sentence-ending punctuation
473
+ if not ref_text.endswith(". ") and not ref_text.endswith("。"):
474
+ if ref_text.endswith("."):
475
+ ref_text += " "
476
+ else:
477
+ ref_text += ". "
478
+
479
+ print("\nref_text ", ref_text)
480
+
481
+ return ref_audio, ref_text
482
+
483
+
484
+ # infer process: chunk text -> infer batches [i.e. infer_batch_process()]
485
+
486
+
487
+ def infer_process(
488
+ ref_audio,
489
+ ref_text,
490
+ gen_text,
491
+ model_obj,
492
+ vocoder,
493
+ mel_spec_type=mel_spec_type,
494
+ show_info=print,
495
+ progress=tqdm,
496
+ target_rms=target_rms,
497
+ cross_fade_duration=cross_fade_duration,
498
+ nfe_step=nfe_step,
499
+ cfg_strength=cfg_strength,
500
+ sway_sampling_coef=sway_sampling_coef,
501
+ speed=speed,
502
+ fix_duration=fix_duration,
503
+ device=device,
504
+ tokenizer="pinyin",
505
+ cls_language=None,
506
+ cls_server_url=None,
507
+ cls_timeout=5.0,
508
+ cls_tokenizer_fn=None,
509
+ ):
510
+ # Split the input text into batches
511
+ audio, sr = torchaudio.load(ref_audio)
512
+ max_chars = int(len(ref_text.encode("utf-8")) / (audio.shape[-1] / sr) * (22 - audio.shape[-1] / sr) * speed)
513
+ gen_text_batches = chunk_text(gen_text, max_chars=max_chars)
514
+ for i, gen_text in enumerate(gen_text_batches):
515
+ print(f"gen_text {i}", gen_text)
516
+ print("\n")
517
+
518
+ show_info(f"Generating audio in {len(gen_text_batches)} batches...")
519
+ return next(
520
+ infer_batch_process(
521
+ (audio, sr),
522
+ ref_text,
523
+ gen_text_batches,
524
+ model_obj,
525
+ vocoder,
526
+ mel_spec_type=mel_spec_type,
527
+ progress=progress,
528
+ target_rms=target_rms,
529
+ cross_fade_duration=cross_fade_duration,
530
+ nfe_step=nfe_step,
531
+ cfg_strength=cfg_strength,
532
+ sway_sampling_coef=sway_sampling_coef,
533
+ speed=speed,
534
+ fix_duration=fix_duration,
535
+ device=device,
536
+ tokenizer=tokenizer,
537
+ cls_language=cls_language,
538
+ cls_server_url=cls_server_url,
539
+ cls_timeout=cls_timeout,
540
+ cls_tokenizer_fn=cls_tokenizer_fn,
541
+ )
542
+ )
543
+
544
+
545
+ # infer batches
546
+
547
+
548
+ def infer_batch_process(
549
+ ref_audio,
550
+ ref_text,
551
+ gen_text_batches,
552
+ model_obj,
553
+ vocoder,
554
+ mel_spec_type="vocos",
555
+ progress=tqdm,
556
+ target_rms=0.1,
557
+ cross_fade_duration=0.15,
558
+ nfe_step=32,
559
+ cfg_strength=2.0,
560
+ sway_sampling_coef=-1,
561
+ speed=1,
562
+ fix_duration=None,
563
+ device=None,
564
+ streaming=False,
565
+ chunk_size=2048,
566
+ tokenizer="pinyin",
567
+ cls_language=None,
568
+ cls_server_url=None,
569
+ cls_timeout=5.0,
570
+ cls_tokenizer_fn=None,
571
+ ):
572
+ audio, sr = ref_audio
573
+ if audio.shape[0] > 1:
574
+ audio = torch.mean(audio, dim=0, keepdim=True)
575
+
576
+ rms = torch.sqrt(torch.mean(torch.square(audio)))
577
+ if rms < target_rms:
578
+ audio = audio * target_rms / rms
579
+ if sr != target_sample_rate:
580
+ resampler = torchaudio.transforms.Resample(orig_freq=sr, new_freq=target_sample_rate)
581
+ audio = resampler(audio)
582
+ audio = audio.to(device)
583
+
584
+ mel_spectrogram = MelSpec(
585
+ n_fft=n_fft,
586
+ hop_length=hop_length,
587
+ win_length=win_length,
588
+ n_mel_channels=n_mel_channels,
589
+ target_sample_rate=target_sample_rate,
590
+ mel_spec_type=mel_spec_type,
591
+ )
592
+ ref_mel = mel_spectrogram(audio)
593
+ if ref_mel.dim() == 3:
594
+ ref_mel = ref_mel[0]
595
+ ref_mel_len = ref_mel.shape[-1]
596
+
597
+ generated_waves = []
598
+ spectrograms = []
599
+
600
+ if len(ref_text[-1].encode("utf-8")) == 1:
601
+ ref_text = ref_text + " "
602
+
603
+ def process_batch(gen_text):
604
+ local_speed = speed
605
+ if len(gen_text.encode("utf-8")) < 10:
606
+ local_speed = 0.3
607
+
608
+ # Prepare the text
609
+ text_list = [ref_text + gen_text]
610
+ final_text_list = tokenize_texts(
611
+ text_list,
612
+ tokenizer=tokenizer,
613
+ cls_language=cls_language,
614
+ cls_server_url=cls_server_url,
615
+ cls_timeout=cls_timeout,
616
+ cls_tokenizer_fn=cls_tokenizer_fn,
617
+ )
618
+
619
+ ref_audio_len = audio.shape[-1] // hop_length
620
+ if fix_duration is not None:
621
+ duration = int(fix_duration * target_sample_rate / hop_length)
622
+ else:
623
+ # Calculate duration
624
+ ref_text_len = len(ref_text.encode("utf-8"))
625
+ gen_text_len = len(gen_text.encode("utf-8"))
626
+ duration = ref_audio_len + int(ref_audio_len / ref_text_len * gen_text_len / local_speed)
627
+
628
+ # inference
629
+ with torch.inference_mode():
630
+ generated, _ = model_obj.sample(
631
+ cond=audio,
632
+ text=final_text_list,
633
+ duration=duration,
634
+ steps=nfe_step,
635
+ cfg_strength=cfg_strength,
636
+ sway_sampling_coef=sway_sampling_coef,
637
+ )
638
+ del _
639
+
640
+ generated = generated.to(torch.float32) # generated mel spectrogram [B, T, n_mel]
641
+ gen = generated[0]
642
+
643
+ # Align ref mel inside generated mel to find the boundary, then cut the robotic head.
644
+ ref_mel_local = ref_mel[:, :ref_mel_len]
645
+ gen_mel = gen.transpose(0, 1) # [n_mel, T]
646
+ if ref_mel_local.shape[0] != gen_mel.shape[0] and ref_mel_local.shape[1] == gen_mel.shape[0]:
647
+ ref_mel_local = ref_mel_local.transpose(0, 1)
648
+ cut_idx = 0
649
+ if gen_mel.shape[1] > ref_mel_local.shape[1]:
650
+ ref_len = ref_mel_local.shape[1]
651
+ gen_unfold = gen_mel.unfold(1, ref_len, 1) # [n_mel, T-ref_len+1, ref_len]
652
+ diff = gen_unfold - ref_mel_local.unsqueeze(1)
653
+ mse = torch.mean(diff * diff, dim=(0, 2))
654
+ best = int(torch.argmin(mse).item())
655
+ cut_idx = max(0, int((best + ref_len) * hop_length))
656
+
657
+ gen = gen.unsqueeze(0)
658
+ gen_mel_spec = gen.permute(0, 2, 1).to(torch.float32)
659
+ if mel_spec_type == "vocos":
660
+ generated_wave = vocoder.decode(gen_mel_spec).cpu()
661
+ elif mel_spec_type == "bigvgan":
662
+ generated_wave = vocoder(gen_mel_spec).squeeze(0).cpu()
663
+ if rms < target_rms:
664
+ generated_wave = generated_wave * rms / target_rms
665
+
666
+ # wav -> numpy
667
+ wave = generated_wave.squeeze(0).to(torch.float32)
668
+ if cut_idx > 0 and cut_idx < wave.numel():
669
+ wave = wave[cut_idx:]
670
+ generated_wave = wave.unsqueeze(0)
671
+ generated_wave = generated_wave.squeeze().cpu().numpy()
672
+
673
+ if streaming:
674
+ for j in range(0, len(generated_wave), chunk_size):
675
+ yield generated_wave[j : j + chunk_size], target_sample_rate
676
+ else:
677
+ generated_cpu = gen_mel_spec[0].cpu().numpy()
678
+ del generated
679
+ yield generated_wave, generated_cpu
680
+
681
+ if streaming:
682
+ for gen_text in progress.tqdm(gen_text_batches) if progress is not None else gen_text_batches:
683
+ for chunk in process_batch(gen_text):
684
+ yield chunk
685
+ else:
686
+ with ThreadPoolExecutor() as executor:
687
+ futures = [executor.submit(process_batch, gen_text) for gen_text in gen_text_batches]
688
+ for future in progress.tqdm(futures) if progress is not None else futures:
689
+ result = future.result()
690
+ if result:
691
+ generated_wave, generated_mel_spec = next(result)
692
+ generated_waves.append(generated_wave)
693
+ spectrograms.append(generated_mel_spec)
694
+
695
+ if generated_waves:
696
+ if cross_fade_duration <= 0:
697
+ # Simply concatenate
698
+ final_wave = np.concatenate(generated_waves)
699
+ else:
700
+ # Combine all generated waves with cross-fading
701
+ final_wave = generated_waves[0]
702
+ for i in range(1, len(generated_waves)):
703
+ prev_wave = final_wave
704
+ next_wave = generated_waves[i]
705
+
706
+ # Calculate cross-fade samples, ensuring it does not exceed wave lengths
707
+ cross_fade_samples = int(cross_fade_duration * target_sample_rate)
708
+ cross_fade_samples = min(cross_fade_samples, len(prev_wave), len(next_wave))
709
+
710
+ if cross_fade_samples <= 0:
711
+ # No overlap possible, concatenate
712
+ final_wave = np.concatenate([prev_wave, next_wave])
713
+ continue
714
+
715
+ # Overlapping parts
716
+ prev_overlap = prev_wave[-cross_fade_samples:]
717
+ next_overlap = next_wave[:cross_fade_samples]
718
+
719
+ # Fade out and fade in
720
+ fade_out = np.linspace(1, 0, cross_fade_samples)
721
+ fade_in = np.linspace(0, 1, cross_fade_samples)
722
+
723
+ # Cross-faded overlap
724
+ cross_faded_overlap = prev_overlap * fade_out + next_overlap * fade_in
725
+
726
+ # Combine
727
+ new_wave = np.concatenate(
728
+ [prev_wave[:-cross_fade_samples], cross_faded_overlap, next_wave[cross_fade_samples:]]
729
+ )
730
+
731
+ final_wave = new_wave
732
+
733
+ # Create a combined spectrogram
734
+ combined_spectrogram = np.concatenate(spectrograms, axis=1)
735
+
736
+ yield final_wave, target_sample_rate, combined_spectrogram
737
+
738
+ else:
739
+ yield None, target_sample_rate, None
740
+
741
+
742
+ # remove silence from generated wav
743
+
744
+
745
+ def remove_silence_for_generated_wav(filename):
746
+ aseg = AudioSegment.from_file(filename)
747
+ non_silent_segs = silence.split_on_silence(
748
+ aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=500, seek_step=10
749
+ )
750
+ non_silent_wave = AudioSegment.silent(duration=0)
751
+ for non_silent_seg in non_silent_segs:
752
+ non_silent_wave += non_silent_seg
753
+ aseg = non_silent_wave
754
+ aseg.export(filename, format="wav")
755
+
756
+
757
+ # save spectrogram
758
+
759
+
760
+ def save_spectrogram(spectrogram, path):
761
+ plt.figure(figsize=(12, 4))
762
+ plt.imshow(spectrogram, origin="lower", aspect="auto")
763
+ plt.colorbar()
764
+ plt.savefig(path)
765
+ plt.close()
src/f5_tts/model/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from f5_tts.model.backbones.dit import DiT
2
+ from f5_tts.model.backbones.mmdit import MMDiT
3
+ from f5_tts.model.backbones.unett import UNetT
4
+ from f5_tts.model.cfm import CFM
5
+ __all__ = ["CFM", "UNetT", "DiT", "MMDiT"]
src/f5_tts/model/backbones/README.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Backbones quick introduction
2
+
3
+
4
+ ### unett.py
5
+ - flat unet transformer
6
+ - structure same as in e2-tts & voicebox paper except using rotary pos emb
7
+ - possible abs pos emb & convnextv2 blocks for embedded text before concat
8
+
9
+ ### dit.py
10
+ - adaln-zero dit
11
+ - embedded timestep as condition
12
+ - concatted noised_input + masked_cond + embedded_text, linear proj in
13
+ - possible abs pos emb & convnextv2 blocks for embedded text before concat
14
+ - possible long skip connection (first layer to last layer)
15
+
16
+ ### mmdit.py
17
+ - stable diffusion 3 block structure
18
+ - timestep as condition
19
+ - left stream: text embedded and applied a abs pos emb
20
+ - right stream: masked_cond & noised_input concatted and with same conv pos emb as unett
src/f5_tts/model/backbones/dit.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ein notation:
3
+ b - batch
4
+ n - sequence
5
+ nt - text sequence
6
+ nw - raw wave length
7
+ d - dimension
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from torch import nn
15
+ from x_transformers.x_transformers import RotaryEmbedding
16
+
17
+ from f5_tts.model.modules import (
18
+ AdaLayerNorm_Final,
19
+ ConvNeXtV2Block,
20
+ ConvPositionEmbedding,
21
+ DiTBlock,
22
+ TimestepEmbedding,
23
+ get_pos_embed_indices,
24
+ precompute_freqs_cis,
25
+ )
26
+
27
+
28
+ # Text embedding
29
+
30
+
31
+ class TextEmbedding(nn.Module):
32
+ def __init__(
33
+ self, text_num_embeds, text_dim, mask_padding=True, average_upsampling=False, conv_layers=0, conv_mult=2
34
+ ):
35
+ super().__init__()
36
+ self.text_embed = nn.Embedding(text_num_embeds + 1, text_dim) # use 0 as filler token
37
+
38
+ self.mask_padding = mask_padding # mask filler and batch padding tokens or not
39
+ self.average_upsampling = average_upsampling # zipvoice-style text late average upsampling (after text encoder)
40
+ if average_upsampling:
41
+ assert mask_padding, "text_embedding_average_upsampling requires text_mask_padding to be True"
42
+
43
+ if conv_layers > 0:
44
+ self.extra_modeling = True
45
+ self.precompute_max_pos = 4096 # ~44s of 24khz audio
46
+ self.register_buffer("freqs_cis", precompute_freqs_cis(text_dim, self.precompute_max_pos), persistent=False)
47
+ self.text_blocks = nn.Sequential(
48
+ *[ConvNeXtV2Block(text_dim, text_dim * conv_mult) for _ in range(conv_layers)]
49
+ )
50
+ else:
51
+ self.extra_modeling = False
52
+
53
+ def average_upsample_text_by_mask(self, text, text_mask, audio_mask):
54
+ batch, text_len, text_dim = text.shape
55
+
56
+ if audio_mask is None:
57
+ audio_mask = torch.ones_like(text_mask, dtype=torch.bool)
58
+ valid_mask = audio_mask & text_mask
59
+ audio_lens = audio_mask.sum(dim=1) # [batch]
60
+ valid_lens = valid_mask.sum(dim=1) # [batch]
61
+
62
+ upsampled_text = torch.zeros_like(text)
63
+
64
+ for i in range(batch):
65
+ audio_len = audio_lens[i].item()
66
+ valid_len = valid_lens[i].item()
67
+
68
+ if valid_len == 0:
69
+ continue
70
+
71
+ valid_ind = torch.where(valid_mask[i])[0]
72
+ valid_data = text[i, valid_ind, :] # [valid_len, text_dim]
73
+
74
+ base_repeat = audio_len // valid_len
75
+ remainder = audio_len % valid_len
76
+
77
+ indices = []
78
+ for j in range(valid_len):
79
+ repeat_count = base_repeat + (1 if j >= valid_len - remainder else 0)
80
+ indices.extend([j] * repeat_count)
81
+
82
+ indices = torch.tensor(indices[:audio_len], device=text.device, dtype=torch.long)
83
+ upsampled = valid_data[indices] # [audio_len, text_dim]
84
+
85
+ upsampled_text[i, :audio_len, :] = upsampled
86
+
87
+ return upsampled_text
88
+
89
+ def forward(self, text: int["b nt"], seq_len, drop_text=False, audio_mask: bool["b n"] | None = None): # noqa: F722
90
+ text = text + 1 # use 0 as filler token. preprocess of batch pad -1, see list_str_to_idx()
91
+ text = text[:, :seq_len] # curtail if character tokens are more than the mel spec tokens
92
+ batch, text_len = text.shape[0], text.shape[1]
93
+ text = F.pad(text, (0, seq_len - text_len), value=0) # (opt.) if not self.average_upsampling:
94
+ if self.mask_padding:
95
+ text_mask = text == 0
96
+
97
+ if drop_text: # cfg for text
98
+ text = torch.zeros_like(text)
99
+
100
+ text = self.text_embed(text) # b n -> b n d
101
+
102
+ # possible extra modeling
103
+ if self.extra_modeling:
104
+ # sinus pos emb
105
+ batch_start = torch.zeros((batch,), device=text.device, dtype=torch.long)
106
+ pos_idx = get_pos_embed_indices(batch_start, seq_len, max_pos=self.precompute_max_pos)
107
+ text_pos_embed = self.freqs_cis[pos_idx]
108
+ text = text + text_pos_embed
109
+
110
+ # convnextv2 blocks
111
+ if self.mask_padding:
112
+ text = text.masked_fill(text_mask.unsqueeze(-1).expand(-1, -1, text.size(-1)), 0.0)
113
+ for block in self.text_blocks:
114
+ text = block(text)
115
+ text = text.masked_fill(text_mask.unsqueeze(-1).expand(-1, -1, text.size(-1)), 0.0)
116
+ else:
117
+ text = self.text_blocks(text)
118
+
119
+ if self.average_upsampling:
120
+ text = self.average_upsample_text_by_mask(text, ~text_mask, audio_mask)
121
+
122
+ return text
123
+
124
+
125
+ # noised input audio and context mixing embedding
126
+
127
+
128
+ class InputEmbedding(nn.Module):
129
+ def __init__(self, mel_dim, text_dim, out_dim):
130
+ super().__init__()
131
+ self.proj = nn.Linear(mel_dim * 2 + text_dim, out_dim)
132
+ self.conv_pos_embed = ConvPositionEmbedding(dim=out_dim)
133
+
134
+ def forward(self, x: float["b n d"], cond: float["b n d"], text_embed: float["b n d"], drop_audio_cond=False): # noqa: F722
135
+ if drop_audio_cond: # cfg for cond audio
136
+ cond = torch.zeros_like(cond)
137
+
138
+ x = self.proj(torch.cat((x, cond, text_embed), dim=-1))
139
+ x = self.conv_pos_embed(x) + x
140
+ return x
141
+
142
+
143
+ # Transformer backbone using DiT blocks
144
+
145
+
146
+ class DiT(nn.Module):
147
+ def __init__(
148
+ self,
149
+ *,
150
+ dim,
151
+ depth=8,
152
+ heads=8,
153
+ dim_head=64,
154
+ dropout=0.1,
155
+ ff_mult=4,
156
+ mel_dim=100,
157
+ text_num_embeds=256,
158
+ text_dim=None,
159
+ text_mask_padding=True,
160
+ text_embedding_average_upsampling=False,
161
+ qk_norm=None,
162
+ conv_layers=0,
163
+ pe_attn_head=None,
164
+ attn_backend="torch", # "torch" | "flash_attn"
165
+ attn_mask_enabled=False,
166
+ long_skip_connection=False,
167
+ checkpoint_activations=False,
168
+ ):
169
+ super().__init__()
170
+
171
+ self.time_embed = TimestepEmbedding(dim)
172
+ if text_dim is None:
173
+ text_dim = mel_dim
174
+ self.text_embed = TextEmbedding(
175
+ text_num_embeds,
176
+ text_dim,
177
+ mask_padding=text_mask_padding,
178
+ average_upsampling=text_embedding_average_upsampling,
179
+ conv_layers=conv_layers,
180
+ )
181
+ self.text_cond, self.text_uncond = None, None # text cache
182
+ self.input_embed = InputEmbedding(mel_dim, text_dim, dim)
183
+
184
+ self.rotary_embed = RotaryEmbedding(dim_head)
185
+
186
+ self.dim = dim
187
+ self.depth = depth
188
+
189
+ self.transformer_blocks = nn.ModuleList(
190
+ [
191
+ DiTBlock(
192
+ dim=dim,
193
+ heads=heads,
194
+ dim_head=dim_head,
195
+ ff_mult=ff_mult,
196
+ dropout=dropout,
197
+ qk_norm=qk_norm,
198
+ pe_attn_head=pe_attn_head,
199
+ attn_backend=attn_backend,
200
+ attn_mask_enabled=attn_mask_enabled,
201
+ )
202
+ for _ in range(depth)
203
+ ]
204
+ )
205
+ self.long_skip_connection = nn.Linear(dim * 2, dim, bias=False) if long_skip_connection else None
206
+
207
+ self.norm_out = AdaLayerNorm_Final(dim) # final modulation
208
+ self.proj_out = nn.Linear(dim, mel_dim)
209
+
210
+ self.checkpoint_activations = checkpoint_activations
211
+
212
+ self.initialize_weights()
213
+
214
+ def initialize_weights(self):
215
+ # Zero-out AdaLN layers in DiT blocks:
216
+ for block in self.transformer_blocks:
217
+ nn.init.constant_(block.attn_norm.linear.weight, 0)
218
+ nn.init.constant_(block.attn_norm.linear.bias, 0)
219
+
220
+ # Zero-out output layers:
221
+ nn.init.constant_(self.norm_out.linear.weight, 0)
222
+ nn.init.constant_(self.norm_out.linear.bias, 0)
223
+ nn.init.constant_(self.proj_out.weight, 0)
224
+ nn.init.constant_(self.proj_out.bias, 0)
225
+
226
+ def ckpt_wrapper(self, module):
227
+ # https://github.com/chuanyangjin/fast-DiT/blob/main/models.py
228
+ def ckpt_forward(*inputs):
229
+ outputs = module(*inputs)
230
+ return outputs
231
+
232
+ return ckpt_forward
233
+
234
+ def get_input_embed(
235
+ self,
236
+ x, # b n d
237
+ cond, # b n d
238
+ text, # b nt
239
+ drop_audio_cond: bool = False,
240
+ drop_text: bool = False,
241
+ cache: bool = True,
242
+ audio_mask: bool["b n"] | None = None, # noqa: F722
243
+ ):
244
+ seq_len = x.shape[1]
245
+ if cache:
246
+ if drop_text:
247
+ if self.text_uncond is None:
248
+ self.text_uncond = self.text_embed(text, seq_len, drop_text=True, audio_mask=audio_mask)
249
+ text_embed = self.text_uncond
250
+ else:
251
+ if self.text_cond is None:
252
+ self.text_cond = self.text_embed(text, seq_len, drop_text=False, audio_mask=audio_mask)
253
+ text_embed = self.text_cond
254
+ else:
255
+ text_embed = self.text_embed(text, seq_len, drop_text=drop_text, audio_mask=audio_mask)
256
+
257
+ # TODO YASH: bfloat conv which leads to flash attention does not support fp32 error happens
258
+ x = self.input_embed(x, cond, text_embed, drop_audio_cond=drop_audio_cond)
259
+
260
+ return x
261
+
262
+ def clear_cache(self):
263
+ self.text_cond, self.text_uncond = None, None
264
+
265
+ def forward(
266
+ self,
267
+ x: float["b n d"], # nosied input audio # noqa: F722
268
+ cond: float["b n d"], # masked cond audio # noqa: F722
269
+ text: int["b nt"], # text # noqa: F722
270
+ time: float["b"] | float[""], # time step # noqa: F821 F722
271
+ mask: bool["b n"] | None = None, # noqa: F722
272
+ drop_audio_cond: bool = False, # cfg for cond audio
273
+ drop_text: bool = False, # cfg for text
274
+ cfg_infer: bool = False, # cfg inference, pack cond & uncond forward
275
+ cache: bool = False,
276
+ skip_flash_attn: bool = False,
277
+ ):
278
+ batch, seq_len = x.shape[0], x.shape[1]
279
+ if time.ndim == 0:
280
+ time = time.repeat(batch)
281
+
282
+ # t: conditioning time, text: text, x: noised audio + cond audio + text
283
+ t = self.time_embed(time)
284
+
285
+ if cfg_infer: # pack cond & uncond forward: b n d -> 2b n d
286
+ x_cond = self.get_input_embed(
287
+ x, cond, text, drop_audio_cond=False, drop_text=False, cache=cache, audio_mask=mask
288
+ )
289
+ x_uncond = self.get_input_embed(
290
+ x, cond, text, drop_audio_cond=True, drop_text=True, cache=cache, audio_mask=mask
291
+ )
292
+ x = torch.cat((x_cond, x_uncond), dim=0)
293
+ t = torch.cat((t, t), dim=0)
294
+ mask = torch.cat((mask, mask), dim=0) if mask is not None else None
295
+ else:
296
+ x = self.get_input_embed(
297
+ x, cond, text, drop_audio_cond=drop_audio_cond, drop_text=drop_text, cache=cache, audio_mask=mask
298
+ )
299
+
300
+ rope = self.rotary_embed.forward_from_seq_len(seq_len)
301
+
302
+ if self.long_skip_connection is not None:
303
+ residual = x
304
+
305
+ for block in self.transformer_blocks:
306
+ if self.checkpoint_activations:
307
+ # https://pytorch.org/docs/stable/checkpoint.html#torch.utils.checkpoint.checkpoint
308
+ x = torch.utils.checkpoint.checkpoint(self.ckpt_wrapper(block), x, t, mask, rope, use_reentrant=False, skip_flash_attn=skip_flash_attn)
309
+ else:
310
+ x = block(x, t, mask=mask, rope=rope, skip_flash_attn=skip_flash_attn)
311
+
312
+ if self.long_skip_connection is not None:
313
+ x = self.long_skip_connection(torch.cat((x, residual), dim=-1))
314
+
315
+ x = self.norm_out(x, t)
316
+ output = self.proj_out(x)
317
+
318
+ return output
src/f5_tts/model/backbones/mmdit.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ein notation:
3
+ b - batch
4
+ n - sequence
5
+ nt - text sequence
6
+ nw - raw wave length
7
+ d - dimension
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import torch
13
+ from torch import nn
14
+ from x_transformers.x_transformers import RotaryEmbedding
15
+
16
+ from f5_tts.model.modules import (
17
+ AdaLayerNorm_Final,
18
+ ConvPositionEmbedding,
19
+ MMDiTBlock,
20
+ TimestepEmbedding,
21
+ get_pos_embed_indices,
22
+ precompute_freqs_cis,
23
+ )
24
+
25
+
26
+ # text embedding
27
+
28
+
29
+ class TextEmbedding(nn.Module):
30
+ def __init__(self, out_dim, text_num_embeds, mask_padding=True):
31
+ super().__init__()
32
+ self.text_embed = nn.Embedding(text_num_embeds + 1, out_dim) # will use 0 as filler token
33
+
34
+ self.mask_padding = mask_padding # mask filler and batch padding tokens or not
35
+
36
+ self.precompute_max_pos = 1024
37
+ self.register_buffer("freqs_cis", precompute_freqs_cis(out_dim, self.precompute_max_pos), persistent=False)
38
+
39
+ def forward(self, text: int["b nt"], drop_text=False) -> int["b nt d"]: # noqa: F722
40
+ text = text + 1 # use 0 as filler token. preprocess of batch pad -1, see list_str_to_idx()
41
+ if self.mask_padding:
42
+ text_mask = text == 0
43
+
44
+ if drop_text: # cfg for text
45
+ text = torch.zeros_like(text)
46
+
47
+ text = self.text_embed(text) # b nt -> b nt d
48
+
49
+ # sinus pos emb
50
+ batch_start = torch.zeros((text.shape[0],), dtype=torch.long)
51
+ batch_text_len = text.shape[1]
52
+ pos_idx = get_pos_embed_indices(batch_start, batch_text_len, max_pos=self.precompute_max_pos)
53
+ text_pos_embed = self.freqs_cis[pos_idx]
54
+
55
+ text = text + text_pos_embed
56
+
57
+ if self.mask_padding:
58
+ text = text.masked_fill(text_mask.unsqueeze(-1).expand(-1, -1, text.size(-1)), 0.0)
59
+
60
+ return text
61
+
62
+
63
+ # noised input & masked cond audio embedding
64
+
65
+
66
+ class AudioEmbedding(nn.Module):
67
+ def __init__(self, in_dim, out_dim):
68
+ super().__init__()
69
+ self.linear = nn.Linear(2 * in_dim, out_dim)
70
+ self.conv_pos_embed = ConvPositionEmbedding(out_dim)
71
+
72
+ def forward(self, x: float["b n d"], cond: float["b n d"], drop_audio_cond=False): # noqa: F722
73
+ if drop_audio_cond:
74
+ cond = torch.zeros_like(cond)
75
+ x = torch.cat((x, cond), dim=-1)
76
+ x = self.linear(x)
77
+ x = self.conv_pos_embed(x) + x
78
+ return x
79
+
80
+
81
+ # Transformer backbone using MM-DiT blocks
82
+
83
+
84
+ class MMDiT(nn.Module):
85
+ def __init__(
86
+ self,
87
+ *,
88
+ dim,
89
+ depth=8,
90
+ heads=8,
91
+ dim_head=64,
92
+ dropout=0.1,
93
+ ff_mult=4,
94
+ mel_dim=100,
95
+ text_num_embeds=256,
96
+ text_mask_padding=True,
97
+ qk_norm=None,
98
+ ):
99
+ super().__init__()
100
+
101
+ self.time_embed = TimestepEmbedding(dim)
102
+ self.text_embed = TextEmbedding(dim, text_num_embeds, mask_padding=text_mask_padding)
103
+ self.text_cond, self.text_uncond = None, None # text cache
104
+ self.audio_embed = AudioEmbedding(mel_dim, dim)
105
+
106
+ self.rotary_embed = RotaryEmbedding(dim_head)
107
+
108
+ self.dim = dim
109
+ self.depth = depth
110
+
111
+ self.transformer_blocks = nn.ModuleList(
112
+ [
113
+ MMDiTBlock(
114
+ dim=dim,
115
+ heads=heads,
116
+ dim_head=dim_head,
117
+ dropout=dropout,
118
+ ff_mult=ff_mult,
119
+ context_pre_only=i == depth - 1,
120
+ qk_norm=qk_norm,
121
+ )
122
+ for i in range(depth)
123
+ ]
124
+ )
125
+ self.norm_out = AdaLayerNorm_Final(dim) # final modulation
126
+ self.proj_out = nn.Linear(dim, mel_dim)
127
+
128
+ self.initialize_weights()
129
+
130
+ def initialize_weights(self):
131
+ # Zero-out AdaLN layers in MMDiT blocks:
132
+ for block in self.transformer_blocks:
133
+ nn.init.constant_(block.attn_norm_x.linear.weight, 0)
134
+ nn.init.constant_(block.attn_norm_x.linear.bias, 0)
135
+ nn.init.constant_(block.attn_norm_c.linear.weight, 0)
136
+ nn.init.constant_(block.attn_norm_c.linear.bias, 0)
137
+
138
+ # Zero-out output layers:
139
+ nn.init.constant_(self.norm_out.linear.weight, 0)
140
+ nn.init.constant_(self.norm_out.linear.bias, 0)
141
+ nn.init.constant_(self.proj_out.weight, 0)
142
+ nn.init.constant_(self.proj_out.bias, 0)
143
+
144
+ def get_input_embed(
145
+ self,
146
+ x, # b n d
147
+ cond, # b n d
148
+ text, # b nt
149
+ drop_audio_cond: bool = False,
150
+ drop_text: bool = False,
151
+ cache: bool = True,
152
+ ):
153
+ if cache:
154
+ if drop_text:
155
+ if self.text_uncond is None:
156
+ self.text_uncond = self.text_embed(text, drop_text=True)
157
+ c = self.text_uncond
158
+ else:
159
+ if self.text_cond is None:
160
+ self.text_cond = self.text_embed(text, drop_text=False)
161
+ c = self.text_cond
162
+ else:
163
+ c = self.text_embed(text, drop_text=drop_text)
164
+ x = self.audio_embed(x, cond, drop_audio_cond=drop_audio_cond)
165
+
166
+ return x, c
167
+
168
+ def clear_cache(self):
169
+ self.text_cond, self.text_uncond = None, None
170
+
171
+ def forward(
172
+ self,
173
+ x: float["b n d"], # nosied input audio # noqa: F722
174
+ cond: float["b n d"], # masked cond audio # noqa: F722
175
+ text: int["b nt"], # text # noqa: F722
176
+ time: float["b"] | float[""], # time step # noqa: F821 F722
177
+ mask: bool["b n"] | None = None, # noqa: F722
178
+ drop_audio_cond: bool = False, # cfg for cond audio
179
+ drop_text: bool = False, # cfg for text
180
+ cfg_infer: bool = False, # cfg inference, pack cond & uncond forward
181
+ cache: bool = False,
182
+ ):
183
+ batch = x.shape[0]
184
+ if time.ndim == 0:
185
+ time = time.repeat(batch)
186
+
187
+ # t: conditioning (time), c: context (text + masked cond audio), x: noised input audio
188
+ t = self.time_embed(time)
189
+ if cfg_infer: # pack cond & uncond forward: b n d -> 2b n d
190
+ x_cond, c_cond = self.get_input_embed(x, cond, text, drop_audio_cond=False, drop_text=False, cache=cache)
191
+ x_uncond, c_uncond = self.get_input_embed(x, cond, text, drop_audio_cond=True, drop_text=True, cache=cache)
192
+ x = torch.cat((x_cond, x_uncond), dim=0)
193
+ c = torch.cat((c_cond, c_uncond), dim=0)
194
+ t = torch.cat((t, t), dim=0)
195
+ mask = torch.cat((mask, mask), dim=0) if mask is not None else None
196
+ else:
197
+ x, c = self.get_input_embed(
198
+ x, cond, text, drop_audio_cond=drop_audio_cond, drop_text=drop_text, cache=cache
199
+ )
200
+
201
+ seq_len = x.shape[1]
202
+ text_len = text.shape[1]
203
+ rope_audio = self.rotary_embed.forward_from_seq_len(seq_len)
204
+ rope_text = self.rotary_embed.forward_from_seq_len(text_len)
205
+
206
+ for block in self.transformer_blocks:
207
+ c, x = block(x, c, t, mask=mask, rope=rope_audio, c_rope=rope_text)
208
+
209
+ x = self.norm_out(x, t)
210
+ output = self.proj_out(x)
211
+
212
+ return output
src/f5_tts/model/backbones/unett.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ein notation:
3
+ b - batch
4
+ n - sequence
5
+ nt - text sequence
6
+ nw - raw wave length
7
+ d - dimension
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Literal
13
+
14
+ import torch
15
+ import torch.nn.functional as F
16
+ from torch import nn
17
+ from x_transformers import RMSNorm
18
+ from x_transformers.x_transformers import RotaryEmbedding
19
+
20
+ from f5_tts.model.modules import (
21
+ Attention,
22
+ AttnProcessor,
23
+ ConvNeXtV2Block,
24
+ ConvPositionEmbedding,
25
+ FeedForward,
26
+ TimestepEmbedding,
27
+ get_pos_embed_indices,
28
+ precompute_freqs_cis,
29
+ )
30
+
31
+
32
+ # Text embedding
33
+
34
+
35
+ class TextEmbedding(nn.Module):
36
+ def __init__(self, text_num_embeds, text_dim, mask_padding=True, conv_layers=0, conv_mult=2):
37
+ super().__init__()
38
+ self.text_embed = nn.Embedding(text_num_embeds + 1, text_dim) # use 0 as filler token
39
+
40
+ self.mask_padding = mask_padding # mask filler and batch padding tokens or not
41
+
42
+ if conv_layers > 0:
43
+ self.extra_modeling = True
44
+ self.precompute_max_pos = 4096 # ~44s of 24khz audio
45
+ self.register_buffer("freqs_cis", precompute_freqs_cis(text_dim, self.precompute_max_pos), persistent=False)
46
+ self.text_blocks = nn.Sequential(
47
+ *[ConvNeXtV2Block(text_dim, text_dim * conv_mult) for _ in range(conv_layers)]
48
+ )
49
+ else:
50
+ self.extra_modeling = False
51
+
52
+ def forward(self, text: int["b nt"], seq_len, drop_text=False): # noqa: F722
53
+ text = text + 1 # use 0 as filler token. preprocess of batch pad -1, see list_str_to_idx()
54
+ text = text[:, :seq_len] # curtail if character tokens are more than the mel spec tokens
55
+ batch, text_len = text.shape[0], text.shape[1]
56
+ text = F.pad(text, (0, seq_len - text_len), value=0)
57
+ if self.mask_padding:
58
+ text_mask = text == 0
59
+
60
+ if drop_text: # cfg for text
61
+ text = torch.zeros_like(text)
62
+
63
+ text = self.text_embed(text) # b n -> b n d
64
+
65
+ # possible extra modeling
66
+ if self.extra_modeling:
67
+ # sinus pos emb
68
+ batch_start = torch.zeros((batch,), dtype=torch.long)
69
+ pos_idx = get_pos_embed_indices(batch_start, seq_len, max_pos=self.precompute_max_pos)
70
+ text_pos_embed = self.freqs_cis[pos_idx]
71
+ text = text + text_pos_embed
72
+
73
+ # convnextv2 blocks
74
+ if self.mask_padding:
75
+ text = text.masked_fill(text_mask.unsqueeze(-1).expand(-1, -1, text.size(-1)), 0.0)
76
+ for block in self.text_blocks:
77
+ text = block(text)
78
+ text = text.masked_fill(text_mask.unsqueeze(-1).expand(-1, -1, text.size(-1)), 0.0)
79
+ else:
80
+ text = self.text_blocks(text)
81
+
82
+ return text
83
+
84
+
85
+ # noised input audio and context mixing embedding
86
+
87
+
88
+ class InputEmbedding(nn.Module):
89
+ def __init__(self, mel_dim, text_dim, out_dim):
90
+ super().__init__()
91
+ self.proj = nn.Linear(mel_dim * 2 + text_dim, out_dim)
92
+ self.conv_pos_embed = ConvPositionEmbedding(dim=out_dim)
93
+
94
+ def forward(self, x: float["b n d"], cond: float["b n d"], text_embed: float["b n d"], drop_audio_cond=False): # noqa: F722
95
+ if drop_audio_cond: # cfg for cond audio
96
+ cond = torch.zeros_like(cond)
97
+
98
+ x = self.proj(torch.cat((x, cond, text_embed), dim=-1))
99
+ x = self.conv_pos_embed(x) + x
100
+ return x
101
+
102
+
103
+ # Flat UNet Transformer backbone
104
+
105
+
106
+ class UNetT(nn.Module):
107
+ def __init__(
108
+ self,
109
+ *,
110
+ dim,
111
+ depth=8,
112
+ heads=8,
113
+ dim_head=64,
114
+ dropout=0.1,
115
+ ff_mult=4,
116
+ mel_dim=100,
117
+ text_num_embeds=256,
118
+ text_dim=None,
119
+ text_mask_padding=True,
120
+ qk_norm=None,
121
+ conv_layers=0,
122
+ pe_attn_head=None,
123
+ attn_backend="torch", # "torch" | "flash_attn"
124
+ attn_mask_enabled=False,
125
+ skip_connect_type: Literal["add", "concat", "none"] = "concat",
126
+ ):
127
+ super().__init__()
128
+ assert depth % 2 == 0, "UNet-Transformer's depth should be even."
129
+
130
+ self.time_embed = TimestepEmbedding(dim)
131
+ if text_dim is None:
132
+ text_dim = mel_dim
133
+ self.text_embed = TextEmbedding(
134
+ text_num_embeds, text_dim, mask_padding=text_mask_padding, conv_layers=conv_layers
135
+ )
136
+ self.text_cond, self.text_uncond = None, None # text cache
137
+ self.input_embed = InputEmbedding(mel_dim, text_dim, dim)
138
+
139
+ self.rotary_embed = RotaryEmbedding(dim_head)
140
+
141
+ # transformer layers & skip connections
142
+
143
+ self.dim = dim
144
+ self.skip_connect_type = skip_connect_type
145
+ needs_skip_proj = skip_connect_type == "concat"
146
+
147
+ self.depth = depth
148
+ self.layers = nn.ModuleList([])
149
+
150
+ for idx in range(depth):
151
+ is_later_half = idx >= (depth // 2)
152
+
153
+ attn_norm = RMSNorm(dim)
154
+ attn = Attention(
155
+ processor=AttnProcessor(
156
+ pe_attn_head=pe_attn_head,
157
+ attn_backend=attn_backend,
158
+ attn_mask_enabled=attn_mask_enabled,
159
+ ),
160
+ dim=dim,
161
+ heads=heads,
162
+ dim_head=dim_head,
163
+ dropout=dropout,
164
+ qk_norm=qk_norm,
165
+ )
166
+
167
+ ff_norm = RMSNorm(dim)
168
+ ff = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh")
169
+
170
+ skip_proj = nn.Linear(dim * 2, dim, bias=False) if needs_skip_proj and is_later_half else None
171
+
172
+ self.layers.append(
173
+ nn.ModuleList(
174
+ [
175
+ skip_proj,
176
+ attn_norm,
177
+ attn,
178
+ ff_norm,
179
+ ff,
180
+ ]
181
+ )
182
+ )
183
+
184
+ self.norm_out = RMSNorm(dim)
185
+ self.proj_out = nn.Linear(dim, mel_dim)
186
+
187
+ def get_input_embed(
188
+ self,
189
+ x, # b n d
190
+ cond, # b n d
191
+ text, # b nt
192
+ drop_audio_cond: bool = False,
193
+ drop_text: bool = False,
194
+ cache: bool = True,
195
+ ):
196
+ seq_len = x.shape[1]
197
+ if cache:
198
+ if drop_text:
199
+ if self.text_uncond is None:
200
+ self.text_uncond = self.text_embed(text, seq_len, drop_text=True)
201
+ text_embed = self.text_uncond
202
+ else:
203
+ if self.text_cond is None:
204
+ self.text_cond = self.text_embed(text, seq_len, drop_text=False)
205
+ text_embed = self.text_cond
206
+ else:
207
+ text_embed = self.text_embed(text, seq_len, drop_text=drop_text)
208
+
209
+ x = self.input_embed(x, cond, text_embed, drop_audio_cond=drop_audio_cond)
210
+
211
+ return x
212
+
213
+ def clear_cache(self):
214
+ self.text_cond, self.text_uncond = None, None
215
+
216
+ def forward(
217
+ self,
218
+ x: float["b n d"], # nosied input audio # noqa: F722
219
+ cond: float["b n d"], # masked cond audio # noqa: F722
220
+ text: int["b nt"], # text # noqa: F722
221
+ time: float["b"] | float[""], # time step # noqa: F821 F722
222
+ mask: bool["b n"] | None = None, # noqa: F722
223
+ drop_audio_cond: bool = False, # cfg for cond audio
224
+ drop_text: bool = False, # cfg for text
225
+ cfg_infer: bool = False, # cfg inference, pack cond & uncond forward
226
+ cache: bool = False,
227
+ ):
228
+ batch, seq_len = x.shape[0], x.shape[1]
229
+ if time.ndim == 0:
230
+ time = time.repeat(batch)
231
+
232
+ # t: conditioning time, c: context (text + masked cond audio), x: noised input audio
233
+ t = self.time_embed(time)
234
+ if cfg_infer: # pack cond & uncond forward: b n d -> 2b n d
235
+ x_cond = self.get_input_embed(x, cond, text, drop_audio_cond=False, drop_text=False, cache=cache)
236
+ x_uncond = self.get_input_embed(x, cond, text, drop_audio_cond=True, drop_text=True, cache=cache)
237
+ x = torch.cat((x_cond, x_uncond), dim=0)
238
+ t = torch.cat((t, t), dim=0)
239
+ mask = torch.cat((mask, mask), dim=0) if mask is not None else None
240
+ else:
241
+ x = self.get_input_embed(x, cond, text, drop_audio_cond=drop_audio_cond, drop_text=drop_text, cache=cache)
242
+
243
+ # postfix time t to input x, [b n d] -> [b n+1 d]
244
+ x = torch.cat([t.unsqueeze(1), x], dim=1) # pack t to x
245
+ if mask is not None:
246
+ mask = F.pad(mask, (1, 0), value=1)
247
+
248
+ rope = self.rotary_embed.forward_from_seq_len(seq_len + 1)
249
+
250
+ # flat unet transformer
251
+ skip_connect_type = self.skip_connect_type
252
+ skips = []
253
+ for idx, (maybe_skip_proj, attn_norm, attn, ff_norm, ff) in enumerate(self.layers):
254
+ layer = idx + 1
255
+
256
+ # skip connection logic
257
+ is_first_half = layer <= (self.depth // 2)
258
+ is_later_half = not is_first_half
259
+
260
+ if is_first_half:
261
+ skips.append(x)
262
+
263
+ if is_later_half:
264
+ skip = skips.pop()
265
+ if skip_connect_type == "concat":
266
+ x = torch.cat((x, skip), dim=-1)
267
+ x = maybe_skip_proj(x)
268
+ elif skip_connect_type == "add":
269
+ x = x + skip
270
+
271
+ # attention and feedforward blocks
272
+ x = attn(attn_norm(x), rope=rope, mask=mask) + x
273
+ x = ff(ff_norm(x)) + x
274
+
275
+ assert len(skips) == 0
276
+
277
+ x = self.norm_out(x)[:, 1:, :] # unpack t from x
278
+
279
+ return self.proj_out(x)
src/f5_tts/model/cfm.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ein notation:
3
+ b - batch
4
+ n - sequence
5
+ nt - text sequence
6
+ nw - raw wave length
7
+ d - dimension
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from random import random
13
+ from typing import Callable
14
+
15
+ import torch
16
+ import torch.nn.functional as F
17
+ from torch import nn
18
+ from torch.nn.utils.rnn import pad_sequence
19
+ from torchdiffeq import odeint
20
+
21
+ from f5_tts.model.modules import MelSpec
22
+ from f5_tts.model.utils import (
23
+ default,
24
+ exists,
25
+ get_epss_timesteps,
26
+ lens_to_mask,
27
+ list_str_to_idx,
28
+ list_str_to_tensor,
29
+ mask_from_frac_lengths,
30
+ )
31
+
32
+
33
+ class CFM(nn.Module):
34
+ def __init__(
35
+ self,
36
+ transformer: nn.Module,
37
+ sigma=0.0,
38
+ odeint_kwargs: dict = dict(
39
+ # atol = 1e-5,
40
+ # rtol = 1e-5,
41
+ method="euler" # 'midpoint'
42
+ ),
43
+ audio_drop_prob=0.3,
44
+ cond_drop_prob=0.2,
45
+ num_channels=None,
46
+ mel_spec_module: nn.Module | None = None,
47
+ mel_spec_kwargs: dict = dict(),
48
+ frac_lengths_mask: tuple[float, float] = (0.7, 1.0),
49
+ vocab_char_map: dict[str:int] | None = None,
50
+ ):
51
+ super().__init__()
52
+
53
+ self.frac_lengths_mask = frac_lengths_mask
54
+
55
+ # mel spec
56
+ self.mel_spec = default(mel_spec_module, MelSpec(**mel_spec_kwargs))
57
+ num_channels = default(num_channels, self.mel_spec.n_mel_channels)
58
+ self.num_channels = num_channels
59
+
60
+ # classifier-free guidance
61
+ self.audio_drop_prob = audio_drop_prob
62
+ self.cond_drop_prob = cond_drop_prob
63
+
64
+ # transformer
65
+ self.transformer = transformer
66
+ dim = transformer.dim
67
+ self.dim = dim
68
+
69
+ # conditional flow related
70
+ self.sigma = sigma
71
+
72
+ # sampling related
73
+ self.odeint_kwargs = odeint_kwargs
74
+
75
+ # vocab map for tokenization
76
+ self.vocab_char_map = vocab_char_map
77
+
78
+ @property
79
+ def device(self):
80
+ return next(self.parameters()).device
81
+
82
+ @torch.no_grad()
83
+ def sample(
84
+ self,
85
+ cond: float["b n d"] | float["b nw"], # noqa: F722
86
+ text: int["b nt"] | list[str], # noqa: F722
87
+ duration: int | int["b"], # noqa: F821
88
+ *,
89
+ lens: int["b"] | None = None, # noqa: F821
90
+ steps=32,
91
+ cfg_strength=1.0,
92
+ sway_sampling_coef=None,
93
+ seed: int | None = None,
94
+ max_duration=4096,
95
+ vocoder: Callable[[float["b d n"]], float["b nw"]] | None = None, # noqa: F722
96
+ use_epss=True,
97
+ no_ref_audio=False,
98
+ duplicate_test=False,
99
+ t_inter=0.1,
100
+ edit_mask=None,
101
+ ):
102
+ try:
103
+ self.eval()
104
+ # raw wave
105
+
106
+ if cond.ndim == 2:
107
+ cond = self.mel_spec(cond)
108
+ cond = cond.permute(0, 2, 1)
109
+ assert cond.shape[-1] == self.num_channels
110
+
111
+ cond = cond.to(next(self.parameters()).dtype)
112
+
113
+ batch, cond_seq_len, device = *cond.shape[:2], cond.device
114
+ if not exists(lens):
115
+ lens = torch.full((batch,), cond_seq_len, device=device, dtype=torch.long)
116
+
117
+ # text
118
+
119
+ if isinstance(text, list):
120
+ if exists(self.vocab_char_map):
121
+ text = list_str_to_idx(text, self.vocab_char_map).to(device)
122
+ else:
123
+ text = list_str_to_tensor(text).to(device)
124
+ assert text.shape[0] == batch
125
+
126
+ # duration
127
+
128
+ cond_mask = lens_to_mask(lens)
129
+ if edit_mask is not None:
130
+ cond_mask = cond_mask & edit_mask
131
+
132
+ if isinstance(duration, int):
133
+ duration = torch.full((batch,), duration, device=device, dtype=torch.long)
134
+
135
+ duration = torch.maximum(
136
+ torch.maximum((text != -1).sum(dim=-1), lens) + 1, duration
137
+ ) # duration at least text/audio prompt length plus one token, so something is generated
138
+ duration = duration.clamp(max=max_duration)
139
+ max_duration = duration.amax()
140
+
141
+ # duplicate test corner for inner time step oberservation
142
+ if duplicate_test:
143
+ test_cond = F.pad(cond, (0, 0, cond_seq_len, max_duration - 2 * cond_seq_len), value=0.0)
144
+
145
+ cond = F.pad(cond, (0, 0, 0, max_duration - cond_seq_len), value=0.0)
146
+ if no_ref_audio:
147
+ cond = torch.zeros_like(cond)
148
+
149
+ cond_mask = F.pad(cond_mask, (0, max_duration - cond_mask.shape[-1]), value=False)
150
+ cond_mask = cond_mask.unsqueeze(-1)
151
+ step_cond = torch.where(
152
+ cond_mask, cond, torch.zeros_like(cond)
153
+ ) # allow direct control (cut cond audio) with lens passed in
154
+
155
+ if batch > 1:
156
+ mask = lens_to_mask(duration)
157
+ else: # save memory and speed up, as single inference need no mask currently
158
+ mask = None
159
+
160
+ # neural ode
161
+
162
+ def fn(t, x):
163
+ # at each step, conditioning is fixed
164
+ # step_cond = torch.where(cond_mask, cond, torch.zeros_like(cond))
165
+
166
+ # predict flow (cond)
167
+ if cfg_strength < 1e-5:
168
+ pred = self.transformer(
169
+ x=x,
170
+ cond=step_cond,
171
+ text=text,
172
+ time=t,
173
+ mask=mask,
174
+ drop_audio_cond=False,
175
+ drop_text=False,
176
+ cache=True,
177
+ skip_flash_attn=True
178
+ )
179
+ return pred
180
+
181
+ # predict flow (cond and uncond), for classifier-free guidance
182
+ pred_cfg = self.transformer(
183
+ x=x,
184
+ cond=step_cond,
185
+ text=text,
186
+ time=t,
187
+ mask=mask,
188
+ cfg_infer=True,
189
+ cache=True,
190
+ skip_flash_attn=True
191
+ )
192
+ pred, null_pred = torch.chunk(pred_cfg, 2, dim=0)
193
+ return pred + (pred - null_pred) * cfg_strength
194
+
195
+ # noise input
196
+ # to make sure batch inference result is same with different batch size, and for sure single inference
197
+ # still some difference maybe due to convolutional layers
198
+ y0 = []
199
+ for dur in duration:
200
+ if exists(seed):
201
+ torch.manual_seed(seed)
202
+ y0.append(torch.randn(dur, self.num_channels, device=self.device, dtype=step_cond.dtype))
203
+ y0 = pad_sequence(y0, padding_value=0, batch_first=True)
204
+
205
+ t_start = 0
206
+
207
+ # duplicate test corner for inner time step oberservation
208
+ if duplicate_test:
209
+ t_start = t_inter
210
+ y0 = (1 - t_start) * y0 + t_start * test_cond
211
+ steps = int(steps * (1 - t_start))
212
+
213
+ if t_start == 0 and use_epss: # use Empirically Pruned Step Sampling for low NFE
214
+ t = get_epss_timesteps(steps, device=self.device, dtype=step_cond.dtype)
215
+ else:
216
+ t = torch.linspace(t_start, 1, steps + 1, device=self.device, dtype=step_cond.dtype)
217
+ if sway_sampling_coef is not None:
218
+ t = t + sway_sampling_coef * (torch.cos(torch.pi / 2 * t) - 1 + t)
219
+
220
+ trajectory = odeint(fn, y0, t, **self.odeint_kwargs)
221
+ self.transformer.clear_cache()
222
+
223
+ sampled = trajectory[-1]
224
+ out = sampled
225
+ # out = torch.where(cond_mask, cond, out)
226
+
227
+ if exists(vocoder):
228
+ out = out.permute(0, 2, 1)
229
+ out = vocoder(out)
230
+
231
+ return out, trajectory
232
+
233
+ except Exception as e:
234
+ print(f"cond shape: {cond.shape}, text shape: {text.shape if torch.is_tensor(text) else 'N/A'}, duration: {duration.shape}, lens: {lens.shape}")
235
+ print(f"cond: {cond}, text: {text}, duration: {duration}, lens: {lens}")
236
+ raise e
237
+
238
+ def forward(
239
+ self,
240
+ inp: float["b n d"] | float["b nw"], # mel or raw wave # noqa: F722
241
+ text: int["b nt"] | list[str], # noqa: F722
242
+ *,
243
+ lens: int["b"] | None = None, # noqa: F821
244
+ noise_scheduler: str | None = None,
245
+ ):
246
+ try:
247
+ # handle raw wave
248
+ # print(f"inp: {inp}, text: {text}, lens: {lens}")
249
+ if inp.ndim == 2:
250
+ inp = self.mel_spec(inp)
251
+ inp = inp.permute(0, 2, 1)
252
+ assert inp.shape[-1] == self.num_channels
253
+
254
+ batch, seq_len, dtype, device, _σ1 = *inp.shape[:2], inp.dtype, self.device, self.sigma
255
+ # handle text as string
256
+ if isinstance(text, list):
257
+ if exists(self.vocab_char_map):
258
+ text = list_str_to_idx(text, self.vocab_char_map).to(device)
259
+ else:
260
+ text = list_str_to_tensor(text).to(device)
261
+ assert text.shape[0] == batch
262
+
263
+ # lens and mask
264
+ if not exists(lens):
265
+ lens = torch.full((batch,), seq_len, device=device)
266
+
267
+
268
+ mask = lens_to_mask(lens, length=seq_len) # useless here, as collate_fn will pad to max length in batch
269
+ audio_frames_in_batch = mask.sum().item()
270
+ max_allowed_frames = mask.shape[0] * mask.shape[1]
271
+ perc_frame_utilised = audio_frames_in_batch / max_allowed_frames
272
+
273
+ # get a random span to mask out for training conditionally
274
+ frac_lengths = torch.zeros((batch,), device=self.device).float().uniform_(*self.frac_lengths_mask)
275
+ rand_span_mask = mask_from_frac_lengths(lens, frac_lengths)
276
+
277
+ if exists(mask):
278
+ rand_span_mask &= mask
279
+
280
+ # mel is x1
281
+ x1 = inp
282
+
283
+ # x0 is gaussian noise
284
+ x0 = torch.randn_like(x1)
285
+
286
+ # time step
287
+ time = torch.rand((batch,), dtype=dtype, device=self.device)
288
+ # TODO. noise_scheduler
289
+
290
+ # sample xt (φ_t(x) in the paper)
291
+ t = time.unsqueeze(-1).unsqueeze(-1)
292
+ φ = (1 - t) * x0 + t * x1
293
+ flow = x1 - x0
294
+
295
+ # only predict what is within the random mask span for infilling
296
+ cond = torch.where(rand_span_mask[..., None], torch.zeros_like(x1), x1)
297
+
298
+ # transformer and cfg training with a drop rate
299
+ drop_audio_cond = random() < self.audio_drop_prob # p_drop in voicebox paper
300
+ if random() < self.cond_drop_prob: # p_uncond in voicebox paper
301
+ drop_audio_cond = True
302
+ drop_text = True
303
+ else:
304
+ drop_text = False
305
+
306
+
307
+ # apply mask will use more memory; might adjust batchsize or batchsampler long sequence threshold
308
+ pred = self.transformer(
309
+ x=φ, cond=cond, text=text, time=time, drop_audio_cond=drop_audio_cond, drop_text=drop_text, mask=mask
310
+ )
311
+
312
+ # flow matching loss
313
+ loss = F.mse_loss(pred, flow, reduction="none")
314
+ loss = loss[rand_span_mask]
315
+
316
+ return loss.mean(), cond, pred, audio_frames_in_batch, max_allowed_frames, perc_frame_utilised, batch, seq_len
317
+ except Exception as e:
318
+ print(f"input shape: {inp.shape}, text shape: {text.shape if torch.is_tensor(text) else 'N/A'}")
319
+ print(f"input: {input}, text: {text}")
320
+ raise e
src/f5_tts/model/modules.py ADDED
@@ -0,0 +1,790 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ein notation:
3
+ b - batch
4
+ n - sequence
5
+ nt - text sequence
6
+ nw - raw wave length
7
+ d - dimension
8
+ """
9
+ # flake8: noqa
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ from typing import Optional
15
+
16
+ import torch
17
+ import torch.nn.functional as F
18
+ import torchaudio
19
+ from librosa.filters import mel as librosa_mel_fn
20
+ from torch import nn
21
+ from x_transformers.x_transformers import apply_rotary_pos_emb
22
+
23
+ from f5_tts.model.utils import is_package_available
24
+
25
+
26
+ # raw wav to mel spec
27
+
28
+
29
+ mel_basis_cache = {}
30
+ hann_window_cache = {}
31
+
32
+
33
+ def get_bigvgan_mel_spectrogram(
34
+ waveform,
35
+ n_fft=1024,
36
+ n_mel_channels=100,
37
+ target_sample_rate=24000,
38
+ hop_length=256,
39
+ win_length=1024,
40
+ fmin=0,
41
+ fmax=None,
42
+ center=False,
43
+ ): # Copy from https://github.com/NVIDIA/BigVGAN/tree/main
44
+ device = waveform.device
45
+ key = f"{n_fft}_{n_mel_channels}_{target_sample_rate}_{hop_length}_{win_length}_{fmin}_{fmax}_{device}"
46
+
47
+ if key not in mel_basis_cache:
48
+ mel = librosa_mel_fn(sr=target_sample_rate, n_fft=n_fft, n_mels=n_mel_channels, fmin=fmin, fmax=fmax)
49
+ mel_basis_cache[key] = torch.from_numpy(mel).float().to(device) # TODO: why they need .float()?
50
+ hann_window_cache[key] = torch.hann_window(win_length).to(device)
51
+
52
+ mel_basis = mel_basis_cache[key]
53
+ hann_window = hann_window_cache[key]
54
+
55
+ padding = (n_fft - hop_length) // 2
56
+ waveform = torch.nn.functional.pad(waveform.unsqueeze(1), (padding, padding), mode="reflect").squeeze(1)
57
+
58
+ spec = torch.stft(
59
+ waveform,
60
+ n_fft,
61
+ hop_length=hop_length,
62
+ win_length=win_length,
63
+ window=hann_window,
64
+ center=center,
65
+ pad_mode="reflect",
66
+ normalized=False,
67
+ onesided=True,
68
+ return_complex=True,
69
+ )
70
+ spec = torch.sqrt(torch.view_as_real(spec).pow(2).sum(-1) + 1e-9)
71
+
72
+ mel_spec = torch.matmul(mel_basis, spec)
73
+ mel_spec = torch.log(torch.clamp(mel_spec, min=1e-5))
74
+
75
+ return mel_spec
76
+
77
+
78
+ def get_vocos_mel_spectrogram(
79
+ waveform,
80
+ n_fft=1024,
81
+ n_mel_channels=100,
82
+ target_sample_rate=24000,
83
+ hop_length=256,
84
+ win_length=1024,
85
+ ):
86
+ mel_stft = torchaudio.transforms.MelSpectrogram(
87
+ sample_rate=target_sample_rate,
88
+ n_fft=n_fft,
89
+ win_length=win_length,
90
+ hop_length=hop_length,
91
+ n_mels=n_mel_channels,
92
+ power=1,
93
+ center=True,
94
+ normalized=False,
95
+ norm=None,
96
+ ).to(waveform.device)
97
+ if len(waveform.shape) == 3:
98
+ waveform = waveform.squeeze(1) # 'b 1 nw -> b nw'
99
+
100
+ assert len(waveform.shape) == 2
101
+
102
+ mel = mel_stft(waveform)
103
+ mel = mel.clamp(min=1e-5).log()
104
+ return mel
105
+
106
+
107
+ class MelSpec(nn.Module):
108
+ def __init__(
109
+ self,
110
+ n_fft=1024,
111
+ hop_length=256,
112
+ win_length=1024,
113
+ n_mel_channels=100,
114
+ target_sample_rate=24_000,
115
+ mel_spec_type="vocos",
116
+ ):
117
+ super().__init__()
118
+ assert mel_spec_type in ["vocos", "bigvgan"], print("We only support two extract mel backend: vocos or bigvgan")
119
+
120
+ self.n_fft = n_fft
121
+ self.hop_length = hop_length
122
+ self.win_length = win_length
123
+ self.n_mel_channels = n_mel_channels
124
+ self.target_sample_rate = target_sample_rate
125
+
126
+ if mel_spec_type == "vocos":
127
+ self.extractor = get_vocos_mel_spectrogram
128
+ elif mel_spec_type == "bigvgan":
129
+ self.extractor = get_bigvgan_mel_spectrogram
130
+
131
+ self.register_buffer("dummy", torch.tensor(0), persistent=False)
132
+
133
+ def forward(self, wav):
134
+ if self.dummy.device != wav.device:
135
+ self.to(wav.device)
136
+
137
+ # Handle stereo/multi-channel audio
138
+ if len(wav.shape) == 3: # (B, C, T)
139
+ if wav.shape[1] > 1:
140
+ wav = torch.mean(wav, dim=1, keepdim=True)
141
+ elif len(wav.shape) == 2: # (C, T) or (B, T)
142
+ # We assume if it's 2D and shape[0] > 1 and not usually a batch size, it might be stereo
143
+ # But better to be explicit in what extractors expect.
144
+ # Most extractors here expect (B, T) after potential squeeze.
145
+ pass
146
+
147
+ mel = self.extractor(
148
+ waveform=wav,
149
+ n_fft=self.n_fft,
150
+ n_mel_channels=self.n_mel_channels,
151
+ target_sample_rate=self.target_sample_rate,
152
+ hop_length=self.hop_length,
153
+ win_length=self.win_length,
154
+ )
155
+
156
+ return mel
157
+
158
+
159
+ # sinusoidal position embedding
160
+
161
+
162
+ class SinusPositionEmbedding(nn.Module):
163
+ def __init__(self, dim):
164
+ super().__init__()
165
+ self.dim = dim
166
+
167
+ def forward(self, x, scale=1000):
168
+ device = x.device
169
+ half_dim = self.dim // 2
170
+ emb = math.log(10000) / (half_dim - 1)
171
+ emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb)
172
+ emb = scale * x.unsqueeze(1) * emb.unsqueeze(0)
173
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
174
+ return emb
175
+
176
+
177
+ # convolutional position embedding
178
+
179
+
180
+ class ConvPositionEmbedding(nn.Module):
181
+ def __init__(self, dim, kernel_size=31, groups=16):
182
+ super().__init__()
183
+ assert kernel_size % 2 != 0
184
+ self.conv1d = nn.Sequential(
185
+ nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=kernel_size // 2),
186
+ nn.Mish(),
187
+ nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=kernel_size // 2),
188
+ nn.Mish(),
189
+ )
190
+
191
+ def forward(self, x: float["b n d"], mask: bool["b n"] | None = None):
192
+ if mask is not None:
193
+ mask = mask[..., None]
194
+ x = x.masked_fill(~mask, 0.0)
195
+
196
+ x = x.permute(0, 2, 1)
197
+ x = self.conv1d(x)
198
+ out = x.permute(0, 2, 1)
199
+
200
+ if mask is not None:
201
+ out = out.masked_fill(~mask, 0.0)
202
+
203
+ return out
204
+
205
+
206
+ # rotary positional embedding related
207
+
208
+
209
+ def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0, theta_rescale_factor=1.0):
210
+ # proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning
211
+ # has some connection to NTK literature
212
+ # https://www.reddit.com/r/LocalLLaMA/comments/14lz7j5/ntkaware_scaled_rope_allows_llama_models_to_have/
213
+ # https://github.com/lucidrains/rotary-embedding-torch/blob/main/rotary_embedding_torch/rotary_embedding_torch.py
214
+ theta *= theta_rescale_factor ** (dim / (dim - 2))
215
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
216
+ t = torch.arange(end, device=freqs.device) # type: ignore
217
+ freqs = torch.outer(t, freqs).float() # type: ignore
218
+ freqs_cos = torch.cos(freqs) # real part
219
+ freqs_sin = torch.sin(freqs) # imaginary part
220
+ return torch.cat([freqs_cos, freqs_sin], dim=-1)
221
+
222
+
223
+ def get_pos_embed_indices(start, length, max_pos, scale=1.0):
224
+ # length = length if isinstance(length, int) else length.max()
225
+ scale = scale * torch.ones_like(start, dtype=torch.float32) # in case scale is a scalar
226
+ pos = (
227
+ start.unsqueeze(1)
228
+ + (torch.arange(length, device=start.device, dtype=torch.float32).unsqueeze(0) * scale.unsqueeze(1)).long()
229
+ )
230
+ # avoid extra long error.
231
+ pos = torch.where(pos < max_pos, pos, max_pos - 1)
232
+ return pos
233
+
234
+
235
+ # Global Response Normalization layer (Instance Normalization ?)
236
+
237
+
238
+ class GRN(nn.Module):
239
+ def __init__(self, dim):
240
+ super().__init__()
241
+ self.gamma = nn.Parameter(torch.zeros(1, 1, dim))
242
+ self.beta = nn.Parameter(torch.zeros(1, 1, dim))
243
+
244
+ def forward(self, x):
245
+ Gx = torch.norm(x, p=2, dim=1, keepdim=True)
246
+ Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6)
247
+ return self.gamma * (x * Nx) + self.beta + x
248
+
249
+
250
+ # ConvNeXt-V2 Block https://github.com/facebookresearch/ConvNeXt-V2/blob/main/models/convnextv2.py
251
+ # ref: https://github.com/bfs18/e2_tts/blob/main/rfwave/modules.py#L108
252
+
253
+
254
+ class ConvNeXtV2Block(nn.Module):
255
+ def __init__(
256
+ self,
257
+ dim: int,
258
+ intermediate_dim: int,
259
+ dilation: int = 1,
260
+ ):
261
+ super().__init__()
262
+ padding = (dilation * (7 - 1)) // 2
263
+ self.dwconv = nn.Conv1d(
264
+ dim, dim, kernel_size=7, padding=padding, groups=dim, dilation=dilation
265
+ ) # depthwise conv
266
+ self.norm = nn.LayerNorm(dim, eps=1e-6)
267
+ self.pwconv1 = nn.Linear(dim, intermediate_dim) # pointwise/1x1 convs, implemented with linear layers
268
+ self.act = nn.GELU()
269
+ self.grn = GRN(intermediate_dim)
270
+ self.pwconv2 = nn.Linear(intermediate_dim, dim)
271
+
272
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
273
+ residual = x
274
+ x = x.transpose(1, 2) # b n d -> b d n
275
+ x = self.dwconv(x)
276
+ x = x.transpose(1, 2) # b d n -> b n d
277
+ x = self.norm(x)
278
+ x = self.pwconv1(x)
279
+ x = self.act(x)
280
+ x = self.grn(x)
281
+ x = self.pwconv2(x)
282
+ return residual + x
283
+
284
+ # RMSNorm
285
+
286
+
287
+ class RMSNorm(nn.Module):
288
+ def __init__(self, dim: int, eps: float):
289
+ super().__init__()
290
+ self.eps = eps
291
+ self.weight = nn.Parameter(torch.ones(dim))
292
+ self.native_rms_norm = float(torch.__version__[:3]) >= 2.4
293
+
294
+ def forward(self, x):
295
+ if self.native_rms_norm:
296
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
297
+ x = x.to(self.weight.dtype)
298
+ x = F.rms_norm(x, normalized_shape=(x.shape[-1],), weight=self.weight, eps=self.eps)
299
+ else:
300
+ variance = x.to(torch.float32).pow(2).mean(-1, keepdim=True)
301
+ x = x * torch.rsqrt(variance + self.eps)
302
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
303
+ x = x.to(self.weight.dtype)
304
+ x = x * self.weight
305
+
306
+ return x
307
+
308
+
309
+ # AdaLayerNorm
310
+ # return with modulated x for attn input, and params for later mlp modulation
311
+
312
+
313
+ class AdaLayerNorm(nn.Module):
314
+ def __init__(self, dim):
315
+ super().__init__()
316
+
317
+ self.silu = nn.SiLU()
318
+ self.linear = nn.Linear(dim, dim * 6)
319
+
320
+ self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
321
+
322
+ def forward(self, x, emb=None):
323
+ emb = self.linear(self.silu(emb))
324
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = torch.chunk(emb, 6, dim=1)
325
+
326
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
327
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
328
+
329
+
330
+ # AdaLayerNorm for final layer
331
+ # return only with modulated x for attn input, cuz no more mlp modulation
332
+
333
+
334
+ class AdaLayerNorm_Final(nn.Module):
335
+ def __init__(self, dim):
336
+ super().__init__()
337
+
338
+ self.silu = nn.SiLU()
339
+ self.linear = nn.Linear(dim, dim * 2)
340
+
341
+ self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
342
+
343
+ def forward(self, x, emb):
344
+ emb = self.linear(self.silu(emb))
345
+ scale, shift = torch.chunk(emb, 2, dim=1)
346
+
347
+ x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
348
+ return x
349
+
350
+
351
+ # FeedForward
352
+
353
+
354
+ class FeedForward(nn.Module):
355
+ def __init__(self, dim, dim_out=None, mult=4, dropout=0.0, approximate: str = "none"):
356
+ super().__init__()
357
+ inner_dim = int(dim * mult)
358
+ dim_out = dim_out if dim_out is not None else dim
359
+
360
+ activation = nn.GELU(approximate=approximate)
361
+ project_in = nn.Sequential(nn.Linear(dim, inner_dim), activation)
362
+ self.ff = nn.Sequential(project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out))
363
+
364
+ def forward(self, x):
365
+ return self.ff(x)
366
+
367
+
368
+ # Attention with possible joint part
369
+ # modified from diffusers/src/diffusers/models/attention_processor.py
370
+
371
+
372
+ class Attention(nn.Module):
373
+ def __init__(
374
+ self,
375
+ processor: JointAttnProcessor | AttnProcessor,
376
+ dim: int,
377
+ heads: int = 8,
378
+ dim_head: int = 64,
379
+ dropout: float = 0.0,
380
+ context_dim: Optional[int] = None, # if not None -> joint attention
381
+ context_pre_only: bool = False,
382
+ qk_norm: Optional[str] = None,
383
+ ):
384
+ super().__init__()
385
+
386
+ if not hasattr(F, "scaled_dot_product_attention"):
387
+ raise ImportError("Attention equires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
388
+
389
+ self.processor = processor
390
+
391
+ self.dim = dim
392
+ self.heads = heads
393
+ self.inner_dim = dim_head * heads
394
+ self.dropout = dropout
395
+
396
+ self.context_dim = context_dim
397
+ self.context_pre_only = context_pre_only
398
+
399
+ self.to_q = nn.Linear(dim, self.inner_dim)
400
+ self.to_k = nn.Linear(dim, self.inner_dim)
401
+ self.to_v = nn.Linear(dim, self.inner_dim)
402
+
403
+ if qk_norm is None:
404
+ self.q_norm = None
405
+ self.k_norm = None
406
+ elif qk_norm == "rms_norm":
407
+ self.q_norm = RMSNorm(dim_head, eps=1e-6)
408
+ self.k_norm = RMSNorm(dim_head, eps=1e-6)
409
+ else:
410
+ raise ValueError(f"Unimplemented qk_norm: {qk_norm}")
411
+
412
+ if self.context_dim is not None:
413
+ self.to_q_c = nn.Linear(context_dim, self.inner_dim)
414
+ self.to_k_c = nn.Linear(context_dim, self.inner_dim)
415
+ self.to_v_c = nn.Linear(context_dim, self.inner_dim)
416
+ if qk_norm is None:
417
+ self.c_q_norm = None
418
+ self.c_k_norm = None
419
+ elif qk_norm == "rms_norm":
420
+ self.c_q_norm = RMSNorm(dim_head, eps=1e-6)
421
+ self.c_k_norm = RMSNorm(dim_head, eps=1e-6)
422
+
423
+ self.to_out = nn.ModuleList([])
424
+ self.to_out.append(nn.Linear(self.inner_dim, dim))
425
+ self.to_out.append(nn.Dropout(dropout))
426
+
427
+ if self.context_dim is not None and not self.context_pre_only:
428
+ self.to_out_c = nn.Linear(self.inner_dim, context_dim)
429
+
430
+ def forward(
431
+ self,
432
+ x: float["b n d"], # noised input x
433
+ c: float["b n d"] = None, # context c
434
+ mask: bool["b n"] | None = None,
435
+ rope=None, # rotary position embedding for x
436
+ c_rope=None, # rotary position embedding for c
437
+ skip_flash_attn: bool = False,
438
+ ) -> torch.Tensor:
439
+ if c is not None:
440
+ return self.processor(self, x, c=c, mask=mask, rope=rope, c_rope=c_rope, skip_flash_attn=skip_flash_attn)
441
+ else:
442
+ return self.processor(self, x, mask=mask, rope=rope, skip_flash_attn=skip_flash_attn)
443
+
444
+
445
+ class AttnProcessor:
446
+ def __init__(
447
+ self,
448
+ pe_attn_head: int | None = None, # number of attention head to apply rope, None for all
449
+ attn_backend: str = "torch", # "torch" or "flash_attn"
450
+ attn_mask_enabled: bool = True,
451
+ ):
452
+ if attn_backend == "flash_attn":
453
+ assert is_package_available("flash_attn"), "Please install flash-attn first."
454
+ from flash_attn.bert_padding import pad_input, unpad_input
455
+ from flash_attn import flash_attn_varlen_func, flash_attn_func
456
+
457
+ self.pe_attn_head = pe_attn_head
458
+ self.attn_backend = attn_backend
459
+ self.attn_mask_enabled = attn_mask_enabled
460
+
461
+ def __call__(
462
+ self,
463
+ attn: Attention,
464
+ x: float["b n d"], # noised input x
465
+ mask: bool["b n"] | None = None,
466
+ rope=None, # rotary position embedding,
467
+ skip_flash_attn: bool = False,
468
+ ) -> torch.FloatTensor:
469
+ batch_size = x.shape[0]
470
+
471
+ # `sample` projections
472
+ query = attn.to_q(x)
473
+ key = attn.to_k(x)
474
+ value = attn.to_v(x)
475
+
476
+ # attention
477
+ inner_dim = key.shape[-1]
478
+ head_dim = inner_dim // attn.heads
479
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
480
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
481
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
482
+
483
+ # qk norm
484
+ if attn.q_norm is not None:
485
+ query = attn.q_norm(query)
486
+ if attn.k_norm is not None:
487
+ key = attn.k_norm(key)
488
+
489
+ # apply rotary position embedding
490
+ if rope is not None:
491
+ freqs, xpos_scale = rope
492
+ q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
493
+
494
+ if self.pe_attn_head is not None:
495
+ pn = self.pe_attn_head
496
+ query[:, :pn, :, :] = apply_rotary_pos_emb(query[:, :pn, :, :], freqs, q_xpos_scale)
497
+ key[:, :pn, :, :] = apply_rotary_pos_emb(key[:, :pn, :, :], freqs, k_xpos_scale)
498
+ else:
499
+ query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
500
+ key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
501
+
502
+ if skip_flash_attn or self.attn_backend == "torch":
503
+ # mask. e.g. inference got a batch with different target durations, mask out the padding
504
+ if self.attn_mask_enabled and mask is not None:
505
+ attn_mask = mask
506
+ attn_mask = attn_mask.unsqueeze(1).unsqueeze(1) # 'b n -> b 1 1 n'
507
+ attn_mask = attn_mask.expand(batch_size, attn.heads, query.shape[-2], key.shape[-2])
508
+ else:
509
+ attn_mask = None
510
+ x = F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, dropout_p=0.0, is_causal=False)
511
+ x = x.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
512
+
513
+ elif self.attn_backend == "flash_attn":
514
+ query = query.transpose(1, 2) # [b, h, n, d] -> [b, n, h, d]
515
+ key = key.transpose(1, 2)
516
+ value = value.transpose(1, 2)
517
+ if self.attn_mask_enabled and mask is not None:
518
+ query, indices, q_cu_seqlens, q_max_seqlen_in_batch, _ = unpad_input(query, mask)
519
+ key, _, k_cu_seqlens, k_max_seqlen_in_batch, _ = unpad_input(key, mask)
520
+ value, _, _, _, _ = unpad_input(value, mask)
521
+ x = flash_attn_varlen_func(
522
+ query,
523
+ key,
524
+ value,
525
+ q_cu_seqlens,
526
+ k_cu_seqlens,
527
+ q_max_seqlen_in_batch,
528
+ k_max_seqlen_in_batch,
529
+ )
530
+ x = pad_input(x, indices, batch_size, q_max_seqlen_in_batch)
531
+ x = x.reshape(batch_size, -1, attn.heads * head_dim)
532
+ else:
533
+ x = flash_attn_func(query, key, value, dropout_p=0.0, causal=False)
534
+ x = x.reshape(batch_size, -1, attn.heads * head_dim)
535
+
536
+ x = x.to(query.dtype)
537
+
538
+ # linear proj
539
+ x = attn.to_out[0](x)
540
+ # dropout
541
+ x = attn.to_out[1](x)
542
+
543
+ if mask is not None:
544
+ mask = mask.unsqueeze(-1)
545
+ x = x.masked_fill(~mask, 0.0)
546
+
547
+ return x
548
+
549
+
550
+ # Joint Attention processor for MM-DiT
551
+ # modified from diffusers/src/diffusers/models/attention_processor.py
552
+
553
+
554
+ class JointAttnProcessor:
555
+ def __init__(self):
556
+ pass
557
+
558
+ def __call__(
559
+ self,
560
+ attn: Attention,
561
+ x: float["b n d"], # noised input x
562
+ c: float["b nt d"] = None, # context c, here text
563
+ mask: bool["b n"] | None = None,
564
+ rope=None, # rotary position embedding for x
565
+ c_rope=None, # rotary position embedding for c
566
+ ) -> torch.FloatTensor:
567
+ residual = x
568
+
569
+ batch_size = c.shape[0]
570
+
571
+ # `sample` projections
572
+ query = attn.to_q(x)
573
+ key = attn.to_k(x)
574
+ value = attn.to_v(x)
575
+
576
+ # `context` projections
577
+ c_query = attn.to_q_c(c)
578
+ c_key = attn.to_k_c(c)
579
+ c_value = attn.to_v_c(c)
580
+
581
+ # attention
582
+ inner_dim = key.shape[-1]
583
+ head_dim = inner_dim // attn.heads
584
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
585
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
586
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
587
+ c_query = c_query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
588
+ c_key = c_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
589
+ c_value = c_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
590
+
591
+ # qk norm
592
+ if attn.q_norm is not None:
593
+ query = attn.q_norm(query)
594
+ if attn.k_norm is not None:
595
+ key = attn.k_norm(key)
596
+ if attn.c_q_norm is not None:
597
+ c_query = attn.c_q_norm(c_query)
598
+ if attn.c_k_norm is not None:
599
+ c_key = attn.c_k_norm(c_key)
600
+
601
+ # apply rope for context and noised input independently
602
+ if rope is not None:
603
+ freqs, xpos_scale = rope
604
+ q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
605
+ query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
606
+ key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
607
+ if c_rope is not None:
608
+ freqs, xpos_scale = c_rope
609
+ q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
610
+ c_query = apply_rotary_pos_emb(c_query, freqs, q_xpos_scale)
611
+ c_key = apply_rotary_pos_emb(c_key, freqs, k_xpos_scale)
612
+
613
+ # joint attention
614
+ query = torch.cat([query, c_query], dim=2)
615
+ key = torch.cat([key, c_key], dim=2)
616
+ value = torch.cat([value, c_value], dim=2)
617
+
618
+ # mask. e.g. inference got a batch with different target durations, mask out the padding
619
+ if mask is not None:
620
+ attn_mask = F.pad(mask, (0, c.shape[1]), value=True) # no mask for c (text)
621
+ attn_mask = attn_mask.unsqueeze(1).unsqueeze(1) # 'b n -> b 1 1 n'
622
+ attn_mask = attn_mask.expand(batch_size, attn.heads, query.shape[-2], key.shape[-2])
623
+ else:
624
+ attn_mask = None
625
+
626
+ x = F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, dropout_p=0.0, is_causal=False)
627
+ x = x.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
628
+ x = x.to(query.dtype)
629
+
630
+ # Split the attention outputs.
631
+ x, c = (
632
+ x[:, : residual.shape[1]],
633
+ x[:, residual.shape[1] :],
634
+ )
635
+
636
+ # linear proj
637
+ x = attn.to_out[0](x)
638
+ # dropout
639
+ x = attn.to_out[1](x)
640
+ if not attn.context_pre_only:
641
+ c = attn.to_out_c(c)
642
+
643
+ if mask is not None:
644
+ mask = mask.unsqueeze(-1)
645
+ x = x.masked_fill(~mask, 0.0)
646
+ # c = c.masked_fill(~mask, 0.) # no mask for c (text)
647
+
648
+ return x, c
649
+
650
+
651
+ # DiT Block
652
+
653
+
654
+ class DiTBlock(nn.Module):
655
+ def __init__(
656
+ self,
657
+ dim,
658
+ heads,
659
+ dim_head,
660
+ ff_mult=4,
661
+ dropout=0.1,
662
+ qk_norm=None,
663
+ pe_attn_head=None,
664
+ attn_backend="torch", # "torch" or "flash_attn"
665
+ attn_mask_enabled=True,
666
+ ):
667
+ super().__init__()
668
+
669
+ self.attn_norm = AdaLayerNorm(dim)
670
+ self.attn = Attention(
671
+ processor=AttnProcessor(
672
+ pe_attn_head=pe_attn_head,
673
+ attn_backend=attn_backend,
674
+ attn_mask_enabled=attn_mask_enabled,
675
+ ),
676
+ dim=dim,
677
+ heads=heads,
678
+ dim_head=dim_head,
679
+ dropout=dropout,
680
+ qk_norm=qk_norm,
681
+ )
682
+
683
+ self.ff_norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
684
+ self.ff = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh")
685
+
686
+ def forward(self, x, t, mask=None, rope=None, skip_flash_attn: bool = False,): # x: noised input, t: time embedding
687
+ # pre-norm & modulation for attention input
688
+ norm, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.attn_norm(x, emb=t)
689
+
690
+ # attention
691
+ attn_output = self.attn(x=norm, mask=mask, rope=rope, skip_flash_attn=skip_flash_attn)
692
+
693
+ # process attention output for input x
694
+ x = x + gate_msa.unsqueeze(1) * attn_output
695
+
696
+ norm = self.ff_norm(x) * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
697
+ ff_output = self.ff(norm)
698
+ x = x + gate_mlp.unsqueeze(1) * ff_output
699
+
700
+ return x
701
+
702
+
703
+ # MMDiT Block https://arxiv.org/abs/2403.03206
704
+
705
+
706
+ class MMDiTBlock(nn.Module):
707
+ r"""
708
+ modified from diffusers/src/diffusers/models/attention.py
709
+
710
+ notes.
711
+ _c: context related. text, cond, etc. (left part in sd3 fig2.b)
712
+ _x: noised input related. (right part)
713
+ context_pre_only: last layer only do prenorm + modulation cuz no more ffn
714
+ """
715
+
716
+ def __init__(
717
+ self, dim, heads, dim_head, ff_mult=4, dropout=0.1, context_dim=None, context_pre_only=False, qk_norm=None
718
+ ):
719
+ super().__init__()
720
+ if context_dim is None:
721
+ context_dim = dim
722
+ self.context_pre_only = context_pre_only
723
+
724
+ self.attn_norm_c = AdaLayerNorm_Final(context_dim) if context_pre_only else AdaLayerNorm(context_dim)
725
+ self.attn_norm_x = AdaLayerNorm(dim)
726
+ self.attn = Attention(
727
+ processor=JointAttnProcessor(),
728
+ dim=dim,
729
+ heads=heads,
730
+ dim_head=dim_head,
731
+ dropout=dropout,
732
+ context_dim=context_dim,
733
+ context_pre_only=context_pre_only,
734
+ qk_norm=qk_norm,
735
+ )
736
+
737
+ if not context_pre_only:
738
+ self.ff_norm_c = nn.LayerNorm(context_dim, elementwise_affine=False, eps=1e-6)
739
+ self.ff_c = FeedForward(dim=context_dim, mult=ff_mult, dropout=dropout, approximate="tanh")
740
+ else:
741
+ self.ff_norm_c = None
742
+ self.ff_c = None
743
+ self.ff_norm_x = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
744
+ self.ff_x = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh")
745
+
746
+ def forward(self, x, c, t, mask=None, rope=None, c_rope=None): # x: noised input, c: context, t: time embedding
747
+ # pre-norm & modulation for attention input
748
+ if self.context_pre_only:
749
+ norm_c = self.attn_norm_c(c, t)
750
+ else:
751
+ norm_c, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.attn_norm_c(c, emb=t)
752
+ norm_x, x_gate_msa, x_shift_mlp, x_scale_mlp, x_gate_mlp = self.attn_norm_x(x, emb=t)
753
+
754
+ # attention
755
+ x_attn_output, c_attn_output = self.attn(x=norm_x, c=norm_c, mask=mask, rope=rope, c_rope=c_rope)
756
+
757
+ # process attention output for context c
758
+ if self.context_pre_only:
759
+ c = None
760
+ else: # if not last layer
761
+ c = c + c_gate_msa.unsqueeze(1) * c_attn_output
762
+
763
+ norm_c = self.ff_norm_c(c) * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
764
+ c_ff_output = self.ff_c(norm_c)
765
+ c = c + c_gate_mlp.unsqueeze(1) * c_ff_output
766
+
767
+ # process attention output for input x
768
+ x = x + x_gate_msa.unsqueeze(1) * x_attn_output
769
+
770
+ norm_x = self.ff_norm_x(x) * (1 + x_scale_mlp[:, None]) + x_shift_mlp[:, None]
771
+ x_ff_output = self.ff_x(norm_x)
772
+ x = x + x_gate_mlp.unsqueeze(1) * x_ff_output
773
+
774
+ return c, x
775
+
776
+
777
+ # time step conditioning embedding
778
+
779
+
780
+ class TimestepEmbedding(nn.Module):
781
+ def __init__(self, dim, freq_embed_dim=256):
782
+ super().__init__()
783
+ self.time_embed = SinusPositionEmbedding(freq_embed_dim)
784
+ self.time_mlp = nn.Sequential(nn.Linear(freq_embed_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
785
+
786
+ def forward(self, timestep: float["b"]):
787
+ time_hidden = self.time_embed(timestep)
788
+ time_hidden = time_hidden.to(timestep.dtype)
789
+ time = self.time_mlp(time_hidden) # b d
790
+ return time
src/f5_tts/model/utils.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import random
5
+ from collections import defaultdict
6
+ from importlib.resources import files
7
+ from typing import List, Union
8
+
9
+ import jieba
10
+ import torch
11
+ from pypinyin import Style, lazy_pinyin
12
+ from torch.nn.utils.rnn import pad_sequence
13
+ import requests
14
+ import json
15
+ import socket
16
+ import subprocess
17
+ from datetime import datetime
18
+
19
+
20
+ # seed everything
21
+
22
+
23
+ def seed_everything(seed=0):
24
+ random.seed(seed)
25
+ os.environ["PYTHONHASHSEED"] = str(seed)
26
+ torch.manual_seed(seed)
27
+ torch.cuda.manual_seed(seed)
28
+ torch.cuda.manual_seed_all(seed)
29
+ torch.backends.cudnn.deterministic = True
30
+ torch.backends.cudnn.benchmark = False
31
+
32
+
33
+ # helpers
34
+
35
+
36
+ def exists(v):
37
+ return v is not None
38
+
39
+
40
+ def default(v, d):
41
+ return v if exists(v) else d
42
+
43
+
44
+ def is_package_available(package_name: str) -> bool:
45
+ try:
46
+ import importlib
47
+
48
+ package_exists = importlib.util.find_spec(package_name) is not None
49
+ return package_exists
50
+ except Exception:
51
+ return False
52
+
53
+
54
+ # tensor helpers
55
+
56
+
57
+ def lens_to_mask(t: int["b"], length: int | None = None) -> bool["b n"]: # noqa: F722 F821
58
+ if not exists(length):
59
+ length = t.amax()
60
+
61
+ seq = torch.arange(length, device=t.device)
62
+ return seq[None, :] < t[:, None]
63
+
64
+
65
+ def mask_from_start_end_indices(seq_len: int["b"], start: int["b"], end: int["b"]): # noqa: F722 F821
66
+ max_seq_len = seq_len.max().item()
67
+ seq = torch.arange(max_seq_len, device=start.device).long()
68
+ start_mask = seq[None, :] >= start[:, None]
69
+ end_mask = seq[None, :] < end[:, None]
70
+ return start_mask & end_mask
71
+
72
+
73
+ def mask_from_frac_lengths(seq_len: int["b"], frac_lengths: float["b"]): # noqa: F722 F821
74
+ lengths = (frac_lengths * seq_len).long()
75
+ max_start = seq_len - lengths
76
+
77
+ rand = torch.rand_like(frac_lengths)
78
+ start = (max_start * rand).long().clamp(min=0)
79
+ end = start + lengths
80
+
81
+ return mask_from_start_end_indices(seq_len, start, end)
82
+
83
+
84
+ def maybe_masked_mean(t: float["b n d"], mask: bool["b n"] = None) -> float["b d"]: # noqa: F722
85
+ if not exists(mask):
86
+ return t.mean(dim=1)
87
+
88
+ t = torch.where(mask[:, :, None], t, torch.tensor(0.0, device=t.device))
89
+ num = t.sum(dim=1)
90
+ den = mask.float().sum(dim=1)
91
+
92
+ return num / den.clamp(min=1.0)
93
+
94
+
95
+ # simple utf-8 tokenizer, since paper went character based
96
+ def list_str_to_tensor(text: list[str], padding_value=-1) -> int["b nt"]: # noqa: F722
97
+ list_tensors = [torch.tensor([*bytes(t, "UTF-8")]) for t in text] # ByT5 style
98
+ text = pad_sequence(list_tensors, padding_value=padding_value, batch_first=True)
99
+ return text
100
+
101
+
102
+ # char tokenizer, based on custom dataset's extracted .txt file
103
+ def list_str_to_idx(
104
+ text: list[str] | list[list[str]],
105
+ vocab_char_map: dict[str, int], # {char: idx}
106
+ padding_value=-1,
107
+ ) -> int["b nt"]: # noqa: F722
108
+ list_idx_tensors = [torch.tensor([vocab_char_map.get(c, 0) for c in t]) for t in text] # pinyin or char style
109
+ text = pad_sequence(list_idx_tensors, padding_value=padding_value, batch_first=True)
110
+ return text
111
+
112
+ # Get tokenizer
113
+
114
+ def _get_tokenizer(dataset_name, tokenizer, extra_vocab_path: str = None):
115
+ """
116
+ tokenizer - "pinyin" do g2p for only chinese characters, need .txt vocab_file
117
+ - "char" for char-wise tokenizer, need .txt vocab_file
118
+ - "byte" for utf-8 tokenizer
119
+ - "custom" if you're directly passing in a path to the vocab.txt you want to use
120
+ vocab_size - if use "pinyin", all available pinyin types, common alphabets (also those with accent) and symbols
121
+ - if use "char", derived from unfiltered character & symbol counts of custom dataset
122
+ - if use "byte", set to 256 (unicode byte range)
123
+ extra_vocab_path - path to txt file containing additional characters (one per line) to expand vocabulary
124
+ """
125
+
126
+ if tokenizer in ["pinyin", "char", "cls"]:
127
+ tokenizer_path = os.path.join(files("f5_tts").joinpath("../../data"), f"{dataset_name}_{tokenizer}/vocab.txt")
128
+ with open(tokenizer_path, "r", encoding="utf-8") as f:
129
+ vocab_char_map = {}
130
+ for i, char in enumerate(f):
131
+ vocab_char_map[char[:-1]] = i
132
+ vocab_size = len(vocab_char_map)
133
+ assert vocab_char_map[" "] == 0, "make sure space is of idx 0 in vocab.txt, cuz 0 is used for unknown char"
134
+
135
+ elif tokenizer == "byte":
136
+ vocab_char_map = None
137
+ vocab_size = 256
138
+
139
+ elif tokenizer == "custom":
140
+ with open(dataset_name, "r", encoding="utf-8") as f:
141
+ vocab_char_map = {}
142
+ for i, char in enumerate(f):
143
+ vocab_char_map[char[:-1]] = i
144
+ vocab_size = len(vocab_char_map)
145
+
146
+ # Load and merge extra vocabulary from txt file
147
+ if extra_vocab_path is not None and os.path.exists(extra_vocab_path):
148
+ if vocab_char_map is not None: # Only extend if not byte tokenizer
149
+ current_vocab_size = len(vocab_char_map)
150
+ with open(extra_vocab_path, "r", encoding="utf-8") as f:
151
+ for char in f:
152
+ char = char.strip()
153
+ if char and char not in vocab_char_map:
154
+ vocab_char_map[char] = len(vocab_char_map)
155
+ vocab_size = len(vocab_char_map)
156
+ print(f"Extended vocabulary with {vocab_size - current_vocab_size} new tokens from {extra_vocab_path}")
157
+
158
+ return vocab_char_map, vocab_size
159
+
160
+
161
+
162
+ def get_tokenizer(dataset_name, tokenizer: str | List[str], extra_vocab_path: str = None):
163
+ """
164
+ Return a dictionary of tokenizers if tokenizer is a list, each key is the tokenizer name and value is a tuple of (vocab_char_map, vocab_size)
165
+ Otherwise, return a dictionary with single tokenizer entry
166
+ """
167
+
168
+ if isinstance(tokenizer, list):
169
+ tokenizers_dict = {}
170
+ for t_name in tokenizer:
171
+ vocab_char_map, vocab_size = _get_tokenizer(dataset_name, t_name, extra_vocab_path)
172
+ tokenizers_dict[t_name] = (vocab_char_map, vocab_size) # Fixed: was using 't' instead of 't_name'
173
+ return tokenizers_dict
174
+ else:
175
+ vocab_char_map, vocab_size = _get_tokenizer(dataset_name, tokenizer, extra_vocab_path)
176
+ return vocab_char_map, vocab_size
177
+
178
+ def save_vocab(vocab_char_map, save_path):
179
+ """Save vocabulary to file"""
180
+ if vocab_char_map is None:
181
+ return
182
+
183
+ print(f"\nSaving vocabulary to: {save_path}")
184
+
185
+ # Create directory if it doesn't exist
186
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
187
+
188
+ # Sort by index to maintain order
189
+ vocab_items = sorted(vocab_char_map.items(), key=lambda x: x[1])
190
+
191
+ with open(save_path, 'w', encoding='utf-8') as f:
192
+ for char, idx in vocab_items:
193
+ f.write(f"{char}\n")
194
+
195
+ print(f"✓ Saved {len(vocab_char_map)} tokens to vocab.txt")
196
+
197
+ def send_slack_notification(message, webhook_url=None, title="Training Notification"):
198
+ """Send a notification to a Slack channel via webhook."""
199
+ if webhook_url is None:
200
+ webhook_url = os.getenv("SLACK_WEBHOOK_URL")
201
+
202
+ if not webhook_url:
203
+ return False
204
+
205
+ hostname = socket.gethostname()
206
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
207
+
208
+ payload = {
209
+ "text": f"*{title}*\n*Time:* {timestamp}\n*Host:* {hostname}\n*Message:* {message}"
210
+ }
211
+
212
+ try:
213
+ response = requests.post(
214
+ webhook_url,
215
+ data=json.dumps(payload),
216
+ headers={'Content-Type': 'application/json'}
217
+ )
218
+ return response.status_code == 200
219
+ except Exception as e:
220
+ print(f"Failed to send Slack notification: {e}")
221
+ return False
222
+
223
+ def track_with_dvc(path):
224
+ """Track a file or directory with DVC."""
225
+ try:
226
+ # Check if dvc is initialized
227
+ if not os.path.exists(".dvc"):
228
+ print("DVC not initialized. Skipping tracking.")
229
+ return False
230
+
231
+ print(f"Tracking with DVC: {path}")
232
+ subprocess.run(["dvc", "add", path], check=True, capture_output=True)
233
+ return True
234
+ except subprocess.CalledProcessError as e:
235
+ print(f"DVC add failed for {path}: {e.stderr.decode() if e.stderr else str(e)}")
236
+ return False
237
+ except Exception as e:
238
+ print(f"Failed to track with DVC: {e}")
239
+ return False
240
+
241
+ # convert char to pinyin
242
+
243
+
244
+ def convert_char_to_pinyin(text_list, polyphone=True):
245
+ if jieba.dt.initialized is False:
246
+ jieba.default_logger.setLevel(50) # CRITICAL
247
+ jieba.initialize()
248
+
249
+ final_text_list = []
250
+ custom_trans = str.maketrans(
251
+ {";": ",", "“": '"', "”": '"', "‘": "'", "’": "'"}
252
+ ) # add custom trans here, to address oov
253
+
254
+ def is_chinese(c):
255
+ return (
256
+ "\u3100" <= c <= "\u9fff" # common chinese characters
257
+ )
258
+
259
+ for text in text_list:
260
+ char_list = []
261
+ text = text.translate(custom_trans)
262
+ for seg in jieba.cut(text):
263
+ seg_byte_len = len(bytes(seg, "UTF-8"))
264
+ if seg_byte_len == len(seg): # if pure alphabets and symbols
265
+ if char_list and seg_byte_len > 1 and char_list[-1] not in " :'\"":
266
+ char_list.append(" ")
267
+ char_list.extend(seg)
268
+ elif polyphone and seg_byte_len == 3 * len(seg): # if pure east asian characters
269
+ seg_ = lazy_pinyin(seg, style=Style.TONE3, tone_sandhi=True)
270
+ for i, c in enumerate(seg):
271
+ if is_chinese(c):
272
+ char_list.append(" ")
273
+ char_list.append(seg_[i])
274
+ else: # if mixed characters, alphabets and symbols
275
+ for c in seg:
276
+ if ord(c) < 256:
277
+ char_list.extend(c)
278
+ elif is_chinese(c):
279
+ char_list.append(" ")
280
+ char_list.extend(lazy_pinyin(c, style=Style.TONE3, tone_sandhi=True))
281
+ else:
282
+ char_list.append(c)
283
+ final_text_list.append(char_list)
284
+
285
+ return final_text_list
286
+
287
+
288
+ # filter func for dirty data with many repetitions
289
+
290
+
291
+ def repetition_found(text, length=2, tolerance=10):
292
+ pattern_count = defaultdict(int)
293
+ for i in range(len(text) - length + 1):
294
+ pattern = text[i : i + length]
295
+ pattern_count[pattern] += 1
296
+ for pattern, count in pattern_count.items():
297
+ if count > tolerance:
298
+ return True
299
+ return False
300
+
301
+
302
+ # get the empirically pruned step for sampling
303
+
304
+
305
+ def get_epss_timesteps(n, device, dtype):
306
+ dt = 1 / 32
307
+ predefined_timesteps = {
308
+ 5: [0, 2, 4, 8, 16, 32],
309
+ 6: [0, 2, 4, 6, 8, 16, 32],
310
+ 7: [0, 2, 4, 6, 8, 16, 24, 32],
311
+ 10: [0, 2, 4, 6, 8, 12, 16, 20, 24, 28, 32],
312
+ 12: [0, 2, 4, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32],
313
+ 16: [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32],
314
+ }
315
+ t = predefined_timesteps.get(n, [])
316
+ if not t:
317
+ return torch.linspace(0, 1, n + 1, device=device, dtype=dtype)
318
+ return dt * torch.tensor(t, device=device, dtype=dtype)
src/f5_tts/socket_client.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ import socket
4
+ import time
5
+
6
+ import numpy as np
7
+ import pyaudio
8
+
9
+
10
+ logging.basicConfig(level=logging.INFO)
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ async def listen_to_F5TTS(text, server_ip="localhost", server_port=9998):
15
+ client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
16
+ await asyncio.get_event_loop().run_in_executor(None, client_socket.connect, (server_ip, int(server_port)))
17
+
18
+ start_time = time.time()
19
+ first_chunk_time = None
20
+
21
+ async def play_audio_stream():
22
+ nonlocal first_chunk_time
23
+ p = pyaudio.PyAudio()
24
+ stream = p.open(format=pyaudio.paFloat32, channels=1, rate=24000, output=True, frames_per_buffer=2048)
25
+
26
+ try:
27
+ while True:
28
+ data = await asyncio.get_event_loop().run_in_executor(None, client_socket.recv, 8192)
29
+ if not data:
30
+ break
31
+ if data == b"END":
32
+ logger.info("End of audio received.")
33
+ break
34
+
35
+ audio_array = np.frombuffer(data, dtype=np.float32)
36
+ stream.write(audio_array.tobytes())
37
+
38
+ if first_chunk_time is None:
39
+ first_chunk_time = time.time()
40
+
41
+ finally:
42
+ stream.stop_stream()
43
+ stream.close()
44
+ p.terminate()
45
+
46
+ logger.info(f"Total time taken: {time.time() - start_time:.4f} seconds")
47
+
48
+ try:
49
+ data_to_send = f"{text}".encode("utf-8")
50
+ await asyncio.get_event_loop().run_in_executor(None, client_socket.sendall, data_to_send)
51
+ await play_audio_stream()
52
+
53
+ except Exception as e:
54
+ logger.error(f"Error in listen_to_F5TTS: {e}")
55
+
56
+ finally:
57
+ client_socket.close()
58
+
59
+
60
+ if __name__ == "__main__":
61
+ text_to_send = "As a Reader assistant, I'm familiar with new technology. which are key to its improved performance in terms of both training speed and inference efficiency. Let's break down the components"
62
+
63
+ asyncio.run(listen_to_F5TTS(text_to_send))
src/f5_tts/socket_server.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gc
3
+ import logging
4
+ import queue
5
+ import socket
6
+ import struct
7
+ import threading
8
+ import traceback
9
+ import wave
10
+ from importlib.resources import files
11
+
12
+ import numpy as np
13
+ import torch
14
+ import torchaudio
15
+ from huggingface_hub import hf_hub_download
16
+ from hydra.utils import get_class
17
+ from omegaconf import OmegaConf
18
+
19
+ from f5_tts.infer.utils_infer import (
20
+ chunk_text,
21
+ infer_batch_process,
22
+ load_model,
23
+ load_vocoder,
24
+ preprocess_ref_audio_text,
25
+ )
26
+
27
+
28
+ logging.basicConfig(level=logging.INFO)
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ class AudioFileWriterThread(threading.Thread):
33
+ """Threaded file writer to avoid blocking the TTS streaming process."""
34
+
35
+ def __init__(self, output_file, sampling_rate):
36
+ super().__init__()
37
+ self.output_file = output_file
38
+ self.sampling_rate = sampling_rate
39
+ self.queue = queue.Queue()
40
+ self.stop_event = threading.Event()
41
+ self.audio_data = []
42
+
43
+ def run(self):
44
+ """Process queued audio data and write it to a file."""
45
+ logger.info("AudioFileWriterThread started.")
46
+ with wave.open(self.output_file, "wb") as wf:
47
+ wf.setnchannels(1)
48
+ wf.setsampwidth(2)
49
+ wf.setframerate(self.sampling_rate)
50
+
51
+ while not self.stop_event.is_set() or not self.queue.empty():
52
+ try:
53
+ chunk = self.queue.get(timeout=0.1)
54
+ if chunk is not None:
55
+ chunk = np.int16(chunk * 32767)
56
+ self.audio_data.append(chunk)
57
+ wf.writeframes(chunk.tobytes())
58
+ except queue.Empty:
59
+ continue
60
+
61
+ def add_chunk(self, chunk):
62
+ """Add a new chunk to the queue."""
63
+ self.queue.put(chunk)
64
+
65
+ def stop(self):
66
+ """Stop writing and ensure all queued data is written."""
67
+ self.stop_event.set()
68
+ self.join()
69
+ logger.info("Audio writing completed.")
70
+
71
+
72
+ class TTSStreamingProcessor:
73
+ def __init__(self, model, ckpt_file, vocab_file, ref_audio, ref_text, device=None, dtype=torch.float32):
74
+ self.device = device or (
75
+ "cuda"
76
+ if torch.cuda.is_available()
77
+ else "xpu"
78
+ if torch.xpu.is_available()
79
+ else "mps"
80
+ if torch.backends.mps.is_available()
81
+ else "cpu"
82
+ )
83
+ model_cfg = OmegaConf.load(str(files("f5_tts").joinpath(f"configs/{model}.yaml")))
84
+ self.model_cls = get_class(f"f5_tts.model.{model_cfg.model.backbone}")
85
+ self.model_arc = model_cfg.model.arch
86
+ self.mel_spec_type = model_cfg.model.mel_spec.mel_spec_type
87
+ self.sampling_rate = model_cfg.model.mel_spec.target_sample_rate
88
+
89
+ self.model = self.load_ema_model(ckpt_file, vocab_file, dtype)
90
+ self.vocoder = self.load_vocoder_model()
91
+
92
+ self.update_reference(ref_audio, ref_text)
93
+ self._warm_up()
94
+ self.file_writer_thread = None
95
+ self.first_package = True
96
+
97
+ def load_ema_model(self, ckpt_file, vocab_file, dtype):
98
+ return load_model(
99
+ self.model_cls,
100
+ self.model_arc,
101
+ ckpt_path=ckpt_file,
102
+ mel_spec_type=self.mel_spec_type,
103
+ vocab_file=vocab_file,
104
+ ode_method="euler",
105
+ use_ema=True,
106
+ device=self.device,
107
+ ).to(self.device, dtype=dtype)
108
+
109
+ def load_vocoder_model(self):
110
+ return load_vocoder(vocoder_name=self.mel_spec_type, is_local=False, local_path=None, device=self.device)
111
+
112
+ def update_reference(self, ref_audio, ref_text):
113
+ self.ref_audio, self.ref_text = preprocess_ref_audio_text(ref_audio, ref_text)
114
+ self.audio, self.sr = torchaudio.load(self.ref_audio)
115
+
116
+ ref_audio_duration = self.audio.shape[-1] / self.sr
117
+ ref_text_byte_len = len(self.ref_text.encode("utf-8"))
118
+ self.max_chars = int(ref_text_byte_len / (ref_audio_duration) * (25 - ref_audio_duration))
119
+ self.few_chars = int(ref_text_byte_len / (ref_audio_duration) * (25 - ref_audio_duration) / 2)
120
+ self.min_chars = int(ref_text_byte_len / (ref_audio_duration) * (25 - ref_audio_duration) / 4)
121
+
122
+ def _warm_up(self):
123
+ logger.info("Warming up the model...")
124
+ gen_text = "Warm-up text for the model."
125
+ for _ in infer_batch_process(
126
+ (self.audio, self.sr),
127
+ self.ref_text,
128
+ [gen_text],
129
+ self.model,
130
+ self.vocoder,
131
+ progress=None,
132
+ device=self.device,
133
+ streaming=True,
134
+ ):
135
+ pass
136
+ logger.info("Warm-up completed.")
137
+
138
+ def generate_stream(self, text, conn):
139
+ text_batches = chunk_text(text, max_chars=self.max_chars)
140
+ if self.first_package:
141
+ text_batches = chunk_text(text_batches[0], max_chars=self.few_chars) + text_batches[1:]
142
+ text_batches = chunk_text(text_batches[0], max_chars=self.min_chars) + text_batches[1:]
143
+ self.first_package = False
144
+
145
+ audio_stream = infer_batch_process(
146
+ (self.audio, self.sr),
147
+ self.ref_text,
148
+ text_batches,
149
+ self.model,
150
+ self.vocoder,
151
+ progress=None,
152
+ device=self.device,
153
+ streaming=True,
154
+ chunk_size=2048,
155
+ )
156
+
157
+ # Reset the file writer thread
158
+ if self.file_writer_thread is not None:
159
+ self.file_writer_thread.stop()
160
+ self.file_writer_thread = AudioFileWriterThread("output.wav", self.sampling_rate)
161
+ self.file_writer_thread.start()
162
+
163
+ for audio_chunk, _ in audio_stream:
164
+ if len(audio_chunk) > 0:
165
+ logger.info(f"Generated audio chunk of size: {len(audio_chunk)}")
166
+
167
+ # Send audio chunk via socket
168
+ conn.sendall(struct.pack(f"{len(audio_chunk)}f", *audio_chunk))
169
+
170
+ # Write to file asynchronously
171
+ self.file_writer_thread.add_chunk(audio_chunk)
172
+
173
+ logger.info("Finished sending audio stream.")
174
+ conn.sendall(b"END") # Send end signal
175
+
176
+ # Ensure all audio data is written before exiting
177
+ self.file_writer_thread.stop()
178
+
179
+
180
+ def handle_client(conn, processor):
181
+ try:
182
+ with conn:
183
+ conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
184
+ while True:
185
+ data = conn.recv(1024)
186
+ if not data:
187
+ processor.first_package = True
188
+ break
189
+ data_str = data.decode("utf-8").strip()
190
+ logger.info(f"Received text: {data_str}")
191
+
192
+ try:
193
+ processor.generate_stream(data_str, conn)
194
+ except Exception as inner_e:
195
+ logger.error(f"Error during processing: {inner_e}")
196
+ traceback.print_exc()
197
+ break
198
+ except Exception as e:
199
+ logger.error(f"Error handling client: {e}")
200
+ traceback.print_exc()
201
+
202
+
203
+ def start_server(host, port, processor):
204
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
205
+ s.bind((host, port))
206
+ s.listen()
207
+ logger.info(f"Server started on {host}:{port}")
208
+ while True:
209
+ conn, addr = s.accept()
210
+ logger.info(f"Connected by {addr}")
211
+ handle_client(conn, processor)
212
+
213
+
214
+ if __name__ == "__main__":
215
+ parser = argparse.ArgumentParser()
216
+
217
+ parser.add_argument("--host", default="0.0.0.0")
218
+ parser.add_argument("--port", default=9998)
219
+
220
+ parser.add_argument(
221
+ "--model",
222
+ default="F5TTS_v1_Base",
223
+ help="The model name, e.g. F5TTS_v1_Base",
224
+ )
225
+ parser.add_argument(
226
+ "--ckpt_file",
227
+ default=str(hf_hub_download(repo_id="SWivid/F5-TTS", filename="F5TTS_v1_Base/model_1250000.safetensors")),
228
+ help="Path to the model checkpoint file",
229
+ )
230
+ parser.add_argument(
231
+ "--vocab_file",
232
+ default="",
233
+ help="Path to the vocab file if customized",
234
+ )
235
+
236
+ parser.add_argument(
237
+ "--ref_audio",
238
+ default=str(files("f5_tts").joinpath("infer/examples/basic/basic_ref_en.wav")),
239
+ help="Reference audio to provide model with speaker characteristics",
240
+ )
241
+ parser.add_argument(
242
+ "--ref_text",
243
+ default="",
244
+ help="Reference audio subtitle, leave empty to auto-transcribe",
245
+ )
246
+
247
+ parser.add_argument("--device", default=None, help="Device to run the model on")
248
+ parser.add_argument("--dtype", default=torch.float32, help="Data type to use for model inference")
249
+
250
+ args = parser.parse_args()
251
+
252
+ try:
253
+ # Initialize the processor with the model and vocoder
254
+ processor = TTSStreamingProcessor(
255
+ model=args.model,
256
+ ckpt_file=args.ckpt_file,
257
+ vocab_file=args.vocab_file,
258
+ ref_audio=args.ref_audio,
259
+ ref_text=args.ref_text,
260
+ device=args.device,
261
+ dtype=args.dtype,
262
+ )
263
+
264
+ # Start the server
265
+ start_server(args.host, args.port, processor)
266
+
267
+ except KeyboardInterrupt:
268
+ gc.collect()
test.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from transformers import AutoModel
3
+
4
+ # --- Paths / model id (adjust if needed) ---
5
+ REPO_DIR = "."
6
+ MODEL_ID = "bharatgenai/sooktam2"
7
+
8
+ REF_AUDIO = "./ref.wav"
9
+ REF_TEXT = "सर, मैं तब से यह कह रहा हूँ कि मैंने अपना टिकट कैंसल कर दिया है, लेकिन अब तक मेरे पैसे वापस नहीं आए हैं। आप इस मामले को देखेंगे भी या नहीं?"
10
+ GEN_TEXT = "यह एक टेस्ट वाक्य है जिसे आवाज़ में बदलना है।"
11
+
12
+ OUT_DIR = os.path.join(REPO_DIR, "outputs")
13
+ OUT_WAV = os.path.join(OUT_DIR, "sooktam_cls.wav")
14
+
15
+ # CLS tokenization is handled inside utils_infer via cls_tokenizer_v2.
16
+
17
+ # --- Load TTS model via AutoModel (auto-download ckpt + vocab from HF) ---
18
+ model = AutoModel.from_pretrained(
19
+ MODEL_ID,
20
+ trust_remote_code=True,
21
+ )
22
+
23
+ os.makedirs(OUT_DIR, exist_ok=True)
24
+
25
+ wav, sr, _ = model.infer(
26
+ ref_file=REF_AUDIO,
27
+ ref_text=REF_TEXT,
28
+ gen_text=GEN_TEXT,
29
+ tokenizer="cls",
30
+ cls_language="hindi",
31
+ file_wave=OUT_WAV,
32
+ )
33
+
34
+ print("Saved:", OUT_WAV, "sample_rate:", sr, "samples:", len(wav))
vocab.txt ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ '
3
+ -
4
+ .
5
+ 0
6
+ 1
7
+ 2
8
+ 3
9
+ 4
10
+ 5
11
+ 6
12
+ 7
13
+ 8
14
+ 9
15
+ ?
16
+ M
17
+ a
18
+ aa
19
+ ae
20
+ ax
21
+ b
22
+ bh
23
+ c
24
+ ch
25
+ d
26
+ dh
27
+ dx
28
+ dxh
29
+ dxhq
30
+ dxq
31
+ e
32
+ ee
33
+ ei
34
+ f
35
+ g
36
+ gh
37
+ gq
38
+ h
39
+ hq
40
+ i
41
+ ii
42
+ j
43
+ jh
44
+ k
45
+ kh
46
+ khq
47
+ kq
48
+ l
49
+ lx
50
+ m
51
+ mq
52
+ n
53
+ nd
54
+ ng
55
+ nj
56
+ nk
57
+ nx
58
+ o
59
+ ou
60
+ p
61
+ ph
62
+ q
63
+ r
64
+ rq
65
+ rqw
66
+ rx
67
+ s
68
+ sh
69
+ sx
70
+ t
71
+ th
72
+ tx
73
+ txh
74
+ u
75
+ uu
76
+ v
77
+ w
78
+ x
79
+ y
80
+ z
81
+ č
82
+ š
83
+ α
84
+ ٮ
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+
145
+
146
+
147
+
148
+
149
+
150
+
151
+
152
+
153
+ 尿
154
+
155
+
156
+
157
+
158
+
159
+
160
+
161
+
162
+
163
+
164
+
165
+
166
+
167
+
168
+
169
+
170
+
171
+
172
+
173
+
174
+
175
+
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+
198
+
199
+
200
+
201
+
202
+
203
+
204
+
205
+
206
+
207
+
208
+
209
+
210
+
211
+
212
+
213
+
214
+ !
215
+ "
216
+ #
217
+ $
218
+ %
219
+ &
220
+ (
221
+ )
222
+ *
223
+ +
224
+ ,
225
+ /
226
+ :
227
+ ;
228
+ <
229
+ =
230
+ >
231
+ @
232
+ [
233
+ \
234
+ ]
235
+ ^
236
+ _
237
+ `
238
+ ag
239
+ ai
240
+ au
241
+ en_a
242
+ en_b
243
+ en_c
244
+ en_d
245
+ en_e
246
+ en_f
247
+ en_g
248
+ en_h
249
+ en_i
250
+ en_j
251
+ en_k
252
+ en_l
253
+ en_m
254
+ en_n
255
+ en_o
256
+ en_p
257
+ en_q
258
+ en_r
259
+ en_s
260
+ en_t
261
+ en_u
262
+ en_v
263
+ en_w
264
+ en_x
265
+ en_y
266
+ en_z
267
+ ln
268
+ lw
269
+ nn
270
+ nw
271
+ oo
272
+ rw
273
+ zh
274
+ {
275
+ |
276
+ }
277
+ ~
278
+ 
279
+ £
280
+ §
281
+ ­
282
+ °
283
+ ·
284
+ ¸
285
+ º
286
+ »
287
+ ½
288
+ ×
289
+ à
290
+ â
291
+ ã
292
+ ç
293
+ è
294
+ é
295
+ î
296
+ ï
297
+ ô
298
+ ö
299
+ ú
300
+ û
301
+ ü
302
+ ý
303
+ þ
304
+ ā
305
+ ʼ
306
+ ˉ
307
+ ˚
308
+ ̄
309
+ ̮
310
+ а
311
+ д
312
+ ж
313
+ й
314
+ к
315
+ о
316
+ ҙ
317
+ ҡ
318
+ ү
319
+ ҳ
320
+ ؀
321
+ ؁
322
+ ،
323
+ ؍
324
+ ؎
325
+ ؐ
326
+ ؑ
327
+ ؒ
328
+ ؓ
329
+ ؔ
330
+ ؕ
331
+ ؛
332
+ ؟
333
+ ء
334
+ آ
335
+ أ
336
+ ؤ
337
+ إ
338
+ ئ
339
+ ا
340
+ ب
341
+ ة
342
+ ت
343
+ ث
344
+ ج
345
+ ح
346
+ خ
347
+ د
348
+ ذ
349
+ ر
350
+ ز
351
+ س
352
+ ش
353
+ ص
354
+ ض
355
+ ط
356
+ ظ
357
+ ع
358
+ غ
359
+ ـ
360
+ ف
361
+ ق
362
+ ك
363
+ ل
364
+ م
365
+ ن
366
+ ه
367
+ و
368
+ ى
369
+ ي
370
+ ً
371
+ ٌ
372
+ ٍ
373
+ َ
374
+ ُ
375
+ ِ
376
+ ّ
377
+ ْ
378
+ ٓ
379
+ ٔ
380
+ ٕ
381
+ ٖ
382
+ ٗ
383
+ ٘
384
+ ٙ
385
+ ٚ
386
+ ٛ
387
+ ٬
388
+ ٰ
389
+ ٱ
390
+ ٴ
391
+ ٶ
392
+ ٸ
393
+ ٹ
394
+ ٻ
395
+ ټ
396
+ ٽ
397
+ پ
398
+ ڀ
399
+ ځ
400
+ ڃ
401
+ ڄ
402
+ څ
403
+ چ
404
+ ڇ
405
+ ڈ
406
+ ڊ
407
+ ڌ
408
+ ڑ
409
+ ړ
410
+ ژ
411
+ ڙ
412
+ ښ
413
+ ڦ
414
+ ک
415
+ ڪ
416
+ ګ
417
+ ڭ
418
+ گ
419
+ ڱ
420
+ ڳ
421
+ ں
422
+ ڻ
423
+ ھ
424
+ ہ
425
+ ۂ
426
+ ۃ
427
+ ۄ
428
+ ۆ
429
+ ی
430
+ ۍ
431
+ ێ
432
+ ې
433
+ ے
434
+ ۓ
435
+ ۔
436
+ ە
437
+ ۖ
438
+ ۡ
439
+ ۤ
440
+ ۪
441
+ ۰
442
+ ۱
443
+ ۲
444
+ ۳
445
+ ۴
446
+ ۵
447
+ ۶
448
+ ۷
449
+ ۸
450
+ ۹
451
+
452
+
453
+
454
+
455
+
456
+
457
+
458
+
459
+
460
+
461
+
462
+
463
+
464
+
465
+
466
+
467
+
468
+
469
+
470
+
471
+
472
+
473
+
474
+
475
+
476
+
477
+
478
+
479
+
480
+
481
+
482
+
483
+
484
+
485
+
486
+
487
+
488
+
489
+
490
+
491
+
492
+
493
+
494
+
495
+
496
+
497
+
498
+
499
+
500
+
501
+
502
+
503
+
504
+
505
+
506
+
507
+
508
+
509
+
510
+
511
+
512
+
513
+
514
+
515
+
516
+
517
+
518
+ ൿ
519
+
520
+
521
+
522
+
523
+
524
+
525
+
526
+
527
+
528
+
529
+
530
+
531
+
532
+
533
+
534
+
535
+
536
+
537
+
538
+
539
+
540
+
541
+
542
+
543
+