积极的屁孩 commited on
Commit
2b30c39
·
1 Parent(s): 70645fe

first commit

Browse files
Files changed (2) hide show
  1. app.py +841 -0
  2. requirements.txt +30 -0
app.py ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import importlib.util
4
+ import site
5
+ import json
6
+ import torch
7
+ import gradio as gr
8
+ import torchaudio
9
+ import numpy as np
10
+ from huggingface_hub import snapshot_download, hf_hub_download
11
+ import subprocess
12
+ import re
13
+
14
+ def install_espeak():
15
+ """检测并安装espeak-ng依赖"""
16
+ try:
17
+ # 检查espeak-ng是否已安装
18
+ result = subprocess.run(["which", "espeak-ng"], capture_output=True, text=True)
19
+ if result.returncode != 0:
20
+ print("检测到系统中未安装espeak-ng,正在尝试安装...")
21
+ # 尝试使用apt-get安装espeak-ng及其数据
22
+ subprocess.run(["apt-get", "update"], check=True)
23
+ # 安装 espeak-ng 和对应的语言数据包
24
+ subprocess.run(["apt-get", "install", "-y", "espeak-ng", "espeak-ng-data"], check=True)
25
+ print("espeak-ng及其数据包安装成功!")
26
+ else:
27
+ print("espeak-ng已安装在系统中。")
28
+ # 即使已安装,也尝试更新数据确保完整性 (可选,但有时有帮助)
29
+ # print("尝试更新 espeak-ng 数据...")
30
+ # subprocess.run(["apt-get", "update"], check=True)
31
+ # subprocess.run(["apt-get", "install", "--only-upgrade", "-y", "espeak-ng-data"], check=True)
32
+
33
+ # 验证中文支持 (可选)
34
+ try:
35
+ voices_result = subprocess.run(["espeak-ng", "--voices=cmn"], capture_output=True, text=True, check=True)
36
+ if "cmn" in voices_result.stdout:
37
+ print("espeak-ng 支持 'cmn' 语言。")
38
+ else:
39
+ print("警告:espeak-ng 安装了,但 'cmn' 语言似乎仍不可用。")
40
+ except Exception as e:
41
+ print(f"验证 espeak-ng 中文支持时出错(可能不影响功能): {e}")
42
+
43
+ except Exception as e:
44
+ print(f"安装espeak-ng时出错: {e}")
45
+ print("请尝试手动运行: apt-get update && apt-get install -y espeak-ng espeak-ng-data")
46
+
47
+ # 在所有其他操作之前安装espeak
48
+ install_espeak()
49
+
50
+ def patch_langsegment_init():
51
+ try:
52
+ # 尝试找到 LangSegment 包的位置
53
+ spec = importlib.util.find_spec("LangSegment")
54
+ if spec is None or spec.origin is None:
55
+ print("无法定位 LangSegment 包。")
56
+ return
57
+
58
+ # 构建 __init__.py 的路径
59
+ init_path = os.path.join(os.path.dirname(spec.origin), '__init__.py')
60
+
61
+ if not os.path.exists(init_path):
62
+ print(f"未找到 LangSegment 的 __init__.py 文件于: {init_path}")
63
+ # 尝试在 site-packages 中查找,适用于某些环境
64
+ for site_pkg_path in site.getsitepackages():
65
+ potential_path = os.path.join(site_pkg_path, 'LangSegment', '__init__.py')
66
+ if os.path.exists(potential_path):
67
+ init_path = potential_path
68
+ print(f"在 site-packages 中找到 __init__.py: {init_path}")
69
+ break
70
+ else: # 如果循环正常结束(没有 break)
71
+ print(f"在 site-packages 中也未找到 __init__.py")
72
+ return
73
+
74
+
75
+ print(f"尝试读取 LangSegment __init__.py: {init_path}")
76
+ with open(init_path, 'r') as f:
77
+ lines = f.readlines()
78
+
79
+ modified = False
80
+ new_lines = []
81
+ target_line_prefix = "from .LangSegment import"
82
+
83
+ for line in lines:
84
+ stripped_line = line.strip()
85
+ if stripped_line.startswith(target_line_prefix):
86
+ if 'setLangfilters' in stripped_line or 'getLangfilters' in stripped_line:
87
+ print(f"发现需要修改的行: {stripped_line}")
88
+ # 移除 setLangfilters 和 getLangfilters
89
+ modified_line = stripped_line.replace(',setLangfilters', '')
90
+ modified_line = modified_line.replace(',getLangfilters', '')
91
+ # 确保逗号处理正确 (例如,如果它们是末尾的项)
92
+ modified_line = modified_line.replace('setLangfilters,', '')
93
+ modified_line = modified_line.replace('getLangfilters,', '')
94
+ # 如果它们是唯一的额外导入,移除可能多余的逗号
95
+ modified_line = modified_line.rstrip(',')
96
+ new_lines.append(modified_line + '\n')
97
+ modified = True
98
+ print(f"修改后的行: {modified_line.strip()}")
99
+ else:
100
+ new_lines.append(line) # 行没问题,保留原样
101
+ else:
102
+ new_lines.append(line) # 非目标行,保留原样
103
+
104
+ if modified:
105
+ print(f"尝试写回已修改的 LangSegment __init__.py 到: {init_path}")
106
+ try:
107
+ with open(init_path, 'w') as f:
108
+ f.writelines(new_lines)
109
+ print("LangSegment __init__.py 修改成功。")
110
+ # 尝试重新加载模块以使更改生效(可能无效,取决于导入链)
111
+ try:
112
+ import LangSegment
113
+ importlib.reload(LangSegment)
114
+ print("LangSegment 模块已尝试重新加载。")
115
+ except Exception as reload_e:
116
+ print(f"重新加载 LangSegment 时出错(可能无影响): {reload_e}")
117
+ except PermissionError:
118
+ print(f"错误:权限不足,无法修改 {init_path}。请考虑修改 requirements.txt。")
119
+ except Exception as write_e:
120
+ print(f"写入 LangSegment __init__.py 时发生其他错误: {write_e}")
121
+ else:
122
+ print("LangSegment __init__.py 无需修改。")
123
+
124
+ except ImportError:
125
+ print("未找到 LangSegment 包,无法进行修复。")
126
+ except Exception as e:
127
+ print(f"修复 LangSegment 包时发生意外错误: {e}")
128
+
129
+ # 在所有其他导入(尤其是可能触发 LangSegment 导入的 Amphion)之前执行修复
130
+ patch_langsegment_init()
131
+
132
+ # 克隆Amphion仓库
133
+ if not os.path.exists("Amphion"):
134
+ subprocess.run(["git", "clone", "https://github.com/open-mmlab/Amphion.git"])
135
+ os.chdir("Amphion")
136
+ else:
137
+ if not os.getcwd().endswith("Amphion"):
138
+ os.chdir("Amphion")
139
+
140
+ # 将Amphion加入到路径中
141
+ if os.path.dirname(os.path.abspath("Amphion")) not in sys.path:
142
+ sys.path.append(os.path.dirname(os.path.abspath("Amphion")))
143
+
144
+ # 确保需要的目录存在
145
+ os.makedirs("wav", exist_ok=True)
146
+ os.makedirs("ckpts/Vevo", exist_ok=True)
147
+
148
+ from models.vc.vevo.vevo_utils import VevoInferencePipeline, save_audio, load_wav
149
+
150
+ # 下载和设置配置文件
151
+ def setup_configs():
152
+ config_path = "models/vc/vevo/config"
153
+ os.makedirs(config_path, exist_ok=True)
154
+
155
+ config_files = [
156
+ "PhoneToVq8192.json",
157
+ "Vocoder.json",
158
+ "Vq32ToVq8192.json",
159
+ "Vq8192ToMels.json",
160
+ "hubert_large_l18_c32.yaml",
161
+ ]
162
+
163
+ for file in config_files:
164
+ file_path = f"{config_path}/{file}"
165
+ if not os.path.exists(file_path):
166
+ try:
167
+ file_data = hf_hub_download(
168
+ repo_id="amphion/Vevo",
169
+ filename=f"config/{file}",
170
+ repo_type="model",
171
+ )
172
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
173
+ # 拷贝文件到目标位置
174
+ subprocess.run(["cp", file_data, file_path])
175
+ except Exception as e:
176
+ print(f"下载配置文件 {file} 时出错: {e}")
177
+
178
+ setup_configs()
179
+
180
+ # 设备配置
181
+ device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
182
+ print(f"使用设备: {device}")
183
+
184
+ # 初始化管道字典
185
+ inference_pipelines = {}
186
+
187
+ def get_pipeline(pipeline_type):
188
+ if pipeline_type in inference_pipelines:
189
+ return inference_pipelines[pipeline_type]
190
+
191
+ # 根据需要的管道类型初始化
192
+ if pipeline_type == "style" or pipeline_type == "voice":
193
+ # 下载Content Tokenizer
194
+ local_dir = snapshot_download(
195
+ repo_id="amphion/Vevo",
196
+ repo_type="model",
197
+ cache_dir="./ckpts/Vevo",
198
+ allow_patterns=["tokenizer/vq32/*"],
199
+ )
200
+ content_tokenizer_ckpt_path = os.path.join(
201
+ local_dir, "tokenizer/vq32/hubert_large_l18_c32.pkl"
202
+ )
203
+
204
+ # 下载Content-Style Tokenizer
205
+ local_dir = snapshot_download(
206
+ repo_id="amphion/Vevo",
207
+ repo_type="model",
208
+ cache_dir="./ckpts/Vevo",
209
+ allow_patterns=["tokenizer/vq8192/*"],
210
+ )
211
+ content_style_tokenizer_ckpt_path = os.path.join(local_dir, "tokenizer/vq8192")
212
+
213
+ # 下载Autoregressive Transformer
214
+ local_dir = snapshot_download(
215
+ repo_id="amphion/Vevo",
216
+ repo_type="model",
217
+ cache_dir="./ckpts/Vevo",
218
+ allow_patterns=["contentstyle_modeling/Vq32ToVq8192/*"],
219
+ )
220
+ ar_cfg_path = "./models/vc/vevo/config/Vq32ToVq8192.json"
221
+ ar_ckpt_path = os.path.join(local_dir, "contentstyle_modeling/Vq32ToVq8192")
222
+
223
+ # 下载Flow Matching Transformer
224
+ local_dir = snapshot_download(
225
+ repo_id="amphion/Vevo",
226
+ repo_type="model",
227
+ cache_dir="./ckpts/Vevo",
228
+ allow_patterns=["acoustic_modeling/Vq8192ToMels/*"],
229
+ )
230
+ fmt_cfg_path = "./models/vc/vevo/config/Vq8192ToMels.json"
231
+ fmt_ckpt_path = os.path.join(local_dir, "acoustic_modeling/Vq8192ToMels")
232
+
233
+ # 下载Vocoder
234
+ local_dir = snapshot_download(
235
+ repo_id="amphion/Vevo",
236
+ repo_type="model",
237
+ cache_dir="./ckpts/Vevo",
238
+ allow_patterns=["acoustic_modeling/Vocoder/*"],
239
+ )
240
+ vocoder_cfg_path = "./models/vc/vevo/config/Vocoder.json"
241
+ vocoder_ckpt_path = os.path.join(local_dir, "acoustic_modeling/Vocoder")
242
+
243
+ # 初始化管道
244
+ inference_pipeline = VevoInferencePipeline(
245
+ content_tokenizer_ckpt_path=content_tokenizer_ckpt_path,
246
+ content_style_tokenizer_ckpt_path=content_style_tokenizer_ckpt_path,
247
+ ar_cfg_path=ar_cfg_path,
248
+ ar_ckpt_path=ar_ckpt_path,
249
+ fmt_cfg_path=fmt_cfg_path,
250
+ fmt_ckpt_path=fmt_ckpt_path,
251
+ vocoder_cfg_path=vocoder_cfg_path,
252
+ vocoder_ckpt_path=vocoder_ckpt_path,
253
+ device=device,
254
+ )
255
+
256
+ elif pipeline_type == "timbre":
257
+ # 下载Content-Style Tokenizer (仅timbre需要)
258
+ local_dir = snapshot_download(
259
+ repo_id="amphion/Vevo",
260
+ repo_type="model",
261
+ cache_dir="./ckpts/Vevo",
262
+ allow_patterns=["tokenizer/vq8192/*"],
263
+ )
264
+ content_style_tokenizer_ckpt_path = os.path.join(local_dir, "tokenizer/vq8192")
265
+
266
+ # 下载Flow Matching Transformer
267
+ local_dir = snapshot_download(
268
+ repo_id="amphion/Vevo",
269
+ repo_type="model",
270
+ cache_dir="./ckpts/Vevo",
271
+ allow_patterns=["acoustic_modeling/Vq8192ToMels/*"],
272
+ )
273
+ fmt_cfg_path = "./models/vc/vevo/config/Vq8192ToMels.json"
274
+ fmt_ckpt_path = os.path.join(local_dir, "acoustic_modeling/Vq8192ToMels")
275
+
276
+ # 下载Vocoder
277
+ local_dir = snapshot_download(
278
+ repo_id="amphion/Vevo",
279
+ repo_type="model",
280
+ cache_dir="./ckpts/Vevo",
281
+ allow_patterns=["acoustic_modeling/Vocoder/*"],
282
+ )
283
+ vocoder_cfg_path = "./models/vc/vevo/config/Vocoder.json"
284
+ vocoder_ckpt_path = os.path.join(local_dir, "acoustic_modeling/Vocoder")
285
+
286
+ # 初始化管道
287
+ inference_pipeline = VevoInferencePipeline(
288
+ content_style_tokenizer_ckpt_path=content_style_tokenizer_ckpt_path,
289
+ fmt_cfg_path=fmt_cfg_path,
290
+ fmt_ckpt_path=fmt_ckpt_path,
291
+ vocoder_cfg_path=vocoder_cfg_path,
292
+ vocoder_ckpt_path=vocoder_ckpt_path,
293
+ device=device,
294
+ )
295
+
296
+ elif pipeline_type == "tts":
297
+ # 下载Content-Style Tokenizer
298
+ local_dir = snapshot_download(
299
+ repo_id="amphion/Vevo",
300
+ repo_type="model",
301
+ cache_dir="./ckpts/Vevo",
302
+ allow_patterns=["tokenizer/vq8192/*"],
303
+ )
304
+ content_style_tokenizer_ckpt_path = os.path.join(local_dir, "tokenizer/vq8192")
305
+
306
+ # 下载Autoregressive Transformer (TTS特有)
307
+ local_dir = snapshot_download(
308
+ repo_id="amphion/Vevo",
309
+ repo_type="model",
310
+ cache_dir="./ckpts/Vevo",
311
+ allow_patterns=["contentstyle_modeling/PhoneToVq8192/*"],
312
+ )
313
+ ar_cfg_path = "./models/vc/vevo/config/PhoneToVq8192.json"
314
+ ar_ckpt_path = os.path.join(local_dir, "contentstyle_modeling/PhoneToVq8192")
315
+
316
+ # 下载Flow Matching Transformer
317
+ local_dir = snapshot_download(
318
+ repo_id="amphion/Vevo",
319
+ repo_type="model",
320
+ cache_dir="./ckpts/Vevo",
321
+ allow_patterns=["acoustic_modeling/Vq8192ToMels/*"],
322
+ )
323
+ fmt_cfg_path = "./models/vc/vevo/config/Vq8192ToMels.json"
324
+ fmt_ckpt_path = os.path.join(local_dir, "acoustic_modeling/Vq8192ToMels")
325
+
326
+ # 下载Vocoder
327
+ local_dir = snapshot_download(
328
+ repo_id="amphion/Vevo",
329
+ repo_type="model",
330
+ cache_dir="./ckpts/Vevo",
331
+ allow_patterns=["acoustic_modeling/Vocoder/*"],
332
+ )
333
+ vocoder_cfg_path = "./models/vc/vevo/config/Vocoder.json"
334
+ vocoder_ckpt_path = os.path.join(local_dir, "acoustic_modeling/Vocoder")
335
+
336
+ # 初始化管道
337
+ inference_pipeline = VevoInferencePipeline(
338
+ content_style_tokenizer_ckpt_path=content_style_tokenizer_ckpt_path,
339
+ ar_cfg_path=ar_cfg_path,
340
+ ar_ckpt_path=ar_ckpt_path,
341
+ fmt_cfg_path=fmt_cfg_path,
342
+ fmt_ckpt_path=fmt_ckpt_path,
343
+ vocoder_cfg_path=vocoder_cfg_path,
344
+ vocoder_ckpt_path=vocoder_ckpt_path,
345
+ device=device,
346
+ )
347
+
348
+ # 缓存管道实例
349
+ inference_pipelines[pipeline_type] = inference_pipeline
350
+ return inference_pipeline
351
+
352
+ # 实现VEVO功能函数
353
+ def vevo_style(content_wav, style_wav):
354
+ temp_content_path = "wav/temp_content.wav"
355
+ temp_style_path = "wav/temp_style.wav"
356
+ output_path = "wav/output_vevostyle.wav"
357
+
358
+ # 检查并处理音频数据
359
+ if content_wav is None or style_wav is None:
360
+ raise ValueError("Please upload audio files")
361
+
362
+ # 处理音频格式
363
+ if isinstance(content_wav, tuple) and len(content_wav) == 2:
364
+ if isinstance(content_wav[0], np.ndarray):
365
+ content_data, content_sr = content_wav
366
+ else:
367
+ content_sr, content_data = content_wav
368
+
369
+ # 确保是单声道
370
+ if len(content_data.shape) > 1 and content_data.shape[1] > 1:
371
+ content_data = np.mean(content_data, axis=1)
372
+
373
+ # 重采样到24kHz
374
+ if content_sr != 24000:
375
+ content_tensor = torch.FloatTensor(content_data).unsqueeze(0)
376
+ content_tensor = torchaudio.functional.resample(content_tensor, content_sr, 24000)
377
+ content_sr = 24000
378
+ else:
379
+ content_tensor = torch.FloatTensor(content_data).unsqueeze(0)
380
+
381
+ # 归一化音量
382
+ content_tensor = content_tensor / (torch.max(torch.abs(content_tensor)) + 1e-6) * 0.95
383
+ else:
384
+ raise ValueError("Invalid content audio format")
385
+
386
+ if isinstance(style_wav, tuple) and len(style_wav) == 2:
387
+ # 确保正确的顺序 (data, sample_rate)
388
+ if isinstance(style_wav[0], np.ndarray):
389
+ style_data, style_sr = style_wav
390
+ else:
391
+ style_sr, style_data = style_wav
392
+ style_tensor = torch.FloatTensor(style_data)
393
+ if style_tensor.ndim == 1:
394
+ style_tensor = style_tensor.unsqueeze(0) # 添加通道维度
395
+ else:
396
+ raise ValueError("Invalid style audio format")
397
+
398
+ # 打印debug信息
399
+ print(f"Content audio shape: {content_tensor.shape}, sample rate: {content_sr}")
400
+ print(f"Style audio shape: {style_tensor.shape}, sample rate: {style_sr}")
401
+
402
+ # 保存音频
403
+ torchaudio.save(temp_content_path, content_tensor, content_sr)
404
+ torchaudio.save(temp_style_path, style_tensor, style_sr)
405
+
406
+ try:
407
+ # 获取管道
408
+ pipeline = get_pipeline("style")
409
+
410
+ # 推理
411
+ gen_audio = pipeline.inference_ar_and_fm(
412
+ src_wav_path=temp_content_path,
413
+ src_text=None,
414
+ style_ref_wav_path=temp_style_path,
415
+ timbre_ref_wav_path=temp_content_path,
416
+ )
417
+
418
+ # 检查生成音频是否为数值异常
419
+ if torch.isnan(gen_audio).any() or torch.isinf(gen_audio).any():
420
+ print("Warning: Generated audio contains NaN or Inf values")
421
+ gen_audio = torch.nan_to_num(gen_audio, nan=0.0, posinf=0.95, neginf=-0.95)
422
+
423
+ print(f"Generated audio shape: {gen_audio.shape}, max: {torch.max(gen_audio)}, min: {torch.min(gen_audio)}")
424
+
425
+ # 保存生成的音频
426
+ save_audio(gen_audio, output_path=output_path)
427
+
428
+ return output_path
429
+ except Exception as e:
430
+ print(f"Error during processing: {e}")
431
+ import traceback
432
+ traceback.print_exc()
433
+ raise e
434
+
435
+ def vevo_timbre(content_wav, reference_wav):
436
+ temp_content_path = "wav/temp_content.wav"
437
+ temp_reference_path = "wav/temp_reference.wav"
438
+ output_path = "wav/output_vevotimbre.wav"
439
+
440
+ # 检查并处理音频数据
441
+ if content_wav is None or reference_wav is None:
442
+ raise ValueError("Please upload audio files")
443
+
444
+ # 处理内容音频格式
445
+ if isinstance(content_wav, tuple) and len(content_wav) == 2:
446
+ if isinstance(content_wav[0], np.ndarray):
447
+ content_data, content_sr = content_wav
448
+ else:
449
+ content_sr, content_data = content_wav
450
+
451
+ # 确保是单声道
452
+ if len(content_data.shape) > 1 and content_data.shape[1] > 1:
453
+ content_data = np.mean(content_data, axis=1)
454
+
455
+ # 重采样到24kHz
456
+ if content_sr != 24000:
457
+ content_tensor = torch.FloatTensor(content_data).unsqueeze(0)
458
+ content_tensor = torchaudio.functional.resample(content_tensor, content_sr, 24000)
459
+ content_sr = 24000
460
+ else:
461
+ content_tensor = torch.FloatTensor(content_data).unsqueeze(0)
462
+
463
+ # 归一化音量
464
+ content_tensor = content_tensor / (torch.max(torch.abs(content_tensor)) + 1e-6) * 0.95
465
+ else:
466
+ raise ValueError("Invalid content audio format")
467
+
468
+ # 处理参考音频格式
469
+ if isinstance(reference_wav, tuple) and len(reference_wav) == 2:
470
+ if isinstance(reference_wav[0], np.ndarray):
471
+ reference_data, reference_sr = reference_wav
472
+ else:
473
+ reference_sr, reference_data = reference_wav
474
+
475
+ # 确保是单声道
476
+ if len(reference_data.shape) > 1 and reference_data.shape[1] > 1:
477
+ reference_data = np.mean(reference_data, axis=1)
478
+
479
+ # 重采样到24kHz
480
+ if reference_sr != 24000:
481
+ reference_tensor = torch.FloatTensor(reference_data).unsqueeze(0)
482
+ reference_tensor = torchaudio.functional.resample(reference_tensor, reference_sr, 24000)
483
+ reference_sr = 24000
484
+ else:
485
+ reference_tensor = torch.FloatTensor(reference_data).unsqueeze(0)
486
+
487
+ # 归一化音量
488
+ reference_tensor = reference_tensor / (torch.max(torch.abs(reference_tensor)) + 1e-6) * 0.95
489
+ else:
490
+ raise ValueError("Invalid reference audio format")
491
+
492
+ # 打印debug信息
493
+ print(f"Content audio shape: {content_tensor.shape}, sample rate: {content_sr}")
494
+ print(f"Reference audio shape: {reference_tensor.shape}, sample rate: {reference_sr}")
495
+
496
+ # 保存上传的音频
497
+ torchaudio.save(temp_content_path, content_tensor, content_sr)
498
+ torchaudio.save(temp_reference_path, reference_tensor, reference_sr)
499
+
500
+ try:
501
+ # 获取管道
502
+ pipeline = get_pipeline("timbre")
503
+
504
+ # 推理
505
+ gen_audio = pipeline.inference_fm(
506
+ src_wav_path=temp_content_path,
507
+ timbre_ref_wav_path=temp_reference_path,
508
+ flow_matching_steps=32,
509
+ )
510
+
511
+ # 检查生成音频是否为数值异常
512
+ if torch.isnan(gen_audio).any() or torch.isinf(gen_audio).any():
513
+ print("Warning: Generated audio contains NaN or Inf values")
514
+ gen_audio = torch.nan_to_num(gen_audio, nan=0.0, posinf=0.95, neginf=-0.95)
515
+
516
+ print(f"Generated audio shape: {gen_audio.shape}, max: {torch.max(gen_audio)}, min: {torch.min(gen_audio)}")
517
+
518
+ # 保存生成的音频
519
+ save_audio(gen_audio, output_path=output_path)
520
+
521
+ return output_path
522
+ except Exception as e:
523
+ print(f"Error during processing: {e}")
524
+ import traceback
525
+ traceback.print_exc()
526
+ raise e
527
+
528
+ def vevo_voice(content_wav, style_reference_wav, timbre_reference_wav):
529
+ temp_content_path = "wav/temp_content.wav"
530
+ temp_style_path = "wav/temp_style.wav"
531
+ temp_timbre_path = "wav/temp_timbre.wav"
532
+ output_path = "wav/output_vevovoice.wav"
533
+
534
+ # 检查并处理音频数据
535
+ if content_wav is None or style_reference_wav is None or timbre_reference_wav is None:
536
+ raise ValueError("Please upload all required audio files")
537
+
538
+ # 处理内容音频格式
539
+ if isinstance(content_wav, tuple) and len(content_wav) == 2:
540
+ if isinstance(content_wav[0], np.ndarray):
541
+ content_data, content_sr = content_wav
542
+ else:
543
+ content_sr, content_data = content_wav
544
+
545
+ # 确保是单声道
546
+ if len(content_data.shape) > 1 and content_data.shape[1] > 1:
547
+ content_data = np.mean(content_data, axis=1)
548
+
549
+ # 重采样到24kHz
550
+ if content_sr != 24000:
551
+ content_tensor = torch.FloatTensor(content_data).unsqueeze(0)
552
+ content_tensor = torchaudio.functional.resample(content_tensor, content_sr, 24000)
553
+ content_sr = 24000
554
+ else:
555
+ content_tensor = torch.FloatTensor(content_data).unsqueeze(0)
556
+
557
+ # 归一化音量
558
+ content_tensor = content_tensor / (torch.max(torch.abs(content_tensor)) + 1e-6) * 0.95
559
+ else:
560
+ raise ValueError("Invalid content audio format")
561
+
562
+ # 处理风格参考音频格式
563
+ if isinstance(style_reference_wav, tuple) and len(style_reference_wav) == 2:
564
+ if isinstance(style_reference_wav[0], np.ndarray):
565
+ style_data, style_sr = style_reference_wav
566
+ else:
567
+ style_sr, style_data = style_reference_wav
568
+
569
+ # 确保是单声道
570
+ if len(style_data.shape) > 1 and style_data.shape[1] > 1:
571
+ style_data = np.mean(style_data, axis=1)
572
+
573
+ # 重采样到24kHz
574
+ if style_sr != 24000:
575
+ style_tensor = torch.FloatTensor(style_data).unsqueeze(0)
576
+ style_tensor = torchaudio.functional.resample(style_tensor, style_sr, 24000)
577
+ style_sr = 24000
578
+ else:
579
+ style_tensor = torch.FloatTensor(style_data).unsqueeze(0)
580
+
581
+ # 归一化音量
582
+ style_tensor = style_tensor / (torch.max(torch.abs(style_tensor)) + 1e-6) * 0.95
583
+ else:
584
+ raise ValueError("Invalid style reference audio format")
585
+
586
+ # 处理音色参考音频格式
587
+ if isinstance(timbre_reference_wav, tuple) and len(timbre_reference_wav) == 2:
588
+ if isinstance(timbre_reference_wav[0], np.ndarray):
589
+ timbre_data, timbre_sr = timbre_reference_wav
590
+ else:
591
+ timbre_sr, timbre_data = timbre_reference_wav
592
+
593
+ # 确保是单声道
594
+ if len(timbre_data.shape) > 1 and timbre_data.shape[1] > 1:
595
+ timbre_data = np.mean(timbre_data, axis=1)
596
+
597
+ # 重采样到24kHz
598
+ if timbre_sr != 24000:
599
+ timbre_tensor = torch.FloatTensor(timbre_data).unsqueeze(0)
600
+ timbre_tensor = torchaudio.functional.resample(timbre_tensor, timbre_sr, 24000)
601
+ timbre_sr = 24000
602
+ else:
603
+ timbre_tensor = torch.FloatTensor(timbre_data).unsqueeze(0)
604
+
605
+ # 归一化音量
606
+ timbre_tensor = timbre_tensor / (torch.max(torch.abs(timbre_tensor)) + 1e-6) * 0.95
607
+ else:
608
+ raise ValueError("Invalid timbre reference audio format")
609
+
610
+ # 打印debug信息
611
+ print(f"Content audio shape: {content_tensor.shape}, sample rate: {content_sr}")
612
+ print(f"Style reference audio shape: {style_tensor.shape}, sample rate: {style_sr}")
613
+ print(f"Timbre reference audio shape: {timbre_tensor.shape}, sample rate: {timbre_sr}")
614
+
615
+ # 保存上传��音频
616
+ torchaudio.save(temp_content_path, content_tensor, content_sr)
617
+ torchaudio.save(temp_style_path, style_tensor, style_sr)
618
+ torchaudio.save(temp_timbre_path, timbre_tensor, timbre_sr)
619
+
620
+ try:
621
+ # 获取管道
622
+ pipeline = get_pipeline("voice")
623
+
624
+ # 推理
625
+ gen_audio = pipeline.inference_ar_and_fm(
626
+ src_wav_path=temp_content_path,
627
+ src_text=None,
628
+ style_ref_wav_path=temp_style_path,
629
+ timbre_ref_wav_path=temp_timbre_path,
630
+ )
631
+
632
+ # 检查生成音频是否为数值异常
633
+ if torch.isnan(gen_audio).any() or torch.isinf(gen_audio).any():
634
+ print("Warning: Generated audio contains NaN or Inf values")
635
+ gen_audio = torch.nan_to_num(gen_audio, nan=0.0, posinf=0.95, neginf=-0.95)
636
+
637
+ print(f"Generated audio shape: {gen_audio.shape}, max: {torch.max(gen_audio)}, min: {torch.min(gen_audio)}")
638
+
639
+ # 保存生成的音频
640
+ save_audio(gen_audio, output_path=output_path)
641
+
642
+ return output_path
643
+ except Exception as e:
644
+ print(f"Error during processing: {e}")
645
+ import traceback
646
+ traceback.print_exc()
647
+ raise e
648
+
649
+ def vevo_tts(text, ref_wav, timbre_ref_wav=None, style_ref_text=None, src_language="en", ref_language="en", style_ref_text_language="en"):
650
+ temp_ref_path = "wav/temp_ref.wav"
651
+ temp_timbre_path = "wav/temp_timbre.wav"
652
+ output_path = "wav/output_vevotts.wav"
653
+
654
+ # 检查并处理音频数据
655
+ if ref_wav is None:
656
+ raise ValueError("Please upload a reference audio file")
657
+
658
+ # 处理参考音频格式
659
+ if isinstance(ref_wav, tuple) and len(ref_wav) == 2:
660
+ if isinstance(ref_wav[0], np.ndarray):
661
+ ref_data, ref_sr = ref_wav
662
+ else:
663
+ ref_sr, ref_data = ref_wav
664
+
665
+ # 确保是单声道
666
+ if len(ref_data.shape) > 1 and ref_data.shape[1] > 1:
667
+ ref_data = np.mean(ref_data, axis=1)
668
+
669
+ # 重采样到24kHz
670
+ if ref_sr != 24000:
671
+ ref_tensor = torch.FloatTensor(ref_data).unsqueeze(0)
672
+ ref_tensor = torchaudio.functional.resample(ref_tensor, ref_sr, 24000)
673
+ ref_sr = 24000
674
+ else:
675
+ ref_tensor = torch.FloatTensor(ref_data).unsqueeze(0)
676
+
677
+ # 归一化音量
678
+ ref_tensor = ref_tensor / (torch.max(torch.abs(ref_tensor)) + 1e-6) * 0.95
679
+ else:
680
+ raise ValueError("Invalid reference audio format")
681
+
682
+ # 打印debug信息
683
+ print(f"Reference audio shape: {ref_tensor.shape}, sample rate: {ref_sr}")
684
+ if style_ref_text:
685
+ print(f"Style reference text: {style_ref_text}, language: {style_ref_text_language}")
686
+
687
+ # 保存上传的音频
688
+ torchaudio.save(temp_ref_path, ref_tensor, ref_sr)
689
+
690
+ if timbre_ref_wav is not None:
691
+ if isinstance(timbre_ref_wav, tuple) and len(timbre_ref_wav) == 2:
692
+ if isinstance(timbre_ref_wav[0], np.ndarray):
693
+ timbre_data, timbre_sr = timbre_ref_wav
694
+ else:
695
+ timbre_sr, timbre_data = timbre_ref_wav
696
+
697
+ # 确保是单声道
698
+ if len(timbre_data.shape) > 1 and timbre_data.shape[1] > 1:
699
+ timbre_data = np.mean(timbre_data, axis=1)
700
+
701
+ # 重采样到24kHz
702
+ if timbre_sr != 24000:
703
+ timbre_tensor = torch.FloatTensor(timbre_data).unsqueeze(0)
704
+ timbre_tensor = torchaudio.functional.resample(timbre_tensor, timbre_sr, 24000)
705
+ timbre_sr = 24000
706
+ else:
707
+ timbre_tensor = torch.FloatTensor(timbre_data).unsqueeze(0)
708
+
709
+ # 归一化音量
710
+ timbre_tensor = timbre_tensor / (torch.max(torch.abs(timbre_tensor)) + 1e-6) * 0.95
711
+
712
+ print(f"Timbre reference audio shape: {timbre_tensor.shape}, sample rate: {timbre_sr}")
713
+ torchaudio.save(temp_timbre_path, timbre_tensor, timbre_sr)
714
+ else:
715
+ raise ValueError("Invalid timbre reference audio format")
716
+ else:
717
+ temp_timbre_path = temp_ref_path
718
+
719
+ try:
720
+ # 获取管道
721
+ pipeline = get_pipeline("tts")
722
+
723
+ # 推理
724
+ gen_audio = pipeline.inference_ar_and_fm(
725
+ src_wav_path=None,
726
+ src_text=text,
727
+ style_ref_wav_path=temp_ref_path,
728
+ timbre_ref_wav_path=temp_timbre_path,
729
+ style_ref_wav_text=style_ref_text,
730
+ src_text_language=src_language,
731
+ style_ref_wav_text_language=style_ref_text_language,
732
+ )
733
+
734
+ # 检查生成音频是否为数值异常
735
+ if torch.isnan(gen_audio).any() or torch.isinf(gen_audio).any():
736
+ print("Warning: Generated audio contains NaN or Inf values")
737
+ gen_audio = torch.nan_to_num(gen_audio, nan=0.0, posinf=0.95, neginf=-0.95)
738
+
739
+ print(f"Generated audio shape: {gen_audio.shape}, max: {torch.max(gen_audio)}, min: {torch.min(gen_audio)}")
740
+
741
+ # 保存生成的音频
742
+ save_audio(gen_audio, output_path=output_path)
743
+
744
+ return output_path
745
+ except Exception as e:
746
+ print(f"Error during processing: {e}")
747
+ import traceback
748
+ traceback.print_exc()
749
+ raise e
750
+
751
+ # 创建Gradio界面
752
+ with gr.Blocks(title="Vevo DEMO") as demo:
753
+ gr.Markdown("# Vevo DEMO")
754
+ # 添加链接标签行
755
+ with gr.Row(elem_id="links_row"):
756
+ gr.HTML("""
757
+ <div style="display: flex; justify-content: flex-start; gap: 8px; margin: 0 0; padding-left: 0px;">
758
+ <a href="https://arxiv.org/abs/2502.07243" target="_blank" style="text-decoration: none;">
759
+ <img alt="arXiv Paper" src="https://img.shields.io/badge/arXiv-Paper-red">
760
+ </a>
761
+ <a href="https://openreview.net/pdf?id=anQDiQZhDP" target="_blank" style="text-decoration: none;">
762
+ <img alt="ICLR Paper" src="https://img.shields.io/badge/ICLR-Paper-64b63a">
763
+ </a>
764
+ <a href="https://huggingface.co/amphion/Vevo" target="_blank" style="text-decoration: none;">
765
+ <img alt="HuggingFace Model" src="https://img.shields.io/badge/%F0%9F%A4%97%20HuggingFace-Model-yellow">
766
+ </a>
767
+ <a href="https://github.com/open-mmlab/Amphion/tree/main/models/vc/vevo" target="_blank" style="text-decoration: none;">
768
+ <img alt="GitHub Repo" src="https://img.shields.io/badge/GitHub-Repo-blue">
769
+ </a>
770
+ </div>
771
+ """)
772
+
773
+ with gr.Tab("Vevo-Timbre"):
774
+ gr.Markdown("### Vevo-Timbre: Maintain style but transfer timbre")
775
+ with gr.Row():
776
+ with gr.Column():
777
+ timbre_content = gr.Audio(label="Source Audio", type="numpy")
778
+ timbre_reference = gr.Audio(label="Timbre Reference", type="numpy")
779
+ timbre_button = gr.Button("Generate")
780
+ with gr.Column():
781
+ timbre_output = gr.Audio(label="Result")
782
+ timbre_button.click(vevo_timbre, inputs=[timbre_content, timbre_reference], outputs=timbre_output)
783
+
784
+ with gr.Tab("Vevo-Style"):
785
+ gr.Markdown("### Vevo-Style: Maintain timbre but transfer style (accent, emotion, etc.)")
786
+ with gr.Row():
787
+ with gr.Column():
788
+ style_content = gr.Audio(label="Source Audio", type="numpy")
789
+ style_reference = gr.Audio(label="Style Reference", type="numpy")
790
+ style_button = gr.Button("Generate")
791
+ with gr.Column():
792
+ style_output = gr.Audio(label="Result")
793
+ style_button.click(vevo_style, inputs=[style_content, style_reference], outputs=style_output)
794
+
795
+ with gr.Tab("Vevo-Voice"):
796
+ gr.Markdown("### Vevo-Voice: Transfers both style and timbre with separate references")
797
+ with gr.Row():
798
+ with gr.Column():
799
+ voice_content = gr.Audio(label="Source Audio", type="numpy")
800
+ voice_style_reference = gr.Audio(label="Style Reference", type="numpy")
801
+ voice_timbre_reference = gr.Audio(label="Timbre Reference", type="numpy")
802
+ voice_button = gr.Button("Generate")
803
+ with gr.Column():
804
+ voice_output = gr.Audio(label="Result")
805
+ voice_button.click(vevo_voice, inputs=[voice_content, voice_style_reference, voice_timbre_reference], outputs=voice_output)
806
+
807
+
808
+
809
+ with gr.Tab("Vevo-TTS"):
810
+ gr.Markdown("### Vevo-TTS: Text-to-speech with separate style and timbre references")
811
+ with gr.Row():
812
+ with gr.Column():
813
+ tts_text = gr.Textbox(label="Target Text", placeholder="Enter text to synthesize...", lines=3)
814
+ tts_src_language = gr.Dropdown(["en", "zh", "de", "fr", "ja", "ko"], label="Text Language", value="en")
815
+ tts_reference = gr.Audio(label="Style Reference", type="numpy")
816
+ tts_style_ref_text = gr.Textbox(label="Style Reference Text", placeholder="Enter style reference text...", lines=3)
817
+ tts_style_ref_text_language = gr.Dropdown(["en", "zh", "de", "fr", "ja", "ko"], label="Style Reference Text Language", value="en")
818
+ tts_timbre_reference = gr.Audio(label="Timbre Reference", type="numpy")
819
+ tts_button = gr.Button("Generate")
820
+ with gr.Column():
821
+ tts_output = gr.Audio(label="Result")
822
+
823
+ tts_button.click(
824
+ vevo_tts,
825
+ inputs=[tts_text, tts_reference, tts_timbre_reference, tts_style_ref_text, tts_src_language, tts_style_ref_text_language],
826
+ outputs=tts_output
827
+ )
828
+
829
+ gr.Markdown("""
830
+ ## About VEVO
831
+ VEVO is a versatile voice synthesis and conversion model that offers four main functionalities:
832
+ 1. **Vevo-Style**: Maintains timbre but transfers style (accent, emotion, etc.)
833
+ 2. **Vevo-Timbre**: Maintains style but transfers timbre
834
+ 3. **Vevo-Voice**: Transfers both style and timbre with separate references
835
+ 4. **Vevo-TTS**: Text-to-speech with separate style and timbre references
836
+
837
+ For more information, visit the [Amphion project](https://github.com/open-mmlab/Amphion)
838
+ """)
839
+
840
+ # 启动应用
841
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio>=3.50.2
2
+ torch>=2.0.0
3
+ torchaudio>=2.0.0
4
+ numpy>=1.20.0
5
+ huggingface_hub>=0.14.1
6
+ librosa>=0.9.2
7
+ PyYAML>=6.0
8
+ accelerate>=0.20.3
9
+ safetensors>=0.3.1
10
+ phonemizer>=3.2.0
11
+ setuptools
12
+ onnxruntime
13
+ transformers==4.41.2
14
+ unidecode
15
+ scipy>=1.12.0
16
+ encodec
17
+ g2p_en
18
+ jieba
19
+ cn2an
20
+ pypinyin
21
+ langsegment==0.2.0
22
+ pyopenjtalk
23
+ pykakasi
24
+ json5
25
+ black>=24.1.1
26
+ ruamel.yaml
27
+ tqdm
28
+ openai-whisper
29
+ ipython
30
+ pyworld