File size: 10,542 Bytes
5c904c4
 
 
 
 
 
 
 
 
 
c4b86ad
 
 
5c904c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78068b2
5c904c4
c4b86ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c904c4
 
c4b86ad
 
5c904c4
65caffe
5c904c4
 
 
 
 
7c09a26
5c904c4
 
 
 
 
 
 
 
 
 
65caffe
c4b86ad
 
5c904c4
 
 
 
 
 
 
 
65caffe
5c904c4
 
 
 
 
65caffe
 
 
 
5c904c4
 
65caffe
5c904c4
 
 
 
c4b86ad
65caffe
c4b86ad
 
 
65caffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c904c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c09a26
5c904c4
 
 
 
 
 
 
78068b2
5c904c4
 
 
 
 
387a00b
5c904c4
 
 
65caffe
 
 
 
7c09a26
65caffe
 
 
5c904c4
 
387a00b
5c904c4
c4b86ad
 
5c904c4
 
 
 
 
 
 
 
65caffe
c4b86ad
5c904c4
65caffe
5c904c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
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
import asyncio
import datetime
import logging
import os
import time
import traceback

import edge_tts
import gradio as gr
import librosa
import numpy as np
from pydub import AudioSegment
from scipy.io import wavfile

from src.rmvpe import RMVPE
from model_loader import ModelLoader

logging.getLogger("fairseq").setLevel(logging.WARNING)
logging.getLogger("numba").setLevel(logging.WARNING)
logging.getLogger("markdown_it").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("matplotlib").setLevel(logging.WARNING)

limitation = os.getenv("SYSTEM") == "spaces"

edge_output_filename = "edge_output.mp3"
tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices())
tts_voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]

model_root = "weights"

print("Loading...")
model_loader = ModelLoader()
gpu_config = model_loader.config
hubert_model = model_loader.load_hubert()

rmvpe_model = RMVPE(
    os.path.join(os.getcwd(), "weights", "rmvpe.pt"),
    gpu_config.is_half,
    gpu_config.device,
)

model_loader.load("char2")

def add_robotic_effect(mp3_path):
    audio = AudioSegment.from_mp3(mp3_path)

    # Convert to numpy array
    data = np.array(audio.get_array_of_samples())
    sample_rate = audio.frame_rate

    # If stereo, average the channels to mono
    if audio.channels == 2:
        data = data.reshape((-1, 2)).mean(axis=1).astype(np.int16)

    # Apply delay effect
    delay = 0.05
    alpha = 0.55
    delay_samples = int(delay * sample_rate)

    delayed_data = np.zeros_like(data)
    delayed_data[delay_samples:] = data[:-delay_samples] * alpha
    delayed_data += data

    # Clip the values to int16 range
    delayed_data = np.clip(delayed_data, -32768, 32767)
    wavfile.write("processed.wav", sample_rate, delayed_data.astype(np.int16))
    return "processed.wav"

def tts(
    rvc,
    effect,
    speed,
    pitch,
    tts_text,
    tts_voice,
    f0_up_key,
    f0_method="rmvpe",
    index_rate=1,
    protect=0.2,
    filter_radius=3,
    resample_sr=0,
    rms_mix_rate=0.25,
):
    print("------------------")
    print(datetime.datetime.now())
    print("tts_text:")
    print(tts_text)
    print(f"tts_voice: {tts_voice}")
    print(f"F0: {f0_method}, Key: {f0_up_key}, Index: {index_rate}, Protect: {protect}")

    edge_output_filename = "edge_output.mp3"

    try:
        if limitation and len(tts_text) > 280:
            print("Error: Text too long")
            return (
                f"Text characters should be at most 280 in this huggingface space, but got {len(tts_text)} characters.",
                None,
                None,
            )

        t0 = time.time()
        if speed >= 0:
            speed_str = f"+{speed}%"
        else:
            speed_str = f"{speed}%"
        if pitch >= 0:
            pitch = f'+{pitch}Hz'
        else:
            pitch = f'{pitch}Hz'
        asyncio.run(
            edge_tts.Communicate(
                tts_text, "-".join(tts_voice.split("-")[:-1]), rate=speed_str, pitch=pitch
            ).save(edge_output_filename)
        )
        t1 = time.time()
        edge_time = t1 - t0

        if not rvc:
            if effect:
                edge_output_filename = add_robotic_effect(edge_output_filename)

            info = f"Success. Time: edge-tts: {edge_time}s"
            print(info)
            return (
                info,
                edge_output_filename,
            )
    
        tgt_sr, net_g, vc, version, index_file, if_f0 = (
            model_loader.tgt_sr,
            model_loader.net_g,
            model_loader.vc,
            model_loader.version,
            model_loader.index_file,
            model_loader.if_f0,
        )
        audio, sr = librosa.load(edge_output_filename, sr=16000, mono=True)
        duration = len(audio) / sr
        print(f"Audio duration: {duration}s")
        if limitation and duration >= 20:
            print("Error: Audio too long")
            return (
                f"Audio should be less than 20 seconds in this huggingface space, but got {duration}s.",
                edge_output_filename,
                None,
            )

        f0_up_key = int(f0_up_key)

        if f0_method == "rmvpe":
            vc.model_rmvpe = rmvpe_model
        times = [0, 0, 0]
        audio_opt = vc.pipeline(
            hubert_model,
            net_g,
            0,
            audio,
            edge_output_filename,
            times,
            f0_up_key,
            f0_method,
            index_file,
            # file_big_npy,
            index_rate,
            if_f0,
            filter_radius,
            tgt_sr,
            resample_sr,
            rms_mix_rate,
            version,
            protect,
            None,
        )
        if tgt_sr != resample_sr >= 16000:
            tgt_sr = resample_sr
        info = f"Success. Time: edge-tts: {edge_time}s, npy: {times[0]}s, f0: {times[1]}s, infer: {times[2]}s"
        print(info)
        return (
            info,
            (tgt_sr, audio_opt),
        )
    except EOFError:
        info = (
            "It seems that the edge-tts output is not valid. "
            "This may occur when the input text and the speaker do not match. "
            "For example, maybe you entered Japanese (without alphabets) text but chose non-Japanese speaker?"
        )
        print(info)
        return info, None
    except:
        info = traceback.format_exc()
        print(info)
        return info, None


