kika2000 commited on
Commit
abd30f8
·
verified ·
1 Parent(s): 50acc31

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +173 -0
app.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
3
+ import torch
4
+ import soundfile as sf
5
+ from xcodec2.modeling_xcodec2 import XCodec2Model
6
+ import torchaudio
7
+ import gradio as gr
8
+ import tempfile
9
+
10
+ llasa_3b ='HKUSTAudio/Llasa-8B'
11
+
12
+ tokenizer = AutoTokenizer.from_pretrained(llasa_3b)
13
+
14
+ model = AutoModelForCausalLM.from_pretrained(
15
+ llasa_3b,
16
+ trust_remote_code=True,
17
+ device_map='cuda',
18
+ )
19
+
20
+ model_path = "srinivasbilla/xcodec2"
21
+
22
+ Codec_model = XCodec2Model.from_pretrained(model_path)
23
+ Codec_model.eval().cuda()
24
+
25
+ whisper_turbo_pipe = pipeline(
26
+ "automatic-speech-recognition",
27
+ model="openai/whisper-large-v3-turbo",
28
+ torch_dtype=torch.float16,
29
+ device='cuda',
30
+ )
31
+
32
+ def ids_to_speech_tokens(speech_ids):
33
+
34
+ speech_tokens_str = []
35
+ for speech_id in speech_ids:
36
+ speech_tokens_str.append(f"<|s_{speech_id}|>")
37
+ return speech_tokens_str
38
+
39
+ def extract_speech_ids(speech_tokens_str):
40
+
41
+ speech_ids = []
42
+ for token_str in speech_tokens_str:
43
+ if token_str.startswith('<|s_') and token_str.endswith('|>'):
44
+ num_str = token_str[4:-2]
45
+
46
+ num = int(num_str)
47
+ speech_ids.append(num)
48
+ else:
49
+ print(f"Unexpected token: {token_str}")
50
+ return speech_ids
51
+
52
+ @spaces.GPU(duration=60)
53
+ def infer(sample_audio_path, target_text, progress=gr.Progress()):
54
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
55
+ progress(0, 'Loading and trimming audio...')
56
+ waveform, sample_rate = torchaudio.load(sample_audio_path)
57
+ if len(waveform[0])/sample_rate > 15:
58
+ gr.Warning("Trimming audio to first 15secs.")
59
+ waveform = waveform[:, :sample_rate*15]
60
+
61
+ # Check if the audio is stereo (i.e., has more than one channel)
62
+ if waveform.size(0) > 1:
63
+ # Convert stereo to mono by averaging the channels
64
+ waveform_mono = torch.mean(waveform, dim=0, keepdim=True)
65
+ else:
66
+ # If already mono, just use the original waveform
67
+ waveform_mono = waveform
68
+
69
+ prompt_wav = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)(waveform_mono)
70
+ prompt_text = whisper_turbo_pipe(prompt_wav[0].numpy())['text'].strip()
71
+ progress(0.5, 'Transcribed! Generating speech...')
72
+
73
+ if len(target_text) == 0:
74
+ return None
75
+ elif len(target_text) > 300:
76
+ gr.Warning("Text is too long. Please keep it under 300 characters.")
77
+ target_text = target_text[:300]
78
+
79
+ input_text = prompt_text + ' ' + target_text
80
+
81
+ #TTS start!
82
+ with torch.no_grad():
83
+ # Encode the prompt wav
84
+ vq_code_prompt = Codec_model.encode_code(input_waveform=prompt_wav)
85
+
86
+ vq_code_prompt = vq_code_prompt[0,0,:]
87
+ # Convert int 12345 to token <|s_12345|>
88
+ speech_ids_prefix = ids_to_speech_tokens(vq_code_prompt)
89
+
90
+ formatted_text = f"<|TEXT_UNDERSTANDING_START|>{input_text}<|TEXT_UNDERSTANDING_END|>"
91
+
92
+ # Tokenize the text and the speech prefix
93
+ chat = [
94
+ {"role": "user", "content": "Convert the text to speech:" + formatted_text},
95
+ {"role": "assistant", "content": "<|SPEECH_GENERATION_START|>" + ''.join(speech_ids_prefix)}
96
+ ]
97
+
98
+ input_ids = tokenizer.apply_chat_template(
99
+ chat,
100
+ tokenize=True,
101
+ return_tensors='pt',
102
+ continue_final_message=True
103
+ )
104
+ input_ids = input_ids.to('cuda')
105
+ speech_end_id = tokenizer.convert_tokens_to_ids('<|SPEECH_GENERATION_END|>')
106
+
107
+ # Generate the speech autoregressively
108
+ outputs = model.generate(
109
+ input_ids,
110
+ max_length=2048, # We trained our model with a max length of 2048
111
+ eos_token_id= speech_end_id ,
112
+ do_sample=True,
113
+ top_p=1,
114
+ temperature=0.8
115
+ )
116
+ # Extract the speech tokens
117
+ generated_ids = outputs[0][input_ids.shape[1]-len(speech_ids_prefix):-1]
118
+
119
+ speech_tokens = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
120
+
121
+ # Convert token <|s_23456|> to int 23456
122
+ speech_tokens = extract_speech_ids(speech_tokens)
123
+
124
+ speech_tokens = torch.tensor(speech_tokens).cuda().unsqueeze(0).unsqueeze(0)
125
+
126
+ # Decode the speech tokens to speech waveform
127
+ gen_wav = Codec_model.decode_code(speech_tokens)
128
+
129
+ # if only need the generated part
130
+ gen_wav = gen_wav[:,:,prompt_wav.shape[1]:]
131
+
132
+ progress(1, 'Synthesized!')
133
+
134
+ return (16000, gen_wav[0, 0, :].cpu().numpy())
135
+
136
+ with gr.Blocks() as app_tts:
137
+ gr.Markdown("# Zero Shot Voice Clone TTS")
138
+ ref_audio_input = gr.Audio(label="Reference Audio", type="filepath")
139
+ gen_text_input = gr.Textbox(label="Text to Generate", lines=10)
140
+
141
+ generate_btn = gr.Button("Synthesize", variant="primary")
142
+
143
+ audio_output = gr.Audio(label="Synthesized Audio")
144
+
145
+ generate_btn.click(
146
+ infer,
147
+ inputs=[
148
+ ref_audio_input,
149
+ gen_text_input,
150
+ ],
151
+ outputs=[audio_output],
152
+ )
153
+
154
+ with gr.Blocks() as app_credits:
155
+ gr.Markdown("""
156
+ # Credits
157
+ * [zhenye234](https://github.com/zhenye234) for the original [repo](https://github.com/zhenye234/LLaSA_training)
158
+ * [mrfakename](https://huggingface.co/mrfakename) for the [gradio demo code](https://huggingface.co/spaces/mrfakename/E2-F5-TTS)
159
+ """)
160
+
161
+ with gr.Blocks() as app:
162
+ gr.Markdown(
163
+ """
164
+ # llasa 3b TTS
165
+ This is a local web UI for llasa 3b SOTA(imo) Zero Shot Voice Cloning and TTS model.
166
+ The checkpoints support English and Chinese.
167
+ If you're having issues, try converting your reference audio to WAV or MP3, clipping it to 15s, and shortening your prompt.
168
+ """
169
+ )
170
+ gr.TabbedInterface([app_tts], ["TTS"])
171
+
172
+
173
+ app.launch()