HKUST-Audio commited on
Commit
0ea1315
·
verified ·
1 Parent(s): 1d6fddf

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -0
app.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import soundfile as sf
4
+ from transformers import AutoTokenizer, AutoModelForCausalLM
5
+ from xcodec2.modeling_xcodec2 import XCodec2Model
6
+ import tempfile
7
+
8
+ device = "cuda" if torch.cuda.is_available() else "cpu"
9
+
10
+ ####################
11
+ # 全局加载模型
12
+ ####################
13
+ llasa_3b = "HKUSTAudio/Llasa-1B-two-speakers-kore-puck"
14
+ print("Loading tokenizer & model ...")
15
+ tokenizer = AutoTokenizer.from_pretrained(llasa_3b)
16
+ model = AutoModelForCausalLM.from_pretrained(llasa_3b)
17
+ model.eval().to(device)
18
+
19
+ print("Loading XCodec2Model ...")
20
+ codec_model_path = "HKUSTAudio/xcodec2"
21
+ Codec_model = XCodec2Model.from_pretrained(codec_model_path)
22
+ Codec_model.eval().to(device)
23
+
24
+ print("Models loaded.")
25
+
26
+ ####################
27
+ # 推理用函数
28
+ ####################
29
+ def extract_speech_ids(speech_tokens_str):
30
+ """
31
+ 将类似 <|s_23456|> 还原为 int 23456
32
+ """
33
+ speech_ids = []
34
+ for token_str in speech_tokens_str:
35
+ if token_str.startswith("<|s_") and token_str.endswith("|>"):
36
+ num_str = token_str[4:-2]
37
+ num = int(num_str)
38
+ speech_ids.append(num)
39
+ else:
40
+ print(f"Unexpected token: {token_str}")
41
+ return speech_ids
42
+
43
+ def text2speech(input_text, speaker_choice):
44
+ """
45
+ 将文本转为语音波形,并返回音频文件路径
46
+ """
47
+ with torch.no_grad():
48
+ # 在输入文本前后拼接提示token
49
+ formatted_text = f"<|TEXT_UNDERSTANDING_START|>{input_text}<|TEXT_UNDERSTANDING_END|>"
50
+ chat = [
51
+ {"role": "user", "content": "Convert the text to speech:" + formatted_text},
52
+ {"role": "assistant", "content": f"Speaker {speaker_choice} <|SPEECH_GENERATION_START|>"}
53
+ ]
54
+
55
+ # tokenizer.apply_chat_template 是 Llasa 风格的对话模式
56
+ input_ids = tokenizer.apply_chat_template(
57
+ chat,
58
+ tokenize=True,
59
+ return_tensors='pt',
60
+ continue_final_message=True
61
+ ).to(device)
62
+
63
+ # 结束符
64
+ speech_end_id = tokenizer.convert_tokens_to_ids("<|SPEECH_GENERATION_END|>")
65
+
66
+ # 文本生成
67
+ outputs = model.generate(
68
+ input_ids,
69
+ max_length=2048,
70
+ eos_token_id=speech_end_id,
71
+ do_sample=True,
72
+ top_p=1,
73
+ temperature=0.8,
74
+ )
75
+
76
+ # 把新生成的 token(不包括输入部分)取出来
77
+ generated_ids = outputs[0][input_ids.shape[1]:-1]
78
+ speech_tokens_str = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
79
+
80
+ # 将 <|s_23456|> 提取成 [23456 ...]
81
+ speech_tokens_int = extract_speech_ids(speech_tokens_str)
82
+ speech_tokens_int = torch.tensor(speech_tokens_int).to(device).unsqueeze(0).unsqueeze(0)
83
+
84
+ # 调用 XCodec2Model 解码波形
85
+ gen_wav = Codec_model.decode_code(speech_tokens_int) # [batch, channels, samples]
86
+
87
+ # 获取音频数据和采样率
88
+ audio = gen_wav[0, 0, :].cpu().numpy()
89
+ sample_rate = 16000
90
+
91
+ # 将音频保存到临时文件
92
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmpfile:
93
+ sf.write(tmpfile.name, audio, sample_rate)
94
+ audio_path = tmpfile.name
95
+
96
+ return audio_path
97
+
98
+ ####################
99
+ # Gradio 界面
100
+ ####################
101
+ speaker_choices = ["puck", "kore"]
102
+
103
+ demo = gr.Interface(
104
+ fn=text2speech,
105
+ inputs=[gr.Textbox(label="Enter text", lines=5),
106
+ gr.Dropdown(choices=speaker_choices, label="Select Speaker", value="puck")],
107
+ outputs=gr.Audio(label="Generated Audio", type="filepath"),
108
+ title="Llasa-1B TTS Demo",
109
+ description="Input a piece of text in English or Chinese, select a speaker (puck or kore), and click to generate speech.\nModel: HKUST-Audio/Llasa-1B + HKUST-Audio/xcodec2"
110
+ )
111
+
112
+ if __name__ == "__main__":
113
+ demo.launch(
114
+ share=True )