initial_md = """
# Text-to-speech webui

This is a text-to-speech webui of RVC models.
"""

app = gr.Blocks()
with app:
    gr.Markdown(initial_md)
    with gr.Row():
        with gr.Column():
            f0_key_up = gr.Number(
                label="Transpose (the best value depends on the models and speakers)",
                value=4,
            )
    with gr.Row():
        with gr.Column():
            tts_voice = gr.Dropdown(
                label="speaker (format: language-Country-Name-Gender)",
                choices=tts_voices,
                allow_custom_value=False,
                value="en-US-JennyNeural-Female",
            )
            speed = gr.Slider(
                minimum=-100,
                maximum=100,
                label="Speech speed (%)",
                value=10,
                step=10,
                interactive=True,
            )
            pitch = gr.Slider(
                minimum=-100,
                maximum=100,
                label="Speech pitch",
                value=20,
                step=5,
                interactive=True,
            )
            tts_text = gr.Textbox(
                label="Input Text",
                value="I'm Never Gonna Give You Up",
            )
            rvc = gr.Checkbox(label="Transform Voice", info="Would you like to apply voice transformation? Check means yes", value=False)
            effect = gr.Checkbox(label="Add Effect", info="Would you like to apply Effect?", value=True)
        with gr.Column():
            but0 = gr.Button("Convert", variant="primary")
            info_text = gr.Textbox(label="Output info")
        with gr.Column():
            tts_output = gr.Audio(label="Result")
        but0.click(
            tts,
            [
                rvc,
                effect,
                speed,
                pitch,
                tts_text,
                tts_voice,
                f0_key_up,
            ],
            [info_text, tts_output],
        )
    with gr.Row():
        examples = gr.Examples(
            examples_per_page=10,
            examples=[
                [
                    "これは日本語テキストから音声への変換デモです。",
                    "ja-JP-NanamiNeural-Female",
                ],
                [
                    "This is an English text to speech conversation demo.",
                    "en-US-AriaNeural-Female",
                ],
                ["這是用來測試的demo啦", "zh-TW-HsiaoChenNeural-Female"],
                ["这是一个中文文本到语音的转换演示。", "zh-CN-XiaoxiaoNeural-Female"],
                [
                    "한국어 텍스트에서 음성으로 변환하는 데모입니다.",
                    "ko-KR-SunHiNeural-Female",
                ],
                [
                    "Il s'agit d'une démo de conversion du texte français à la parole.",
                    "fr-FR-DeniseNeural-Female",
                ],
                [
                    "Dies ist eine Demo zur Umwandlung von Deutsch in Sprache.",
                    "de-DE-AmalaNeural-Female",
                ],
                [
                    "Tämä on suomenkielinen tekstistä puheeksi -esittely.",
                    "fi-FI-NooraNeural-Female",
                ],
                [
                    "Это демонстрационный пример преобразования русского текста в речь.",
                    "ru-RU-SvetlanaNeural-Female",
                ],
                [
                    "Αυτή είναι μια επίδειξη μετατροπής ελληνικού κειμένου σε ομιλία.",
                    "el-GR-AthinaNeural-Female",
                ],
                [
                    "Esta es una demostración de conversión de texto a voz en español.",
                    "es-ES-ElviraNeural-Female",
                ],
                [
                    "Questa è una dimostrazione di sintesi vocale in italiano.",
                    "it-IT-ElsaNeural-Female",
                ],
                [
                    "Esta é uma demonstração de conversão de texto em fala em português.",
                    "pt-PT-RaquelNeural-Female",
                ],
                [
                    "Це демонстрація тексту до мовлення українською мовою.",
                    "uk-UA-PolinaNeural-Female",
                ],
                [
                    "هذا عرض توضيحي عربي لتحويل النص إلى كلام.",
                    "ar-EG-SalmaNeural-Female",
                ],
                [
                    "இது தமிழ் உரையிலிருந்து பேச்சு மாற்ற டெமோ.",
                    "ta-IN-PallaviNeural-Female",
                ],
            ],
            inputs=[tts_text, tts_voice],
        )

app.launch(inbrowser=True)