vbanonyme commited on
Commit
e14f253
1 Parent(s): aa02f7c

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +254 -0
  2. requirements.txt +15 -0
app.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Preinstall requirements from TTS
2
+ TTS @ git+https://github.com/thinhlpg/TTS.git@ff217b3f27b294de194cc59c5119d1e08b06413c
3
+ typing-extensions>=4.8.0
4
+ cutlet
5
+ mecab-python3==1.0.6
6
+ unidic-lite==1.0.8
7
+ unidic==1.1.0
8
+ langid
9
+ deepspeed
10
+ pydub
11
+ gradio==4.36.1
12
+
13
+ # Vietnamese 101
14
+ vinorm==2.0.7
15
+ underthesea==6.8.0