John6666 commited on
Commit
229a02e
·
verified ·
1 Parent(s): 68915a2

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +2 -2
  2. app.py +699 -316
  3. requirements.txt +4 -3
README.md CHANGED
@@ -4,11 +4,11 @@ emoji: ⚡
4
  colorFrom: blue
5
  colorTo: blue
6
  sdk: gradio
7
- sdk_version: 5.16.1
8
  python_version: "3.10"
9
  app_file: app.py
10
  pinned: false
11
- duplicated_from: litagin/rvc_okiba_TTS
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
4
  colorFrom: blue
5
  colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 6.9.0
8
  python_version: "3.10"
9
  app_file: app.py
10
  pinned: false
11
+ duplicated_from: NoCrypt/mikuTTS
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
@@ -1,316 +1,699 @@
1
- import spaces # in windows env, delete related to "spaces"
2
- @spaces.GPU
3
- def gpu():
4
- pass
5
-
6
- import asyncio
7
- import datetime
8
- import logging
9
- import os
10
- import time
11
- import traceback
12
-
13
- import edge_tts
14
- import gradio as gr
15
- import librosa
16
- import torch
17
- from fairseq import checkpoint_utils
18
- from huggingface_hub import snapshot_download
19
-
20
-
21
- from config import Config
22
- from lib.infer_pack.models import (
23
- SynthesizerTrnMs256NSFsid,
24
- SynthesizerTrnMs256NSFsid_nono,
25
- SynthesizerTrnMs768NSFsid,
26
- SynthesizerTrnMs768NSFsid_nono,
27
- )
28
- from rmvpe import RMVPE
29
- from vc_infer_pipeline import VC
30
-
31
- logging.getLogger("fairseq").setLevel(logging.WARNING)
32
- logging.getLogger("numba").setLevel(logging.WARNING)
33
- logging.getLogger("markdown_it").setLevel(logging.WARNING)
34
- logging.getLogger("urllib3").setLevel(logging.WARNING)
35
- logging.getLogger("matplotlib").setLevel(logging.WARNING)
36
-
37
- limitation = os.getenv("SYSTEM") == "spaces"
38
-
39
- config = Config()
40
-
41
- # Edge TTS
42
- edge_output_filename = "edge_output.mp3"
43
- tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices())
44
- tts_voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
45
-
46
- # RVC models
47
- model_root = snapshot_download(repo_id="NoCrypt/miku_RVC", token=os.getenv("TOKEN", None))
48
- models = [d for d in os.listdir(model_root) if os.path.isdir(f"{model_root}/{d}")]
49
- models.sort()
50
-
51
-
52
- def model_data(model_name):
53
- # global n_spk, tgt_sr, net_g, vc, cpt, version, index_file
54
- pth_path = [
55
- f"{model_root}/{model_name}/{f}"
56
- for f in os.listdir(f"{model_root}/{model_name}")
57
- if f.endswith(".pth")
58
- ][0]
59
- print(f"Loading {pth_path}")
60
- cpt = torch.load(pth_path, map_location="cpu")
61
- tgt_sr = cpt["config"][-1]
62
- cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
63
- if_f0 = cpt.get("f0", 1)
64
- version = cpt.get("version", "v1")
65
- if version == "v1":
66
- if if_f0 == 1:
67
- net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
68
- else:
69
- net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
70
- elif version == "v2":
71
- if if_f0 == 1:
72
- net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
73
- else:
74
- net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
75
- else:
76
- raise ValueError("Unknown version")
77
- del net_g.enc_q
78
- net_g.load_state_dict(cpt["weight"], strict=False)
79
- print("Model loaded")
80
- net_g.eval().to(config.device)
81
- if config.is_half:
82
- net_g = net_g.half()
83
- else:
84
- net_g = net_g.float()
85
- vc = VC(tgt_sr, config)
86
- # n_spk = cpt["config"][-3]
87
-
88
- index_files = [
89
- f"{model_root}/{model_name}/{f}"
90
- for f in os.listdir(f"{model_root}/{model_name}")
91
- if f.endswith(".index")
92
- ]
93
- if len(index_files) == 0:
94
- print("No index file found")
95
- index_file = ""
96
- else:
97
- index_file = index_files[0]
98
- print(f"Index file found: {index_file}")
99
-
100
- return tgt_sr, net_g, vc, version, index_file, if_f0
101
-
102
-
103
- def load_hubert():
104
- # global hubert_model
105
- models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
106
- ["hubert_base.pt"],
107
- suffix="",
108
- )
109
- hubert_model = models[0]
110
- hubert_model = hubert_model.to(config.device)
111
- if config.is_half:
112
- hubert_model = hubert_model.half()
113
- else:
114
- hubert_model = hubert_model.float()
115
- return hubert_model.eval()
116
-
117
-
118
- def tts(
119
- model_name,
120
- speed,
121
- tts_text,
122
- tts_voice,
123
- f0_up_key,
124
- f0_method,
125
- index_rate,
126
- protect,
127
- filter_radius=3,
128
- resample_sr=0,
129
- rms_mix_rate=0.25,
130
- ):
131
- print("------------------")
132
- print(datetime.datetime.now())
133
- print("tts_text:")
134
- print(tts_text)
135
- print(f"tts_voice: {tts_voice}, speed: {speed}")
136
- print(f"Model name: {model_name}")
137
- print(f"F0: {f0_method}, Key: {f0_up_key}, Index: {index_rate}, Protect: {protect}")
138
- try:
139
- if limitation and len(tts_text) > 1000:
140
- print("Error: Text too long")
141
- return (
142
- f"Text characters should be at most 1000 in this huggingface space, but got {len(tts_text)} characters.",
143
- None,
144
- None,
145
- )
146
- t0 = time.time()
147
- if speed >= 0:
148
- speed_str = f"+{speed}%"
149
- else:
150
- speed_str = f"{speed}%"
151
- asyncio.run(
152
- edge_tts.Communicate(
153
- tts_text, "-".join(tts_voice.split("-")[:-1]), rate=speed_str
154
- ).save(edge_output_filename)
155
- )
156
- t1 = time.time()
157
- edge_time = t1 - t0
158
- audio, sr = librosa.load(edge_output_filename, sr=16000, mono=True)
159
- duration = len(audio) / sr
160
- print(f"Audio duration: {duration}s")
161
- if limitation and duration >= 200:
162
- print("Error: Audio too long")
163
- return (
164
- f"Audio should be less than 200 seconds in this huggingface space, but got {duration}s.",
165
- edge_output_filename,
166
- None,
167
- )
168
- f0_up_key = int(f0_up_key)
169
-
170
- tgt_sr, net_g, vc, version, index_file, if_f0 = model_data(model_name)
171
- if f0_method == "rmvpe":
172
- vc.model_rmvpe = rmvpe_model
173
- times = [0, 0, 0]
174
- audio_opt = vc.pipeline(
175
- hubert_model,
176
- net_g,
177
- 0,
178
- audio,
179
- edge_output_filename,
180
- times,
181
- f0_up_key,
182
- f0_method,
183
- index_file,
184
- # file_big_npy,
185
- index_rate,
186
- if_f0,
187
- filter_radius,
188
- tgt_sr,
189
- resample_sr,
190
- rms_mix_rate,
191
- version,
192
- protect,
193
- None,
194
- )
195
- if tgt_sr != resample_sr >= 16000:
196
- tgt_sr = resample_sr
197
- info = f"Success. Time: edge-tts: {edge_time}s, npy: {times[0]}s, f0: {times[1]}s, infer: {times[2]}s"
198
- print(info)
199
- return (
200
- info,
201
- edge_output_filename,
202
- (tgt_sr, audio_opt),
203
- )
204
- except EOFError:
205
- info = (
206
- "It seems that the edge-tts output is not valid. "
207
- "This may occur when the input text and the speaker do not match. "
208
- "For example, maybe you entered Japanese (without alphabets) text but chose non-Japanese speaker?"
209
- )
210
- print(info)
211
- return info, None, None
212
- except:
213
- info = traceback.format_exc()
214
- print(info)
215
- return info, None, None
216
-
217
-
218
- print("Loading hubert model...")
219
- hubert_model = load_hubert()
220
- print("Hubert model loaded.")
221
-
222
- print("Loading rmvpe model...")
223
- rmvpe_model = RMVPE("rmvpe.pt", config.is_half, config.device)
224
- print("rmvpe model loaded.")
225
-
226
- initial_md = """
227
- ![banner that says mikutts](https://huggingface.co/spaces/NoCrypt/mikuTTS/resolve/main/imgs/banner_mikutts.webp)
228
- """
229
-
230
- app = gr.Blocks(theme='NoCrypt/miku')
231
- with app:
232
- gr.Markdown(initial_md)
233
- with gr.Row():
234
- with gr.Column():
235
- model_name = gr.Dropdown(
236
- label="Model",
237
- choices=models,
238
- value=models[0],
239
- )
240
- f0_key_up = gr.Number(
241
- label="Tune",
242
- value=6,
243
- )
244
- with gr.Column():
245
- f0_method = gr.Radio(
246
- label="Pitch extraction method (pm: very fast, low quality, rmvpe: a little slow, high quality)",
247
- choices=["pm", "rmvpe"], # harvest and crepe is too slow
248
- value="rmvpe",
249
- interactive=True,
250
- )
251
- index_rate = gr.Slider(
252
- minimum=0,
253
- maximum=1,
254
- label="Index rate",
255
- value=1,
256
- interactive=True,
257
- )
258
- protect0 = gr.Slider(
259
- minimum=0,
260
- maximum=0.5,
261
- label="Protect",
262
- value=0.33,
263
- step=0.01,
264
- interactive=True,
265
- )
266
- with gr.Row():
267
- with gr.Column():
268
- tts_voice = gr.Dropdown(
269
- label="Edge-tts speaker (format: language-Country-Name-Gender), make sure the gender matches the model",
270
- choices=tts_voices,
271
- allow_custom_value=False,
272
- value="ja-JP-NanamiNeural-Female",
273
- )
274
- speed = gr.Slider(
275
- minimum=-100,
276
- maximum=100,
277
- label="Speech speed (%)",
278
- value=0,
279
- step=10,
280
- interactive=True,
281
- )
282
- tts_text = gr.Textbox(label="Input Text", value="こんにちは、私の名前は初音ミクです!")
283
- with gr.Column():
284
- but0 = gr.Button("Convert", variant="primary")
285
- info_text = gr.Textbox(label="Output info")
286
- with gr.Column():
287
- with gr.Accordion("Edge Voice", open=False):
288
- edge_tts_output = gr.Audio(label="Edge Voice", type="filepath")
289
- tts_output = gr.Audio(label="Result")
290
- but0.click(
291
- tts,
292
- [
293
- model_name,
294
- speed,
295
- tts_text,
296
- tts_voice,
297
- f0_key_up,
298
- f0_method,
299
- index_rate,
300
- protect0,
301
- ],
302
- [info_text, edge_tts_output, tts_output],
303
- )
304
- with gr.Row():
305
- examples = gr.Examples(
306
- examples_per_page=100,
307
- examples=[
308
- ["こんにちは、私の名前は初音ミクです!", "ja-JP-NanamiNeural-Female", 6],
309
- ["Hello there. My name is Hatsune Miku!","en-CA-ClaraNeural-Female", 6],
310
- ["Halo. Nama saya Hatsune Miku!","id-ID-GadisNeural-Female", 4],
311
- ["Halo. Jenengku Hatsune Miku!","jv-ID-SitiNeural-Female", 10],
312
- ],
313
- inputs=[tts_text, tts_voice, f0_key_up],
314
- )
315
-
316
- app.launch(ssr_mode=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces # in windows env, delete related to "spaces"
2
+ @spaces.GPU
3
+ def gpu():
4
+ pass
5
+ import asyncio
6
+ import datetime
7
+ import logging
8
+ import re
9
+ import os
10
+ import time
11
+ import traceback
12
+ from functools import lru_cache
13
+ import edge_tts
14
+ import gradio as gr
15
+ import librosa
16
+ import torch
17
+ from fairseq import checkpoint_utils
18
+ from huggingface_hub import snapshot_download
19
+ from config import Config
20
+ from lib.infer_pack.models import (
21
+ SynthesizerTrnMs256NSFsid,
22
+ SynthesizerTrnMs256NSFsid_nono,
23
+ SynthesizerTrnMs768NSFsid,
24
+ SynthesizerTrnMs768NSFsid_nono,
25
+ )
26
+ from rmvpe import RMVPE
27
+ from vc_infer_pipeline import VC
28
+ logging.getLogger("fairseq").setLevel(logging.WARNING)
29
+ logging.getLogger("numba").setLevel(logging.WARNING)
30
+ logging.getLogger("markdown_it").setLevel(logging.WARNING)
31
+ logging.getLogger("urllib3").setLevel(logging.WARNING)
32
+ logging.getLogger("matplotlib").setLevel(logging.WARNING)
33
+ limitation = os.getenv("SYSTEM") == "spaces"
34
+ config = Config()
35
+ # Edge TTS
36
+ edge_output_filename = "edge_output.mp3"
37
+ tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices())
38
+ tts_voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
39
+ INITIAL_TTS_VOICE = "ja-JP-NanamiNeural-Female"
40
+ INITIAL_TTS_TEXT = "こんにちは、私の名前は初音ミクです!"
41
+ RECOMMENDED_VOICE_CANDIDATES_BY_LOCALE = {
42
+ "ja-JP": [
43
+ "ja-JP-NanamiNeural-Female",
44
+ "ja-JP-AoiNeural-Female",
45
+ "ja-JP-MayuNeural-Female",
46
+ "ja-JP-ShioriNeural-Female",
47
+ ],
48
+ "en-CA": [
49
+ "en-CA-ClaraNeural-Female",
50
+ ],
51
+ "id-ID": [
52
+ "id-ID-GadisNeural-Female",
53
+ ],
54
+ "jv-ID": [
55
+ "jv-ID-SitiNeural-Female",
56
+ ],
57
+ "pt-BR": [
58
+ "pt-BR-ThalitaNeural-Female",
59
+ "pt-BR-FranciscaNeural-Female",
60
+ "pt-BR-BrendaNeural-Female",
61
+ "pt-BR-ElzaNeural-Female",
62
+ "pt-BR-GiovannaNeural-Female",
63
+ "pt-BR-LeilaNeural-Female",
64
+ "pt-BR-ManuelaNeural-Female",
65
+ "pt-BR-YaraNeural-Female",
66
+ ],
67
+ "fr-FR": [
68
+ "fr-FR-DeniseNeural-Female",
69
+ "fr-FR-BrigitteNeural-Female",
70
+ "fr-FR-CelesteNeural-Female",
71
+ "fr-FR-CoralieNeural-Female",
72
+ "fr-FR-JacquelineNeural-Female",
73
+ "fr-FR-JosephineNeural-Female",
74
+ "fr-FR-YvetteNeural-Female",
75
+ ],
76
+ "ru-RU": [
77
+ "ru-RU-SvetlanaNeural-Female",
78
+ "ru-RU-DariyaNeural-Female",
79
+ ],
80
+ }
81
+ SCRIPT_WARNING_RULES = [
82
+ {
83
+ "name": "Japanese script",
84
+ "matches_text": lambda text: any(
85
+ ("ぁ" <= ch <= "ゟ") or ("゠" <= ch <= "ヿ") for ch in text
86
+ ),
87
+ "allowed_locales": {"ja-JP"},
88
+ "message": "Japanese script detected. A Japanese single-locale voice is usually the safest choice.",
89
+ "recommended_locale": "ja-JP",
90
+ },
91
+ {
92
+ "name": "Cyrillic script",
93
+ "matches_text": lambda text: any("Ѐ" <= ch <= "ӿ" for ch in text),
94
+ "allowed_locales": {"ru-RU", "uk-UA", "bg-BG", "sr-RS", "kk-KZ", "ky-KG", "mk-MK", "mn-MN", "uz-UZ"},
95
+ "message": "Cyrillic script detected. A Cyrillic-locale voice is usually safer than a cross-language multilingual voice.",
96
+ "recommended_locale": "ru-RU",
97
+ },
98
+ {
99
+ "name": "Hangul script",
100
+ "matches_text": lambda text: any("가" <= ch <= "힣" for ch in text),
101
+ "allowed_locales": {"ko-KR"},
102
+ "message": "Hangul detected. A Korean voice is usually the safest choice.",
103
+ "recommended_locale": None,
104
+ },
105
+ ]
106
+ LATIN_HINT_RULES = [
107
+ {
108
+ "name": "Portuguese (Brazil) hints",
109
+ "matches_text": lambda lowered: any(
110
+ token in lowered
111
+ for token in ["olá", "você", "meu nome", "não", "ção", "ções", "hã", "muito"]
112
+ ),
113
+ "recommended_locale": "pt-BR",
114
+ "message": "Portuguese-looking text detected. A pt-BR single-locale voice is usually the safest choice.",
115
+ },
116
+ {
117
+ "name": "French hints",
118
+ "matches_text": lambda lowered: any(
119
+ token in lowered
120
+ for token in ["bonjour", "je m'appelle", "fran", "ç", "é", "è", "ê", "à", "où"]
121
+ ),
122
+ "recommended_locale": "fr-FR",
123
+ "message": "French-looking text detected. A fr-FR single-locale voice is usually the safest choice.",
124
+ },
125
+ {
126
+ "name": "Indonesian hints",
127
+ "matches_text": lambda lowered: any(
128
+ token in lowered
129
+ for token in ["halo", "nama saya", "selamat", "terima kasih", "saya "]
130
+ ),
131
+ "recommended_locale": "id-ID",
132
+ "message": "Indonesian-looking text detected. An id-ID single-locale voice is usually the safest choice.",
133
+ },
134
+ {
135
+ "name": "Javanese hints",
136
+ "matches_text": lambda lowered: any(
137
+ token in lowered
138
+ for token in ["jenengku", "aku", "sugeng", "kulo", "monggo"]
139
+ ),
140
+ "recommended_locale": "jv-ID",
141
+ "message": "Javanese-looking text detected. A jv-ID single-locale voice is usually the safest choice.",
142
+ },
143
+ {
144
+ "name": "English hints",
145
+ "matches_text": lambda lowered: any(
146
+ token in lowered
147
+ for token in ["hello", "my name is", "thanks", "good morning", "good evening"]
148
+ ),
149
+ "recommended_locale": "en-CA",
150
+ "message": "English-looking text detected. An English single-locale voice is usually the safest choice.",
151
+ },
152
+ ]
153
+ VOICE_REDIRECT_CANDIDATES = {
154
+ # pt-BR: reported regression on the multilingual Thalita voice.
155
+ "pt-BR-ThalitaMultilingualNeural-Female": [
156
+ "pt-BR-ThalitaNeural-Female",
157
+ "pt-BR-FranciscaNeural-Female",
158
+ "pt-BR-BrendaNeural-Female",
159
+ "pt-BR-ManuelaNeural-Female",
160
+ "pt-BR-YaraNeural-Female",
161
+ ],
162
+ }
163
+ CROSS_LANGUAGE_REDIRECTS = [
164
+ {
165
+ "voices": {
166
+ "fr-FR-VivienneMultilingualNeural-Female",
167
+ "fr-FR-Vivienne:DragonHDLatestNeural-Female",
168
+ },
169
+ "matches_text": lambda text: any("Ѐ" <= ch <= "ӿ" for ch in text),
170
+ "fallbacks": [
171
+ "ru-RU-SvetlanaNeural-Female",
172
+ "ru-RU-DariyaNeural-Female",
173
+ ],
174
+ "reason": "Known cross-language fallback for Cyrillic text.",
175
+ },
176
+ ]
177
+ def unique_keep_order(items):
178
+ seen = set()
179
+ ordered = []
180
+ for item in items:
181
+ if item and item not in seen:
182
+ ordered.append(item)
183
+ seen.add(item)
184
+ return ordered
185
+ def get_voice_locale(tts_voice):
186
+ parts = tts_voice.split("-")
187
+ if len(parts) >= 2:
188
+ return "-".join(parts[:2])
189
+ return ""
190
+ def is_multilingual_voice(tts_voice):
191
+ return "Multilingual" in tts_voice
192
+ def pick_available_candidates(candidates):
193
+ return [candidate for candidate in candidates if candidate in tts_voices]
194
+ def pick_first_available(candidates):
195
+ available = pick_available_candidates(candidates)
196
+ if available:
197
+ return available[0]
198
+ return None
199
+ def detect_latin_hint_messages(tts_text):
200
+ lowered = tts_text.lower()
201
+ locales = []
202
+ messages = []
203
+ for rule in LATIN_HINT_RULES:
204
+ if rule["matches_text"](lowered):
205
+ locales.append(rule["recommended_locale"])
206
+ messages.append(rule["message"])
207
+ return unique_keep_order(locales), unique_keep_order(messages)
208
+ def get_safe_tts_voice_value(tts_voice):
209
+ if tts_voice in tts_voices:
210
+ return tts_voice
211
+ if INITIAL_TTS_VOICE in tts_voices:
212
+ return INITIAL_TTS_VOICE
213
+ if tts_voices:
214
+ return tts_voices[0]
215
+ return tts_voice
216
+
217
+ def get_contextual_recommended_voices(tts_voice, tts_text):
218
+ suggestions = []
219
+ safe_tts_voice = get_safe_tts_voice_value(tts_voice)
220
+ direct_fallbacks = VOICE_REDIRECT_CANDIDATES.get(tts_voice)
221
+ if direct_fallbacks:
222
+ suggestions.extend(pick_available_candidates(direct_fallbacks))
223
+ for rule in CROSS_LANGUAGE_REDIRECTS:
224
+ if tts_voice in rule["voices"] and rule["matches_text"](tts_text):
225
+ suggestions.extend(pick_available_candidates(rule["fallbacks"]))
226
+ selected_locale = get_voice_locale(safe_tts_voice)
227
+ suggestions.extend(
228
+ pick_available_candidates(
229
+ RECOMMENDED_VOICE_CANDIDATES_BY_LOCALE.get(selected_locale, [])
230
+ )
231
+ )
232
+ for rule in SCRIPT_WARNING_RULES:
233
+ if rule["matches_text"](tts_text) and rule["recommended_locale"]:
234
+ suggestions.extend(
235
+ pick_available_candidates(
236
+ RECOMMENDED_VOICE_CANDIDATES_BY_LOCALE.get(
237
+ rule["recommended_locale"], []
238
+ )
239
+ )
240
+ )
241
+ latin_hint_locales, _ = detect_latin_hint_messages(tts_text)
242
+ for locale in latin_hint_locales:
243
+ suggestions.extend(
244
+ pick_available_candidates(
245
+ RECOMMENDED_VOICE_CANDIDATES_BY_LOCALE.get(locale, [])
246
+ )
247
+ )
248
+ suggestions = unique_keep_order(pick_available_candidates(suggestions))
249
+ if not suggestions:
250
+ suggestions = [safe_tts_voice]
251
+ elif safe_tts_voice in suggestions:
252
+ suggestions = [safe_tts_voice] + [voice for voice in suggestions if voice != safe_tts_voice]
253
+ return suggestions
254
+
255
+ def normalize_dropdown_value(value, choices, fallback=None):
256
+ deduped_choices = unique_keep_order(list(choices))
257
+ if value in deduped_choices:
258
+ return deduped_choices, value
259
+ if fallback in deduped_choices:
260
+ return deduped_choices, fallback
261
+ if deduped_choices:
262
+ return deduped_choices, deduped_choices[0]
263
+ return deduped_choices, fallback
264
+ def format_guidance_section(title, items):
265
+ if not items:
266
+ return [f"**{title}**", "- None"]
267
+ return [f"**{title}**", *[f"- {item}" for item in items]]
268
+ def build_voice_guidance(tts_voice, tts_text, auto_applied_from=None):
269
+ info_messages = []
270
+ caution_messages = []
271
+ warning_messages = []
272
+ selected_locale = get_voice_locale(tts_voice)
273
+ resolved_tts_voice, redirect_info = resolve_tts_voice(tts_voice, tts_text)
274
+ if auto_applied_from and auto_applied_from != tts_voice:
275
+ info_messages.append(
276
+ f"Auto-applied the top recommended voice: `{auto_applied_from}` -> `{tts_voice}`."
277
+ )
278
+ if redirect_info is not None and resolved_tts_voice != tts_voice:
279
+ caution_messages.append(
280
+ f"This Space will internally resolve `{tts_voice}` to `{resolved_tts_voice}` at conversion time."
281
+ )
282
+ if is_multilingual_voice(tts_voice):
283
+ caution_messages.append(
284
+ f"Selected voice is multilingual: `{tts_voice}`. Single-locale female voices are usually more stable in this Space."
285
+ )
286
+ for rule in SCRIPT_WARNING_RULES:
287
+ if rule["matches_text"](tts_text) and selected_locale not in rule["allowed_locales"]:
288
+ warning_messages.append(
289
+ f"{rule['message']} Current locale: `{selected_locale}`."
290
+ )
291
+ latin_hint_locales, latin_hint_messages = detect_latin_hint_messages(tts_text)
292
+ for locale, message in zip(latin_hint_locales, latin_hint_messages):
293
+ if selected_locale != locale:
294
+ caution_messages.append(f"{message} Current locale: `{selected_locale}`.")
295
+ if not caution_messages and not warning_messages:
296
+ info_messages.append(
297
+ f"Current text / voice pair looks reasonable for `{tts_voice}`."
298
+ )
299
+ recommended = get_contextual_recommended_voices(tts_voice, tts_text)
300
+ lines = ["**Voice guidance**", ""]
301
+ lines.extend(format_guidance_section("Info", unique_keep_order(info_messages)))
302
+ lines.append("")
303
+ lines.extend(format_guidance_section("Caution", unique_keep_order(caution_messages)))
304
+ lines.append("")
305
+ lines.extend(format_guidance_section("Warning", unique_keep_order(warning_messages)))
306
+ lines.append("")
307
+ lines.append("**Recommended voices**")
308
+ lines.extend(f"- `{voice}`" for voice in recommended[:6])
309
+ return "\n".join(lines)
310
+ def refresh_voice_controls(tts_voice, tts_text, auto_apply_recommended):
311
+ safe_current_voice = get_safe_tts_voice_value(tts_voice)
312
+ recommended = get_contextual_recommended_voices(safe_current_voice, tts_text)
313
+ target_voice = safe_current_voice
314
+ auto_applied_from = None
315
+ if auto_apply_recommended and recommended:
316
+ candidate = recommended[0]
317
+ if candidate != safe_current_voice:
318
+ auto_applied_from = safe_current_voice
319
+ target_voice = get_safe_tts_voice_value(candidate)
320
+ recommended = get_contextual_recommended_voices(target_voice, tts_text)
321
+ recommended, recommended_value = normalize_dropdown_value(
322
+ recommended[0] if recommended else None,
323
+ recommended,
324
+ fallback=target_voice,
325
+ )
326
+ guidance = build_voice_guidance(
327
+ target_voice,
328
+ tts_text,
329
+ auto_applied_from=auto_applied_from,
330
+ )
331
+ return (
332
+ gr.update(choices=recommended, value=recommended_value),
333
+ guidance,
334
+ gr.update(value=target_voice),
335
+ )
336
+ def refresh_voice_controls_no_auto(tts_voice, tts_text):
337
+ safe_current_voice = get_safe_tts_voice_value(tts_voice)
338
+ recommended = get_contextual_recommended_voices(safe_current_voice, tts_text)
339
+ recommended, recommended_value = normalize_dropdown_value(
340
+ recommended[0] if recommended else None,
341
+ recommended,
342
+ fallback=safe_current_voice,
343
+ )
344
+ return (
345
+ gr.update(choices=recommended, value=recommended_value),
346
+ build_voice_guidance(safe_current_voice, tts_text),
347
+ )
348
+ def apply_recommended_voice(recommended_voice, tts_text):
349
+ target_voice = get_safe_tts_voice_value(recommended_voice)
350
+ return gr.update(value=target_voice)
351
+ def resolve_tts_voice(tts_voice, tts_text):
352
+ direct_fallbacks = VOICE_REDIRECT_CANDIDATES.get(tts_voice)
353
+ if direct_fallbacks:
354
+ resolved = pick_first_available(direct_fallbacks)
355
+ if resolved is not None:
356
+ return resolved, f"Known-stable fallback selected: {tts_voice} -> {resolved}"
357
+ for rule in CROSS_LANGUAGE_REDIRECTS:
358
+ if tts_voice in rule["voices"] and rule["matches_text"](tts_text):
359
+ resolved = pick_first_available(rule["fallbacks"])
360
+ if resolved is not None:
361
+ return resolved, f"{rule['reason']} {tts_voice} -> {resolved}"
362
+ return tts_voice, None
363
+ # RVC models
364
+ model_root = snapshot_download(repo_id="NoCrypt/miku_RVC", token=os.getenv("TOKEN", None))
365
+ models = [d for d in os.listdir(model_root) if os.path.isdir(f"{model_root}/{d}")]
366
+ models.sort()
367
+ MODEL_CACHE_SIZE = 3
368
+
369
+ @lru_cache(maxsize=MODEL_CACHE_SIZE)
370
+ def model_data(model_name):
371
+ # global n_spk, tgt_sr, net_g, vc, cpt, version, index_file
372
+ pth_path = [
373
+ f"{model_root}/{model_name}/{f}"
374
+ for f in os.listdir(f"{model_root}/{model_name}")
375
+ if f.endswith(".pth")
376
+ ][0]
377
+ print(f"Loading {pth_path}")
378
+ cpt = torch.load(pth_path, map_location="cpu", weights_only=True)
379
+ tgt_sr = cpt["config"][-1]
380
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
381
+ if_f0 = cpt.get("f0", 1)
382
+ version = cpt.get("version", "v1")
383
+ if version == "v1":
384
+ if if_f0 == 1:
385
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
386
+ else:
387
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
388
+ elif version == "v2":
389
+ if if_f0 == 1:
390
+ net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
391
+ else:
392
+ net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
393
+ else:
394
+ raise ValueError("Unknown version")
395
+ del net_g.enc_q
396
+ net_g.load_state_dict(cpt["weight"], strict=False)
397
+ print("Model loaded")
398
+ net_g.eval().to(config.device)
399
+ if config.is_half:
400
+ net_g = net_g.half()
401
+ else:
402
+ net_g = net_g.float()
403
+ vc = VC(tgt_sr, config)
404
+ # n_spk = cpt["config"][-3]
405
+ index_files = [
406
+ f"{model_root}/{model_name}/{f}"
407
+ for f in os.listdir(f"{model_root}/{model_name}")
408
+ if f.endswith(".index")
409
+ ]
410
+ if len(index_files) == 0:
411
+ print("No index file found")
412
+ index_file = ""
413
+ else:
414
+ index_file = index_files[0]
415
+ print(f"Index file found: {index_file}")
416
+ return tgt_sr, net_g, vc, version, index_file, if_f0
417
+ def load_hubert():
418
+ # global hubert_model
419
+ models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
420
+ ["hubert_base.pt"],
421
+ suffix="",
422
+ )
423
+ hubert_model = models[0]
424
+ hubert_model = hubert_model.to(config.device)
425
+ if config.is_half:
426
+ hubert_model = hubert_model.half()
427
+ else:
428
+ hubert_model = hubert_model.float()
429
+ return hubert_model.eval()
430
+ def tts(
431
+ model_name,
432
+ speed,
433
+ volume,
434
+ pitch,
435
+ tts_text,
436
+ tts_voice,
437
+ f0_up_key,
438
+ f0_method,
439
+ index_rate,
440
+ protect,
441
+ filter_radius=3,
442
+ resample_sr=0,
443
+ rms_mix_rate=0.25,
444
+ ):
445
+ print("------------------")
446
+ print(datetime.datetime.now())
447
+ print("tts_text:")
448
+ print(tts_text)
449
+ print(f"tts_voice: {tts_voice}, speed: {speed}, volume: {volume}, pitch: {pitch}")
450
+ print(f"Model name: {model_name}")
451
+ print(f"F0: {f0_method}, Key: {f0_up_key}, Index: {index_rate}, Protect: {protect}")
452
+ try:
453
+ if limitation and len(tts_text) > 1000:
454
+ print("Error: Text too long")
455
+ return (
456
+ f"Text characters should be at most 1000 in this huggingface space, but got {len(tts_text)} characters.",
457
+ None,
458
+ None,
459
+ )
460
+ t0 = time.time()
461
+ if speed >= 0:
462
+ speed_str = f"+{speed}%"
463
+ else:
464
+ speed_str = f"{speed}%"
465
+ if volume >= 0:
466
+ volume_str = f"+{volume}%"
467
+ else:
468
+ volume_str = f"{volume}%"
469
+ if pitch >= 0:
470
+ pitch_str = f"+{pitch}Hz"
471
+ else:
472
+ pitch_str = f"{pitch}Hz"
473
+ resolved_tts_voice, redirect_info = resolve_tts_voice(tts_voice, tts_text)
474
+ if redirect_info is not None:
475
+ print(redirect_info)
476
+ asyncio.run(
477
+ edge_tts.Communicate(
478
+ tts_text,
479
+ "-".join(resolved_tts_voice.split("-")[:-1]),
480
+ rate=speed_str,
481
+ volume=volume_str,
482
+ pitch=pitch_str,
483
+ ).save(edge_output_filename)
484
+ )
485
+ t1 = time.time()
486
+ edge_time = t1 - t0
487
+ audio, sr = librosa.load(edge_output_filename, sr=16000, mono=True)
488
+ duration = len(audio) / sr
489
+ print(f"Audio duration: {duration}s")
490
+ if limitation and duration >= 200:
491
+ print("Error: Audio too long")
492
+ return (
493
+ f"Audio should be less than 200 seconds in this huggingface space, but got {duration}s.",
494
+ edge_output_filename,
495
+ None,
496
+ )
497
+ f0_up_key = int(f0_up_key)
498
+ tgt_sr, net_g, vc, version, index_file, if_f0 = model_data(model_name)
499
+ if f0_method == "rmvpe":
500
+ vc.model_rmvpe = rmvpe_model
501
+ times = [0, 0, 0]
502
+ audio_opt = vc.pipeline(
503
+ hubert_model,
504
+ net_g,
505
+ 0,
506
+ audio,
507
+ edge_output_filename,
508
+ times,
509
+ f0_up_key,
510
+ f0_method,
511
+ index_file,
512
+ # file_big_npy,
513
+ index_rate,
514
+ if_f0,
515
+ filter_radius,
516
+ tgt_sr,
517
+ resample_sr,
518
+ rms_mix_rate,
519
+ version,
520
+ protect,
521
+ None,
522
+ )
523
+ if tgt_sr != resample_sr >= 16000:
524
+ tgt_sr = resample_sr
525
+ voice_info = resolved_tts_voice
526
+ if resolved_tts_voice != tts_voice:
527
+ voice_info = f"{tts_voice} -> {resolved_tts_voice}"
528
+ info = (
529
+ f"Success. Voice: {voice_info}. Speed: {speed_str}, volume: {volume_str}, pitch: {pitch_str}. "
530
+ f"Time: edge-tts: {edge_time}s, npy: {times[0]}s, f0: {times[1]}s, infer: {times[2]}s"
531
+ )
532
+ print(info)
533
+ return (
534
+ info,
535
+ edge_output_filename,
536
+ (tgt_sr, audio_opt),
537
+ )
538
+ except EOFError:
539
+ info = (
540
+ "It seems that the edge-tts output is not valid. "
541
+ "This may occur when the input text and the speaker do not match. "
542
+ "For example, maybe you entered Japanese (without alphabets) text but chose non-Japanese speaker?"
543
+ )
544
+ print(info)
545
+ return info, None, None
546
+ except:
547
+ info = traceback.format_exc()
548
+ print(info)
549
+ return info, None, None
550
+ print("Loading hubert model...")
551
+ hubert_model = load_hubert()
552
+ print("Hubert model loaded.")
553
+ print("Loading rmvpe model...")
554
+ rmvpe_model = RMVPE("rmvpe.pt", config.is_half, config.device)
555
+ print("rmvpe model loaded.")
556
+ initial_md = """
557
+ ![banner that says mikutts](https://huggingface.co/spaces/NoCrypt/mikuTTS/resolve/main/imgs/banner_mikutts.webp)
558
+ """
559
+ initial_recommended_voices = get_contextual_recommended_voices(INITIAL_TTS_VOICE, INITIAL_TTS_TEXT)
560
+ initial_voice_guidance = build_voice_guidance(INITIAL_TTS_VOICE, INITIAL_TTS_TEXT)
561
+ app = gr.Blocks()
562
+ with app:
563
+ gr.Markdown(initial_md)
564
+ with gr.Row():
565
+ with gr.Column():
566
+ model_name = gr.Dropdown(
567
+ label="Model",
568
+ choices=models,
569
+ value=models[0],
570
+ )
571
+ f0_key_up = gr.Number(
572
+ label="Tune",
573
+ value=6,
574
+ )
575
+ with gr.Column():
576
+ f0_method = gr.Radio(
577
+ label="Pitch extraction method (pm: very fast, low quality, rmvpe: a little slow, high quality)",
578
+ choices=["pm", "rmvpe"], # harvest and crepe is too slow
579
+ value="rmvpe",
580
+ interactive=True,
581
+ )
582
+ index_rate = gr.Slider(
583
+ minimum=0,
584
+ maximum=1,
585
+ label="Index rate",
586
+ value=1,
587
+ interactive=True,
588
+ )
589
+ protect0 = gr.Slider(
590
+ minimum=0,
591
+ maximum=0.5,
592
+ label="Protect",
593
+ value=0.33,
594
+ step=0.01,
595
+ interactive=True,
596
+ )
597
+ with gr.Row():
598
+ with gr.Column():
599
+ recommended_voice = gr.Dropdown(
600
+ label="Recommended voice (single-locale female first)",
601
+ choices=initial_recommended_voices,
602
+ allow_custom_value=False,
603
+ value=initial_recommended_voices[0],
604
+ )
605
+ auto_apply_recommended = gr.Checkbox(
606
+ label="Auto-apply top recommended voice",
607
+ value=False,
608
+ )
609
+ with gr.Accordion("Advanced: full Edge voice list", open=False):
610
+ tts_voice = gr.Dropdown(
611
+ label="Edge-tts speaker (format: language-Country-Name-Gender), make sure the gender matches the model",
612
+ choices=tts_voices,
613
+ allow_custom_value=False,
614
+ value=INITIAL_TTS_VOICE,
615
+ )
616
+ speed = gr.Slider(
617
+ minimum=-100,
618
+ maximum=100,
619
+ label="Speech speed (%)",
620
+ value=0,
621
+ step=10,
622
+ interactive=True,
623
+ )
624
+ volume = gr.Slider(
625
+ minimum=-100,
626
+ maximum=100,
627
+ label="Speech volume (%)",
628
+ value=0,
629
+ step=10,
630
+ interactive=True,
631
+ )
632
+ pitch = gr.Slider(
633
+ minimum=-50,
634
+ maximum=50,
635
+ label="Speech pitch (Hz)",
636
+ value=0,
637
+ step=5,
638
+ interactive=True,
639
+ )
640
+ tts_text = gr.Textbox(label="Input Text", value=INITIAL_TTS_TEXT)
641
+ voice_guidance = gr.Markdown(initial_voice_guidance)
642
+ with gr.Column():
643
+ but0 = gr.Button("Convert", variant="primary")
644
+ info_text = gr.Textbox(label="Output info")
645
+ with gr.Column():
646
+ with gr.Accordion("Edge Voice", open=False):
647
+ edge_tts_output = gr.Audio(label="Edge Voice", type="filepath")
648
+ tts_output = gr.Audio(label="Result")
649
+ but0.click(
650
+ tts,
651
+ [
652
+ model_name,
653
+ speed,
654
+ volume,
655
+ pitch,
656
+ tts_text,
657
+ tts_voice,
658
+ f0_key_up,
659
+ f0_method,
660
+ index_rate,
661
+ protect0,
662
+ ],
663
+ [info_text, edge_tts_output, tts_output],
664
+ )
665
+ tts_voice.change(
666
+ refresh_voice_controls_no_auto,
667
+ [tts_voice, tts_text],
668
+ [recommended_voice, voice_guidance],
669
+ )
670
+ tts_text.change(
671
+ refresh_voice_controls,
672
+ [tts_voice, tts_text, auto_apply_recommended],
673
+ [recommended_voice, voice_guidance, tts_voice],
674
+ )
675
+ auto_apply_recommended.change(
676
+ refresh_voice_controls,
677
+ [tts_voice, tts_text, auto_apply_recommended],
678
+ [recommended_voice, voice_guidance, tts_voice],
679
+ )
680
+ recommended_voice.change(
681
+ apply_recommended_voice,
682
+ [recommended_voice, tts_text],
683
+ [tts_voice],
684
+ )
685
+ with gr.Row():
686
+ examples = gr.Examples(
687
+ examples_per_page=100,
688
+ examples=[
689
+ ["こんにちは、私の名前は初音ミクです!", "ja-JP-NanamiNeural-Female", 6],
690
+ ["Hello there. My name is Hatsune Miku!", "en-CA-ClaraNeural-Female", 6],
691
+ ["Halo. Nama saya Hatsune Miku!", "id-ID-GadisNeural-Female", 4],
692
+ ["Halo. Jenengku Hatsune Miku!", "jv-ID-SitiNeural-Female", 10],
693
+ ["Olá! Meu nome é Hatsune Miku!", "pt-BR-FranciscaNeural-Female", 6],
694
+ ["Bonjour. Je m'appelle Hatsune Miku!", "fr-FR-DeniseNeural-Female", 6],
695
+ ["Привет. Меня зовут Хацунэ Мику!", "ru-RU-SvetlanaNeural-Female", 6],
696
+ ],
697
+ inputs=[tts_text, tts_voice, f0_key_up],
698
+ )
699
+ app.launch(theme="NoCrypt/miku", ssr_mode=False)
requirements.txt CHANGED
@@ -5,12 +5,13 @@ aiohttp>=3.9
5
  certifi>=2024.0.0
6
  fairseq>=0.12.2
7
  faiss_cpu>=1.7.4
8
- #gradio==3.38.0
9
  librosa>=0.9.1
10
  numpy==1.23.5
11
  praat-parselmouth>=0.4.3
12
  pyworld>=0.3.4
13
  torchcrepe>=0.0.20
14
  huggingface_hub
15
- pydantic==2.10.6
16
- # https://github.com/facebookresearch/fairseq/issues/5511
 
 
5
  certifi>=2024.0.0
6
  fairseq>=0.12.2
7
  faiss_cpu>=1.7.4
8
+ #gradio==6.9.0
9
  librosa>=0.9.1
10
  numpy==1.23.5
11
  praat-parselmouth>=0.4.3
12
  pyworld>=0.3.4
13
  torchcrepe>=0.0.20
14
  huggingface_hub
15
+ hf_xet
16
+ #pydantic==2.10.6
17
+ # https://github.com/facebookresearch/fairseq/issues/5511