aiqcamp commited on
Commit
3230030
·
verified ·
1 Parent(s): 7b6a167

Update inference_webui.py

Browse files
Files changed (1) hide show
  1. inference_webui.py +224 -659
inference_webui.py CHANGED
@@ -1,673 +1,238 @@
1
- '''
2
- 按中英混合识别
3
- 按日英混合识别
4
- 多语种启动切分识别语种
5
- 全部按中文识别
6
- 全部按英文识别
7
- 全部按日文识别
8
- '''
9
- import logging
10
- import traceback
11
-
12
- logging.getLogger("markdown_it").setLevel(logging.ERROR)
13
- logging.getLogger("urllib3").setLevel(logging.ERROR)
14
- logging.getLogger("httpcore").setLevel(logging.ERROR)
15
- logging.getLogger("httpx").setLevel(logging.ERROR)
16
- logging.getLogger("asyncio").setLevel(logging.ERROR)
17
- logging.getLogger("charset_normalizer").setLevel(logging.ERROR)
18
- logging.getLogger("torchaudio._extension").setLevel(logging.ERROR)
19
- logging.getLogger("multipart.multipart").setLevel(logging.ERROR)
20
- import gradio.analytics as analytics
21
- analytics.version_check = lambda:None
22
- analytics.get_local_ip_address= lambda :"127.0.0.1"##不干掉本地联不通亚马逊的get_local_ip服务器
23
- import nltk
24
- nltk.download('averaged_perceptron_tagger_eng')
25
- import LangSegment, os, re, sys, json
26
- import pdb
27
- import spaces
28
- import torch
29
-
30
- version="v2"#os.environ.get("version","v2")
31
- cnhubert_base_path = os.environ.get(
32
- "cnhubert_base_path", "pretrained_models/chinese-hubert-base"
33
- )
34
- bert_path = os.environ.get(
35
- "bert_path", "pretrained_models/chinese-roberta-wwm-ext-large"
36
- )
37
-
38
- punctuation = set(['!', '?', '…', ',', '.', '-'," "])
39
  import gradio as gr
40
- from transformers import AutoModelForMaskedLM, AutoTokenizer
41
  import numpy as np
