vbanonyme commited on
Commit
d95ef59
·
verified ·
1 Parent(s): e14f253

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -254
app.py CHANGED
@@ -1,254 +1,171 @@
1
- import csv
2
- import datetime
3
- import os
4
- import re
5
- import time
6
- import uuid
7
- from io import StringIO
8
-
9
- import gradio as gr
10
- import spaces
11
- import torch
12
- import torchaudio
13
- from huggingface_hub import HfApi, hf_hub_download, snapshot_download
14
- from TTS.tts.configs.xtts_config import XttsConfig
15
- from TTS.tts.models.xtts import Xtts
16
- from vinorm import TTSnorm
17
-
18
- # download for mecab
19
- os.system("python -m unidic download")
20
-
21
- HF_TOKEN = os.environ.get("HF_TOKEN")
22
- api = HfApi(token=HF_TOKEN)
23
-
24
- # This will trigger downloading model
25
- print("Downloading if not downloaded viXTTS")
26
- checkpoint_dir = "model/"
27
- repo_id = "capleaf/viXTTS"
28
- use_deepspeed = False
29
-
30
- os.makedirs(checkpoint_dir, exist_ok=True)
31
-
32
- required_files = ["model.pth", "config.json", "vocab.json", "speakers_xtts.pth"]
33
- files_in_dir = os.listdir(checkpoint_dir)
34
- if not all(file in files_in_dir for file in required_files):
35
- snapshot_download(
36
- repo_id=repo_id,
37
- repo_type="model",
38
- local_dir=checkpoint_dir,
39
- )
40
- hf_hub_download(
41
- repo_id="coqui/XTTS-v2",
42
- filename="speakers_xtts.pth",
43
- local_dir=checkpoint_dir,
44
- )
45
-
46
- xtts_config = os.path.join(checkpoint_dir, "config.json")
47
- config = XttsConfig()
48
- config.load_json(xtts_config)
49
- MODEL = Xtts.init_from_config(config)
50
- MODEL.load_checkpoint(
51
- config, checkpoint_dir=checkpoint_dir, use_deepspeed=use_deepspeed
52
- )
53
- if torch.cuda.is_available():
54
- MODEL.cuda()
55
-
56
- supported_languages = config.languages
57
- if not "vi" in supported_languages:
58
- supported_languages.append("vi")
59
-
60
-
61
- def normalize_vietnamese_text(text):
62
- text = (
63
- TTSnorm(text, unknown=False, lower=False, rule=True)
64
- .replace("..", ".")
65
- .replace("!.", "!")
66
- .replace("?.", "?")
67
- .replace(" .", ".")
68
- .replace(" ,", ",")
69
- .replace('"', "")
70
- .replace("'", "")
71
- .replace("AI", "Ây Ai")
72
- .replace("A.I", "Ây Ai")
73
- )
74
- return text
75
-
76
-
77
- def calculate_keep_len(text, lang):
78
- """Simple hack for short sentences"""
79
- if lang in ["ja", "zh-cn"]:
80
- return -1
81
-
82
- word_count = len(text.split())
83
- num_punct = text.count(".") + text.count("!") + text.count("?") + text.count(",")
84
-
85
- if word_count < 5:
86
- return 15000 * word_count + 2000 * num_punct
87
- elif word_count < 10:
88
- return 13000 * word_count + 2000 * num_punct
89
- return -1
90
-
91
-
92
- @spaces.GPU
93
- def predict(
94
- prompt,
95
- language,
96
- audio_file_pth,
97
- normalize_text=True,
98
- ):
99
- if language not in supported_languages:
100
- metrics_text = gr.Warning(
101
- f"Language you put {language} in is not in our Supported Languages, please choose from dropdown"
102
- )
103
-
104
- return (None, metrics_text)
105
-
106
- speaker_wav = audio_file_pth
107
-
108
- if len(prompt) < 2:
109
- metrics_text = gr.Warning("Please give a longer prompt text")
110
- return (None, metrics_text)
111
-
112
- try:
113
- metrics_text = ""
114
- t_latent = time.time()
115
-
116
- try:
117
- (
118
- gpt_cond_latent,
119
- speaker_embedding,
120
- ) = MODEL.get_conditioning_latents(
121
- audio_path=speaker_wav,
122
- gpt_cond_len=30,
123
- gpt_cond_chunk_len=4,
124
- max_ref_length=60,
125
- )
126
-
127
- except Exception as e:
128
- print("Speaker encoding error", str(e))
129
- metrics_text = gr.Warning(
130
- "It appears something wrong with reference, did you unmute your microphone?"
131
- )
132
- return (None, metrics_text)
133
-
134
- prompt = re.sub("([^\x00-\x7F]|\w)(\.|\。|\?)", r"\1 \2\2", prompt)
135
-
136
- if normalize_text and language == "vi":
137
- prompt = normalize_vietnamese_text(prompt)
138
-
139
- print("I: Generating new audio...")
140
- t0 = time.time()
141
- out = MODEL.inference(
142
- prompt,
143
- language,
144
- gpt_cond_latent,
145
- speaker_embedding,
146
- repetition_penalty=5.0,
147
- temperature=0.75,
148
- enable_text_splitting=True,
149
- )
150
- inference_time = time.time() - t0
151
- print(f"I: Time to generate audio: {round(inference_time*1000)} milliseconds")
152
- metrics_text += (
153
- f"Time to generate audio: {round(inference_time*1000)} milliseconds\n"
154
- )
155
- real_time_factor = (time.time() - t0) / out["wav"].shape[-1] * 24000
156
- print(f"Real-time factor (RTF): {real_time_factor}")
157
- metrics_text += f"Real-time factor (RTF): {real_time_factor:.2f}\n"
158
-
159
- # Temporary hack for short sentences
160
- keep_len = calculate_keep_len(prompt, language)
161
- out["wav"] = out["wav"][:keep_len]
162
-
163
- torchaudio.save("output.wav", torch.tensor(out["wav"]).unsqueeze(0), 24000)
164
-
165
- except RuntimeError as e:
166
- if "device-side assert" in str(e):
167
- # cannot do anything on cuda device side error, need tor estart
168
- print(
169
- f"Exit due to: Unrecoverable exception caused by language:{language} prompt:{prompt}",
170
- flush=True,
171
- )
172
- gr.Warning("Unhandled Exception encounter, please retry in a minute")
173
- print("Cuda device-assert Runtime encountered need restart")
174
-
175
- error_time = datetime.datetime.now().strftime("%d-%m-%Y-%H:%M:%S")
176
- error_data = [
177
- error_time,
178
- prompt,
179
- language,
180
- audio_file_pth,
181
- ]
182
- error_data = [str(e) if type(e) != str else e for e in error_data]
183
- print(error_data)
184
- print(speaker_wav)
185
- write_io = StringIO()
186
- csv.writer(write_io).writerows([error_data])
187
- csv_upload = write_io.getvalue().encode()
188
-
189
- filename = error_time + "_" + str(uuid.uuid4()) + ".csv"
190
- print("Writing error csv")
191
- error_api = HfApi()
192
- error_api.upload_file(
193
- path_or_fileobj=csv_upload,
194
- path_in_repo=filename,
195
- repo_id="coqui/xtts-flagged-dataset",
196
- repo_type="dataset",
197
- )
198
-
199
- # speaker_wav
200
- print("Writing error reference audio")
201
- speaker_filename = error_time + "_reference_" + str(uuid.uuid4()) + ".wav"
202
- error_api = HfApi()
203
- error_api.upload_file(
204
- path_or_fileobj=speaker_wav,
205
- path_in_repo=speaker_filename,
206
- repo_id="coqui/xtts-flagged-dataset",
207
- repo_type="dataset",
208
- )
209
-
210
- # HF Space specific.. This error is unrecoverable need to restart space
211
- space = api.get_space_runtime(repo_id=repo_id)
212
- if space.stage != "BUILDING":
213
- api.restart_space(repo_id=repo_id)
214
- else:
215
- print("TRIED TO RESTART but space is building")
216
-
217
- else:
218
- if "Failed to decode" in str(e):
219
- print("Speaker encoding error", str(e))
220
- metrics_text = gr.Warning(
221
- metrics_text="It appears something wrong with reference, did you unmute your microphone?"
222
- )
223
- else:
224
- print("RuntimeError: non device-side assert error:", str(e))
225
- metrics_text = gr.Warning(
226
- "Something unexpected happened please retry again."
227
- )
228
- return (None, metrics_text)
229
- return ("output.wav", metrics_text)
230
-
231
-
232
- with gr.Blocks(analytics_enabled=False) as demo:
233
- with gr.Row():
234
- with gr.Column():
235
- gr.Markdown(
236
- """
237
- # viXTTS Demo ✨
238
- - Github: https://github.com/thinhlpg/vixtts-demo/
239
- - viVoice: https://github.com/thinhlpg/viVoice
240
- """
241
- )
242
- with gr.Column():
243
- # placeholder to align the image
244
- pass
245
-
246
- with gr.Row():
247
- with gr.Column():
248
- input_text_gr = gr.Textbox(
249
- label="Text Prompt (Văn bản cần đọc)",
250
- info="Mỗi câu nên từ 10 từ trở lên.",
251
- value="Xin chào, tôi là một mô hình chuyển đổi văn bản thành giọng nói tiếng Việt.",
252
- )
253
- language_gr = gr.Dropdown(
254
- labe
 
1
+ import csv
2
+ import datetime
3
+ import os
4
+ import re
5
+ import time
6
+ import uuid
7
+ from io import StringIO
8
+
9
+ import gradio as gr
10
+ import torch
11
+ import torchaudio
12
+ from huggingface_hub import HfApi, hf_hub_download, snapshot_download
13
+ from TTS.tts.configs.xtts_config import XttsConfig
14
+ from TTS.tts.models.xtts import Xtts
15
+ from vinorm import TTSnorm
16
+
17
+ # Download necessary components
18
+ os.system("python -m unidic download")
19
+
20
+ # Hugging Face token and API setup
21
+ HF_TOKEN = os.environ.get("HF_TOKEN")
22
+ api = HfApi(token=HF_TOKEN)
23
+
24
+ # Setup checkpoint directory
25
+ checkpoint_dir = "model/"
26
+ os.makedirs(checkpoint_dir, exist_ok=True)
27
+
28
+ # Required files for the model
29
+ required_files = ["model.pth", "config.json", "vocab.json", "speakers_xtts.pth"]
30
+
31
+ # Download model and configurations if not present
32
+ files_in_dir = os.listdir(checkpoint_dir)
33
+ if not all(file in files_in_dir for file in required_files):
34
+ snapshot_download(
35
+ repo_id="capleaf/viXTTS",
36
+ repo_type="model",
37
+ local_dir=checkpoint_dir,
38
+ )
39
+ hf_hub_download(
40
+ repo_id="coqui/XTTS-v2",
41
+ filename="speakers_xtts.pth",
42
+ local_dir=checkpoint_dir,
43
+ )
44
+
45
+ # Initialize XTTS model from configuration
46
+ xtts_config = os.path.join(checkpoint_dir, "config.json")
47
+ config = XttsConfig()
48
+ config.load_json(xtts_config)
49
+ MODEL = Xtts.init_from_config(config)
50
+ MODEL.load_checkpoint(
51
+ config, checkpoint_dir=checkpoint_dir, use_deepspeed=False
52
+ )
53
+ if torch.cuda.is_available():
54
+ MODEL.cuda()
55
+
56
+ # Supported languages for TTS
57
+ supported_languages = config.languages
58
+ if "vi" not in supported_languages:
59
+ supported_languages.append("vi")
60
+
61
+ # Function to normalize Vietnamese text
62
+ def normalize_vietnamese_text(text):
63
+ text = (
64
+ TTSnorm(text, unknown=False, lower=False, rule=True)
65
+ .replace("..", ".")
66
+ .replace("!.", "!")
67
+ .replace("?.", "?")
68
+ .replace(" .", ".")
69
+ .replace(" ,", ",")
70
+ .replace('"', "")
71
+ .replace("'", "")
72
+ .replace("AI", "Ây Ai")
73
+ .replace("A.I", "Ây Ai")
74
+ )
75
+ return text
76
+
77
+ # Function to calculate length to keep based on text properties
78
+ def calculate_keep_len(text, lang):
79
+ if lang in ["ja", "zh-cn"]:
80
+ return -1
81
+
82
+ word_count = len(text.split())
83
+ num_punct = text.count(".") + text.count("!") + text.count("?") + text.count(",")
84
+
85
+ if word_count < 5:
86
+ return 15000 * word_count + 2000 * num_punct
87
+ elif word_count < 10:
88
+ return 13000 * word_count + 2000 * num_punct
89
+ return -1
90
+
91
+ # Function for TTS prediction
92
+ def predict(prompt, language, audio_file_pth, normalize_text=True):
93
+ if language not in supported_languages:
94
+ return (None, gr.Warning(f"Language '{language}' is not supported."))
95
+
96
+ speaker_wav = audio_file_pth
97
+
98
+ try:
99
+ if len(prompt) < 2:
100
+ return (None, gr.Warning("Please provide a longer prompt text."))
101
+
102
+ # Normalize Vietnamese text if specified
103
+ if normalize_text and language == "vi":
104
+ prompt = normalize_vietnamese_text(prompt)
105
+
106
+ # Get conditioning latents for the model
107
+ gpt_cond_latent, speaker_embedding = MODEL.get_conditioning_latents(
108
+ audio_path=speaker_wav,
109
+ gpt_cond_len=30,
110
+ gpt_cond_chunk_len=4,
111
+ max_ref_length=60,
112
+ )
113
+
114
+ # Perform inference to generate audio
115
+ out = MODEL.inference(
116
+ prompt,
117
+ language,
118
+ gpt_cond_latent,
119
+ speaker_embedding,
120
+ repetition_penalty=5.0,
121
+ temperature=0.75,
122
+ enable_text_splitting=True,
123
+ )
124
+
125
+ # Calculate inference time and real-time factor
126
+ inference_time = time.time() - t0
127
+ real_time_factor = (time.time() - t0) / out["wav"].shape[-1] * 24000
128
+
129
+ # Limit output length based on text properties
130
+ keep_len = calculate_keep_len(prompt, language)
131
+ out["wav"] = out["wav"][:keep_len]
132
+
133
+ # Save generated audio
134
+ torchaudio.save("output.wav", torch.tensor(out["wav"]).unsqueeze(0), 24000)
135
+
136
+ except RuntimeError as e:
137
+ # Handle runtime errors
138
+ error_message = "Unexpected error occurred during inference."
139
+ return (None, gr.Warning(error_message))
140
+
141
+ return ("output.wav", "")
142
+
143
+ # Gradio interface setup
144
+ demo = gr.Interface(
145
+ fn=predict,
146
+ inputs=[
147
+ gr.Textbox(
148
+ label="Text Prompt (Văn bản cần đọc)",
149
+ placeholder="Xin chào, tôi là một mô hình chuyển đổi văn bản thành giọng nói tiếng Việt.",
150
+ ),
151
+ gr.Dropdown(
152
+ label="Language (Ngôn ngữ)",
153
+ choices=[
154
+ "vi", "en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl",
155
+ "cs", "ar", "zh-cn", "ja", "ko", "hu", "hi"
156
+ ],
157
+ default="vi",
158
+ label_size="20px",
159
+ ),
160
+ gr.File(label="Reference Audio (Giọng mẫu)", type="file"),
161
+ gr.Checkbox(label="Normalize Vietnamese text", default=True),
162
+ ],
163
+ outputs=[
164
+ gr.Audio(label="Synthesized Audio"),
165
+ gr.Textbox(label="Metrics"),
166
+ ],
167
+ title="viXTTS Demo ✨",
168
+ description="Generate speech from text input using viXTTS.",
169
+ )
170
+
171
+ demo.launch()