Spaces:
Running
on
Zero
Running
on
Zero
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import spaces
|
2 |
+
import gradio as gr
|
3 |
+
import torch
|
4 |
+
import soundfile as sf
|
5 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
6 |
+
from xcodec2.modeling_xcodec2 import XCodec2Model
|
7 |
+
import tempfile
|
8 |
+
|
9 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
10 |
+
|
11 |
+
####################
|
12 |
+
# 全局加载模型
|
13 |
+
####################
|
14 |
+
llasa_3b = "HKUSTAudio/Llasa-1B-multi-speakers-genshin"
|
15 |
+
print("Loading tokenizer & model ...")
|
16 |
+
tokenizer = AutoTokenizer.from_pretrained(llasa_3b)
|
17 |
+
model = AutoModelForCausalLM.from_pretrained(llasa_3b)
|
18 |
+
model.eval().to(device)
|
19 |
+
|
20 |
+
print("Loading XCodec2Model ...")
|
21 |
+
codec_model_path = "HKUSTAudio/xcodec2"
|
22 |
+
Codec_model = XCodec2Model.from_pretrained(codec_model_path)
|
23 |
+
Codec_model.eval().to(device)
|
24 |
+
|
25 |
+
print("Models loaded.")
|
26 |
+
|
27 |
+
####################
|
28 |
+
# 推理用函数
|
29 |
+
####################
|
30 |
+
def extract_speech_ids(speech_tokens_str):
|
31 |
+
"""
|
32 |
+
将类似 <|s_23456|> 还原为 int 23456
|
33 |
+
"""
|
34 |
+
speech_ids = []
|
35 |
+
for token_str in speech_tokens_str:
|
36 |
+
if token_str.startswith("<|s_") and token_str.endswith("|>"):
|
37 |
+
num_str = token_str[4:-2]
|
38 |
+
num = int(num_str)
|
39 |
+
speech_ids.append(num)
|
40 |
+
else:
|
41 |
+
print(f"Unexpected token: {token_str}")
|
42 |
+
return speech_ids
|
43 |
+
@spaces.GPU
|
44 |
+
def text2speech(input_text, speaker_choice):
|
45 |
+
"""
|
46 |
+
将文本转为语音波形,并返回音频文件路径
|
47 |
+
"""
|
48 |
+
with torch.no_grad():
|
49 |
+
# 在输入文本前后拼接提示token
|
50 |
+
formatted_text = f"<|TEXT_UNDERSTANDING_START|>{input_text}<|TEXT_UNDERSTANDING_END|>"
|
51 |
+
chat = [
|
52 |
+
{"role": "user", "content": "Convert the text to speech:" + formatted_text},
|
53 |
+
{"role": "assistant", "content": f"Speaker {speaker_choice} <|SPEECH_GENERATION_START|>"}
|
54 |
+
]
|
55 |
+
|
56 |
+
# tokenizer.apply_chat_template 是 Llasa 风格的对话模式
|
57 |
+
input_ids = tokenizer.apply_chat_template(
|
58 |
+
chat,
|
59 |
+
tokenize=True,
|
60 |
+
return_tensors='pt',
|
61 |
+
continue_final_message=True
|
62 |
+
).to(device)
|
63 |
+
|
64 |
+
# 结束符
|
65 |
+
speech_end_id = tokenizer.convert_tokens_to_ids("<|SPEECH_GENERATION_END|>")
|
66 |
+
|
67 |
+
# 文本生成
|
68 |
+
outputs = model.generate(
|
69 |
+
input_ids,
|
70 |
+
max_length=2048, # We trained our model with a max length of 2048
|
71 |
+
eos_token_id= speech_end_id ,
|
72 |
+
do_sample=True,
|
73 |
+
top_p=0.95, # Adjusts the diversity of generated content
|
74 |
+
temperature=0.9, # Controls randomness in output
|
75 |
+
repetition_penalty= 1.2,
|
76 |
+
)
|
77 |
+
|
78 |
+
# 把新生成的 token(不包括输入部分)取出来
|
79 |
+
generated_ids = outputs[0][input_ids.shape[1]:-1]
|
80 |
+
speech_tokens_str = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
|
81 |
+
|
82 |
+
# 将 <|s_23456|> 提取成 [23456 ...]
|
83 |
+
speech_tokens_int = extract_speech_ids(speech_tokens_str)
|
84 |
+
speech_tokens_int = torch.tensor(speech_tokens_int).to(device).unsqueeze(0).unsqueeze(0)
|
85 |
+
|
86 |
+
# 调用 XCodec2Model 解码波形
|
87 |
+
gen_wav = Codec_model.decode_code(speech_tokens_int) # [batch, channels, samples]
|
88 |
+
|
89 |
+
# 获取音频数据和采样率
|
90 |
+
audio = gen_wav[0, 0, :].cpu().numpy()
|
91 |
+
sample_rate = 16000
|
92 |
+
|
93 |
+
# 将音频保存到临时文件
|
94 |
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmpfile:
|
95 |
+
sf.write(tmpfile.name, audio, sample_rate)
|
96 |
+
audio_path = tmpfile.name
|
97 |
+
|
98 |
+
return audio_path
|
99 |
+
|
100 |
+
####################
|
101 |
+
# Gradio 界面
|
102 |
+
####################
|
103 |
+
speaker_choices = [
|
104 |
+
'Paimon', 'Traveler', 'Nahida', 'Navia', 'Furina', 'Lyney', 'Layla', 'Neuvillette',
|
105 |
+
'Kaveh', 'Tighnari', 'Alhaitham', 'Kaeya', 'Dehya', 'Zhongli', 'Cyno', 'Yoimiya',
|
106 |
+
'Ningguang', 'Nilou', 'Faruzan', 'Wriothesley', 'Collei', 'Thoma', 'Noelle',
|
107 |
+
'Venti', 'Lynette', 'Charlotte', 'Diona', 'Yelan', 'Clorinde', 'Sigewinne', 'Beidou',
|
108 |
+
'Gorou', 'Lisa', 'Yanfei', 'Sucrose', 'Sayu', 'Ganyu', 'Chiori', 'Chongyun', 'Freminet',
|
109 |
+
'Barbara', 'Baizhu', 'Kirara', 'Dainsleif', 'Klee', 'Albedo', 'Dori', 'Eula', 'Xiao',
|
110 |
+
'Mona', 'Bennett', 'Amber', 'Xingqiu', 'Shenhe', 'Childe', 'Xiangling', 'Jean', 'Diluc',
|
111 |
+
'Katheryne', 'Mika', 'Keqing', 'Candace'
|
112 |
+
]
|
113 |
+
#["puck", "kore"]
|
114 |
+
|
115 |
+
demo = gr.Interface(
|
116 |
+
fn=text2speech,
|
117 |
+
inputs=[gr.Textbox(label="Enter text", lines=5),
|
118 |
+
gr.Dropdown(choices=speaker_choices, label="Select Speaker", value="Paimon")],
|
119 |
+
outputs=gr.Audio(label="Generated Audio", type="filepath"),
|
120 |
+
title="Llasa-1B TTS finetuned using simon3000/genshin-voice",
|
121 |
+
description = (
|
122 |
+
"Input a piece of text (Chinese, English, Japanese, Korean), select a speaker, "
|
123 |
+
"and click to generate speech. If fail, try a few more times\n"
|
124 |
+
"Speakers (角色选择):\n"
|
125 |
+
"'Paimon(派蒙)', 'Traveler(旅行者)', 'Nahida(纳西妲)', 'Navia(纳维亚)', 'Furina(芙宁娜)', "
|
126 |
+
"'Lyney(莱依拉)', 'Layla(莱依拉)', 'Neuvillette(诺维利特)', 'Kaveh(卡维赫)', 'Tighnari(提纳里)', "
|
127 |
+
"'Alhaitham(艾尔海森)', 'Kaeya(凯亚)', 'Dehya(迪希雅)', 'Zhongli(钟离)', 'Cyno(赛诺)', 'Yoimiya(宵宫)', "
|
128 |
+
"'Ningguang(凝光)', 'Nilou(妮露)', 'Faruzan(法露珊)', 'Wriothesley(维欧塞利)', 'Collei(可莉)', 'Thoma(托马)', "
|
129 |
+
"'Noelle(诺艾尔)', 'Venti(温迪)', 'Lynette(莉妮特)', 'Charlotte(夏洛特)', 'Diona(迪奥娜)', 'Yelan(夜兰)', "
|
130 |
+
"'Clorinde(克洛琳德)', 'Sigewinne(希格温)', 'Beidou(北斗)', 'Gorou(五郎)', 'Lisa(丽莎)', 'Yanfei(烟绯)', "
|
131 |
+
"'Sucrose(砂糖)', 'Sayu(早柚)', 'Ganyu(甘雨)', 'Chiori(千里)', 'Chongyun(重云)', 'Freminet(弗雷明内)', "
|
132 |
+
"'Barbara(芭芭拉)', 'Baizhu(白术)', 'Kirara(切尔拉)', 'Dainsleif(戴因斯雷布)', 'Klee(可莉)', 'Albedo(阿贝多)', "
|
133 |
+
"'Dori(多莉)', 'Eula(优菈)', 'Xiao(魈)', 'Mona(莫娜)', 'Bennett(班尼特)', 'Amber(安柏)', 'Xingqiu(行秋)', "
|
134 |
+
"'Shenhe(申鹤)', 'Childe(公子)', 'Xiangling(香菱)', 'Jean(琴)', 'Diluc(迪卢克)', 'Katheryne(凯瑟琳)', "
|
135 |
+
"'Mika(米卡)', 'Keqing(刻晴)', 'Candace(坎蒂丝)'"
|
136 |
+
))
|
137 |
+
|
138 |
+
if __name__ == "__main__":
|
139 |
+
demo.launch(
|
140 |
+
share=True )
|