42
- import librosa
43
- from feature_extractor import cnhubert
44
-
45
- cnhubert.cnhubert_base_path = cnhubert_base_path
46
-
47
- from module.models import SynthesizerTrn
48
- from AR.models.t2s_lightning_module import Text2SemanticLightningModule
49
- from text import cleaned_text_to_sequence
50
- from text.cleaner import clean_text
51
- from time import time as ttime
52
- from module.mel_processing import spectrogram_torch
53
- from tools.my_utils import load_audio
54
- from tools.i18n.i18n import I18nAuto, scan_language_list
55
-
56
- # language=os.environ.get("language","Auto")
57
- # language=sys.argv[-1] if sys.argv[-1] in scan_language_list() else language
58
- i18n = I18nAuto(language="Auto")
59
-
60
- # os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1' # 确保直接启动推理UI时也能够设置。
61
-
62
- if torch.cuda.is_available():
63
- device = "cuda"
64
- is_half = True # eval(os.environ.get("is_half", "True")) and torch.cuda.is_available()
65
- else:
66
- device = "cpu"
67
- is_half=False
68
-
69
- dict_language_v1 = {
70
- i18n("中文"): "all_zh",#全部按中文识别
71
- i18n("英文"): "en",#全部按英文识别#######不变
72
- i18n("日文"): "all_ja",#全部按日文识别
73
- i18n("中英混合"): "zh",#按中英混合识别####不变
74
- i18n("日英混合"): "ja",#按日英混合识别####不变
75
- i18n("多语种混合"): "auto",#多语种启动切分识别语种
76
- }
77
- dict_language_v2 = {
78
- i18n("中文"): "all_zh",#全部按中文识别
79
- i18n("英文"): "en",#全部按英文识别#######不变
80
- i18n("日文"): "all_ja",#全部按日文识别
81
- i18n("粤语"): "all_yue",#全部按中文识别
82
- i18n("韩文"): "all_ko",#全部按韩文识别
83
- i18n("中英混合"): "zh",#按中英混合识别####不变
84
- i18n("日英混合"): "ja",#按日英混合识别####不变
85
- i18n("粤英混合"): "yue",#按粤英混合识别####不变
86
- i18n("韩英混合"): "ko",#按韩英混合识别####不变
87
- i18n("多语种混合"): "auto",#多语种启动切分识别语种
88
- i18n("多语种混合(粤语)"): "auto_yue",#多语种启动切分识别语种
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  }
90
- dict_language = dict_language_v1 if version =='v1' else dict_language_v2
91
-
92
- tokenizer = AutoTokenizer.from_pretrained(bert_path)
93
- bert_model = AutoModelForMaskedLM.from_pretrained(bert_path)
94
- if is_half == True:
95
- bert_model = bert_model.half().to(device)
96
- else:
97
- bert_model = bert_model.to(device)
98
-
99
-
100
- def get_bert_feature(text, word2ph):
101
- with torch.no_grad():
102
- inputs = tokenizer(text, return_tensors="pt")
103
- for i in inputs:
104
- inputs[i] = inputs[i].to(device)
105
- res = bert_model(**inputs, output_hidden_states=True)
106
- res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()[1:-1]
107
- assert len(word2ph) == len(text)
108
- phone_level_feature = []
109
- for i in range(len(word2ph)):
110
- repeat_feature = res[i].repeat(word2ph[i], 1)
111
- phone_level_feature.append(repeat_feature)
112
- phone_level_feature = torch.cat(phone_level_feature, dim=0)
113
- return phone_level_feature.T
114
-
115
-
116
- class DictToAttrRecursive(dict):
117
- def __init__(self, input_dict):
118
- super().__init__(input_dict)
119
- for key, value in input_dict.items():
120
- if isinstance(value, dict):
121
- value = DictToAttrRecursive(value)
122
- self[key] = value
123
- setattr(self, key, value)
124
-
125
- def __getattr__(self, item):
126
- try:
127
- return self[item]
128
- except KeyError:
129
- raise AttributeError(f"Attribute {item} not found")
130
-
131
- def __setattr__(self, key, value):
132
- if isinstance(value, dict):
133
- value = DictToAttrRecursive(value)
134
- super(DictToAttrRecursive, self).__setitem__(key, value)
135
- super().__setattr__(key, value)
136
-
137
- def __delattr__(self, item):
138
- try:
139
- del self[item]
140
- except KeyError:
141
- raise AttributeError(f"Attribute {item} not found")
142
-
143
-
144
- ssl_model = cnhubert.get_model()
145
- if is_half == True:
146
- ssl_model = ssl_model.half().to(device)
147
- else:
148
- ssl_model = ssl_model.to(device)
149
-
150
-
151
- def change_sovits_weights(sovits_path,prompt_language=None,text_language=None):
152
- global vq_model, hps, version, dict_language
153
- dict_s2 = torch.load(sovits_path, map_location="cpu")
154
- hps = dict_s2["config"]
155
- hps = DictToAttrRecursive(hps)
156
- hps.model.semantic_frame_rate = "25hz"
157
- if dict_s2['weight']['enc_p.text_embedding.weight'].shape[0] == 322:
158
- hps.model.version = "v1"
159
- else:
160
- hps.model.version = "v2"
161
- version = hps.model.version
162
- # print("sovits版本:",hps.model.version)
163
- vq_model = SynthesizerTrn(
164
- hps.data.filter_length // 2 + 1,
165
- hps.train.segment_size // hps.data.hop_length,
166
- n_speakers=hps.data.n_speakers,
167
- **hps.model
168
- )
169
- if ("pretrained" not in sovits_path):
170
- del vq_model.enc_q
171
- if is_half == True:
172
- vq_model = vq_model.half().to(device)
173
- else:
174
- vq_model = vq_model.to(device)
175
- vq_model.eval()
176
- print(vq_model.load_state_dict(dict_s2["weight"], strict=False))
177
- dict_language = dict_language_v1 if version =='v1' else dict_language_v2
178
- if prompt_language is not None and text_language is not None:
179
- if prompt_language in list(dict_language.keys()):
180
- prompt_text_update, prompt_language_update = {'__type__':'update'}, {'__type__':'update', 'value':prompt_language}
181
- else:
182
- prompt_text_update = {'__type__':'update', 'value':''}
183
- prompt_language_update = {'__type__':'update', 'value':i18n("中文")}
184
- if text_language in list(dict_language.keys()):
185
- text_update, text_language_update = {'__type__':'update'}, {'__type__':'update', 'value':text_language}
186
- else:
187
- text_update = {'__type__':'update', 'value':''}
188
- text_language_update = {'__type__':'update', 'value':i18n("中文")}
189
- return {'__type__':'update', 'choices':list(dict_language.keys())}, {'__type__':'update', 'choices':list(dict_language.keys())}, prompt_text_update, prompt_language_update, text_update, text_language_update
190
-
191
-
192
-
193
- change_sovits_weights("pretrained_models/gsv-v2final-pretrained/s2G2333k.pth")
194
-
195
-
196
- def change_gpt_weights(gpt_path):
197
- global hz, max_sec, t2s_model, config
198
- hz = 50
199
- dict_s1 = torch.load(gpt_path, map_location="cpu")
200
- config = dict_s1["config"]
201
- max_sec = config["data"]["max_sec"]
202
- t2s_model = Text2SemanticLightningModule(config, "****", is_train=False)
203
- t2s_model.load_state_dict(dict_s1["weight"])
204
- if is_half == True:
205
- t2s_model = t2s_model.half()
206
- t2s_model = t2s_model.to(device)
207
- t2s_model.eval()
208
- total = sum([param.nelement() for param in t2s_model.parameters()])
209
- print("Number of parameter: %.2fM" % (total / 1e6))
210
-
211
-
212
- change_gpt_weights("pretrained_models/gsv-v2final-pretrained/s1bert25hz-5kh-longer-epoch=12-step=369668.ckpt")
213
-
214
-
215
- def get_spepc(hps, filename):
216
- audio = load_audio(filename, int(hps.data.sampling_rate))
217
- audio = torch.FloatTensor(audio)
218
- maxx=audio.abs().max()
219
- if(maxx>1):audio/=min(2,maxx)
220
- audio_norm = audio
221
- audio_norm = audio_norm.unsqueeze(0)
222
- spec = spectrogram_torch(
223
- audio_norm,
224
- hps.data.filter_length,
225
- hps.data.sampling_rate,
226
- hps.data.hop_length,
227
- hps.data.win_length,
228
- center=False,
229
- )
230
- return spec
231
-
232
- def clean_text_inf(text, language, version):
233
- phones, word2ph, norm_text = clean_text(text, language, version)
234
- phones = cleaned_text_to_sequence(phones, version)
235
- return phones, word2ph, norm_text
236
-
237
- dtype=torch.float16 if is_half == True else torch.float32
238
- def get_bert_inf(phones, word2ph, norm_text, language):
239
- language=language.replace("all_","")
240
- if language == "zh":
241
- bert = get_bert_feature(norm_text, word2ph).to(device)#.to(dtype)
242
- else:
243
- bert = torch.zeros(
244
- (1024, len(phones)),
245
- dtype=torch.float16 if is_half == True else torch.float32,
246
- ).to(device)
247
-
248
- return bert
249
-
250
-
251
- splits = {",", "。", "?", "!", ",", ".", "?", "!", "~", ":", ":", "—", "…", }
252
-
253
-
254
- def get_first(text):
255
- pattern = "[" + "".join(re.escape(sep) for sep in splits) + "]"
256
- text = re.split(pattern, text)[0].strip()
257
- return text
258
-
259
- from text import chinese
260
- def get_phones_and_bert(text,language,version):
261
- if language in {"en", "all_zh", "all_ja", "all_ko", "all_yue"}:
262
- language = language.replace("all_","")
263
- if language == "en":
264
- LangSegment.setfilters(["en"])
265
- formattext = " ".join(tmp["text"] for tmp in LangSegment.getTexts(text))
266
- else:
267
- # 因无法区别中日韩文汉字,以用户输入为准
268
- formattext = text
269
- while " " in formattext:
270
- formattext = formattext.replace(" ", " ")
271
- if language == "zh":
272
- if re.search(r'[A-Za-z]', formattext):
273
- formattext = re.sub(r'[a-z]', lambda x: x.group(0).upper(), formattext)
274
- formattext = chinese.mix_text_normalize(formattext)
275
- return get_phones_and_bert(formattext,"zh",version)
276
- else:
277
- phones, word2ph, norm_text = clean_text_inf(formattext, language, version)
278
- bert = get_bert_feature(norm_text, word2ph).to(device)
279
- elif language == "yue" and re.search(r'[A-Za-z]', formattext):
280
- formattext = re.sub(r'[a-z]', lambda x: x.group(0).upper(), formattext)
281
- formattext = chinese.mix_text_normalize(formattext)
282
- return get_phones_and_bert(formattext,"yue",version)
283
- else:
284
- phones, word2ph, norm_text = clean_text_inf(formattext, language, version)
285
- bert = torch.zeros(
286
- (1024, len(phones)),
287
- dtype=torch.float16 if is_half == True else torch.float32,
288
- ).to(device)
289
- elif language in {"zh", "ja", "ko", "yue", "auto", "auto_yue"}:
290
- textlist=[]
291
- langlist=[]
292
- LangSegment.setfilters(["zh","ja","en","ko"])
293
- if language == "auto":
294
- for tmp in LangSegment.getTexts(text):
295
- langlist.append(tmp["lang"])
296
- textlist.append(tmp["text"])
297
- elif language == "auto_yue":
298
- for tmp in LangSegment.getTexts(text):
299
- if tmp["lang"] == "zh":
300
- tmp["lang"] = "yue"
301
- langlist.append(tmp["lang"])
302
- textlist.append(tmp["text"])
303
- else:
304
- for tmp in LangSegment.getTexts(text):
305
- if tmp["lang"] == "en":
306
- langlist.append(tmp["lang"])
307
- else:
308
- # 因无法区别中日韩文汉字,以用户输入为准
309
- langlist.append(language)
310
- textlist.append(tmp["text"])
311
- print(textlist)
312
- print(langlist)
313
- phones_list = []
314
- bert_list = []
315
- norm_text_list = []
316
- for i in range(len(textlist)):
317
- lang = langlist[i]
318
- phones, word2ph, norm_text = clean_text_inf(textlist[i], lang, version)
319
- bert = get_bert_inf(phones, word2ph, norm_text, lang)
320
- phones_list.append(phones)
321
- norm_text_list.append(norm_text)
322
- bert_list.append(bert)
323
- bert = torch.cat(bert_list, dim=1)
324
- phones = sum(phones_list, [])
325
- norm_text = ''.join(norm_text_list)
326
 
