zomehwh commited on
Commit
fb66b67
1 Parent(s): 5dbcf5d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +304 -305
app.py CHANGED
@@ -1,305 +1,304 @@
1
- import os
2
- cnhubert_base_path = "pretrained_models/chinese-hubert-base"
3
- bert_path = "pretrained_models/chinese-roberta-wwm-ext-large"
4
-
5
- import gradio as gr
6
- from transformers import AutoModelForMaskedLM, AutoTokenizer
7
- import sys,torch,numpy as np
8
- from pathlib import Path
9
- import os,pdb,utils,librosa,math,traceback,requests,argparse,torch,multiprocessing,pandas as pd,torch.multiprocessing as mp,soundfile
10
- # torch.backends.cuda.sdp_kernel("flash")
11
- # torch.backends.cuda.enable_flash_sdp(True)
12
- # torch.backends.cuda.enable_mem_efficient_sdp(True) # Not avaliable if torch version is lower than 2.0
13
- # torch.backends.cuda.enable_math_sdp(True)
14
- from random import shuffle
15
- from AR.utils import get_newest_ckpt
16
- from glob import glob
17
- from tqdm import tqdm
18
- from feature_extractor import cnhubert
19
- cnhubert.cnhubert_base_path=cnhubert_base_path
20
- from io import BytesIO
21
- from module.models import SynthesizerTrn
22
- from AR.models.t2s_lightning_module import Text2SemanticLightningModule
23
- from AR.utils.io import load_yaml_config
24
- from text import cleaned_text_to_sequence
25
- from text.cleaner import text_to_sequence, clean_text
26
- from time import time as ttime
27
- from module.mel_processing import spectrogram_torch
28
- from my_utils import load_audio
29
-
30
- import logging
31
- logging.getLogger('httpx').setLevel(logging.WARNING)
32
- logging.getLogger('httpcore').setLevel(logging.WARNING)
33
- logging.getLogger('multipart').setLevel(logging.WARNING)
34
-
35
- device = "cpu"
36
- is_half = False
37
-
38
- tokenizer = AutoTokenizer.from_pretrained(bert_path)
39
- bert_model=AutoModelForMaskedLM.from_pretrained(bert_path)
40
- if(is_half==True):bert_model=bert_model.half().to(device)
41
- else:bert_model=bert_model.to(device)
42
- # bert_model=bert_model.to(device)
43
- def get_bert_feature(text, word2ph):
44
- with torch.no_grad():
45
- inputs = tokenizer(text, return_tensors="pt")
46
- for i in inputs:
47
- inputs[i] = inputs[i].to(device)#####输入是long不用管精度问题,精度随bert_model
48
- res = bert_model(**inputs, output_hidden_states=True)
49
- res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()[1:-1]
50
- assert len(word2ph) == len(text)
51
- phone_level_feature = []
52
- for i in range(len(word2ph)):
53
- repeat_feature = res[i].repeat(word2ph[i], 1)
54
- phone_level_feature.append(repeat_feature)
55
- phone_level_feature = torch.cat(phone_level_feature, dim=0)
56
- # if(is_half==True):phone_level_feature=phone_level_feature.half()
57
- return phone_level_feature.T
58
-
59
-
60
- def load_model(sovits_path, gpt_path):
61
- n_semantic = 1024
62
- dict_s2 = torch.load(sovits_path, map_location="cpu")
63
- hps = dict_s2["config"]
64
-
65
- class DictToAttrRecursive:
66
- def __init__(self, input_dict):
67
- for key, value in input_dict.items():
68
- if isinstance(value, dict):
69
- # 如果值是字典,递归调用构造函数
70
- setattr(self, key, DictToAttrRecursive(value))
71
- else:
72
- setattr(self, key, value)
73
-
74
- hps = DictToAttrRecursive(hps)
75
- hps.model.semantic_frame_rate = "25hz"
76
- dict_s1 = torch.load(gpt_path, map_location="cpu")
77
- config = dict_s1["config"]
78
- ssl_model = cnhubert.get_model()
79
- if (is_half == True):
80
- ssl_model = ssl_model.half().to(device)
81
- else:
82
- ssl_model = ssl_model.to(device)
83
-
84
- vq_model = SynthesizerTrn(
85
- hps.data.filter_length // 2 + 1,
86
- hps.train.segment_size // hps.data.hop_length,
87
- n_speakers=hps.data.n_speakers,
88
- **hps.model)
89
- if (is_half == True):
90
- vq_model = vq_model.half().to(device)
91
- else:
92
- vq_model = vq_model.to(device)
93
- vq_model.eval()
94
- vq_model.load_state_dict(dict_s2["weight"], strict=False)
95
- hz = 50
96
- max_sec = config['data']['max_sec']
97
- # t2s_model = Text2SemanticLightningModule.load_from_checkpoint(checkpoint_path=gpt_path, config=config, map_location="cpu")#########todo
98
- t2s_model = Text2SemanticLightningModule(config, "ojbk", is_train=False)
99
- t2s_model.load_state_dict(dict_s1["weight"])
100
- if (is_half == True): t2s_model = t2s_model.half()
101
- t2s_model = t2s_model.to(device)
102
- t2s_model.eval()
103
- total = sum([param.nelement() for param in t2s_model.parameters()])
104
- print("Number of parameter: %.2fM" % (total / 1e6))
105
- return vq_model, ssl_model, t2s_model, hps, config, hz, max_sec
106
-
107
-
108
- def get_spepc(hps, filename):
109
- audio=load_audio(filename,int(hps.data.sampling_rate))
110
- audio=torch.FloatTensor(audio)
111
- audio_norm = audio
112
- audio_norm = audio_norm.unsqueeze(0)
113
- spec = spectrogram_torch(audio_norm, hps.data.filter_length,hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length,center=False)
114
- return spec
115
-
116
-
117
- def create_tts_fn(vq_model, ssl_model, t2s_model, hps, config, hz, max_sec):
118
- def tts_fn(ref_wav_path, prompt_text, prompt_language, text, text_language):
119
- t0 = ttime()
120
- prompt_text=prompt_text.strip("\n")
121
- prompt_language,text=prompt_language,text.strip("\n")
122
- print(text)
123
- if len(text) > 50:
124
- return f"Error: Text is too long, ({len(text)}>50)", None
125
- with torch.no_grad():
126
- wav16k, sr = librosa.load(ref_wav_path, sr=16000) # 派蒙
127
- wav16k = torch.from_numpy(wav16k)
128
- if(is_half==True):wav16k=wav16k.half().to(device)
129
- else:wav16k=wav16k.to(device)
130
- ssl_content = ssl_model.model(wav16k.unsqueeze(0))["last_hidden_state"].transpose(1, 2)#.float()
131
- codes = vq_model.extract_latent(ssl_content)
132
- prompt_semantic = codes[0, 0]
133
- t1 = ttime()
134
- phones1, word2ph1, norm_text1 = clean_text(prompt_text, prompt_language)
135
- phones1=cleaned_text_to_sequence(phones1)
136
- texts=text.split("\n")
137
- audio_opt = []
138
- zero_wav=np.zeros(int(hps.data.sampling_rate*0.3),dtype=np.float16 if is_half==True else np.float32)
139
- for text in texts:
140
- phones2, word2ph2, norm_text2 = clean_text(text, text_language)
141
- phones2 = cleaned_text_to_sequence(phones2)
142
- if(prompt_language=="zh"):bert1 = get_bert_feature(norm_text1, word2ph1).to(device)
143
- else:bert1 = torch.zeros((1024, len(phones1)),dtype=torch.float16 if is_half==True else torch.float32).to(device)
144
- if(text_language=="zh"):bert2 = get_bert_feature(norm_text2, word2ph2).to(device)
145
- else:bert2 = torch.zeros((1024, len(phones2))).to(bert1)
146
- bert = torch.cat([bert1, bert2], 1)
147
-
148
- all_phoneme_ids = torch.LongTensor(phones1+phones2).to(device).unsqueeze(0)
149
- bert = bert.to(device).unsqueeze(0)
150
- all_phoneme_len = torch.tensor([all_phoneme_ids.shape[-1]]).to(device)
151
- prompt = prompt_semantic.unsqueeze(0).to(device)
152
- t2 = ttime()
153
- with torch.no_grad():
154
- # pred_semantic = t2s_model.model.infer(
155
- pred_semantic,idx = t2s_model.model.infer_panel(
156
- all_phoneme_ids,
157
- all_phoneme_len,
158
- prompt,
159
- bert,
160
- # prompt_phone_len=ph_offset,
161
- top_k=config['inference']['top_k'],
162
- early_stop_num=hz * max_sec)
163
- t3 = ttime()
164
- # print(pred_semantic.shape,idx)
165
- pred_semantic = pred_semantic[:,-idx:].unsqueeze(0) # .unsqueeze(0)#mq要多unsqueeze一次
166
- refer = get_spepc(hps, ref_wav_path)#.to(device)
167
- if(is_half==True):refer=refer.half().to(device)
168
- else:refer=refer.to(device)
169
- # audio = vq_model.decode(pred_semantic, all_phoneme_ids, refer).detach().cpu().numpy()[0, 0]
170
- audio = vq_model.decode(pred_semantic, torch.LongTensor(phones2).to(device).unsqueeze(0), refer).detach().cpu().numpy()[0, 0]###试试重建不带上prompt部分
171
- audio_opt.append(audio)
172
- audio_opt.append(zero_wav)
173
- t4 = ttime()
174
- print("%.3f\t%.3f\t%.3f\t%.3f" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
175
- return "Success", (hps.data.sampling_rate,(np.concatenate(audio_opt,0)*32768).astype(np.int16))
176
- return tts_fn
177
-
178
-
179
- splits={",","。","?","!",",",".","?","!","~",":",":","—","…",}#不考虑省略号
180
- def split(todo_text):
181
- todo_text = todo_text.replace("……", "。").replace("——", ",")
182
- if (todo_text[-1] not in splits): todo_text += "。"
183
- i_split_head = i_split_tail = 0
184
- len_text = len(todo_text)
185
- todo_texts = []
186
- while (1):
187
- if (i_split_head >= len_text): break # 结尾一定有标点,所以直接跳出即可,最后一段在上次已加入
188
- if (todo_text[i_split_head] in splits):
189
- i_split_head += 1
190
- todo_texts.append(todo_text[i_split_tail:i_split_head])
191
- i_split_tail = i_split_head
192
- else:
193
- i_split_head += 1
194
- return todo_texts
195
-
196
-
197
- def change_reference_audio(prompt_text, transcripts):
198
- return transcripts[prompt_text]
199
-
200
-
201
- models = []
202
- models_info = {
203
- "alice": {
204
- "gpt_weight": "blue_archive/alice/alice-e15.ckpt",
205
- "sovits_weight": "blue_archive/alice/alice_e8_s216.pth",
206
- "title": "Blue Archive-天童アリス",
207
- "cover": "https://pic.imgdb.cn/item/65a7dad6871b83018a48f494.png",
208
- "example_reference": "召喚にお応じろ!ゴーレムよ!主人の命令に従い!"
209
- },
210
- "yuuka": {
211
- "gpt_weight": "blue_archive/yuuka/yuuka-e15.ckpt",
212
- "sovits_weight": "blue_archive/yuuka/yuuka_e8_s208.pth",
213
- "title": "Blue Archive-早瀬ユウカ",
214
- "cover": "https://pic.imgdb.cn/item/65a7da95871b83018a47a721.png",
215
- "example_reference": "せ~ん~せ~い~。もう少し頑張ってください!"
216
- },
217
- "mika": {
218
- "gpt_weight": "blue_archive/mika/mika-e15.ckpt",
219
- "sovits_weight": "blue_archive/mika/mika_e8_s176.pth",
220
- "title": "Blue Archive-聖園ミカ",
221
- "cover": "https://pic.imgdb.cn/item/65a7daf6871b83018a499034.png",
222
- "example_reference": "あけましておめでとう、先生!こんな私だけど、今年もよろしくね☆"
223
- }
224
- }
225
- for i, info in models_info.items():
226
- title = info['title']
227
- cover = info['cover']
228
- gpt_weight = info['gpt_weight']
229
- sovits_weight = info['sovits_weight']
230
- example_reference = info['example_reference']
231
- transcripts = {}
232
- with open(f"blue_archive/{i}/reference_audio/transcript.txt", 'r', encoding='utf-8') as file:
233
- for line in file:
234
- line = line.strip()
235
- wav, t = line.split("|")
236
- transcripts[t] = os.path.join(f"blue_archive/{i}/reference_audio", wav)
237
-
238
- vq_model, ssl_model, t2s_model, hps, config, hz, max_sec = load_model(sovits_weight, gpt_weight)
239
-
240
-
241
- models.append(
242
- (
243
- i,
244
- title,
245
- cover,
246
- transcripts,
247
- example_reference,
248
- create_tts_fn(
249
- vq_model, ssl_model, t2s_model, hps, config, hz, max_sec
250
- )
251
- )
252
- )
253
- with gr.Blocks() as app:
254
- gr.Markdown(
255
- "# <center> GPT-SoVITS \n"
256
- "## <center> https://github.com/RVC-Boss/GPT-SoVITS\n"
257
-
258
- )
259
- with gr.Tabs():
260
- for (name, title, cover, transcripts, example_reference, tts_fn) in models:
261
- with gr.TabItem(name):
262
- with gr.Row():
263
- gr.Markdown(
264
- '<div align="center">'
265
- f'<a><strong>{title}</strong></a>'
266
- f'<img style="width:auto;height:300px;" src="{cover}">' if cover else ""
267
- '</div>')
268
- with gr.Row():
269
- with gr.Column():
270
- prompt_text = gr.Dropdown(
271
- label="Transcript of the Reference Audio",
272
- value=example_reference,
273
- choices=transcripts.keys()
274
- )
275
- inp_ref_audio = gr.Audio(
276
- label="Reference Audio",
277
- type="filepath",
278
- interactive=False,
279
- value=transcripts[example_reference]
280
- )
281
- transcripts_state = gr.State(value=transcripts)
282
- prompt_text.change(
283
- fn=change_reference_audio,
284
- inputs=[prompt_text, transcripts_state],
285
- outputs=[inp_ref_audio]
286
- )
287
- prompt_language = gr.State(value="ja")
288
- with gr.Column():
289
- text = gr.Textbox(label="Input Text", value="はいきなり、春の嵐のように突然訪れた。")
290
- text_language = gr.Dropdown(
291
- label="Language",
292
- choices=["zh", "en", "ja"],
293
- value="ja"
294
- )
295
- inference_button = gr.Button("Generate", variant="primary")
296
- om = gr.Textbox(label="Output Message")
297
- output = gr.Audio(label="Output Audio")
298
- inference_button.click(
299
- fn=tts_fn,
300
- inputs=[inp_ref_audio, prompt_text, prompt_language, text, text_language],
301
- outputs=[om, output],
302
- concurrency_limit=2
303
- )
304
-
305
- app.queue(max_size=30).launch()
 
1
+ import os
2
+ cnhubert_base_path = "pretrained_models/chinese-hubert-base"
3
+ bert_path = "pretrained_models/chinese-roberta-wwm-ext-large"
4
+
5
+ import gradio as gr
6
+ from transformers import AutoModelForMaskedLM, AutoTokenizer
7
+ import sys,torch,numpy as np
8
+ from pathlib import Path
9
+ import os,pdb,utils,librosa,math,traceback,requests,argparse,torch,multiprocessing,pandas as pd,torch.multiprocessing as mp,soundfile
10
+ # torch.backends.cuda.sdp_kernel("flash")
11
+ # torch.backends.cuda.enable_flash_sdp(True)
12
+ # torch.backends.cuda.enable_mem_efficient_sdp(True) # Not avaliable if torch version is lower than 2.0
13
+ # torch.backends.cuda.enable_math_sdp(True)
14
+ from random import shuffle
15
+ from AR.utils import get_newest_ckpt
16
+ from glob import glob
17
+ from tqdm import tqdm
18
+ from feature_extractor import cnhubert
19
+ cnhubert.cnhubert_base_path=cnhubert_base_path
20
+ from io import BytesIO
21
+ from module.models import SynthesizerTrn
22
+ from AR.models.t2s_lightning_module import Text2SemanticLightningModule
23
+ from AR.utils.io import load_yaml_config
24
+ from text import cleaned_text_to_sequence
25
+ from text.cleaner import text_to_sequence, clean_text
26
+ from time import time as ttime
27
+ from module.mel_processing import spectrogram_torch
28
+ from my_utils import load_audio
29
+
30
+ import logging
31
+ logging.getLogger('httpx').setLevel(logging.WARNING)
32
+ logging.getLogger('httpcore').setLevel(logging.WARNING)
33
+ logging.getLogger('multipart').setLevel(logging.WARNING)
34
+
35
+ device = "cpu"
36
+ is_half = False
37
+
38
+ tokenizer = AutoTokenizer.from_pretrained(bert_path)
39
+ bert_model=AutoModelForMaskedLM.from_pretrained(bert_path)
40
+ if(is_half==True):bert_model=bert_model.half().to(device)
41
+ else:bert_model=bert_model.to(device)
42
+ # bert_model=bert_model.to(device)
43
+ def get_bert_feature(text, word2ph):
44
+ with torch.no_grad():
45
+ inputs = tokenizer(text, return_tensors="pt")
46
+ for i in inputs:
47
+ inputs[i] = inputs[i].to(device)#####输入是long不用管精度问题,精度随bert_model
48
+ res = bert_model(**inputs, output_hidden_states=True)
49
+ res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()[1:-1]
50
+ assert len(word2ph) == len(text)
51
+ phone_level_feature = []
52
+ for i in range(len(word2ph)):
53
+ repeat_feature = res[i].repeat(word2ph[i], 1)
54
+ phone_level_feature.append(repeat_feature)
55
+ phone_level_feature = torch.cat(phone_level_feature, dim=0)
56
+ # if(is_half==True):phone_level_feature=phone_level_feature.half()
57
+ return phone_level_feature.T
58
+
59
+
60
+ def load_model(sovits_path, gpt_path):
61
+ n_semantic = 1024
62
+ dict_s2 = torch.load(sovits_path, map_location="cpu")
63
+ hps = dict_s2["config"]
64
+
65
+ class DictToAttrRecursive:
66
+ def __init__(self, input_dict):
67
+ for key, value in input_dict.items():
68
+ if isinstance(value, dict):
69
+ # 如果值是字典,递归调用构造函数
70
+ setattr(self, key, DictToAttrRecursive(value))
71
+ else:
72
+ setattr(self, key, value)
73
+
74
+ hps = DictToAttrRecursive(hps)
75
+ hps.model.semantic_frame_rate = "25hz"
76
+ dict_s1 = torch.load(gpt_path, map_location="cpu")
77
+ config = dict_s1["config"]
78
+ ssl_model = cnhubert.get_model()
79
+ if (is_half == True):
80
+ ssl_model = ssl_model.half().to(device)
81
+ else:
82
+ ssl_model = ssl_model.to(device)
83
+
84
+ vq_model = SynthesizerTrn(
85
+ hps.data.filter_length // 2 + 1,
86
+ hps.train.segment_size // hps.data.hop_length,
87
+ n_speakers=hps.data.n_speakers,
88
+ **hps.model)
89
+ if (is_half == True):
90
+ vq_model = vq_model.half().to(device)
91
+ else:
92
+ vq_model = vq_model.to(device)
93
+ vq_model.eval()
94
+ vq_model.load_state_dict(dict_s2["weight"], strict=False)
95
+ hz = 50
96
+ max_sec = config['data']['max_sec']
97
+ # t2s_model = Text2SemanticLightningModule.load_from_checkpoint(checkpoint_path=gpt_path, config=config, map_location="cpu")#########todo
98
+ t2s_model = Text2SemanticLightningModule(config, "ojbk", is_train=False)
99
+ t2s_model.load_state_dict(dict_s1["weight"])
100
+ if (is_half == True): t2s_model = t2s_model.half()
101
+ t2s_model = t2s_model.to(device)
102
+ t2s_model.eval()
103
+ total = sum([param.nelement() for param in t2s_model.parameters()])
104
+ print("Number of parameter: %.2fM" % (total / 1e6))
105
+ return vq_model, ssl_model, t2s_model, hps, config, hz, max_sec
106
+
107
+
108
+ def get_spepc(hps, filename):
109
+ audio=load_audio(filename,int(hps.data.sampling_rate))
110
+ audio=torch.FloatTensor(audio)
111
+ audio_norm = audio
112
+ audio_norm = audio_norm.unsqueeze(0)
113
+ spec = spectrogram_torch(audio_norm, hps.data.filter_length,hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length,center=False)
114
+ return spec
115
+
116
+
117
+ def create_tts_fn(vq_model, ssl_model, t2s_model, hps, config, hz, max_sec):
118
+ def tts_fn(ref_wav_path, prompt_text, prompt_language, text, text_language):
119
+ t0 = ttime()
120
+ prompt_text=prompt_text.strip("\n")
121
+ prompt_language,text=prompt_language,text.strip("\n")
122
+ print(text)
123
+ if len(text) > 50:
124
+ return f"Error: Text is too long, ({len(text)}>50)", None
125
+ with torch.no_grad():
126
+ wav16k, sr = librosa.load(ref_wav_path, sr=16000) # 派蒙
127
+ wav16k = torch.from_numpy(wav16k)
128
+ if(is_half==True):wav16k=wav16k.half().to(device)
129
+ else:wav16k=wav16k.to(device)
130
+ ssl_content = ssl_model.model(wav16k.unsqueeze(0))["last_hidden_state"].transpose(1, 2)#.float()
131
+ codes = vq_model.extract_latent(ssl_content)
132
+ prompt_semantic = codes[0, 0]
133
+ t1 = ttime()
134
+ phones1, word2ph1, norm_text1 = clean_text(prompt_text, prompt_language)
135
+ phones1=cleaned_text_to_sequence(phones1)
136
+ texts=text.split("\n")
137
+ audio_opt = []
138
+ zero_wav=np.zeros(int(hps.data.sampling_rate*0.3),dtype=np.float16 if is_half==True else np.float32)
139
+ for text in texts:
140
+ phones2, word2ph2, norm_text2 = clean_text(text, text_language)
141
+ phones2 = cleaned_text_to_sequence(phones2)
142
+ if(prompt_language=="zh"):bert1 = get_bert_feature(norm_text1, word2ph1).to(device)
143
+ else:bert1 = torch.zeros((1024, len(phones1)),dtype=torch.float16 if is_half==True else torch.float32).to(device)
144
+ if(text_language=="zh"):bert2 = get_bert_feature(norm_text2, word2ph2).to(device)
145
+ else:bert2 = torch.zeros((1024, len(phones2))).to(bert1)
146
+ bert = torch.cat([bert1, bert2], 1)
147
+
148
+ all_phoneme_ids = torch.LongTensor(phones1+phones2).to(device).unsqueeze(0)
149
+ bert = bert.to(device).unsqueeze(0)
150
+ all_phoneme_len = torch.tensor([all_phoneme_ids.shape[-1]]).to(device)
151
+ prompt = prompt_semantic.unsqueeze(0).to(device)
152
+ t2 = ttime()
153
+ with torch.no_grad():
154
+ # pred_semantic = t2s_model.model.infer(
155
+ pred_semantic,idx = t2s_model.model.infer_panel(
156
+ all_phoneme_ids,
157
+ all_phoneme_len,
158
+ prompt,
159
+ bert,
160
+ # prompt_phone_len=ph_offset,
161
+ top_k=config['inference']['top_k'],
162
+ early_stop_num=hz * max_sec)
163
+ t3 = ttime()
164
+ # print(pred_semantic.shape,idx)
165
+ pred_semantic = pred_semantic[:,-idx:].unsqueeze(0) # .unsqueeze(0)#mq要多unsqueeze一次
166
+ refer = get_spepc(hps, ref_wav_path)#.to(device)
167
+ if(is_half==True):refer=refer.half().to(device)
168
+ else:refer=refer.to(device)
169
+ # audio = vq_model.decode(pred_semantic, all_phoneme_ids, refer).detach().cpu().numpy()[0, 0]
170
+ audio = vq_model.decode(pred_semantic, torch.LongTensor(phones2).to(device).unsqueeze(0), refer).detach().cpu().numpy()[0, 0]###试试重建不带上prompt部分
171
+ audio_opt.append(audio)
172
+ audio_opt.append(zero_wav)
173
+ t4 = ttime()
174
+ print("%.3f\t%.3f\t%.3f\t%.3f" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
175
+ return "Success", (hps.data.sampling_rate,(np.concatenate(audio_opt,0)*32768).astype(np.int16))
176
+ return tts_fn
177
+
178
+
179
+ splits={",","。","?","!",",",".","?","!","~",":",":","—","…",}#不考虑省略号
180
+ def split(todo_text):
181
+ todo_text = todo_text.replace("……", "。").replace("——", ",")
182
+ if (todo_text[-1] not in splits): todo_text += "。"
183
+ i_split_head = i_split_tail = 0
184
+ len_text = len(todo_text)
185
+ todo_texts = []
186
+ while (1):
187
+ if (i_split_head >= len_text): break # 结尾一定有标点,所以直接跳出即可,最后一段在上次已加入
188
+ if (todo_text[i_split_head] in splits):
189
+ i_split_head += 1
190
+ todo_texts.append(todo_text[i_split_tail:i_split_head])
191
+ i_split_tail = i_split_head
192
+ else:
193
+ i_split_head += 1
194
+ return todo_texts
195
+
196
+
197
+ def change_reference_audio(prompt_text, transcripts):
198
+ return transcripts[prompt_text]
199
+
200
+
201
+ models = []
202
+ models_info = {
203
+ "alice": {
204
+ "gpt_weight": "blue_archive/alice/alice-e15.ckpt",
205
+ "sovits_weight": "blue_archive/alice/alice_e8_s216.pth",
206
+ "title": "Blue Archive-天童アリス",
207
+ "cover": "https://pic.imgdb.cn/item/65a7dad6871b83018a48f494.png",
208
+ "example_reference": "召喚にお応じろ!ゴーレムよ!主人の命令に従い!"
209
+ },
210
+ "yuuka": {
211
+ "gpt_weight": "blue_archive/yuuka/yuuka-e15.ckpt",
212
+ "sovits_weight": "blue_archive/yuuka/yuuka_e8_s208.pth",
213
+ "title": "Blue Archive-早瀬ユウカ",
214
+ "cover": "https://pic.imgdb.cn/item/65a7da95871b83018a47a721.png",
215
+ "example_reference": "せ~ん~せ~い~。もう少し頑張ってください!"
216
+ },
217
+ "mika": {
218
+ "gpt_weight": "blue_archive/mika/mika-e15.ckpt",
219
+ "sovits_weight": "blue_archive/mika/mika_e8_s176.pth",
220
+ "title": "Blue Archive-聖園ミカ",
221
+ "cover": "https://pic.imgdb.cn/item/65a7daf6871b83018a499034.png",
222
+ "example_reference": "あけましておめでとう、先生!こんな私だけど、今年もよろしくね☆"
223
+ }
224
+ }
225
+ for i, info in models_info.items():
226
+ title = info['title']
227
+ cover = info['cover']
228
+ gpt_weight = info['gpt_weight']
229
+ sovits_weight = info['sovits_weight']
230
+ example_reference = info['example_reference']
231
+ transcripts = {}
232
+ with open(f"blue_archive/{i}/reference_audio/transcript.txt", 'r', encoding='utf-8') as file:
233
+ for line in file:
234
+ line = line.strip()
235
+ wav, t = line.split("|")
236
+ transcripts[t] = os.path.join(f"blue_archive/{i}/reference_audio", wav)
237
+
238
+ vq_model, ssl_model, t2s_model, hps, config, hz, max_sec = load_model(sovits_weight, gpt_weight)
239
+
240
+
241
+ models.append(
242
+ (
243
+ i,
244
+ title,
245
+ cover,
246
+ transcripts,
247
+ example_reference,
248
+ create_tts_fn(
249
+ vq_model, ssl_model, t2s_model, hps, config, hz, max_sec
250
+ )
251
+ )
252
+ )
253
+ with gr.Blocks() as app:
254
+ gr.Markdown(
255
+ "# <center> GPT-SoVITS \n"
256
+ "## <center> https://github.com/RVC-Boss/GPT-SoVITS\n"
257
+
258
+ )
259
+ with gr.Tabs():
260
+ for (name, title, cover, transcripts, example_reference, tts_fn) in models:
261
+ with gr.TabItem(name):
262
+ with gr.Row():
263
+ gr.Markdown(
264
+ '<div align="center">'
265
+ f'<a><strong>{title}</strong></a>'
266
+ f'<img style="width:auto;height:300px;" src="{cover}">' if cover else ""
267
+ '</div>')
268
+ with gr.Row():
269
+ with gr.Column():
270
+ prompt_text = gr.Dropdown(
271
+ label="Transcript of the Reference Audio",
272
+ value=example_reference,
273
+ choices=transcripts.keys()
274
+ )
275
+ inp_ref_audio = gr.Audio(
276
+ label="Reference Audio",
277
+ type="filepath",
278
+ interactive=False,
279
+ value=transcripts[example_reference]
280
+ )
281
+ transcripts_state = gr.State(value=transcripts)
282
+ prompt_text.change(
283
+ fn=change_reference_audio,
284
+ inputs=[prompt_text, transcripts_state],
285
+ outputs=[inp_ref_audio]
286
+ )
287
+ prompt_language = gr.State(value="ja")
288
+ with gr.Column():
289
+ text = gr.Textbox(label="Input Text", value="はいきなり、春の嵐のように突然訪れた。")
290
+ text_language = gr.Dropdown(
291
+ label="Language",
292
+ choices=["zh", "en", "ja"],
293
+ value="ja"
294
+ )
295
+ inference_button = gr.Button("Generate", variant="primary")
296
+ om = gr.Textbox(label="Output Message")
297
+ output = gr.Audio(label="Output Audio")
298
+ inference_button.click(
299
+ fn=tts_fn,
300
+ inputs=[inp_ref_audio, prompt_text, prompt_language, text, text_language],
301
+ outputs=[om, output]
302
+ )
303
+
304
+ app.queue().launch()