Spaces:
Running
on
Zero
Running
on
Zero
Upload 6 files
Browse files- infer/README.md +191 -0
- infer/SHARED.md +74 -0
- infer/infer_cli.py +226 -0
- infer/infer_gradio.py +851 -0
- infer/speech_edit.py +193 -0
- infer/utils_infer.py +538 -0
infer/README.md
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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** including both prompt and output audio. However, you can provide `infer_cli` and `infer_gradio` with longer text, will automatically do chunk generation. Long reference audio will be **clip short to ~15s**.
|
8 |
+
|
9 |
+
To avoid possible inference failures, make sure you have seen through the following instructions.
|
10 |
+
|
11 |
+
- Use reference audio <15s and leave some silence (e.g. 1s) at the end. Otherwise there is a risk of truncating in the middle of word, leading to suboptimal generation.
|
12 |
+
- Uppercased letters will be uttered letter by letter, so use lowercased letters for normal words.
|
13 |
+
- Add some spaces (blank: " ") or punctuations (e.g. "," ".") to explicitly introduce some pauses.
|
14 |
+
- Preprocess numbers to Chinese letters if you want to have them read in Chinese, otherwise in English.
|
15 |
+
|
16 |
+
|
17 |
+
## Gradio App
|
18 |
+
|
19 |
+
Currently supported features:
|
20 |
+
|
21 |
+
- Basic TTS with Chunk Inference
|
22 |
+
- Multi-Style / Multi-Speaker Generation
|
23 |
+
- Voice Chat powered by Qwen2.5-3B-Instruct
|
24 |
+
|
25 |
+
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.
|
26 |
+
|
27 |
+
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.
|
28 |
+
|
29 |
+
Could also be used as a component for larger application.
|
30 |
+
```python
|
31 |
+
import gradio as gr
|
32 |
+
from f5_tts.infer.infer_gradio import app
|
33 |
+
|
34 |
+
with gr.Blocks() as main_app:
|
35 |
+
gr.Markdown("# This is an example of using F5-TTS within a bigger Gradio app")
|
36 |
+
|
37 |
+
# ... other Gradio components
|
38 |
+
|
39 |
+
app.render()
|
40 |
+
|
41 |
+
main_app.launch()
|
42 |
+
```
|
43 |
+
|
44 |
+
|
45 |
+
## CLI Inference
|
46 |
+
|
47 |
+
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.
|
48 |
+
|
49 |
+
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`.
|
50 |
+
|
51 |
+
For change vocab.txt use `--vocab_file` to provide your `vocab.txt` file.
|
52 |
+
|
53 |
+
Basically you can inference with flags:
|
54 |
+
```bash
|
55 |
+
# Leave --ref_text "" will have ASR model transcribe (extra GPU memory usage)
|
56 |
+
f5-tts_infer-cli \
|
57 |
+
--model "F5-TTS" \
|
58 |
+
--ref_audio "ref_audio.wav" \
|
59 |
+
--ref_text "The content, subtitle or transcription of reference audio." \
|
60 |
+
--gen_text "Some text you want TTS model generate for you."
|
61 |
+
|
62 |
+
# Choose Vocoder
|
63 |
+
f5-tts_infer-cli --vocoder_name bigvgan --load_vocoder_from_local --ckpt_file <YOUR_CKPT_PATH, eg:ckpts/F5TTS_Base_bigvgan/model_1250000.pt>
|
64 |
+
f5-tts_infer-cli --vocoder_name vocos --load_vocoder_from_local --ckpt_file <YOUR_CKPT_PATH, eg:ckpts/F5TTS_Base/model_1200000.safetensors>
|
65 |
+
```
|
66 |
+
|
67 |
+
And a `.toml` file would help with more flexible usage.
|
68 |
+
|
69 |
+
```bash
|
70 |
+
f5-tts_infer-cli -c custom.toml
|
71 |
+
```
|
72 |
+
|
73 |
+
For example, you can use `.toml` to pass in variables, refer to `src/f5_tts/infer/examples/basic/basic.toml`:
|
74 |
+
|
75 |
+
```toml
|
76 |
+
# F5-TTS | E2-TTS
|
77 |
+
model = "F5-TTS"
|
78 |
+
ref_audio = "infer/examples/basic/basic_ref_en.wav"
|
79 |
+
# If an empty "", transcribes the reference audio automatically.
|
80 |
+
ref_text = "Some call me nature, others call me mother nature."
|
81 |
+
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."
|
82 |
+
# File with text to generate. Ignores the text above.
|
83 |
+
gen_file = ""
|
84 |
+
remove_silence = false
|
85 |
+
output_dir = "tests"
|
86 |
+
```
|
87 |
+
|
88 |
+
You can also leverage `.toml` file to do multi-style generation, refer to `src/f5_tts/infer/examples/multi/story.toml`.
|
89 |
+
|
90 |
+
```toml
|
91 |
+
# F5-TTS | E2-TTS
|
92 |
+
model = "F5-TTS"
|
93 |
+
ref_audio = "infer/examples/multi/main.flac"
|
94 |
+
# If an empty "", transcribes the reference audio automatically.
|
95 |
+
ref_text = ""
|
96 |
+
gen_text = ""
|
97 |
+
# File with text to generate. Ignores the text above.
|
98 |
+
gen_file = "infer/examples/multi/story.txt"
|
99 |
+
remove_silence = true
|
100 |
+
output_dir = "tests"
|
101 |
+
|
102 |
+
[voices.town]
|
103 |
+
ref_audio = "infer/examples/multi/town.flac"
|
104 |
+
ref_text = ""
|
105 |
+
|
106 |
+
[voices.country]
|
107 |
+
ref_audio = "infer/examples/multi/country.flac"
|
108 |
+
ref_text = ""
|
109 |
+
```
|
110 |
+
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`.
|
111 |
+
|
112 |
+
## Speech Editing
|
113 |
+
|
114 |
+
To test speech editing capabilities, use the following command:
|
115 |
+
|
116 |
+
```bash
|
117 |
+
python src/f5_tts/infer/speech_edit.py
|
118 |
+
```
|
119 |
+
|
120 |
+
## Socket Realtime Client
|
121 |
+
|
122 |
+
To communicate with socket server you need to run
|
123 |
+
```bash
|
124 |
+
python src/f5_tts/socket_server.py
|
125 |
+
```
|
126 |
+
|
127 |
+
<details>
|
128 |
+
<summary>Then create client to communicate</summary>
|
129 |
+
|
130 |
+
``` python
|
131 |
+
import socket
|
132 |
+
import numpy as np
|
133 |
+
import asyncio
|
134 |
+
import pyaudio
|
135 |
+
|
136 |
+
async def listen_to_voice(text, server_ip='localhost', server_port=9999):
|
137 |
+
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
138 |
+
client_socket.connect((server_ip, server_port))
|
139 |
+
|
140 |
+
async def play_audio_stream():
|
141 |
+
buffer = b''
|
142 |
+
p = pyaudio.PyAudio()
|
143 |
+
stream = p.open(format=pyaudio.paFloat32,
|
144 |
+
channels=1,
|
145 |
+
rate=24000, # Ensure this matches the server's sampling rate
|
146 |
+
output=True,
|
147 |
+
frames_per_buffer=2048)
|
148 |
+
|
149 |
+
try:
|
150 |
+
while True:
|
151 |
+
chunk = await asyncio.get_event_loop().run_in_executor(None, client_socket.recv, 1024)
|
152 |
+
if not chunk: # End of stream
|
153 |
+
break
|
154 |
+
if b"END_OF_AUDIO" in chunk:
|
155 |
+
buffer += chunk.replace(b"END_OF_AUDIO", b"")
|
156 |
+
if buffer:
|
157 |
+
audio_array = np.frombuffer(buffer, dtype=np.float32).copy() # Make a writable copy
|
158 |
+
stream.write(audio_array.tobytes())
|
159 |
+
break
|
160 |
+
buffer += chunk
|
161 |
+
if len(buffer) >= 4096:
|
162 |
+
audio_array = np.frombuffer(buffer[:4096], dtype=np.float32).copy() # Make a writable copy
|
163 |
+
stream.write(audio_array.tobytes())
|
164 |
+
buffer = buffer[4096:]
|
165 |
+
finally:
|
166 |
+
stream.stop_stream()
|
167 |
+
stream.close()
|
168 |
+
p.terminate()
|
169 |
+
|
170 |
+
try:
|
171 |
+
# Send only the text to the server
|
172 |
+
await asyncio.get_event_loop().run_in_executor(None, client_socket.sendall, text.encode('utf-8'))
|
173 |
+
await play_audio_stream()
|
174 |
+
print("Audio playback finished.")
|
175 |
+
|
176 |
+
except Exception as e:
|
177 |
+
print(f"Error in listen_to_voice: {e}")
|
178 |
+
|
179 |
+
finally:
|
180 |
+
client_socket.close()
|
181 |
+
|
182 |
+
# Example usage: Replace this with your actual server IP and port
|
183 |
+
async def main():
|
184 |
+
await listen_to_voice("my name is jenny..", server_ip='localhost', server_port=9998)
|
185 |
+
|
186 |
+
# Run the main async function
|
187 |
+
asyncio.run(main())
|
188 |
+
```
|
189 |
+
|
190 |
+
</details>
|
191 |
+
|
infer/SHARED.md
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 Base @ pretrain @ zh \& en](#f5-tts-base--pretrain--zh--en)
|
20 |
+
- [Mandarin](#mandarin)
|
21 |
+
- [Japanese](#japanese)
|
22 |
+
- [F5-TTS Base @ pretrain/finetune @ ja](#f5-tts-base--pretrainfinetune--ja)
|
23 |
+
- [English](#english)
|
24 |
+
- [French](#french)
|
25 |
+
- [French LibriVox @ finetune @ fr](#french-librivox--finetune--fr)
|
26 |
+
|
27 |
+
|
28 |
+
## Multilingual
|
29 |
+
|
30 |
+
#### F5-TTS Base @ pretrain @ zh & en
|
31 |
+
|Model|🤗Hugging Face|Data (Hours)|Model License|
|
32 |
+
|:---:|:------------:|:-----------:|:-------------:|
|
33 |
+
|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|
|
34 |
+
|
35 |
+
```bash
|
36 |
+
MODEL_CKPT: hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors
|
37 |
+
VOCAB_FILE: hf://SWivid/F5-TTS/F5TTS_Base/vocab.txt
|
38 |
+
```
|
39 |
+
|
40 |
+
*Other infos, e.g. Author info, Github repo, Link to some sampled results, Usage instruction, Tutorial (Blog, Video, etc.) ...*
|
41 |
+
|
42 |
+
|
43 |
+
## Mandarin
|
44 |
+
|
45 |
+
## Japanese
|
46 |
+
|
47 |
+
#### F5-TTS Base @ pretrain/finetune @ ja
|
48 |
+
|Model|🤗Hugging Face|Data (Hours)|Model License|
|
49 |
+
|:---:|:------------:|:-----------:|:-------------:|
|
50 |
+
|F5-TTS Base|[ckpt & vocab](https://huggingface.co/Jmica/F5TTS/tree/main/JA_8500000)|[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|
|
51 |
+
|
52 |
+
```bash
|
53 |
+
MODEL_CKPT: hf://Jmica/F5TTS/JA_8500000/model_8499660.pt
|
54 |
+
VOCAB_FILE: hf://Jmica/F5TTS/JA_8500000/vocab_updated.txt
|
55 |
+
```
|
56 |
+
|
57 |
+
## English
|
58 |
+
|
59 |
+
|
60 |
+
## French
|
61 |
+
|
62 |
+
#### French LibriVox @ finetune @ fr
|
63 |
+
|Model|🤗Hugging Face|Data (Hours)|Model License|
|
64 |
+
|:---:|:------------:|:-----------:|:-------------:|
|
65 |
+
|F5-TTS French|[ckpt & vocab](https://huggingface.co/RASPIAUDIO/F5-French-MixedSpeakers-reduced)|[LibriVox](https://librivox.org/)|cc-by-nc-4.0|
|
66 |
+
|
67 |
+
```bash
|
68 |
+
MODEL_CKPT: hf://RASPIAUDIO/F5-French-MixedSpeakers-reduced/model_last_reduced.pt
|
69 |
+
VOCAB_FILE: hf://RASPIAUDIO/F5-French-MixedSpeakers-reduced/vocab.txt
|
70 |
+
```
|
71 |
+
|
72 |
+
- [Online Inference with Hugging Face Space](https://huggingface.co/spaces/RASPIAUDIO/f5-tts_french).
|
73 |
+
- [Tutorial video to train a new language model](https://www.youtube.com/watch?v=UO4usaOojys).
|
74 |
+
- [Discussion about this training can be found here](https://github.com/SWivid/F5-TTS/issues/434).
|
infer/infer_cli.py
ADDED
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import codecs
|
3 |
+
import os
|
4 |
+
import re
|
5 |
+
from importlib.resources import files
|
6 |
+
from pathlib import Path
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
import soundfile as sf
|
10 |
+
import tomli
|
11 |
+
from cached_path import cached_path
|
12 |
+
|
13 |
+
from f5_tts.infer.utils_infer import (
|
14 |
+
infer_process,
|
15 |
+
load_model,
|
16 |
+
load_vocoder,
|
17 |
+
preprocess_ref_audio_text,
|
18 |
+
remove_silence_for_generated_wav,
|
19 |
+
)
|
20 |
+
from f5_tts.model import DiT, UNetT
|
21 |
+
|
22 |
+
parser = argparse.ArgumentParser(
|
23 |
+
prog="python3 infer-cli.py",
|
24 |
+
description="Commandline interface for E2/F5 TTS with Advanced Batch Processing.",
|
25 |
+
epilog="Specify options above to override one or more settings from config.",
|
26 |
+
)
|
27 |
+
parser.add_argument(
|
28 |
+
"-c",
|
29 |
+
"--config",
|
30 |
+
help="Configuration file. Default=infer/examples/basic/basic.toml",
|
31 |
+
default=os.path.join(files("f5_tts").joinpath("infer/examples/basic"), "basic.toml"),
|
32 |
+
)
|
33 |
+
parser.add_argument(
|
34 |
+
"-m",
|
35 |
+
"--model",
|
36 |
+
help="F5-TTS | E2-TTS",
|
37 |
+
)
|
38 |
+
parser.add_argument(
|
39 |
+
"-p",
|
40 |
+
"--ckpt_file",
|
41 |
+
help="The Checkpoint .pt",
|
42 |
+
)
|
43 |
+
parser.add_argument(
|
44 |
+
"-v",
|
45 |
+
"--vocab_file",
|
46 |
+
help="The vocab .txt",
|
47 |
+
)
|
48 |
+
parser.add_argument("-r", "--ref_audio", type=str, help="Reference audio file < 15 seconds.")
|
49 |
+
parser.add_argument("-s", "--ref_text", type=str, default="666", help="Subtitle for the reference audio.")
|
50 |
+
parser.add_argument(
|
51 |
+
"-t",
|
52 |
+
"--gen_text",
|
53 |
+
type=str,
|
54 |
+
help="Text to generate.",
|
55 |
+
)
|
56 |
+
parser.add_argument(
|
57 |
+
"-f",
|
58 |
+
"--gen_file",
|
59 |
+
type=str,
|
60 |
+
help="File with text to generate. Ignores --gen_text",
|
61 |
+
)
|
62 |
+
parser.add_argument(
|
63 |
+
"-o",
|
64 |
+
"--output_dir",
|
65 |
+
type=str,
|
66 |
+
help="Path to output folder..",
|
67 |
+
)
|
68 |
+
parser.add_argument(
|
69 |
+
"-w",
|
70 |
+
"--output_file",
|
71 |
+
type=str,
|
72 |
+
help="Filename of output file..",
|
73 |
+
)
|
74 |
+
parser.add_argument(
|
75 |
+
"--remove_silence",
|
76 |
+
help="Remove silence.",
|
77 |
+
)
|
78 |
+
parser.add_argument("--vocoder_name", type=str, default="vocos", choices=["vocos", "bigvgan"], help="vocoder name")
|
79 |
+
parser.add_argument(
|
80 |
+
"--load_vocoder_from_local",
|
81 |
+
action="store_true",
|
82 |
+
help="load vocoder from local. Default: ../checkpoints/charactr/vocos-mel-24khz",
|
83 |
+
)
|
84 |
+
parser.add_argument(
|
85 |
+
"--speed",
|
86 |
+
type=float,
|
87 |
+
default=1.0,
|
88 |
+
help="Adjust the speed of the audio generation (default: 1.0)",
|
89 |
+
)
|
90 |
+
args = parser.parse_args()
|
91 |
+
|
92 |
+
config = tomli.load(open(args.config, "rb"))
|
93 |
+
|
94 |
+
ref_audio = args.ref_audio if args.ref_audio else config["ref_audio"]
|
95 |
+
ref_text = args.ref_text if args.ref_text != "666" else config["ref_text"]
|
96 |
+
gen_text = args.gen_text if args.gen_text else config["gen_text"]
|
97 |
+
gen_file = args.gen_file if args.gen_file else config["gen_file"]
|
98 |
+
|
99 |
+
# patches for pip pkg user
|
100 |
+
if "infer/examples/" in ref_audio:
|
101 |
+
ref_audio = str(files("f5_tts").joinpath(f"{ref_audio}"))
|
102 |
+
if "infer/examples/" in gen_file:
|
103 |
+
gen_file = str(files("f5_tts").joinpath(f"{gen_file}"))
|
104 |
+
if "voices" in config:
|
105 |
+
for voice in config["voices"]:
|
106 |
+
voice_ref_audio = config["voices"][voice]["ref_audio"]
|
107 |
+
if "infer/examples/" in voice_ref_audio:
|
108 |
+
config["voices"][voice]["ref_audio"] = str(files("f5_tts").joinpath(f"{voice_ref_audio}"))
|
109 |
+
|
110 |
+
if gen_file:
|
111 |
+
gen_text = codecs.open(gen_file, "r", "utf-8").read()
|
112 |
+
output_dir = args.output_dir if args.output_dir else config["output_dir"]
|
113 |
+
output_file = args.output_file if args.output_file else config["output_file"]
|
114 |
+
model = args.model if args.model else config["model"]
|
115 |
+
ckpt_file = args.ckpt_file if args.ckpt_file else ""
|
116 |
+
vocab_file = args.vocab_file if args.vocab_file else ""
|
117 |
+
remove_silence = args.remove_silence if args.remove_silence else config["remove_silence"]
|
118 |
+
speed = args.speed
|
119 |
+
|
120 |
+
wave_path = Path(output_dir) / output_file
|
121 |
+
# spectrogram_path = Path(output_dir) / "infer_cli_out.png"
|
122 |
+
|
123 |
+
vocoder_name = args.vocoder_name
|
124 |
+
mel_spec_type = args.vocoder_name
|
125 |
+
if vocoder_name == "vocos":
|
126 |
+
vocoder_local_path = "../checkpoints/vocos-mel-24khz"
|
127 |
+
elif vocoder_name == "bigvgan":
|
128 |
+
vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x"
|
129 |
+
|
130 |
+
vocoder = load_vocoder(vocoder_name=mel_spec_type, is_local=args.load_vocoder_from_local, local_path=vocoder_local_path)
|
131 |
+
|
132 |
+
|
133 |
+
# load models
|
134 |
+
if model == "F5-TTS":
|
135 |
+
model_cls = DiT
|
136 |
+
model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
137 |
+
if ckpt_file == "":
|
138 |
+
if vocoder_name == "vocos":
|
139 |
+
repo_name = "F5-TTS"
|
140 |
+
exp_name = "F5TTS_Base"
|
141 |
+
ckpt_step = 1200000
|
142 |
+
ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors"))
|
143 |
+
# ckpt_file = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors; local path
|
144 |
+
elif vocoder_name == "bigvgan":
|
145 |
+
repo_name = "F5-TTS"
|
146 |
+
exp_name = "F5TTS_Base_bigvgan"
|
147 |
+
ckpt_step = 1250000
|
148 |
+
ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.pt"))
|
149 |
+
|
150 |
+
elif model == "E2-TTS":
|
151 |
+
assert vocoder_name == "vocos", "E2-TTS only supports vocoder vocos"
|
152 |
+
model_cls = UNetT
|
153 |
+
model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
|
154 |
+
if ckpt_file == "":
|
155 |
+
repo_name = "E2-TTS"
|
156 |
+
exp_name = "E2TTS_Base"
|
157 |
+
ckpt_step = 1200000
|
158 |
+
ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors"))
|
159 |
+
# ckpt_file = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors; local path
|
160 |
+
|
161 |
+
|
162 |
+
print(f"Using {model}...")
|
163 |
+
ema_model = load_model(model_cls, model_cfg, ckpt_file, mel_spec_type=mel_spec_type, vocab_file=vocab_file)
|
164 |
+
|
165 |
+
|
166 |
+
def main_process(ref_audio, ref_text, text_gen, model_obj, mel_spec_type, remove_silence, speed):
|
167 |
+
main_voice = {"ref_audio": ref_audio, "ref_text": ref_text}
|
168 |
+
if "voices" not in config:
|
169 |
+
voices = {"main": main_voice}
|
170 |
+
else:
|
171 |
+
voices = config["voices"]
|
172 |
+
voices["main"] = main_voice
|
173 |
+
for voice in voices:
|
174 |
+
voices[voice]["ref_audio"], voices[voice]["ref_text"] = preprocess_ref_audio_text(
|
175 |
+
voices[voice]["ref_audio"], voices[voice]["ref_text"]
|
176 |
+
)
|
177 |
+
print("Voice:", voice)
|
178 |
+
print("Ref_audio:", voices[voice]["ref_audio"])
|
179 |
+
print("Ref_text:", voices[voice]["ref_text"])
|
180 |
+
|
181 |
+
generated_audio_segments = []
|
182 |
+
reg1 = r"(?=\[\w+\])"
|
183 |
+
chunks = re.split(reg1, text_gen)
|
184 |
+
reg2 = r"\[(\w+)\]"
|
185 |
+
for text in chunks:
|
186 |
+
if not text.strip():
|
187 |
+
continue
|
188 |
+
match = re.match(reg2, text)
|
189 |
+
if match:
|
190 |
+
voice = match[1]
|
191 |
+
else:
|
192 |
+
print("No voice tag found, using main.")
|
193 |
+
voice = "main"
|
194 |
+
if voice not in voices:
|
195 |
+
print(f"Voice {voice} not found, using main.")
|
196 |
+
voice = "main"
|
197 |
+
text = re.sub(reg2, "", text)
|
198 |
+
gen_text = text.strip()
|
199 |
+
ref_audio = voices[voice]["ref_audio"]
|
200 |
+
ref_text = voices[voice]["ref_text"]
|
201 |
+
print(f"Voice: {voice}")
|
202 |
+
audio, final_sample_rate, spectragram = infer_process(
|
203 |
+
ref_audio, ref_text, gen_text, model_obj, vocoder, mel_spec_type=mel_spec_type, speed=speed
|
204 |
+
)
|
205 |
+
generated_audio_segments.append(audio)
|
206 |
+
|
207 |
+
if generated_audio_segments:
|
208 |
+
final_wave = np.concatenate(generated_audio_segments)
|
209 |
+
|
210 |
+
if not os.path.exists(output_dir):
|
211 |
+
os.makedirs(output_dir)
|
212 |
+
|
213 |
+
with open(wave_path, "wb") as f:
|
214 |
+
sf.write(f.name, final_wave, final_sample_rate)
|
215 |
+
# Remove silence
|
216 |
+
if remove_silence:
|
217 |
+
remove_silence_for_generated_wav(f.name)
|
218 |
+
print(f.name)
|
219 |
+
|
220 |
+
|
221 |
+
def main():
|
222 |
+
main_process(ref_audio, ref_text, gen_text, ema_model, mel_spec_type, remove_silence, speed)
|
223 |
+
|
224 |
+
|
225 |
+
if __name__ == "__main__":
|
226 |
+
main()
|
infer/infer_gradio.py
ADDED
@@ -0,0 +1,851 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ruff: noqa: E402
|
2 |
+
# Above allows ruff to ignore E402: module level import not at top of file
|
3 |
+
|
4 |
+
import re
|
5 |
+
import tempfile
|
6 |
+
from collections import OrderedDict
|
7 |
+
from importlib.resources import files
|
8 |
+
|
9 |
+
import click
|
10 |
+
import gradio as gr
|
11 |
+
import numpy as np
|
12 |
+
import soundfile as sf
|
13 |
+
import torchaudio
|
14 |
+
from cached_path import cached_path
|
15 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
16 |
+
|
17 |
+
try:
|
18 |
+
import spaces
|
19 |
+
|
20 |
+
USING_SPACES = True
|
21 |
+
except ImportError:
|
22 |
+
USING_SPACES = False
|
23 |
+
|
24 |
+
|
25 |
+
def gpu_decorator(func):
|
26 |
+
if USING_SPACES:
|
27 |
+
return spaces.GPU(func)
|
28 |
+
else:
|
29 |
+
return func
|
30 |
+
|
31 |
+
|
32 |
+
from f5_tts.model import DiT, UNetT
|
33 |
+
from f5_tts.infer.utils_infer import (
|
34 |
+
load_vocoder,
|
35 |
+
load_model,
|
36 |
+
preprocess_ref_audio_text,
|
37 |
+
infer_process,
|
38 |
+
remove_silence_for_generated_wav,
|
39 |
+
save_spectrogram,
|
40 |
+
)
|
41 |
+
|
42 |
+
|
43 |
+
DEFAULT_TTS_MODEL = "F5-TTS"
|
44 |
+
tts_model_choice = DEFAULT_TTS_MODEL
|
45 |
+
|
46 |
+
|
47 |
+
# load models
|
48 |
+
|
49 |
+
vocoder = load_vocoder()
|
50 |
+
|
51 |
+
|
52 |
+
def load_f5tts(ckpt_path=str(cached_path("hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors"))):
|
53 |
+
F5TTS_model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
54 |
+
return load_model(DiT, F5TTS_model_cfg, ckpt_path)
|
55 |
+
|
56 |
+
|
57 |
+
def load_e2tts(ckpt_path=str(cached_path("hf://SWivid/E2-TTS/E2TTS_Base/model_1200000.safetensors"))):
|
58 |
+
E2TTS_model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
|
59 |
+
return load_model(UNetT, E2TTS_model_cfg, ckpt_path)
|
60 |
+
|
61 |
+
|
62 |
+
def load_custom(ckpt_path: str, vocab_path="", model_cfg=None):
|
63 |
+
ckpt_path, vocab_path = ckpt_path.strip(), vocab_path.strip()
|
64 |
+
if ckpt_path.startswith("hf://"):
|
65 |
+
ckpt_path = str(cached_path(ckpt_path))
|
66 |
+
if vocab_path.startswith("hf://"):
|
67 |
+
vocab_path = str(cached_path(vocab_path))
|
68 |
+
if model_cfg is None:
|
69 |
+
model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
70 |
+
return load_model(DiT, model_cfg, ckpt_path, vocab_file=vocab_path)
|
71 |
+
|
72 |
+
|
73 |
+
F5TTS_ema_model = load_f5tts()
|
74 |
+
E2TTS_ema_model = load_e2tts() if USING_SPACES else None
|
75 |
+
custom_ema_model, pre_custom_path = None, ""
|
76 |
+
|
77 |
+
chat_model_state = None
|
78 |
+
chat_tokenizer_state = None
|
79 |
+
|
80 |
+
|
81 |
+
@gpu_decorator
|
82 |
+
def generate_response(messages, model, tokenizer):
|
83 |
+
"""Generate response using Qwen"""
|
84 |
+
text = tokenizer.apply_chat_template(
|
85 |
+
messages,
|
86 |
+
tokenize=False,
|
87 |
+
add_generation_prompt=True,
|
88 |
+
)
|
89 |
+
|
90 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
91 |
+
generated_ids = model.generate(
|
92 |
+
**model_inputs,
|
93 |
+
max_new_tokens=512,
|
94 |
+
temperature=0.7,
|
95 |
+
top_p=0.95,
|
96 |
+
)
|
97 |
+
|
98 |
+
generated_ids = [
|
99 |
+
output_ids[len(input_ids) :] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
|
100 |
+
]
|
101 |
+
return tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
102 |
+
|
103 |
+
|
104 |
+
@gpu_decorator
|
105 |
+
def infer(
|
106 |
+
ref_audio_orig, ref_text, gen_text, model, remove_silence, cross_fade_duration=0.15, speed=1, show_info=gr.Info
|
107 |
+
):
|
108 |
+
ref_audio, ref_text = preprocess_ref_audio_text(ref_audio_orig, ref_text, show_info=show_info)
|
109 |
+
|
110 |
+
if model == "F5-TTS":
|
111 |
+
ema_model = F5TTS_ema_model
|
112 |
+
elif model == "E2-TTS":
|
113 |
+
global E2TTS_ema_model
|
114 |
+
if E2TTS_ema_model is None:
|
115 |
+
show_info("Loading E2-TTS model...")
|
116 |
+
E2TTS_ema_model = load_e2tts()
|
117 |
+
ema_model = E2TTS_ema_model
|
118 |
+
elif isinstance(model, list) and model[0] == "Custom":
|
119 |
+
assert not USING_SPACES, "Only official checkpoints allowed in Spaces."
|
120 |
+
global custom_ema_model, pre_custom_path
|
121 |
+
if pre_custom_path != model[1]:
|
122 |
+
show_info("Loading Custom TTS model...")
|
123 |
+
custom_ema_model = load_custom(model[1], vocab_path=model[2])
|
124 |
+
pre_custom_path = model[1]
|
125 |
+
ema_model = custom_ema_model
|
126 |
+
|
127 |
+
final_wave, final_sample_rate, combined_spectrogram = infer_process(
|
128 |
+
ref_audio,
|
129 |
+
ref_text,
|
130 |
+
gen_text,
|
131 |
+
ema_model,
|
132 |
+
vocoder,
|
133 |
+
cross_fade_duration=cross_fade_duration,
|
134 |
+
speed=speed,
|
135 |
+
show_info=show_info,
|
136 |
+
progress=gr.Progress(),
|
137 |
+
)
|
138 |
+
|
139 |
+
# Remove silence
|
140 |
+
if remove_silence:
|
141 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
|
142 |
+
sf.write(f.name, final_wave, final_sample_rate)
|
143 |
+
remove_silence_for_generated_wav(f.name)
|
144 |
+
final_wave, _ = torchaudio.load(f.name)
|
145 |
+
final_wave = final_wave.squeeze().cpu().numpy()
|
146 |
+
|
147 |
+
# Save the spectrogram
|
148 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:
|
149 |
+
spectrogram_path = tmp_spectrogram.name
|
150 |
+
save_spectrogram(combined_spectrogram, spectrogram_path)
|
151 |
+
|
152 |
+
return (final_sample_rate, final_wave), spectrogram_path, ref_text
|
153 |
+
|
154 |
+
|
155 |
+
with gr.Blocks() as app_credits:
|
156 |
+
gr.Markdown("""
|
157 |
+
# Credits
|
158 |
+
|
159 |
+
* [mrfakename](https://github.com/fakerybakery) for the original [online demo](https://huggingface.co/spaces/mrfakename/E2-F5-TTS)
|
160 |
+
* [RootingInLoad](https://github.com/RootingInLoad) for initial chunk generation and podcast app exploration
|
161 |
+
* [jpgallegoar](https://github.com/jpgallegoar) for multiple speech-type generation & voice chat
|
162 |
+
""")
|
163 |
+
with gr.Blocks() as app_tts:
|
164 |
+
gr.Markdown("# Batched TTS")
|
165 |
+
ref_audio_input = gr.Audio(label="Reference Audio", type="filepath")
|
166 |
+
gen_text_input = gr.Textbox(label="Text to Generate", lines=10)
|
167 |
+
generate_btn = gr.Button("Synthesize", variant="primary")
|
168 |
+
with gr.Accordion("Advanced Settings", open=False):
|
169 |
+
ref_text_input = gr.Textbox(
|
170 |
+
label="Reference Text",
|
171 |
+
info="Leave blank to automatically transcribe the reference audio. If you enter text it will override automatic transcription.",
|
172 |
+
lines=2,
|
173 |
+
)
|
174 |
+
remove_silence = gr.Checkbox(
|
175 |
+
label="Remove Silences",
|
176 |
+
info="The model tends to produce silences, especially on longer audio. We can manually remove silences if needed. Note that this is an experimental feature and may produce strange results. This will also increase generation time.",
|
177 |
+
value=False,
|
178 |
+
)
|
179 |
+
speed_slider = gr.Slider(
|
180 |
+
label="Speed",
|
181 |
+
minimum=0.3,
|
182 |
+
maximum=2.0,
|
183 |
+
value=1.0,
|
184 |
+
step=0.1,
|
185 |
+
info="Adjust the speed of the audio.",
|
186 |
+
)
|
187 |
+
cross_fade_duration_slider = gr.Slider(
|
188 |
+
label="Cross-Fade Duration (s)",
|
189 |
+
minimum=0.0,
|
190 |
+
maximum=1.0,
|
191 |
+
value=0.15,
|
192 |
+
step=0.01,
|
193 |
+
info="Set the duration of the cross-fade between audio clips.",
|
194 |
+
)
|
195 |
+
|
196 |
+
audio_output = gr.Audio(label="Synthesized Audio")
|
197 |
+
spectrogram_output = gr.Image(label="Spectrogram")
|
198 |
+
|
199 |
+
@gpu_decorator
|
200 |
+
def basic_tts(
|
201 |
+
ref_audio_input,
|
202 |
+
ref_text_input,
|
203 |
+
gen_text_input,
|
204 |
+
remove_silence,
|
205 |
+
cross_fade_duration_slider,
|
206 |
+
speed_slider,
|
207 |
+
):
|
208 |
+
audio_out, spectrogram_path, ref_text_out = infer(
|
209 |
+
ref_audio_input,
|
210 |
+
ref_text_input,
|
211 |
+
gen_text_input,
|
212 |
+
tts_model_choice,
|
213 |
+
remove_silence,
|
214 |
+
cross_fade_duration_slider,
|
215 |
+
speed_slider,
|
216 |
+
)
|
217 |
+
return audio_out, spectrogram_path, gr.update(value=ref_text_out)
|
218 |
+
|
219 |
+
generate_btn.click(
|
220 |
+
basic_tts,
|
221 |
+
inputs=[
|
222 |
+
ref_audio_input,
|
223 |
+
ref_text_input,
|
224 |
+
gen_text_input,
|
225 |
+
remove_silence,
|
226 |
+
cross_fade_duration_slider,
|
227 |
+
speed_slider,
|
228 |
+
],
|
229 |
+
outputs=[audio_output, spectrogram_output, ref_text_input],
|
230 |
+
)
|
231 |
+
|
232 |
+
|
233 |
+
def parse_speechtypes_text(gen_text):
|
234 |
+
# Pattern to find {speechtype}
|
235 |
+
pattern = r"\{(.*?)\}"
|
236 |
+
|
237 |
+
# Split the text by the pattern
|
238 |
+
tokens = re.split(pattern, gen_text)
|
239 |
+
|
240 |
+
segments = []
|
241 |
+
|
242 |
+
current_style = "Regular"
|
243 |
+
|
244 |
+
for i in range(len(tokens)):
|
245 |
+
if i % 2 == 0:
|
246 |
+
# This is text
|
247 |
+
text = tokens[i].strip()
|
248 |
+
if text:
|
249 |
+
segments.append({"style": current_style, "text": text})
|
250 |
+
else:
|
251 |
+
# This is style
|
252 |
+
style = tokens[i].strip()
|
253 |
+
current_style = style
|
254 |
+
|
255 |
+
return segments
|
256 |
+
|
257 |
+
|
258 |
+
with gr.Blocks() as app_multistyle:
|
259 |
+
# New section for multistyle generation
|
260 |
+
gr.Markdown(
|
261 |
+
"""
|
262 |
+
# Multiple Speech-Type Generation
|
263 |
+
|
264 |
+
This section allows you to generate multiple speech types or multiple people's voices. Enter your text in the format shown below, and 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.
|
265 |
+
"""
|
266 |
+
)
|
267 |
+
|
268 |
+
with gr.Row():
|
269 |
+
gr.Markdown(
|
270 |
+
"""
|
271 |
+
**Example Input:**
|
272 |
+
{Regular} Hello, I'd like to order a sandwich please.
|
273 |
+
{Surprised} What do you mean you're out of bread?
|
274 |
+
{Sad} I really wanted a sandwich though...
|
275 |
+
{Angry} You know what, darn you and your little shop!
|
276 |
+
{Whisper} I'll just go back home and cry now.
|
277 |
+
{Shouting} Why me?!
|
278 |
+
"""
|
279 |
+
)
|
280 |
+
|
281 |
+
gr.Markdown(
|
282 |
+
"""
|
283 |
+
**Example Input 2:**
|
284 |
+
{Speaker1_Happy} Hello, I'd like to order a sandwich please.
|
285 |
+
{Speaker2_Regular} Sorry, we're out of bread.
|
286 |
+
{Speaker1_Sad} I really wanted a sandwich though...
|
287 |
+
{Speaker2_Whisper} I'll give you the last one I was hiding.
|
288 |
+
"""
|
289 |
+
)
|
290 |
+
|
291 |
+
gr.Markdown(
|
292 |
+
"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."
|
293 |
+
)
|
294 |
+
|
295 |
+
# Regular speech type (mandatory)
|
296 |
+
with gr.Row():
|
297 |
+
with gr.Column():
|
298 |
+
regular_name = gr.Textbox(value="Regular", label="Speech Type Name")
|
299 |
+
regular_insert = gr.Button("Insert Label", variant="secondary")
|
300 |
+
regular_audio = gr.Audio(label="Regular Reference Audio", type="filepath")
|
301 |
+
regular_ref_text = gr.Textbox(label="Reference Text (Regular)", lines=2)
|
302 |
+
|
303 |
+
# Regular speech type (max 100)
|
304 |
+
max_speech_types = 100
|
305 |
+
speech_type_rows = [] # 99
|
306 |
+
speech_type_names = [regular_name] # 100
|
307 |
+
speech_type_audios = [regular_audio] # 100
|
308 |
+
speech_type_ref_texts = [regular_ref_text] # 100
|
309 |
+
speech_type_delete_btns = [] # 99
|
310 |
+
speech_type_insert_btns = [regular_insert] # 100
|
311 |
+
|
312 |
+
# Additional speech types (99 more)
|
313 |
+
for i in range(max_speech_types - 1):
|
314 |
+
with gr.Row(visible=False) as row:
|
315 |
+
with gr.Column():
|
316 |
+
name_input = gr.Textbox(label="Speech Type Name")
|
317 |
+
delete_btn = gr.Button("Delete Type", variant="secondary")
|
318 |
+
insert_btn = gr.Button("Insert Label", variant="secondary")
|
319 |
+
audio_input = gr.Audio(label="Reference Audio", type="filepath")
|
320 |
+
ref_text_input = gr.Textbox(label="Reference Text", lines=2)
|
321 |
+
speech_type_rows.append(row)
|
322 |
+
speech_type_names.append(name_input)
|
323 |
+
speech_type_audios.append(audio_input)
|
324 |
+
speech_type_ref_texts.append(ref_text_input)
|
325 |
+
speech_type_delete_btns.append(delete_btn)
|
326 |
+
speech_type_insert_btns.append(insert_btn)
|
327 |
+
|
328 |
+
# Button to add speech type
|
329 |
+
add_speech_type_btn = gr.Button("Add Speech Type")
|
330 |
+
|
331 |
+
# Keep track of current number of speech types
|
332 |
+
speech_type_count = gr.State(value=1)
|
333 |
+
|
334 |
+
# Function to add a speech type
|
335 |
+
def add_speech_type_fn(speech_type_count):
|
336 |
+
if speech_type_count < max_speech_types:
|
337 |
+
speech_type_count += 1
|
338 |
+
# Prepare updates for the rows
|
339 |
+
row_updates = []
|
340 |
+
for i in range(1, max_speech_types):
|
341 |
+
if i < speech_type_count:
|
342 |
+
row_updates.append(gr.update(visible=True))
|
343 |
+
else:
|
344 |
+
row_updates.append(gr.update())
|
345 |
+
else:
|
346 |
+
# Optionally, show a warning
|
347 |
+
row_updates = [gr.update() for _ in range(1, max_speech_types)]
|
348 |
+
return [speech_type_count] + row_updates
|
349 |
+
|
350 |
+
add_speech_type_btn.click(
|
351 |
+
add_speech_type_fn, inputs=speech_type_count, outputs=[speech_type_count] + speech_type_rows
|
352 |
+
)
|
353 |
+
|
354 |
+
# Function to delete a speech type
|
355 |
+
def make_delete_speech_type_fn(index):
|
356 |
+
def delete_speech_type_fn(speech_type_count):
|
357 |
+
# Prepare updates
|
358 |
+
row_updates = []
|
359 |
+
|
360 |
+
for i in range(1, max_speech_types):
|
361 |
+
if i == index:
|
362 |
+
row_updates.append(gr.update(visible=False))
|
363 |
+
else:
|
364 |
+
row_updates.append(gr.update())
|
365 |
+
|
366 |
+
speech_type_count = max(1, speech_type_count)
|
367 |
+
|
368 |
+
return [speech_type_count] + row_updates
|
369 |
+
|
370 |
+
return delete_speech_type_fn
|
371 |
+
|
372 |
+
# Update delete button clicks
|
373 |
+
for i, delete_btn in enumerate(speech_type_delete_btns):
|
374 |
+
delete_fn = make_delete_speech_type_fn(i)
|
375 |
+
delete_btn.click(delete_fn, inputs=speech_type_count, outputs=[speech_type_count] + speech_type_rows)
|
376 |
+
|
377 |
+
# Text input for the prompt
|
378 |
+
gen_text_input_multistyle = gr.Textbox(
|
379 |
+
label="Text to Generate",
|
380 |
+
lines=10,
|
381 |
+
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?!",
|
382 |
+
)
|
383 |
+
|
384 |
+
def make_insert_speech_type_fn(index):
|
385 |
+
def insert_speech_type_fn(current_text, speech_type_name):
|
386 |
+
current_text = current_text or ""
|
387 |
+
speech_type_name = speech_type_name or "None"
|
388 |
+
updated_text = current_text + f"{{{speech_type_name}}} "
|
389 |
+
return gr.update(value=updated_text)
|
390 |
+
|
391 |
+
return insert_speech_type_fn
|
392 |
+
|
393 |
+
for i, insert_btn in enumerate(speech_type_insert_btns):
|
394 |
+
insert_fn = make_insert_speech_type_fn(i)
|
395 |
+
insert_btn.click(
|
396 |
+
insert_fn,
|
397 |
+
inputs=[gen_text_input_multistyle, speech_type_names[i]],
|
398 |
+
outputs=gen_text_input_multistyle,
|
399 |
+
)
|
400 |
+
|
401 |
+
with gr.Accordion("Advanced Settings", open=False):
|
402 |
+
remove_silence_multistyle = gr.Checkbox(
|
403 |
+
label="Remove Silences",
|
404 |
+
value=True,
|
405 |
+
)
|
406 |
+
|
407 |
+
# Generate button
|
408 |
+
generate_multistyle_btn = gr.Button("Generate Multi-Style Speech", variant="primary")
|
409 |
+
|
410 |
+
# Output audio
|
411 |
+
audio_output_multistyle = gr.Audio(label="Synthesized Audio")
|
412 |
+
|
413 |
+
@gpu_decorator
|
414 |
+
def generate_multistyle_speech(
|
415 |
+
gen_text,
|
416 |
+
*args,
|
417 |
+
):
|
418 |
+
speech_type_names_list = args[:max_speech_types]
|
419 |
+
speech_type_audios_list = args[max_speech_types : 2 * max_speech_types]
|
420 |
+
speech_type_ref_texts_list = args[2 * max_speech_types : 3 * max_speech_types]
|
421 |
+
remove_silence = args[3 * max_speech_types]
|
422 |
+
# Collect the speech types and their audios into a dict
|
423 |
+
speech_types = OrderedDict()
|
424 |
+
|
425 |
+
ref_text_idx = 0
|
426 |
+
for name_input, audio_input, ref_text_input in zip(
|
427 |
+
speech_type_names_list, speech_type_audios_list, speech_type_ref_texts_list
|
428 |
+
):
|
429 |
+
if name_input and audio_input:
|
430 |
+
speech_types[name_input] = {"audio": audio_input, "ref_text": ref_text_input}
|
431 |
+
else:
|
432 |
+
speech_types[f"@{ref_text_idx}@"] = {"audio": "", "ref_text": ""}
|
433 |
+
ref_text_idx += 1
|
434 |
+
|
435 |
+
# Parse the gen_text into segments
|
436 |
+
segments = parse_speechtypes_text(gen_text)
|
437 |
+
|
438 |
+
# For each segment, generate speech
|
439 |
+
generated_audio_segments = []
|
440 |
+
current_style = "Regular"
|
441 |
+
|
442 |
+
for segment in segments:
|
443 |
+
style = segment["style"]
|
444 |
+
text = segment["text"]
|
445 |
+
|
446 |
+
if style in speech_types:
|
447 |
+
current_style = style
|
448 |
+
else:
|
449 |
+
# If style not available, default to Regular
|
450 |
+
current_style = "Regular"
|
451 |
+
|
452 |
+
ref_audio = speech_types[current_style]["audio"]
|
453 |
+
ref_text = speech_types[current_style].get("ref_text", "")
|
454 |
+
|
455 |
+
# Generate speech for this segment
|
456 |
+
audio_out, _, ref_text_out = infer(
|
457 |
+
ref_audio, ref_text, text, tts_model_choice, remove_silence, 0, show_info=print
|
458 |
+
) # show_info=print no pull to top when generating
|
459 |
+
sr, audio_data = audio_out
|
460 |
+
|
461 |
+
generated_audio_segments.append(audio_data)
|
462 |
+
speech_types[current_style]["ref_text"] = ref_text_out
|
463 |
+
|
464 |
+
# Concatenate all audio segments
|
465 |
+
if generated_audio_segments:
|
466 |
+
final_audio_data = np.concatenate(generated_audio_segments)
|
467 |
+
return [(sr, final_audio_data)] + [
|
468 |
+
gr.update(value=speech_types[style]["ref_text"]) for style in speech_types
|
469 |
+
]
|
470 |
+
else:
|
471 |
+
gr.Warning("No audio generated.")
|
472 |
+
return [None] + [gr.update(value=speech_types[style]["ref_text"]) for style in speech_types]
|
473 |
+
|
474 |
+
generate_multistyle_btn.click(
|
475 |
+
generate_multistyle_speech,
|
476 |
+
inputs=[
|
477 |
+
gen_text_input_multistyle,
|
478 |
+
]
|
479 |
+
+ speech_type_names
|
480 |
+
+ speech_type_audios
|
481 |
+
+ speech_type_ref_texts
|
482 |
+
+ [
|
483 |
+
remove_silence_multistyle,
|
484 |
+
],
|
485 |
+
outputs=[audio_output_multistyle] + speech_type_ref_texts,
|
486 |
+
)
|
487 |
+
|
488 |
+
# Validation function to disable Generate button if speech types are missing
|
489 |
+
def validate_speech_types(gen_text, regular_name, *args):
|
490 |
+
speech_type_names_list = args[:max_speech_types]
|
491 |
+
|
492 |
+
# Collect the speech types names
|
493 |
+
speech_types_available = set()
|
494 |
+
if regular_name:
|
495 |
+
speech_types_available.add(regular_name)
|
496 |
+
for name_input in speech_type_names_list:
|
497 |
+
if name_input:
|
498 |
+
speech_types_available.add(name_input)
|
499 |
+
|
500 |
+
# Parse the gen_text to get the speech types used
|
501 |
+
segments = parse_speechtypes_text(gen_text)
|
502 |
+
speech_types_in_text = set(segment["style"] for segment in segments)
|
503 |
+
|
504 |
+
# Check if all speech types in text are available
|
505 |
+
missing_speech_types = speech_types_in_text - speech_types_available
|
506 |
+
|
507 |
+
if missing_speech_types:
|
508 |
+
# Disable the generate button
|
509 |
+
return gr.update(interactive=False)
|
510 |
+
else:
|
511 |
+
# Enable the generate button
|
512 |
+
return gr.update(interactive=True)
|
513 |
+
|
514 |
+
gen_text_input_multistyle.change(
|
515 |
+
validate_speech_types,
|
516 |
+
inputs=[gen_text_input_multistyle, regular_name] + speech_type_names,
|
517 |
+
outputs=generate_multistyle_btn,
|
518 |
+
)
|
519 |
+
|
520 |
+
|
521 |
+
with gr.Blocks() as app_chat:
|
522 |
+
gr.Markdown(
|
523 |
+
"""
|
524 |
+
# Voice Chat
|
525 |
+
Have a conversation with an AI using your reference voice!
|
526 |
+
1. Upload a reference audio clip and optionally its transcript.
|
527 |
+
2. Load the chat model.
|
528 |
+
3. Record your message through your microphone.
|
529 |
+
4. The AI will respond using the reference voice.
|
530 |
+
"""
|
531 |
+
)
|
532 |
+
|
533 |
+
if not USING_SPACES:
|
534 |
+
load_chat_model_btn = gr.Button("Load Chat Model", variant="primary")
|
535 |
+
|
536 |
+
chat_interface_container = gr.Column(visible=False)
|
537 |
+
|
538 |
+
@gpu_decorator
|
539 |
+
def load_chat_model():
|
540 |
+
global chat_model_state, chat_tokenizer_state
|
541 |
+
if chat_model_state is None:
|
542 |
+
show_info = gr.Info
|
543 |
+
show_info("Loading chat model...")
|
544 |
+
model_name = "Qwen/Qwen2.5-3B-Instruct"
|
545 |
+
chat_model_state = AutoModelForCausalLM.from_pretrained(
|
546 |
+
model_name, torch_dtype="auto", device_map="auto"
|
547 |
+
)
|
548 |
+
chat_tokenizer_state = AutoTokenizer.from_pretrained(model_name)
|
549 |
+
show_info("Chat model loaded.")
|
550 |
+
|
551 |
+
return gr.update(visible=False), gr.update(visible=True)
|
552 |
+
|
553 |
+
load_chat_model_btn.click(load_chat_model, outputs=[load_chat_model_btn, chat_interface_container])
|
554 |
+
|
555 |
+
else:
|
556 |
+
chat_interface_container = gr.Column()
|
557 |
+
|
558 |
+
if chat_model_state is None:
|
559 |
+
model_name = "Qwen/Qwen2.5-3B-Instruct"
|
560 |
+
chat_model_state = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")
|
561 |
+
chat_tokenizer_state = AutoTokenizer.from_pretrained(model_name)
|
562 |
+
|
563 |
+
with chat_interface_container:
|
564 |
+
with gr.Row():
|
565 |
+
with gr.Column():
|
566 |
+
ref_audio_chat = gr.Audio(label="Reference Audio", type="filepath")
|
567 |
+
with gr.Column():
|
568 |
+
with gr.Accordion("Advanced Settings", open=False):
|
569 |
+
remove_silence_chat = gr.Checkbox(
|
570 |
+
label="Remove Silences",
|
571 |
+
value=True,
|
572 |
+
)
|
573 |
+
ref_text_chat = gr.Textbox(
|
574 |
+
label="Reference Text",
|
575 |
+
info="Optional: Leave blank to auto-transcribe",
|
576 |
+
lines=2,
|
577 |
+
)
|
578 |
+
system_prompt_chat = gr.Textbox(
|
579 |
+
label="System Prompt",
|
580 |
+
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.",
|
581 |
+
lines=2,
|
582 |
+
)
|
583 |
+
|
584 |
+
chatbot_interface = gr.Chatbot(label="Conversation")
|
585 |
+
|
586 |
+
with gr.Row():
|
587 |
+
with gr.Column():
|
588 |
+
audio_input_chat = gr.Microphone(
|
589 |
+
label="Speak your message",
|
590 |
+
type="filepath",
|
591 |
+
)
|
592 |
+
audio_output_chat = gr.Audio(autoplay=True)
|
593 |
+
with gr.Column():
|
594 |
+
text_input_chat = gr.Textbox(
|
595 |
+
label="Type your message",
|
596 |
+
lines=1,
|
597 |
+
)
|
598 |
+
send_btn_chat = gr.Button("Send Message")
|
599 |
+
clear_btn_chat = gr.Button("Clear Conversation")
|
600 |
+
|
601 |
+
conversation_state = gr.State(
|
602 |
+
value=[
|
603 |
+
{
|
604 |
+
"role": "system",
|
605 |
+
"content": "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.",
|
606 |
+
}
|
607 |
+
]
|
608 |
+
)
|
609 |
+
|
610 |
+
# Modify process_audio_input to use model and tokenizer from state
|
611 |
+
@gpu_decorator
|
612 |
+
def process_audio_input(audio_path, text, history, conv_state):
|
613 |
+
"""Handle audio or text input from user"""
|
614 |
+
|
615 |
+
if not audio_path and not text.strip():
|
616 |
+
return history, conv_state, ""
|
617 |
+
|
618 |
+
if audio_path:
|
619 |
+
text = preprocess_ref_audio_text(audio_path, text)[1]
|
620 |
+
|
621 |
+
if not text.strip():
|
622 |
+
return history, conv_state, ""
|
623 |
+
|
624 |
+
conv_state.append({"role": "user", "content": text})
|
625 |
+
history.append((text, None))
|
626 |
+
|
627 |
+
response = generate_response(conv_state, chat_model_state, chat_tokenizer_state)
|
628 |
+
|
629 |
+
conv_state.append({"role": "assistant", "content": response})
|
630 |
+
history[-1] = (text, response)
|
631 |
+
|
632 |
+
return history, conv_state, ""
|
633 |
+
|
634 |
+
@gpu_decorator
|
635 |
+
def generate_audio_response(history, ref_audio, ref_text, remove_silence):
|
636 |
+
"""Generate TTS audio for AI response"""
|
637 |
+
if not history or not ref_audio:
|
638 |
+
return None
|
639 |
+
|
640 |
+
last_user_message, last_ai_response = history[-1]
|
641 |
+
if not last_ai_response:
|
642 |
+
return None
|
643 |
+
|
644 |
+
audio_result, _, ref_text_out = infer(
|
645 |
+
ref_audio,
|
646 |
+
ref_text,
|
647 |
+
last_ai_response,
|
648 |
+
tts_model_choice,
|
649 |
+
remove_silence,
|
650 |
+
cross_fade_duration=0.15,
|
651 |
+
speed=1.0,
|
652 |
+
show_info=print, # show_info=print no pull to top when generating
|
653 |
+
)
|
654 |
+
return audio_result, gr.update(value=ref_text_out)
|
655 |
+
|
656 |
+
def clear_conversation():
|
657 |
+
"""Reset the conversation"""
|
658 |
+
return [], [
|
659 |
+
{
|
660 |
+
"role": "system",
|
661 |
+
"content": "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.",
|
662 |
+
}
|
663 |
+
]
|
664 |
+
|
665 |
+
def update_system_prompt(new_prompt):
|
666 |
+
"""Update the system prompt and reset the conversation"""
|
667 |
+
new_conv_state = [{"role": "system", "content": new_prompt}]
|
668 |
+
return [], new_conv_state
|
669 |
+
|
670 |
+
# Handle audio input
|
671 |
+
audio_input_chat.stop_recording(
|
672 |
+
process_audio_input,
|
673 |
+
inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state],
|
674 |
+
outputs=[chatbot_interface, conversation_state],
|
675 |
+
).then(
|
676 |
+
generate_audio_response,
|
677 |
+
inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, remove_silence_chat],
|
678 |
+
outputs=[audio_output_chat, ref_text_chat],
|
679 |
+
).then(
|
680 |
+
lambda: None,
|
681 |
+
None,
|
682 |
+
audio_input_chat,
|
683 |
+
)
|
684 |
+
|
685 |
+
# Handle text input
|
686 |
+
text_input_chat.submit(
|
687 |
+
process_audio_input,
|
688 |
+
inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state],
|
689 |
+
outputs=[chatbot_interface, conversation_state],
|
690 |
+
).then(
|
691 |
+
generate_audio_response,
|
692 |
+
inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, remove_silence_chat],
|
693 |
+
outputs=[audio_output_chat, ref_text_chat],
|
694 |
+
).then(
|
695 |
+
lambda: None,
|
696 |
+
None,
|
697 |
+
text_input_chat,
|
698 |
+
)
|
699 |
+
|
700 |
+
# Handle send button
|
701 |
+
send_btn_chat.click(
|
702 |
+
process_audio_input,
|
703 |
+
inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state],
|
704 |
+
outputs=[chatbot_interface, conversation_state],
|
705 |
+
).then(
|
706 |
+
generate_audio_response,
|
707 |
+
inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, remove_silence_chat],
|
708 |
+
outputs=[audio_output_chat, ref_text_chat],
|
709 |
+
).then(
|
710 |
+
lambda: None,
|
711 |
+
None,
|
712 |
+
text_input_chat,
|
713 |
+
)
|
714 |
+
|
715 |
+
# Handle clear button
|
716 |
+
clear_btn_chat.click(
|
717 |
+
clear_conversation,
|
718 |
+
outputs=[chatbot_interface, conversation_state],
|
719 |
+
)
|
720 |
+
|
721 |
+
# Handle system prompt change and reset conversation
|
722 |
+
system_prompt_chat.change(
|
723 |
+
update_system_prompt,
|
724 |
+
inputs=system_prompt_chat,
|
725 |
+
outputs=[chatbot_interface, conversation_state],
|
726 |
+
)
|
727 |
+
|
728 |
+
|
729 |
+
with gr.Blocks() as app:
|
730 |
+
gr.Markdown(
|
731 |
+
"""
|
732 |
+
# E2/F5 TTS
|
733 |
+
|
734 |
+
This is a local web UI for F5 TTS with advanced batch processing support. This app supports the following TTS models:
|
735 |
+
|
736 |
+
* [F5-TTS](https://arxiv.org/abs/2410.06885) (A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching)
|
737 |
+
* [E2 TTS](https://arxiv.org/abs/2406.18009) (Embarrassingly Easy Fully Non-Autoregressive Zero-Shot TTS)
|
738 |
+
|
739 |
+
The checkpoints currently support English and Chinese.
|
740 |
+
|
741 |
+
If you're having issues, try converting your reference audio to WAV or MP3, clipping it to 15s with ✂ in the bottom right corner (otherwise might have non-optimal auto-trimmed result).
|
742 |
+
|
743 |
+
**NOTE: Reference text will be automatically transcribed with Whisper if not provided. For best results, keep your reference clips short (<15s). Ensure the audio is fully uploaded before generating.**
|
744 |
+
"""
|
745 |
+
)
|
746 |
+
|
747 |
+
last_used_custom = files("f5_tts").joinpath("infer/.cache/last_used_custom.txt")
|
748 |
+
|
749 |
+
def load_last_used_custom():
|
750 |
+
try:
|
751 |
+
with open(last_used_custom, "r") as f:
|
752 |
+
return f.read().split(",")
|
753 |
+
except FileNotFoundError:
|
754 |
+
last_used_custom.parent.mkdir(parents=True, exist_ok=True)
|
755 |
+
return [
|
756 |
+
"hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors",
|
757 |
+
"hf://SWivid/F5-TTS/F5TTS_Base/vocab.txt",
|
758 |
+
]
|
759 |
+
|
760 |
+
def switch_tts_model(new_choice):
|
761 |
+
global tts_model_choice
|
762 |
+
if new_choice == "Custom": # override in case webpage is refreshed
|
763 |
+
custom_ckpt_path, custom_vocab_path = load_last_used_custom()
|
764 |
+
tts_model_choice = ["Custom", custom_ckpt_path, custom_vocab_path]
|
765 |
+
return gr.update(visible=True, value=custom_ckpt_path), gr.update(visible=True, value=custom_vocab_path)
|
766 |
+
else:
|
767 |
+
tts_model_choice = new_choice
|
768 |
+
return gr.update(visible=False), gr.update(visible=False)
|
769 |
+
|
770 |
+
def set_custom_model(custom_ckpt_path, custom_vocab_path):
|
771 |
+
global tts_model_choice
|
772 |
+
tts_model_choice = ["Custom", custom_ckpt_path, custom_vocab_path]
|
773 |
+
with open(last_used_custom, "w") as f:
|
774 |
+
f.write(f"{custom_ckpt_path},{custom_vocab_path}")
|
775 |
+
|
776 |
+
with gr.Row():
|
777 |
+
if not USING_SPACES:
|
778 |
+
choose_tts_model = gr.Radio(
|
779 |
+
choices=[DEFAULT_TTS_MODEL, "E2-TTS", "Custom"], label="Choose TTS Model", value=DEFAULT_TTS_MODEL
|
780 |
+
)
|
781 |
+
else:
|
782 |
+
choose_tts_model = gr.Radio(
|
783 |
+
choices=[DEFAULT_TTS_MODEL, "E2-TTS"], label="Choose TTS Model", value=DEFAULT_TTS_MODEL
|
784 |
+
)
|
785 |
+
custom_ckpt_path = gr.Dropdown(
|
786 |
+
choices=["hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors"],
|
787 |
+
value=load_last_used_custom()[0],
|
788 |
+
allow_custom_value=True,
|
789 |
+
label="MODEL CKPT: local_path | hf://user_id/repo_id/model_ckpt",
|
790 |
+
visible=False,
|
791 |
+
)
|
792 |
+
custom_vocab_path = gr.Dropdown(
|
793 |
+
choices=["hf://SWivid/F5-TTS/F5TTS_Base/vocab.txt"],
|
794 |
+
value=load_last_used_custom()[1],
|
795 |
+
allow_custom_value=True,
|
796 |
+
label="VOCAB FILE: local_path | hf://user_id/repo_id/vocab_file",
|
797 |
+
visible=False,
|
798 |
+
)
|
799 |
+
|
800 |
+
choose_tts_model.change(
|
801 |
+
switch_tts_model,
|
802 |
+
inputs=[choose_tts_model],
|
803 |
+
outputs=[custom_ckpt_path, custom_vocab_path],
|
804 |
+
show_progress="hidden",
|
805 |
+
)
|
806 |
+
custom_ckpt_path.change(
|
807 |
+
set_custom_model,
|
808 |
+
inputs=[custom_ckpt_path, custom_vocab_path],
|
809 |
+
show_progress="hidden",
|
810 |
+
)
|
811 |
+
custom_vocab_path.change(
|
812 |
+
set_custom_model,
|
813 |
+
inputs=[custom_ckpt_path, custom_vocab_path],
|
814 |
+
show_progress="hidden",
|
815 |
+
)
|
816 |
+
|
817 |
+
gr.TabbedInterface(
|
818 |
+
[app_tts, app_multistyle, app_chat, app_credits],
|
819 |
+
["Basic-TTS", "Multi-Speech", "Voice-Chat", "Credits"],
|
820 |
+
)
|
821 |
+
|
822 |
+
|
823 |
+
@click.command()
|
824 |
+
@click.option("--port", "-p", default=None, type=int, help="Port to run the app on")
|
825 |
+
@click.option("--host", "-H", default=None, help="Host to run the app on")
|
826 |
+
@click.option(
|
827 |
+
"--share",
|
828 |
+
"-s",
|
829 |
+
default=False,
|
830 |
+
is_flag=True,
|
831 |
+
help="Share the app via Gradio share link",
|
832 |
+
)
|
833 |
+
@click.option("--api", "-a", default=True, is_flag=True, help="Allow API access")
|
834 |
+
@click.option(
|
835 |
+
"--root_path",
|
836 |
+
"-r",
|
837 |
+
default=None,
|
838 |
+
type=str,
|
839 |
+
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".',
|
840 |
+
)
|
841 |
+
def main(port, host, share, api, root_path):
|
842 |
+
global app
|
843 |
+
print("Starting app...")
|
844 |
+
app.queue(api_open=api).launch(server_name=host, server_port=port, share=share, show_api=api, root_path=root_path)
|
845 |
+
|
846 |
+
|
847 |
+
if __name__ == "__main__":
|
848 |
+
if not USING_SPACES:
|
849 |
+
main()
|
850 |
+
else:
|
851 |
+
app.queue().launch()
|
infer/speech_edit.py
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
os.environ["PYTOCH_ENABLE_MPS_FALLBACK"] = "1" # for MPS device compatibility
|
4 |
+
|
5 |
+
import torch
|
6 |
+
import torch.nn.functional as F
|
7 |
+
import torchaudio
|
8 |
+
|
9 |
+
from f5_tts.infer.utils_infer import load_checkpoint, load_vocoder, save_spectrogram
|
10 |
+
from f5_tts.model import CFM, DiT, UNetT
|
11 |
+
from f5_tts.model.utils import convert_char_to_pinyin, get_tokenizer
|
12 |
+
|
13 |
+
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
14 |
+
|
15 |
+
|
16 |
+
# --------------------- Dataset Settings -------------------- #
|
17 |
+
|
18 |
+
target_sample_rate = 24000
|
19 |
+
n_mel_channels = 100
|
20 |
+
hop_length = 256
|
21 |
+
win_length = 1024
|
22 |
+
n_fft = 1024
|
23 |
+
mel_spec_type = "vocos" # 'vocos' or 'bigvgan'
|
24 |
+
target_rms = 0.1
|
25 |
+
|
26 |
+
tokenizer = "pinyin"
|
27 |
+
dataset_name = "Emilia_ZH_EN"
|
28 |
+
|
29 |
+
|
30 |
+
# ---------------------- infer setting ---------------------- #
|
31 |
+
|
32 |
+
seed = None # int | None
|
33 |
+
|
34 |
+
exp_name = "F5TTS_Base" # F5TTS_Base | E2TTS_Base
|
35 |
+
ckpt_step = 1200000
|
36 |
+
|
37 |
+
nfe_step = 32 # 16, 32
|
38 |
+
cfg_strength = 2.0
|
39 |
+
ode_method = "euler" # euler | midpoint
|
40 |
+
sway_sampling_coef = -1.0
|
41 |
+
speed = 1.0
|
42 |
+
|
43 |
+
if exp_name == "F5TTS_Base":
|
44 |
+
model_cls = DiT
|
45 |
+
model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
46 |
+
|
47 |
+
elif exp_name == "E2TTS_Base":
|
48 |
+
model_cls = UNetT
|
49 |
+
model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
|
50 |
+
|
51 |
+
ckpt_path = f"ckpts/{exp_name}/model_{ckpt_step}.safetensors"
|
52 |
+
output_dir = "tests"
|
53 |
+
|
54 |
+
# [leverage https://github.com/MahmoudAshraf97/ctc-forced-aligner to get char level alignment]
|
55 |
+
# pip install git+https://github.com/MahmoudAshraf97/ctc-forced-aligner.git
|
56 |
+
# [write the origin_text into a file, e.g. tests/test_edit.txt]
|
57 |
+
# 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"
|
58 |
+
# [result will be saved at same path of audio file]
|
59 |
+
# [--language "zho" for Chinese, "eng" for English]
|
60 |
+
# [if local ckpt, set --alignment_model "../checkpoints/mms-300m-1130-forced-aligner"]
|
61 |
+
|
62 |
+
audio_to_edit = "src/f5_tts/infer/examples/basic/basic_ref_en.wav"
|
63 |
+
origin_text = "Some call me nature, others call me mother nature."
|
64 |
+
target_text = "Some call me optimist, others call me realist."
|
65 |
+
parts_to_edit = [
|
66 |
+
[1.42, 2.44],
|
67 |
+
[4.04, 4.9],
|
68 |
+
] # stard_ends of "nature" & "mother nature", in seconds
|
69 |
+
fix_duration = [
|
70 |
+
1.2,
|
71 |
+
1,
|
72 |
+
] # fix duration for "optimist" & "realist", in seconds
|
73 |
+
|
74 |
+
# audio_to_edit = "src/f5_tts/infer/examples/basic/basic_ref_zh.wav"
|
75 |
+
# origin_text = "对,这就是我,万人敬仰的太乙真人。"
|
76 |
+
# target_text = "对,那就是你,万人敬仰的太白金星。"
|
77 |
+
# parts_to_edit = [[0.84, 1.4], [1.92, 2.4], [4.26, 6.26], ]
|
78 |
+
# fix_duration = None # use origin text duration
|
79 |
+
|
80 |
+
|
81 |
+
# -------------------------------------------------#
|
82 |
+
|
83 |
+
use_ema = True
|
84 |
+
|
85 |
+
if not os.path.exists(output_dir):
|
86 |
+
os.makedirs(output_dir)
|
87 |
+
|
88 |
+
# Vocoder model
|
89 |
+
local = False
|
90 |
+
if mel_spec_type == "vocos":
|
91 |
+
vocoder_local_path = "../checkpoints/charactr/vocos-mel-24khz"
|
92 |
+
elif mel_spec_type == "bigvgan":
|
93 |
+
vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x"
|
94 |
+
vocoder = load_vocoder(vocoder_name=mel_spec_type, is_local=local, local_path=vocoder_local_path)
|
95 |
+
|
96 |
+
# Tokenizer
|
97 |
+
vocab_char_map, vocab_size = get_tokenizer(dataset_name, tokenizer)
|
98 |
+
|
99 |
+
# Model
|
100 |
+
model = CFM(
|
101 |
+
transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
|
102 |
+
mel_spec_kwargs=dict(
|
103 |
+
n_fft=n_fft,
|
104 |
+
hop_length=hop_length,
|
105 |
+
win_length=win_length,
|
106 |
+
n_mel_channels=n_mel_channels,
|
107 |
+
target_sample_rate=target_sample_rate,
|
108 |
+
mel_spec_type=mel_spec_type,
|
109 |
+
),
|
110 |
+
odeint_kwargs=dict(
|
111 |
+
method=ode_method,
|
112 |
+
),
|
113 |
+
vocab_char_map=vocab_char_map,
|
114 |
+
).to(device)
|
115 |
+
|
116 |
+
dtype = torch.float32 if mel_spec_type == "bigvgan" else None
|
117 |
+
model = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
|
118 |
+
|
119 |
+
# Audio
|
120 |
+
audio, sr = torchaudio.load(audio_to_edit)
|
121 |
+
if audio.shape[0] > 1:
|
122 |
+
audio = torch.mean(audio, dim=0, keepdim=True)
|
123 |
+
rms = torch.sqrt(torch.mean(torch.square(audio)))
|
124 |
+
if rms < target_rms:
|
125 |
+
audio = audio * target_rms / rms
|
126 |
+
if sr != target_sample_rate:
|
127 |
+
resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
|
128 |
+
audio = resampler(audio)
|
129 |
+
offset = 0
|
130 |
+
audio_ = torch.zeros(1, 0)
|
131 |
+
edit_mask = torch.zeros(1, 0, dtype=torch.bool)
|
132 |
+
for part in parts_to_edit:
|
133 |
+
start, end = part
|
134 |
+
part_dur = end - start if fix_duration is None else fix_duration.pop(0)
|
135 |
+
part_dur = part_dur * target_sample_rate
|
136 |
+
start = start * target_sample_rate
|
137 |
+
audio_ = torch.cat((audio_, audio[:, round(offset) : round(start)], torch.zeros(1, round(part_dur))), dim=-1)
|
138 |
+
edit_mask = torch.cat(
|
139 |
+
(
|
140 |
+
edit_mask,
|
141 |
+
torch.ones(1, round((start - offset) / hop_length), dtype=torch.bool),
|
142 |
+
torch.zeros(1, round(part_dur / hop_length), dtype=torch.bool),
|
143 |
+
),
|
144 |
+
dim=-1,
|
145 |
+
)
|
146 |
+
offset = end * target_sample_rate
|
147 |
+
# audio = torch.cat((audio_, audio[:, round(offset):]), dim = -1)
|
148 |
+
edit_mask = F.pad(edit_mask, (0, audio.shape[-1] // hop_length - edit_mask.shape[-1] + 1), value=True)
|
149 |
+
audio = audio.to(device)
|
150 |
+
edit_mask = edit_mask.to(device)
|
151 |
+
|
152 |
+
# Text
|
153 |
+
text_list = [target_text]
|
154 |
+
if tokenizer == "pinyin":
|
155 |
+
final_text_list = convert_char_to_pinyin(text_list)
|
156 |
+
else:
|
157 |
+
final_text_list = [text_list]
|
158 |
+
print(f"text : {text_list}")
|
159 |
+
print(f"pinyin: {final_text_list}")
|
160 |
+
|
161 |
+
# Duration
|
162 |
+
ref_audio_len = 0
|
163 |
+
duration = audio.shape[-1] // hop_length
|
164 |
+
|
165 |
+
# Inference
|
166 |
+
with torch.inference_mode():
|
167 |
+
generated, trajectory = model.sample(
|
168 |
+
cond=audio,
|
169 |
+
text=final_text_list,
|
170 |
+
duration=duration,
|
171 |
+
steps=nfe_step,
|
172 |
+
cfg_strength=cfg_strength,
|
173 |
+
sway_sampling_coef=sway_sampling_coef,
|
174 |
+
seed=seed,
|
175 |
+
edit_mask=edit_mask,
|
176 |
+
)
|
177 |
+
print(f"Generated mel: {generated.shape}")
|
178 |
+
|
179 |
+
# Final result
|
180 |
+
generated = generated.to(torch.float32)
|
181 |
+
generated = generated[:, ref_audio_len:, :]
|
182 |
+
gen_mel_spec = generated.permute(0, 2, 1)
|
183 |
+
if mel_spec_type == "vocos":
|
184 |
+
generated_wave = vocoder.decode(gen_mel_spec).cpu()
|
185 |
+
elif mel_spec_type == "bigvgan":
|
186 |
+
generated_wave = vocoder(gen_mel_spec).squeeze(0).cpu()
|
187 |
+
|
188 |
+
if rms < target_rms:
|
189 |
+
generated_wave = generated_wave * rms / target_rms
|
190 |
+
|
191 |
+
save_spectrogram(gen_mel_spec[0].cpu().numpy(), f"{output_dir}/speech_edit_out.png")
|
192 |
+
torchaudio.save(f"{output_dir}/speech_edit_out.wav", generated_wave, target_sample_rate)
|
193 |
+
print(f"Generated wav: {generated_wave.shape}")
|
infer/utils_infer.py
ADDED
@@ -0,0 +1,538 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
6 |
+
os.environ["PYTOCH_ENABLE_MPS_FALLBACK"] = "1" # for MPS device compatibility
|
7 |
+
sys.path.append(f"../../{os.path.dirname(os.path.abspath(__file__))}/third_party/BigVGAN/")
|
8 |
+
|
9 |
+
import hashlib
|
10 |
+
import re
|
11 |
+
import tempfile
|
12 |
+
from importlib.resources import files
|
13 |
+
|
14 |
+
import matplotlib
|
15 |
+
|
16 |
+
matplotlib.use("Agg")
|
17 |
+
|
18 |
+
import matplotlib.pylab as plt
|
19 |
+
import numpy as np
|
20 |
+
import torch
|
21 |
+
import torchaudio
|
22 |
+
import tqdm
|
23 |
+
from huggingface_hub import snapshot_download, hf_hub_download
|
24 |
+
from pydub import AudioSegment, silence
|
25 |
+
from transformers import pipeline
|
26 |
+
from vocos import Vocos
|
27 |
+
|
28 |
+
from f5_tts.model import CFM
|
29 |
+
from f5_tts.model.utils import (
|
30 |
+
get_tokenizer,
|
31 |
+
convert_char_to_pinyin,
|
32 |
+
)
|
33 |
+
|
34 |
+
_ref_audio_cache = {}
|
35 |
+
|
36 |
+
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
37 |
+
|
38 |
+
# -----------------------------------------
|
39 |
+
|
40 |
+
target_sample_rate = 24000
|
41 |
+
n_mel_channels = 100
|
42 |
+
hop_length = 256
|
43 |
+
win_length = 1024
|
44 |
+
n_fft = 1024
|
45 |
+
mel_spec_type = "vocos"
|
46 |
+
target_rms = 0.1
|
47 |
+
cross_fade_duration = 0.15
|
48 |
+
ode_method = "euler"
|
49 |
+
nfe_step = 32 # 16, 32
|
50 |
+
cfg_strength = 2.0
|
51 |
+
sway_sampling_coef = -1.0
|
52 |
+
speed = 1.0
|
53 |
+
fix_duration = None
|
54 |
+
|
55 |
+
# -----------------------------------------
|
56 |
+
|
57 |
+
|
58 |
+
# chunk text into smaller pieces
|
59 |
+
|
60 |
+
|
61 |
+
def chunk_text(text, max_chars=135):
|
62 |
+
"""
|
63 |
+
Splits the input text into chunks, each with a maximum number of characters.
|
64 |
+
|
65 |
+
Args:
|
66 |
+
text (str): The text to be split.
|
67 |
+
max_chars (int): The maximum number of characters per chunk.
|
68 |
+
|
69 |
+
Returns:
|
70 |
+
List[str]: A list of text chunks.
|
71 |
+
"""
|
72 |
+
chunks = []
|
73 |
+
current_chunk = ""
|
74 |
+
# Split the text into sentences based on punctuation followed by whitespace
|
75 |
+
sentences = re.split(r"(?<=[;:,.!?])\s+|(?<=[;:,。!?])", text)
|
76 |
+
|
77 |
+
for sentence in sentences:
|
78 |
+
if len(current_chunk.encode("utf-8")) + len(sentence.encode("utf-8")) <= max_chars:
|
79 |
+
current_chunk += sentence + " " if sentence and len(sentence[-1].encode("utf-8")) == 1 else sentence
|
80 |
+
else:
|
81 |
+
if current_chunk:
|
82 |
+
chunks.append(current_chunk.strip())
|
83 |
+
current_chunk = sentence + " " if sentence and len(sentence[-1].encode("utf-8")) == 1 else sentence
|
84 |
+
|
85 |
+
if current_chunk:
|
86 |
+
chunks.append(current_chunk.strip())
|
87 |
+
|
88 |
+
return chunks
|
89 |
+
|
90 |
+
|
91 |
+
# load vocoder
|
92 |
+
def load_vocoder(vocoder_name="vocos", is_local=False, local_path="", device=device, hf_cache_dir=None):
|
93 |
+
if vocoder_name == "vocos":
|
94 |
+
# vocoder = Vocos.from_pretrained("charactr/vocos-mel-24khz").to(device)
|
95 |
+
if is_local:
|
96 |
+
print(f"Load vocos from local path {local_path}")
|
97 |
+
config_path = f"{local_path}/config.yaml"
|
98 |
+
model_path = f"{local_path}/pytorch_model.bin"
|
99 |
+
else:
|
100 |
+
print("Download Vocos from huggingface charactr/vocos-mel-24khz")
|
101 |
+
repo_id = "charactr/vocos-mel-24khz"
|
102 |
+
config_path = hf_hub_download(repo_id=repo_id, cache_dir=hf_cache_dir, filename="config.yaml")
|
103 |
+
model_path = hf_hub_download(repo_id=repo_id, cache_dir=hf_cache_dir, filename="pytorch_model.bin")
|
104 |
+
vocoder = Vocos.from_hparams(config_path)
|
105 |
+
state_dict = torch.load(model_path, map_location="cpu", weights_only=True)
|
106 |
+
from vocos.feature_extractors import EncodecFeatures
|
107 |
+
|
108 |
+
if isinstance(vocoder.feature_extractor, EncodecFeatures):
|
109 |
+
encodec_parameters = {
|
110 |
+
"feature_extractor.encodec." + key: value
|
111 |
+
for key, value in vocoder.feature_extractor.encodec.state_dict().items()
|
112 |
+
}
|
113 |
+
state_dict.update(encodec_parameters)
|
114 |
+
vocoder.load_state_dict(state_dict)
|
115 |
+
vocoder = vocoder.eval().to(device)
|
116 |
+
elif vocoder_name == "bigvgan":
|
117 |
+
try:
|
118 |
+
from third_party.BigVGAN import bigvgan
|
119 |
+
except ImportError:
|
120 |
+
print("You need to follow the README to init submodule and change the BigVGAN source code.")
|
121 |
+
if is_local:
|
122 |
+
"""download from https://huggingface.co/nvidia/bigvgan_v2_24khz_100band_256x/tree/main"""
|
123 |
+
vocoder = bigvgan.BigVGAN.from_pretrained(local_path, use_cuda_kernel=False)
|
124 |
+
else:
|
125 |
+
local_path = snapshot_download(repo_id="nvidia/bigvgan_v2_24khz_100band_256x", cache_dir=hf_cache_dir)
|
126 |
+
vocoder = bigvgan.BigVGAN.from_pretrained(local_path, use_cuda_kernel=False)
|
127 |
+
|
128 |
+
vocoder.remove_weight_norm()
|
129 |
+
vocoder = vocoder.eval().to(device)
|
130 |
+
return vocoder
|
131 |
+
|
132 |
+
|
133 |
+
# load asr pipeline
|
134 |
+
|
135 |
+
asr_pipe = None
|
136 |
+
|
137 |
+
|
138 |
+
def initialize_asr_pipeline(device: str = device, dtype=None):
|
139 |
+
if dtype is None:
|
140 |
+
dtype = (
|
141 |
+
torch.float16 if "cuda" in device and torch.cuda.get_device_properties(device).major >= 6 else torch.float32
|
142 |
+
)
|
143 |
+
global asr_pipe
|
144 |
+
asr_pipe = pipeline(
|
145 |
+
"automatic-speech-recognition",
|
146 |
+
model="openai/whisper-large-v3-turbo",
|
147 |
+
torch_dtype=dtype,
|
148 |
+
device=device,
|
149 |
+
)
|
150 |
+
|
151 |
+
|
152 |
+
# transcribe
|
153 |
+
|
154 |
+
|
155 |
+
def transcribe(ref_audio, language=None):
|
156 |
+
global asr_pipe
|
157 |
+
if asr_pipe is None:
|
158 |
+
initialize_asr_pipeline(device=device)
|
159 |
+
return asr_pipe(
|
160 |
+
ref_audio,
|
161 |
+
chunk_length_s=30,
|
162 |
+
batch_size=128,
|
163 |
+
generate_kwargs={"task": "transcribe", "language": language} if language else {"task": "transcribe"},
|
164 |
+
return_timestamps=False,
|
165 |
+
)["text"].strip()
|
166 |
+
|
167 |
+
|
168 |
+
# load model checkpoint for inference
|
169 |
+
|
170 |
+
|
171 |
+
def load_checkpoint(model, ckpt_path, device: str, dtype=None, use_ema=True):
|
172 |
+
if dtype is None:
|
173 |
+
dtype = (
|
174 |
+
torch.float16 if "cuda" in device and torch.cuda.get_device_properties(device).major >= 6 else torch.float32
|
175 |
+
)
|
176 |
+
model = model.to(dtype)
|
177 |
+
|
178 |
+
ckpt_type = ckpt_path.split(".")[-1]
|
179 |
+
if ckpt_type == "safetensors":
|
180 |
+
from safetensors.torch import load_file
|
181 |
+
|
182 |
+
checkpoint = load_file(ckpt_path, device=device)
|
183 |
+
else:
|
184 |
+
checkpoint = torch.load(ckpt_path, map_location=device, weights_only=True)
|
185 |
+
|
186 |
+
if use_ema:
|
187 |
+
if ckpt_type == "safetensors":
|
188 |
+
checkpoint = {"ema_model_state_dict": checkpoint}
|
189 |
+
checkpoint["model_state_dict"] = {
|
190 |
+
k.replace("ema_model.", ""): v
|
191 |
+
for k, v in checkpoint["ema_model_state_dict"].items()
|
192 |
+
if k not in ["initted", "step"]
|
193 |
+
}
|
194 |
+
|
195 |
+
# patch for backward compatibility, 305e3ea
|
196 |
+
for key in ["mel_spec.mel_stft.mel_scale.fb", "mel_spec.mel_stft.spectrogram.window"]:
|
197 |
+
if key in checkpoint["model_state_dict"]:
|
198 |
+
del checkpoint["model_state_dict"][key]
|
199 |
+
|
200 |
+
model.load_state_dict(checkpoint["model_state_dict"])
|
201 |
+
else:
|
202 |
+
if ckpt_type == "safetensors":
|
203 |
+
checkpoint = {"model_state_dict": checkpoint}
|
204 |
+
model.load_state_dict(checkpoint["model_state_dict"])
|
205 |
+
|
206 |
+
del checkpoint
|
207 |
+
torch.cuda.empty_cache()
|
208 |
+
|
209 |
+
return model.to(device)
|
210 |
+
|
211 |
+
|
212 |
+
# load model for inference
|
213 |
+
|
214 |
+
|
215 |
+
def load_model(
|
216 |
+
model_cls,
|
217 |
+
model_cfg,
|
218 |
+
ckpt_path,
|
219 |
+
mel_spec_type=mel_spec_type,
|
220 |
+
vocab_file="",
|
221 |
+
ode_method=ode_method,
|
222 |
+
use_ema=True,
|
223 |
+
device=device,
|
224 |
+
):
|
225 |
+
if vocab_file == "":
|
226 |
+
vocab_file = str(files("f5_tts").joinpath("infer/examples/vocab.txt"))
|
227 |
+
tokenizer = "custom"
|
228 |
+
|
229 |
+
print("\nvocab : ", vocab_file)
|
230 |
+
print("token : ", tokenizer)
|
231 |
+
print("model : ", ckpt_path, "\n")
|
232 |
+
|
233 |
+
vocab_char_map, vocab_size = get_tokenizer(vocab_file, tokenizer)
|
234 |
+
model = CFM(
|
235 |
+
transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
|
236 |
+
mel_spec_kwargs=dict(
|
237 |
+
n_fft=n_fft,
|
238 |
+
hop_length=hop_length,
|
239 |
+
win_length=win_length,
|
240 |
+
n_mel_channels=n_mel_channels,
|
241 |
+
target_sample_rate=target_sample_rate,
|
242 |
+
mel_spec_type=mel_spec_type,
|
243 |
+
),
|
244 |
+
odeint_kwargs=dict(
|
245 |
+
method=ode_method,
|
246 |
+
),
|
247 |
+
vocab_char_map=vocab_char_map,
|
248 |
+
).to(device)
|
249 |
+
|
250 |
+
dtype = torch.float32 if mel_spec_type == "bigvgan" else None
|
251 |
+
model = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
|
252 |
+
|
253 |
+
return model
|
254 |
+
|
255 |
+
|
256 |
+
def remove_silence_edges(audio, silence_threshold=-42):
|
257 |
+
# Remove silence from the start
|
258 |
+
non_silent_start_idx = silence.detect_leading_silence(audio, silence_threshold=silence_threshold)
|
259 |
+
audio = audio[non_silent_start_idx:]
|
260 |
+
|
261 |
+
# Remove silence from the end
|
262 |
+
non_silent_end_duration = audio.duration_seconds
|
263 |
+
for ms in reversed(audio):
|
264 |
+
if ms.dBFS > silence_threshold:
|
265 |
+
break
|
266 |
+
non_silent_end_duration -= 0.001
|
267 |
+
trimmed_audio = audio[: int(non_silent_end_duration * 1000)]
|
268 |
+
|
269 |
+
return trimmed_audio
|
270 |
+
|
271 |
+
|
272 |
+
# preprocess reference audio and text
|
273 |
+
|
274 |
+
|
275 |
+
def preprocess_ref_audio_text(ref_audio_orig, ref_text, clip_short=True, show_info=print, device=device):
|
276 |
+
show_info("Converting audio...")
|
277 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
|
278 |
+
aseg = AudioSegment.from_file(ref_audio_orig)
|
279 |
+
|
280 |
+
if clip_short:
|
281 |
+
# 1. try to find long silence for clipping
|
282 |
+
non_silent_segs = silence.split_on_silence(
|
283 |
+
aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=1000, seek_step=10
|
284 |
+
)
|
285 |
+
non_silent_wave = AudioSegment.silent(duration=0)
|
286 |
+
for non_silent_seg in non_silent_segs:
|
287 |
+
if len(non_silent_wave) > 6000 and len(non_silent_wave + non_silent_seg) > 15000:
|
288 |
+
show_info("Audio is over 15s, clipping short. (1)")
|
289 |
+
break
|
290 |
+
non_silent_wave += non_silent_seg
|
291 |
+
|
292 |
+
# 2. try to find short silence for clipping if 1. failed
|
293 |
+
if len(non_silent_wave) > 15000:
|
294 |
+
non_silent_segs = silence.split_on_silence(
|
295 |
+
aseg, min_silence_len=100, silence_thresh=-40, keep_silence=1000, seek_step=10
|
296 |
+
)
|
297 |
+
non_silent_wave = AudioSegment.silent(duration=0)
|
298 |
+
for non_silent_seg in non_silent_segs:
|
299 |
+
if len(non_silent_wave) > 6000 and len(non_silent_wave + non_silent_seg) > 15000:
|
300 |
+
show_info("Audio is over 15s, clipping short. (2)")
|
301 |
+
break
|
302 |
+
non_silent_wave += non_silent_seg
|
303 |
+
|
304 |
+
aseg = non_silent_wave
|
305 |
+
|
306 |
+
# 3. if no proper silence found for clipping
|
307 |
+
if len(aseg) > 15000:
|
308 |
+
aseg = aseg[:15000]
|
309 |
+
show_info("Audio is over 15s, clipping short. (3)")
|
310 |
+
|
311 |
+
aseg = remove_silence_edges(aseg) + AudioSegment.silent(duration=50)
|
312 |
+
aseg.export(f.name, format="wav")
|
313 |
+
ref_audio = f.name
|
314 |
+
|
315 |
+
# Compute a hash of the reference audio file
|
316 |
+
with open(ref_audio, "rb") as audio_file:
|
317 |
+
audio_data = audio_file.read()
|
318 |
+
audio_hash = hashlib.md5(audio_data).hexdigest()
|
319 |
+
|
320 |
+
if not ref_text.strip():
|
321 |
+
global _ref_audio_cache
|
322 |
+
if audio_hash in _ref_audio_cache:
|
323 |
+
# Use cached asr transcription
|
324 |
+
show_info("Using cached reference text...")
|
325 |
+
ref_text = _ref_audio_cache[audio_hash]
|
326 |
+
else:
|
327 |
+
show_info("No reference text provided, transcribing reference audio...")
|
328 |
+
ref_text = transcribe(ref_audio)
|
329 |
+
# Cache the transcribed text (not caching custom ref_text, enabling users to do manual tweak)
|
330 |
+
_ref_audio_cache[audio_hash] = ref_text
|
331 |
+
else:
|
332 |
+
show_info("Using custom reference text...")
|
333 |
+
|
334 |
+
# Ensure ref_text ends with a proper sentence-ending punctuation
|
335 |
+
if not ref_text.endswith(". ") and not ref_text.endswith("。"):
|
336 |
+
if ref_text.endswith("."):
|
337 |
+
ref_text += " "
|
338 |
+
else:
|
339 |
+
ref_text += ". "
|
340 |
+
|
341 |
+
print("ref_text ", ref_text)
|
342 |
+
|
343 |
+
return ref_audio, ref_text
|
344 |
+
|
345 |
+
|
346 |
+
# infer process: chunk text -> infer batches [i.e. infer_batch_process()]
|
347 |
+
|
348 |
+
|
349 |
+
def infer_process(
|
350 |
+
ref_audio,
|
351 |
+
ref_text,
|
352 |
+
gen_text,
|
353 |
+
model_obj,
|
354 |
+
vocoder,
|
355 |
+
mel_spec_type=mel_spec_type,
|
356 |
+
show_info=print,
|
357 |
+
progress=tqdm,
|
358 |
+
target_rms=target_rms,
|
359 |
+
cross_fade_duration=cross_fade_duration,
|
360 |
+
nfe_step=nfe_step,
|
361 |
+
cfg_strength=cfg_strength,
|
362 |
+
sway_sampling_coef=sway_sampling_coef,
|
363 |
+
speed=speed,
|
364 |
+
fix_duration=fix_duration,
|
365 |
+
device=device,
|
366 |
+
):
|
367 |
+
# Split the input text into batches
|
368 |
+
audio, sr = torchaudio.load(ref_audio)
|
369 |
+
max_chars = int(len(ref_text.encode("utf-8")) / (audio.shape[-1] / sr) * (25 - audio.shape[-1] / sr))
|
370 |
+
gen_text_batches = chunk_text(gen_text, max_chars=max_chars)
|
371 |
+
for i, gen_text in enumerate(gen_text_batches):
|
372 |
+
print(f"gen_text {i}", gen_text)
|
373 |
+
|
374 |
+
show_info(f"Generating audio in {len(gen_text_batches)} batches...")
|
375 |
+
return infer_batch_process(
|
376 |
+
(audio, sr),
|
377 |
+
ref_text,
|
378 |
+
gen_text_batches,
|
379 |
+
model_obj,
|
380 |
+
vocoder,
|
381 |
+
mel_spec_type=mel_spec_type,
|
382 |
+
progress=progress,
|
383 |
+
target_rms=target_rms,
|
384 |
+
cross_fade_duration=cross_fade_duration,
|
385 |
+
nfe_step=nfe_step,
|
386 |
+
cfg_strength=cfg_strength,
|
387 |
+
sway_sampling_coef=sway_sampling_coef,
|
388 |
+
speed=speed,
|
389 |
+
fix_duration=fix_duration,
|
390 |
+
device=device,
|
391 |
+
)
|
392 |
+
|
393 |
+
|
394 |
+
# infer batches
|
395 |
+
|
396 |
+
|
397 |
+
def infer_batch_process(
|
398 |
+
ref_audio,
|
399 |
+
ref_text,
|
400 |
+
gen_text_batches,
|
401 |
+
model_obj,
|
402 |
+
vocoder,
|
403 |
+
mel_spec_type="vocos",
|
404 |
+
progress=tqdm,
|
405 |
+
target_rms=0.1,
|
406 |
+
cross_fade_duration=0.15,
|
407 |
+
nfe_step=32,
|
408 |
+
cfg_strength=2.0,
|
409 |
+
sway_sampling_coef=-1,
|
410 |
+
speed=1,
|
411 |
+
fix_duration=None,
|
412 |
+
device=None,
|
413 |
+
):
|
414 |
+
audio, sr = ref_audio
|
415 |
+
if audio.shape[0] > 1:
|
416 |
+
audio = torch.mean(audio, dim=0, keepdim=True)
|
417 |
+
|
418 |
+
rms = torch.sqrt(torch.mean(torch.square(audio)))
|
419 |
+
if rms < target_rms:
|
420 |
+
audio = audio * target_rms / rms
|
421 |
+
if sr != target_sample_rate:
|
422 |
+
resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
|
423 |
+
audio = resampler(audio)
|
424 |
+
audio = audio.to(device)
|
425 |
+
|
426 |
+
generated_waves = []
|
427 |
+
spectrograms = []
|
428 |
+
|
429 |
+
if len(ref_text[-1].encode("utf-8")) == 1:
|
430 |
+
ref_text = ref_text + " "
|
431 |
+
for i, gen_text in enumerate(progress.tqdm(gen_text_batches)):
|
432 |
+
# Prepare the text
|
433 |
+
text_list = [ref_text + gen_text]
|
434 |
+
final_text_list = convert_char_to_pinyin(text_list)
|
435 |
+
|
436 |
+
ref_audio_len = audio.shape[-1] // hop_length
|
437 |
+
if fix_duration is not None:
|
438 |
+
duration = int(fix_duration * target_sample_rate / hop_length)
|
439 |
+
else:
|
440 |
+
# Calculate duration
|
441 |
+
ref_text_len = len(ref_text.encode("utf-8"))
|
442 |
+
gen_text_len = len(gen_text.encode("utf-8"))
|
443 |
+
duration = ref_audio_len + int(ref_audio_len / ref_text_len * gen_text_len / speed)
|
444 |
+
|
445 |
+
# inference
|
446 |
+
with torch.inference_mode():
|
447 |
+
generated, _ = model_obj.sample(
|
448 |
+
cond=audio,
|
449 |
+
text=final_text_list,
|
450 |
+
duration=duration,
|
451 |
+
steps=nfe_step,
|
452 |
+
cfg_strength=cfg_strength,
|
453 |
+
sway_sampling_coef=sway_sampling_coef,
|
454 |
+
)
|
455 |
+
|
456 |
+
generated = generated.to(torch.float32)
|
457 |
+
generated = generated[:, ref_audio_len:, :]
|
458 |
+
generated_mel_spec = generated.permute(0, 2, 1)
|
459 |
+
if mel_spec_type == "vocos":
|
460 |
+
generated_wave = vocoder.decode(generated_mel_spec)
|
461 |
+
elif mel_spec_type == "bigvgan":
|
462 |
+
generated_wave = vocoder(generated_mel_spec)
|
463 |
+
if rms < target_rms:
|
464 |
+
generated_wave = generated_wave * rms / target_rms
|
465 |
+
|
466 |
+
# wav -> numpy
|
467 |
+
generated_wave = generated_wave.squeeze().cpu().numpy()
|
468 |
+
|
469 |
+
generated_waves.append(generated_wave)
|
470 |
+
spectrograms.append(generated_mel_spec[0].cpu().numpy())
|
471 |
+
|
472 |
+
# Combine all generated waves with cross-fading
|
473 |
+
if cross_fade_duration <= 0:
|
474 |
+
# Simply concatenate
|
475 |
+
final_wave = np.concatenate(generated_waves)
|
476 |
+
else:
|
477 |
+
final_wave = generated_waves[0]
|
478 |
+
for i in range(1, len(generated_waves)):
|
479 |
+
prev_wave = final_wave
|
480 |
+
next_wave = generated_waves[i]
|
481 |
+
|
482 |
+
# Calculate cross-fade samples, ensuring it does not exceed wave lengths
|
483 |
+
cross_fade_samples = int(cross_fade_duration * target_sample_rate)
|
484 |
+
cross_fade_samples = min(cross_fade_samples, len(prev_wave), len(next_wave))
|
485 |
+
|
486 |
+
if cross_fade_samples <= 0:
|
487 |
+
# No overlap possible, concatenate
|
488 |
+
final_wave = np.concatenate([prev_wave, next_wave])
|
489 |
+
continue
|
490 |
+
|
491 |
+
# Overlapping parts
|
492 |
+
prev_overlap = prev_wave[-cross_fade_samples:]
|
493 |
+
next_overlap = next_wave[:cross_fade_samples]
|
494 |
+
|
495 |
+
# Fade out and fade in
|
496 |
+
fade_out = np.linspace(1, 0, cross_fade_samples)
|
497 |
+
fade_in = np.linspace(0, 1, cross_fade_samples)
|
498 |
+
|
499 |
+
# Cross-faded overlap
|
500 |
+
cross_faded_overlap = prev_overlap * fade_out + next_overlap * fade_in
|
501 |
+
|
502 |
+
# Combine
|
503 |
+
new_wave = np.concatenate(
|
504 |
+
[prev_wave[:-cross_fade_samples], cross_faded_overlap, next_wave[cross_fade_samples:]]
|
505 |
+
)
|
506 |
+
|
507 |
+
final_wave = new_wave
|
508 |
+
|
509 |
+
# Create a combined spectrogram
|
510 |
+
combined_spectrogram = np.concatenate(spectrograms, axis=1)
|
511 |
+
|
512 |
+
return final_wave, target_sample_rate, combined_spectrogram
|
513 |
+
|
514 |
+
|
515 |
+
# remove silence from generated wav
|
516 |
+
|
517 |
+
|
518 |
+
def remove_silence_for_generated_wav(filename):
|
519 |
+
aseg = AudioSegment.from_file(filename)
|
520 |
+
non_silent_segs = silence.split_on_silence(
|
521 |
+
aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=500, seek_step=10
|
522 |
+
)
|
523 |
+
non_silent_wave = AudioSegment.silent(duration=0)
|
524 |
+
for non_silent_seg in non_silent_segs:
|
525 |
+
non_silent_wave += non_silent_seg
|
526 |
+
aseg = non_silent_wave
|
527 |
+
aseg.export(filename, format="wav")
|
528 |
+
|
529 |
+
|
530 |
+
# save spectrogram
|
531 |
+
|
532 |
+
|
533 |
+
def save_spectrogram(spectrogram, path):
|
534 |
+
plt.figure(figsize=(12, 4))
|
535 |
+
plt.imshow(spectrogram, origin="lower", aspect="auto")
|
536 |
+
plt.colorbar()
|
537 |
+
plt.savefig(path)
|
538 |
+
plt.close()
|