327
- return phones,bert.to(dtype),norm_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
 
 
 
 
 
 
 
329
 
330
- def merge_short_text_in_array(texts, threshold):
331
- if (len(texts)) < 2:
332
- return texts
333
- result = []
334
- text = ""
335
- for ele in texts:
336
- text += ele
337
- if len(text) >= threshold:
338
- result.append(text)
339
- text = ""
340
- if (len(text) > 0):
341
- if len(result) == 0:
342
- result.append(text)
343
- else:
344
- result[len(result) - 1] += text
345
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
 
347
- ##ref_wav_path+prompt_text+prompt_language+text(单个)+text_language+top_k+top_p+temperature
348
- # cache_tokens={}#暂未实现清理机制
349
- cache= {}
350
- @torch.inference_mode()
351
- @spaces.GPU
352
- def get_tts_wav(ref_wav_path, prompt_text, prompt_language, text, text_language, how_to_cut=i18n("不切"), top_k=20, top_p=0.6, temperature=0.6, ref_free = False,speed=1,if_freeze=False,inp_refs=123):
353
- global cache
354
- if ref_wav_path:pass
355
- else:gr.Warning(i18n('请上传参考音频'))
356
- if text:pass
357
- else:gr.Warning(i18n('请填入推理文本'))
358
- t = []
359
- if prompt_text is None or len(prompt_text) == 0:
360
- ref_free = True
361
- t0 = ttime()
362
- prompt_language = dict_language[prompt_language]
363
- text_language = dict_language[text_language]
364
 
365
 
366
- if not ref_free:
367
- prompt_text = prompt_text.strip("\n")
368
- if (prompt_text[-1] not in splits): prompt_text += "。" if prompt_language != "en" else "."
369
- print(i18n("实际输入的参考文本:"), prompt_text)
370
- text = text.strip("\n")
371
- if (text[0] not in splits and len(get_first(text)) < 4): text = "。" + text if text_language != "en" else "." + text
372
 
373
- print(i18n("实际输入的目标文本:"), text)
374
- zero_wav = np.zeros(
375
- int(hps.data.sampling_rate * 0.3),
376
- dtype=np.float16 if is_half == True else np.float32,
377
  )
378
- if not ref_free:
379
- with torch.no_grad():
380
- wav16k, sr = librosa.load(ref_wav_path, sr=16000)
381
- if (wav16k.shape[0] > 160000 or wav16k.shape[0] < 48000):
382
- gr.Warning(i18n("参考音频在3~10秒范围外,请更换!"))
383
- raise OSError(i18n("参考音频在3~10秒范围外,请更换!"))
384
- wav16k = torch.from_numpy(wav16k)
385
- zero_wav_torch = torch.from_numpy(zero_wav)
386
- if is_half == True:
387
- wav16k = wav16k.half().to(device)
388
- zero_wav_torch = zero_wav_torch.half().to(device)
389
- else:
390
- wav16k = wav16k.to(device)
391
- zero_wav_torch = zero_wav_torch.to(device)
392
- wav16k = torch.cat([wav16k, zero_wav_torch])
393
- ssl_content = ssl_model.model(wav16k.unsqueeze(0))[
394
- "last_hidden_state"
395
- ].transpose(
396
- 1, 2
397
- ) # .float()
398
- codes = vq_model.extract_latent(ssl_content)
399
- prompt_semantic = codes[0, 0]
400
- prompt = prompt_semantic.unsqueeze(0).to(device)
401
-
402
- t1 = ttime()
403
- t.append(t1-t0)
404
-
405
- if (how_to_cut == i18n("凑四句一切")):
406
- text = cut1(text)
407
- elif (how_to_cut == i18n("凑50字一切")):
408
- text = cut2(text)
409
- elif (how_to_cut == i18n("按中文句号。切")):
410
- text = cut3(text)
411
- elif (how_to_cut == i18n("按英文句号.切")):
412
- text = cut4(text)
413
- elif (how_to_cut == i18n("按标点符号切")):
414
- text = cut5(text)
415
- while "\n\n" in text:
416
- text = text.replace("\n\n", "\n")
417
- print(i18n("实际输入的目标文本(切句后):"), text)
418
- texts = text.split("\n")
419
- texts = process_text(texts)
420
- texts = merge_short_text_in_array(texts, 5)
421
- audio_opt = []
422
- if not ref_free:
423
- phones1,bert1,norm_text1=get_phones_and_bert(prompt_text, prompt_language, version)
424
-
425
- for i_text,text in enumerate(texts):
426
- # 解决输入目标文本的空行导致报错的问题
427
- if (len(text.strip()) == 0):
428
- continue
429
- if (text[-1] not in splits): text += "。" if text_language != "en" else "."
430
- print(i18n("实际输入的目标文本(每句):"), text)
431
- phones2,bert2,norm_text2=get_phones_and_bert(text, text_language, version)
432
- print(i18n("前端处理后的文本(每句):"), norm_text2)
433
- if not ref_free:
434
- bert = torch.cat([bert1, bert2], 1)
435
- all_phoneme_ids = torch.LongTensor(phones1+phones2).to(device).unsqueeze(0)
436
- else:
437
- bert = bert2
438
- all_phoneme_ids = torch.LongTensor(phones2).to(device).unsqueeze(0)
439
-
440
- bert = bert.to(device).unsqueeze(0)
441
- all_phoneme_len = torch.tensor([all_phoneme_ids.shape[-1]]).to(device)
442
 
443
- t2 = ttime()
444
- # cache_key="%s-%s-%s-%s-%s-%s-%s-%s"%(ref_wav_path,prompt_text,prompt_language,text,text_language,top_k,top_p,temperature)
445
- # print(cache.keys(),if_freeze)
446
- if(i_text in cache and if_freeze==True):pred_semantic=cache[i_text]
447
- else:
448
- with torch.no_grad():
449
- pred_semantic, idx = t2s_model.model.infer_panel(
450
- all_phoneme_ids,
451
- all_phoneme_len,
452
- None if ref_free else prompt,
453
- bert,
454
- # prompt_phone_len=ph_offset,
455
- top_k=top_k,
456
- top_p=top_p,
457
- temperature=temperature,
458
- early_stop_num=hz * max_sec,
459
- )
460
- pred_semantic = pred_semantic[:, -idx:].unsqueeze(0)
461
- cache[i_text]=pred_semantic
462
- t3 = ttime()
463
- refers=[]
464
- if(inp_refs):
465
- for path in inp_refs:
466
- try:
467
- refer = get_spepc(hps, path.name).to(dtype).to(device)
468
- refers.append(refer)
469
- except:
470
- traceback.print_exc()
471
- if(len(refers)==0):refers = [get_spepc(hps, ref_wav_path).to(dtype).to(device)]
472
- audio = (vq_model.decode(pred_semantic, torch.LongTensor(phones2).to(device).unsqueeze(0), refers,speed=speed).detach().cpu().numpy()[0, 0])
473
- max_audio=np.abs(audio).max()#简单防止16bit爆音
474
- if max_audio>1:audio/=max_audio
475
- audio_opt.append(audio)
476
- audio_opt.append(zero_wav)
477
- t4 = ttime()
478
- t.extend([t2 - t1,t3 - t2, t4 - t3])
479
- t1 = ttime()
480
- print("%.3f\t%.3f\t%.3f\t%.3f" %
481
- (t[0], sum(t[1::3]), sum(t[2::3]), sum(t[3::3]))
482
- )
483
- yield hps.data.sampling_rate, (np.concatenate(audio_opt, 0) * 32768).astype(
484
- np.int16
485
  )
486
 
487
-
488
- def split(todo_text):
489
- todo_text = todo_text.replace("……", "。").replace("——", ",")
490
- if todo_text[-1] not in splits:
491
- todo_text += "。"
492
- i_split_head = i_split_tail = 0
493
- len_text = len(todo_text)
494
- todo_texts = []
495
- while 1:
496
- if i_split_head >= len_text:
497
- break # 结尾一定有标点,所以直接跳出即可,最后一段在上次已加入
498
- if todo_text[i_split_head] in splits:
499
- i_split_head += 1
500
- todo_texts.append(todo_text[i_split_tail:i_split_head])
501
- i_split_tail = i_split_head
502
- else:
503
- i_split_head += 1
504
- return todo_texts
505
-
506
-
507
- def cut1(inp):
508
- inp = inp.strip("\n")
509
- inps = split(inp)
510
- split_idx = list(range(0, len(inps), 4))
511
- split_idx[-1] = None
512
- if len(split_idx) > 1:
513
- opts = []
514
- for idx in range(len(split_idx) - 1):
515
- opts.append("".join(inps[split_idx[idx]: split_idx[idx + 1]]))
516
- else:
517
- opts = [inp]
518
- opts = [item for item in opts if not set(item).issubset(punctuation)]
519
- return "\n".join(opts)
520
-
521
-
522
- def cut2(inp):
523
- inp = inp.strip("\n")
524
- inps = split(inp)
525
- if len(inps) < 2:
526
- return inp
527
- opts = []
528
- summ = 0
529
- tmp_str = ""
530
- for i in range(len(inps)):
531
- summ += len(inps[i])
532
- tmp_str += inps[i]
533
- if summ > 50:
534
- summ = 0
535
- opts.append(tmp_str)
536
- tmp_str = ""
537
- if tmp_str != "":
538
- opts.append(tmp_str)
539
- # print(opts)
540
- if len(opts) > 1 and len(opts[-1]) < 50: ##如果最后一个太短了,和前一个合一起
541
- opts[-2] = opts[-2] + opts[-1]
542
- opts = opts[:-1]
543
- opts = [item for item in opts if not set(item).issubset(punctuation)]
544
- return "\n".join(opts)
545
-
546
-
547
- def cut3(inp):
548
- inp = inp.strip("\n")
549
- opts = ["%s" % item for item in inp.strip("。").split("。")]
550
- opts = [item for item in opts if not set(item).issubset(punctuation)]
551
- return "\n".join(opts)
552
-
553
- def cut4(inp):
554
- inp = inp.strip("\n")
555
- opts = ["%s" % item for item in inp.strip(".").split(".")]
556
- opts = [item for item in opts if not set(item).issubset(punctuation)]
557
- return "\n".join(opts)
558
-
559
-
560
- # contributed by https://github.com/AI-Hobbyist/GPT-SoVITS/blob/main/GPT_SoVITS/inference_webui.py
561
- def cut5(inp):
562
- inp = inp.strip("\n")
563
- punds = {',', '.', ';', '?', '!', '、', ',', '。', '?', '!', ';', ':', '…'}
564
- mergeitems = []
565
- items = []
566
-
567
- for i, char in enumerate(inp):
568
- if char in punds:
569
- if char == '.' and i > 0 and i < len(inp) - 1 and inp[i - 1].isdigit() and inp[i + 1].isdigit():
570
- items.append(char)
571
- else:
572
- items.append(char)
573
- mergeitems.append("".join(items))
574
- items = []
575
- else:
576
- items.append(char)
577
-
578
- if items:
579
- mergeitems.append("".join(items))
580
-
581
- opt = [item for item in mergeitems if not set(item).issubset(punds)]
582
- return "\n".join(opt)
583
-
584
-
585
- def custom_sort_key(s):
586
- # 使用正则表达式提取字符串中的数字部分和非数字部分
587
- parts = re.split('(\d+)', s)
588
- # 将数字部分转换为整数,非数字部分保持不变
589
- parts = [int(part) if part.isdigit() else part for part in parts]
590
- return parts
591
-
592
- def process_text(texts):
593
- _text=[]
594
- if all(text in [None, " ", "\n",""] for text in texts):
595
- raise ValueError(i18n("请输入有效文本"))
596
- for text in texts:
597
- if text in [None, " ", ""]:
598
- pass
599
- else:
600
- _text.append(text)
601
- return _text
602
-
603
-
604
- def html_center(text, label='p'):
605
- return f"""<div style="text-align: center; margin: 100; padding: 50;">
606
- <{label} style="margin: 0; padding: 0;">{text}</{label}>
607
- </div>"""
608
-
609
- def html_left(text, label='p'):
610
- return f"""<div style="text-align: left; margin: 0; padding: 0;">
611
- <{label} style="margin: 0; padding: 0;">{text}</{label}>
612
- </div>"""
613
-
614
- css = """
615
- footer {
616
- visibility: hidden;
617
- }
618
- """
619
-
620
- with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as app:
621
-
622
- with gr.Group():
623
- gr.Markdown(html_center(i18n("*请上传并填写参考信息"),'h3'))
624
- with gr.Row():
625
- inp_ref = gr.Audio(label=i18n("请上传3~10秒内参考音频,超过会报错!"), type="filepath")
626
- with gr.Column():
627
- ref_text_free = gr.Checkbox(label=i18n("开启无参考文本模式。不填参考文本亦相当于开启。"), value=False, interactive=True, show_label=True)
628
- gr.Markdown(html_left(i18n("使用无参考文本模式时建议使用微调的GPT,听不清参考音频说的啥(不晓得写啥)可以开。<br>开启后无视填写的参考文本。")))
629
- prompt_text = gr.Textbox(label=i18n("参考音频的文本"), value="", lines=3, max_lines=3)
630
- prompt_language = gr.Dropdown(
631
- label=i18n("参考音频的语种"), choices=list(dict_language.keys()), value=i18n("中文")
632
- )
633
- inp_refs = gr.File(label=i18n("可选项:通过拖拽多个文件上传多个参考音频(建议同性),平均融合他们的音色。如不填写此项,音色由左侧单个参考音频控制。"),file_count="multiple")
634
- gr.Markdown(html_center(i18n("*请填写需要合成的目标文本和语种模式"),'h3'))
635
- with gr.Row():
636
- with gr.Column():
637
- text = gr.Textbox(label=i18n("需要合成的文本"), value="", lines=26, max_lines=26)
638
- with gr.Column():
639
- text_language = gr.Dropdown(
640
- label=i18n("需要合成的语种")+i18n(".限制范围越小判别效果越好。"), choices=list(dict_language.keys()), value=i18n("中文")
641
- )
642
- how_to_cut = gr.Dropdown(
643
- label=i18n("怎么切"),
644
- choices=[i18n("不切"), i18n("凑四句一切"), i18n("凑50字一切"), i18n("按中文句号。切"), i18n("按英文句号.切"), i18n("按标点符号切"), ],
645
- value=i18n("凑四句一切"),
646
- interactive=True
647
- )
648
- gr.Markdown(value=html_center(i18n("语速调整,高为更快")))
649
- if_freeze=gr.Checkbox(label=i18n("是否直接对上次合成结果调整语速和音色。防止随机性。"), value=False, interactive=True,show_label=True)
650
- speed = gr.Slider(minimum=0.6,maximum=1.65,step=0.05,label=i18n("语速"),value=1,interactive=True)
651
- gr.Markdown(html_center(i18n("GPT采样参数(无参考文本时不要太低。不懂就用默认):")))
652
- top_k = gr.Slider(minimum=1,maximum=100,step=1,label=i18n("top_k"),value=15,interactive=True)
653
- top_p = gr.Slider(minimum=0,maximum=1,step=0.05,label=i18n("top_p"),value=1,interactive=True)
654
- temperature = gr.Slider(minimum=0,maximum=1,step=0.05,label=i18n("temperature"),value=1,interactive=True)
655
- with gr.Row():
656
- inference_button = gr.Button(i18n("合成语音"), variant="primary", size='lg')
657
- output = gr.Audio(label=i18n("输出的语音"))
658
-
659
- inference_button.click(
660
- get_tts_wav,
661
- [inp_ref, prompt_text, prompt_language, text, text_language, how_to_cut, top_k, top_p, temperature, ref_text_free,speed,if_freeze,inp_refs],
662
- [output],
663
- )
664
-
665
- if __name__ == '__main__':
666
- # app.queue(concurrency_count=511, max_size=1022).launch(
667
- app.queue().launch(
668
- server_name="0.0.0.0",
669
- inbrowser=True,
670
- # share=True,
671
- # server_port=infer_ttswebui,
672
- quiet=True,
673
- )
 
1
+ import random
2
+ import os
3
+ import uuid
4
+ from datetime import datetime
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  import gradio as gr
 
6
  import numpy as np
7
+ import spaces
8
+ import torch
9
+ from diffusers import DiffusionPipeline
10
+ from PIL import Image
11
+
12
+ # Create permanent storage directory
13
+ SAVE_DIR = "saved_images" # Gradio will handle the persistence
14
+ if not os.path.exists(SAVE_DIR):
15
+ os.makedirs(SAVE_DIR, exist_ok=True)
16
+
17
+ # Load the default image
18
+ DEFAULT_IMAGE_PATH = "cover1.webp"
19
+
20
+ device = "cuda" if torch.cuda.is_available() else "cpu"
21
+ repo_id = "black-forest-labs/FLUX.1-dev"
22
+ adapter_id = "strangerzonehf/Ctoon-Plus-Plus"
23
+
24
+ pipeline = DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch.bfloat16)
25
+ pipeline.load_lora_weights(adapter_id)
26
+ pipeline = pipeline.to(device)
27
+
28
+ MAX_SEED = np.iinfo(np.int32).max
29
+ MAX_IMAGE_SIZE = 1024
30
+
31
+ def save_generated_image(image, prompt):
32
+ # Generate unique filename with timestamp
33
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
34
+ unique_id = str(uuid.uuid4())[:8]
35
+ filename = f"{timestamp}_{unique_id}.png"
36
+ filepath = os.path.join(SAVE_DIR, filename)
37
+
38
+ # Save the image
39
+ image.save(filepath)
40
+
41
+ # Save metadata
42
+ metadata_file = os.path.join(SAVE_DIR, "metadata.txt")
43
+ with open(metadata_file, "a", encoding="utf-8") as f:
44
+ f.write(f"{filename}|{prompt}|{timestamp}\n")
45
+
46
+ return filepath
47
+
48
+ def load_generated_images():
49
+ if not os.path.exists(SAVE_DIR):
50
+ return []
51
+
52
+ # Load all images from the directory
53
+ image_files = [os.path.join(SAVE_DIR, f) for f in os.listdir(SAVE_DIR)
54
+ if f.endswith(('.png', '.jpg', '.jpeg', '.webp'))]
55
+ # Sort by creation time (newest first)
56
+ image_files.sort(key=lambda x: os.path.getctime(x), reverse=True)
57
+ return image_files
58
+
59
+ def load_predefined_images():
60
+ # Return empty list since we're not using predefined images
61
+ return []
62
+
63
+ @spaces.GPU(duration=120)
64
+ def inference(
65
+ prompt: str,
66
+ seed: int,
67
+ randomize_seed: bool,
68
+ width: int,
69
+ height: int,
70
+ guidance_scale: float,
71
+ num_inference_steps: int,
72
+ lora_scale: float,
73
+ progress: gr.Progress = gr.Progress(track_tqdm=True),
74
+ ):
75
+ if randomize_seed:
76
+ seed = random.randint(0, MAX_SEED)
77
+ generator = torch.Generator(device=device).manual_seed(seed)
78
+
79
+ image = pipeline(
80
+ prompt=prompt,
81
+ guidance_scale=guidance_scale,
82
+ num_inference_steps=num_inference_steps,
83
+ width=width,
84
+ height=height,
85
+ generator=generator,
86
+ joint_attention_kwargs={"scale": lora_scale},
87
+ ).images[0]
88
+
89
+ # Save the generated image
90
+ filepath = save_generated_image(image, prompt)
91
+
92
+ # Return the image, seed, and updated gallery
93
+ return image, seed, load_generated_images()
94
+
95
+
96
+ examples = [
97
+ "A cartoon drawing of a majestic Persian cat wearing a tiny golden hanbok and crown. The cat has sparkling blue eyes and perfectly groomed white fur that seems to glow. It sits with regal posture on a traditional Korean cushion decorated with cloud patterns. The background is a soft pink with delicate cherry blossom petals floating around. The cat's expression shows a mix of dignity and subtle amusement. [trigger]",
98
+
99
+ "A cartoon drawing of an enthusiastic orange tabby cat in a puffy white chef's hat. The cat stands on its hind legs at a tiny wooden counter, wearing a white apron covered in flour pawprints. Its green eyes are focused intently on the cookie dough it's rolling with a miniature rolling pin. The background is a warm cream color with tiny floating cooking utensils and swirling steam patterns. [trigger]",
100
+
101
+ "A cartoon drawing of a sophisticated tuxedo cat photographer with round wire-rimmed glasses perched on its nose. The cat balances carefully on a tree branch, one paw holding a vintage camera while its tail curls in concentration. It wears a tiny brown beret and leather camera bag. The background is a soft blue with playful butterfly silhouettes and floating leaves. [trigger]",
102
+
103
+ "A cartoon drawing of a chubby Scottish Fold cat floating in a space capsule. The cat wears an adorable white spacesuit with colorful patches, its round face visible through the helmet visor. Its paws are batting at star-shaped toys that float around in zero gravity. The background shows a stylized view of Earth and twinkling stars through the capsule window. [trigger]",
104
+
105
+ "A cartoon drawing of an elegant Siamese ballet dancer cat in mid-twirl. The cat wears a sparkly pink tutu that flares out perfectly, with tiny satin ribbons wrapped around its ankles. Its blue eyes are closed in graceful concentration as it performs a pirouette. The background is a soft lavender with swirling musical notes and floating rose petals. [trigger]",
106
+
107
+ "A cartoon drawing of an adventurous calico cat riding atop a smiling elephant. The cat wears a tiny khaki explorer's vest filled with equipment, and a safari hat tilted at a jaunty angle. It holds a comically large map while the elephant's trunk curls up playfully. The background is a warm orange sunset with stylized acacia trees and cartoon birds soaring past. [trigger]"
108
+ ]
109
+ css = """
110
+ footer {
111
+ visibility: hidden;
112
  }
113
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
+ with gr.Blocks(theme=gr.themes.Soft(), css=css, analytics_enabled=False) as demo:
116
+ gr.HTML('<div class="title"> Cartoon Image Generation </div>')
117
+
118
+ gr.HTML("""<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fginigen-cartoon.hf.space">
119
+ <img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fginigen-cartoon.hf.space&countColor=%23263759" />
120
+ </a>""")
121
+
122
+
123
+ with gr.Tabs() as tabs:
124
+ with gr.Tab("Generation"):
125
+ with gr.Column(elem_id="col-container"):
126
+ with gr.Row():
127
+ prompt = gr.Text(
128
+ label="Prompt",
129
+ show_label=False,
130
+ max_lines=1,
131
+ placeholder="Enter your prompt",
132
+ container=False,
133
+ )
134
+ run_button = gr.Button("Run", scale=0)
135
 
136
+ # Modified to include the default image
137
+ result = gr.Image(
138
+ label="Result",
139
+ show_label=False,
140
+ value=DEFAULT_IMAGE_PATH # Set the default image
141
+ )
142
 
143
+ with gr.Accordion("Advanced Settings", open=False):
144
+ seed = gr.Slider(
145
+ label="Seed",
146
+ minimum=0,
147
+ maximum=MAX_SEED,
148
+ step=1,
149
+ value=42,
150
+ )
151
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
152
+
153
+ with gr.Row():
154
+ width = gr.Slider(
155
+ label="Width",
156
+ minimum=256,
157
+ maximum=MAX_IMAGE_SIZE,
158
+ step=32,
159
+ value=1024,
160
+ )
161
+ height = gr.Slider(
162
+ label="Height",
163
+ minimum=256,
164
+ maximum=MAX_IMAGE_SIZE,
165
+ step=32,
166
+ value=768,
167
+ )
168
+
169
+ with gr.Row():
170
+ guidance_scale = gr.Slider(
171
+ label="Guidance scale",
172
+ minimum=0.0,
173
+ maximum=10.0,
174
+ step=0.1,
175
+ value=3.5,
176
+ )
177
+ num_inference_steps = gr.Slider(
178
+ label="Number of inference steps",
179
+ minimum=1,
180
+ maximum=50,
181
+ step=1,
182
+ value=30,
183
+ )
184
+ lora_scale = gr.Slider(
185
+ label="LoRA scale",
186
+ minimum=0.0,
187
+ maximum=1.0,
188
+ step=0.1,
189
+ value=1.0,
190
+ )
191
+
192
+ gr.Examples(
193
+ examples=examples,
194
+ inputs=[prompt],
195
+ outputs=[result, seed],
196
+ )
197
 
198
+ with gr.Tab("Gallery"):
199
+ gallery_header = gr.Markdown("### Generated Images Gallery")
200
+ generated_gallery = gr.Gallery(
201
+ label="Generated Images",
202
+ columns=6,
203
+ show_label=False,
204
+ value=load_generated_images(),
205
+ elem_id="generated_gallery",
206
+ height="auto"
207
+ )
208
+ refresh_btn = gr.Button("🔄 Refresh Gallery")
 
 
 
 
 
 
209
 
210
 
211
+ # Event handlers
212
+ def refresh_gallery():
213
+ return load_generated_images()
 
 
 
214
 
215
+ refresh_btn.click(
216
+ fn=refresh_gallery,
217
+ inputs=None,
218
+ outputs=generated_gallery,
219
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
+ gr.on(
222
+ triggers=[run_button.click, prompt.submit],
223
+ fn=inference,
224
+ inputs=[
225
+ prompt,
226
+ seed,
227
+ randomize_seed,
228
+ width,
229
+ height,
230
+ guidance_scale,
231
+ num_inference_steps,
232
+ lora_scale,
233
+ ],
234
+ outputs=[result, seed, generated_gallery],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  )
236
 
237
+ demo.queue()
238
+ demo.launch()