haoyue518 commited on
Commit
f5d2e4c
·
verified ·
1 Parent(s): 9aed1d6

Upload 3 files

Browse files
Files changed (2) hide show
  1. app.py +116 -121
  2. requirements.txt +1 -2
app.py CHANGED
@@ -5,18 +5,34 @@ import soundfile as sf
5
  import librosa
6
  import torch
7
 
8
- # 加载 Silero VAD 模型(用于检测说话)
9
- try:
10
- from silero_vad import load_silero_vad, get_speech_timestamps
11
- SILERO_AVAILABLE = True
12
- except:
13
- SILERO_AVAILABLE = False
14
- print("⚠️ Silero VAD 不可用,将使用传统算法")
15
-
16
  # 检查 GPU
17
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
18
  SAMPLE_RATE = 44100
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def extract_audio_from_video(video_path, output_path):
21
  """从视频中提取音频"""
22
  try:
@@ -107,6 +123,10 @@ def detect_speech_with_silero(vocals_audio, sr):
107
  返回:speech_mask (1=说话, 0=其他)
108
  """
109
  try:
 
 
 
 
110
  # 重采样到 16kHz(Silero VAD 要求)
111
  if sr != 16000:
112
  vocals_16k = librosa.resample(vocals_audio, orig_sr=sr, target_sr=16000)
@@ -115,31 +135,25 @@ def detect_speech_with_silero(vocals_audio, sr):
115
  vocals_16k = vocals_audio
116
  sr_work = 16000
117
 
118
- # 加载模型
119
- model = load_silero_vad()
120
-
121
  # 转换为 torch tensor
122
- audio_tensor = torch.from_numpy(vocals_16k).float()
123
 
124
- # 获取说话时间戳
125
- speech_timestamps = get_speech_timestamps(
126
- audio_tensor,
127
- model,
128
- threshold=0.5, # 检测阈值
129
- sampling_rate=sr_work,
130
- min_speech_duration_ms=250, # 最短说话时长
131
- min_silence_duration_ms=100, # 最短静音时长
132
- window_size_samples=512,
133
- speech_pad_ms=30
134
- )
135
 
136
- # 创建掩码
137
- speech_mask = np.zeros(len(vocals_16k), dtype=np.float32)
 
 
 
 
 
 
138
 
139
- for ts in speech_timestamps:
140
- start = ts['start']
141
- end = ts['end']
142
- speech_mask[start:end] = 1.0
143
 
144
  # 调整回原始采样率
145
  if sr != sr_work:
@@ -164,50 +178,12 @@ def detect_speech_with_silero(vocals_audio, sr):
164
  print(f"Silero VAD 检测失败: {str(e)}")
165
  import traceback
166
  traceback.print_exc()
167
- # 失败时返回全零
168
  return np.zeros(len(vocals_audio), dtype=np.float32)
169
 
170
 
171
- def detect_singing_hybrid(vocals_audio, sr, mode='strict'):
172
- """
173
- 混合检测策略:
174
- 1. 先用 Silero VAD 检测"说话"
175
- 2. 其余全部归入"唱歌/音乐"
176
-
177
- mode='strict': 严格模式,只有明确的说话才归入对白
178
- mode='balanced': 平衡模式,包含部分 Rap
179
- """
180
- try:
181
- if SILERO_AVAILABLE:
182
- print("🎯 使用 Silero VAD 深度学习模型检测说话...")
183
- speech_mask = detect_speech_with_silero(vocals_audio, sr)
184
- else:
185
- print("⚠️ Silero 不可用,使用传统算法...")
186
- speech_mask = detect_speech_fallback(vocals_audio, sr)
187
-
188
- if mode == 'strict':
189
- # 严格模式:只保留明确的说话
190
- # 缩小说话区域,避免误判
191
- from scipy.ndimage import binary_erosion
192
- kernel_size = int(0.05 * sr) # 50ms
193
- if kernel_size > 1:
194
- speech_mask = binary_erosion(speech_mask, structure=np.ones(kernel_size)).astype(np.float32)
195
-
196
- # 说话 = 1, 唱歌 = 0
197
- # 我们需要返回唱歌掩码,所以要反转
198
- singing_mask = 1 - speech_mask
199
-
200
- return singing_mask
201
-
202
- except Exception as e:
203
- print(f"检测失败: {str(e)}")
204
- return np.ones(len(vocals_audio), dtype=np.float32) # 全部归入唱歌
205
-
206
-
207
  def detect_speech_fallback(vocals_audio, sr):
208
  """传统算法备用方案(当 Silero 不可用时)"""
209
  try:
210
- # 使用能量 + 零交叉率检测说话
211
  hop_length = 512
212
 
213
  # 能量
@@ -234,6 +210,40 @@ def detect_speech_fallback(vocals_audio, sr):
234
  return np.zeros(len(vocals_audio), dtype=np.float32)
235
 
236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  def process_audio_full(audio_file, detection_mode, enable_singing_detection):
238
  """完整的音频分离流程"""
239
  if audio_file is None:
@@ -243,6 +253,17 @@ def process_audio_full(audio_file, detection_mode, enable_singing_detection):
243
 
244
  try:
245
  with tempfile.TemporaryDirectory() as tmpdir:
 
 
 
 
 
 
 
 
 
 
 
246
  # 1. 加载音频
247
  status_messages.append("📂 正在加载文件...")
248
  yield None, None, None, "\n".join(status_messages)
@@ -261,10 +282,6 @@ def process_audio_full(audio_file, detection_mode, enable_singing_detection):
261
 
262
  # 2. Demucs 分离
263
  status_messages.append("🎵 使用 Demucs AI 模型分离人声和伴奏...")
264
- if SILERO_AVAILABLE:
265
- status_messages.append(" ✅ 已启用 Silero VAD 深度学习检测器")
266
- else:
267
- status_messages.append(" ⚠️ 使用传统算法(准确率较低)")
268
  yield None, None, None, "\n".join(status_messages)
269
 
270
  vocals_path, instrumental_path = run_demucs_separation(temp_wav, tmpdir)
@@ -274,10 +291,9 @@ def process_audio_full(audio_file, detection_mode, enable_singing_detection):
274
 
275
  # 3. 说话/唱歌检测
276
  if enable_singing_detection:
277
- status_messages.append("🎤 正在检测说话片段(AI深度学习)...")
278
  yield None, None, None, "\n".join(status_messages)
279
 
280
- # singing_mask: 1=唱歌, 0=说话
281
  singing_mask = detect_singing_hybrid(vocals, sr, mode=detection_mode)
282
  else:
283
  status_messages.append("⚠️ 已关闭智能检测,所有人声归入对白")
@@ -287,7 +303,7 @@ def process_audio_full(audio_file, detection_mode, enable_singing_detection):
287
  status_messages.append("✂️ 正在分离对白和背景音乐...")
288
  yield None, None, None, "\n".join(status_messages)
289
 
290
- dialog_mask = 1 - singing_mask # 说话掩码
291
 
292
  dialog_vocals = vocals * dialog_mask
293
  singing_vocals = vocals * singing_mask
@@ -334,12 +350,10 @@ def process_audio_full(audio_file, detection_mode, enable_singing_detection):
334
  status_messages.append(f" 运行设备: {DEVICE.upper()}")
335
 
336
  if enable_singing_detection:
337
- if SILERO_AVAILABLE:
338
  status_messages.append(f"\n💡 检测算法: Silero VAD 深度学习")
339
- status_messages.append(f" 准确率: 约 85-90%")
340
  else:
341
  status_messages.append(f"\n💡 检测算法: 传统信号处理")
342
- status_messages.append(f" 准确率: 约 70-75%")
343
 
344
  status_messages.append(f"━━━━━━━━━━━━━━━━━━━━")
345
 
@@ -363,17 +377,16 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI音频分离工具") as demo:
363
  gr.Markdown(f"""
364
  # 🎵 AI 音频分离工具 - 深度学习版
365
 
366
- **当前运行设备**: {DEVICE.upper()} {'✅ GPU加速' if DEVICE == 'cuda' else '⚠️ CPU模式'}
367
- **AI检测器**: {'✅ Silero VAD (深度学习)' if SILERO_AVAILABLE else '⚠️ 传统算法'}
368
 
369
- ## 功能说明(新定义)
370
  - **A - 纯对白**: 旁白、解说、对话(不含Rap/口号)
371
  - **B - 背景音乐+人声**: 伴奏 + 唱歌 + Rap + 和声
372
  - **C - 纯伴奏**: 去除所有人声的纯音乐
373
 
374
  💡 **核心技术**:
375
  - Demucs 4.0 深度学习模型(人声/伴奏分离)
376
- - Silero VAD 神经网络(说话检测,准确率 85%+)
377
  """)
378
 
379
  with gr.Row():
@@ -405,7 +418,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI音频分离工具") as demo:
405
  )
406
  gr.Markdown("""
407
  **模式说明**:
408
- - **严格模式**(推荐):只有清晰的说话才归入对白,Rap/口号归入背景音乐
409
  - **平衡模式**:包含部分 Rap 风格的说话
410
 
411
  💡 **大部分场景用严格模式效果最好!**
@@ -437,53 +450,35 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AI音频分离工具") as demo:
437
 
438
  gr.Markdown("""
439
  ---
440
- ## 📌 技术说明
441
-
442
- ### 🎯 为什么改成"纯对白"定义
443
-
444
- 根据实际测试,我们发现:
445
- - **Rap 介于说话和唱歌之间**,传统算法很难区分
446
- - **大部分用户真正需要的是"旁白/解说"**,而不是 Rap
447
- - **唱歌检测的核心难点在于 Rap**(它有节奏但不是旋律)
448
-
449
- 因此新版本:
450
- - ✅ A区域:只保留纯说话(旁白、对话、解说)
451
- - ✅ B区域:包含所有"有节奏感的人声"(唱歌、Rap、和声、口号)
452
- - ✅ C区域:纯音乐(无人声)
453
-
454
- ### 🧠 Silero VAD 深度学习模型
455
 
456
- - **训练数据**: 超过 10000 小时的语音数据
457
- - **准确率**: 说话检测准确率 85-90%
458
- - **优势**: 专门训练识别"自然说话",对 Rap/唱歌免疫
459
- - **开源**: 完全免费,MIT 协议
460
 
461
- ### ⚠️ 仍然存在的局限
 
 
 
462
 
463
- 即使用深度学习,以下场景仍有挑战:
464
- - **说唱风格旁白**(如快速口播广告)
465
- - **唱歌式说话**(如儿童节目主持)
466
- - **多人快速对话 + 背景音乐**
467
 
468
- 这些边缘情况需要**专门训练的分类器**,超出了通用工具的范围。
 
 
469
 
470
- ### 💡 使用建议
471
 
472
- 1. **优先用严格模式**
473
- 2. 如果对白被漏掉太多,试试平衡模式
474
- 3. 如果还不满意,考虑:
475
- - 在专业音频软件中手动编辑
476
- - 使用付费商业软件(如 Adobe Audition)
477
- - 训练专门的分类模型(需要大量数据)
478
 
479
- ### 🔬 技术对比
480
 
481
- | 方法 | 准确率 | 优点 | 缺点 |
482
- |------|--------|------|------|
483
- | 音高检测 | 60-70% | 简单快速 | 误判 Rap |
484
- | 多特征融合 | 70-75% | 准确率提升 | 仍难处理边缘情况 |
485
- | **Silero VAD** | **85-90%** | **专���训练** | **需要网络下载模型** |
486
- | 商业软件 | 95%+ | 接近完美 | 付费、闭源 |
487
  """)
488
 
489
  if __name__ == "__main__":
 
5
  import librosa
6
  import torch
7
 
 
 
 
 
 
 
 
 
8
  # 检查 GPU
9
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
10
  SAMPLE_RATE = 44100
11
 
12
+ # 全局加载 Silero VAD 模型
13
+ SILERO_MODEL = None
14
+
15
+ def load_silero_model():
16
+ """加载 Silero VAD 模型"""
17
+ global SILERO_MODEL
18
+ if SILERO_MODEL is None:
19
+ try:
20
+ print("📥 正在下载 Silero VAD 模型...")
21
+ SILERO_MODEL, utils = torch.hub.load(
22
+ repo_or_dir='snakers4/silero-vad',
23
+ model='silero_vad',
24
+ force_reload=False,
25
+ onnx=False
26
+ )
27
+ SILERO_MODEL = SILERO_MODEL.to(DEVICE)
28
+ print("✅ Silero VAD 模型加载成功")
29
+ return True
30
+ except Exception as e:
31
+ print(f"⚠️ Silero VAD 加载失败: {str(e)}")
32
+ SILERO_MODEL = None
33
+ return False
34
+ return True
35
+
36
  def extract_audio_from_video(video_path, output_path):
37
  """从视频中提取音频"""
38
  try:
 
123
  返回:speech_mask (1=说话, 0=其他)
124
  """
125
  try:
126
+ global SILERO_MODEL
127
+ if SILERO_MODEL is None:
128
+ raise RuntimeError("Silero 模型未加载")
129
+
130
  # 重采样到 16kHz(Silero VAD 要求)
131
  if sr != 16000:
132
  vocals_16k = librosa.resample(vocals_audio, orig_sr=sr, target_sr=16000)
 
135
  vocals_16k = vocals_audio
136
  sr_work = 16000
137
 
 
 
 
138
  # 转换为 torch tensor
139
+ audio_tensor = torch.from_numpy(vocals_16k).float().to(DEVICE)
140
 
141
+ # 使用 Silero VAD 检测
142
+ window_size_samples = 512
143
+ speech_probs = []
 
 
 
 
 
 
 
 
144
 
145
+ for i in range(0, len(audio_tensor), window_size_samples):
146
+ chunk = audio_tensor[i:i+window_size_samples]
147
+ if len(chunk) < window_size_samples:
148
+ chunk = torch.nn.functional.pad(chunk, (0, window_size_samples - len(chunk)))
149
+
150
+ with torch.no_grad():
151
+ speech_prob = SILERO_MODEL(chunk.unsqueeze(0), sr_work).item()
152
+ speech_probs.append(speech_prob)
153
 
154
+ # 创建掩码
155
+ speech_mask = np.repeat(speech_probs, window_size_samples)[:len(vocals_16k)]
156
+ speech_mask = (speech_mask > 0.5).astype(np.float32)
 
157
 
158
  # 调整回原始采样率
159
  if sr != sr_work:
 
178
  print(f"Silero VAD 检测失败: {str(e)}")
179
  import traceback
180
  traceback.print_exc()
 
181
  return np.zeros(len(vocals_audio), dtype=np.float32)
182
 
183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  def detect_speech_fallback(vocals_audio, sr):
185
  """传统算法备用方案(当 Silero 不可用时)"""
186
  try:
 
187
  hop_length = 512
188
 
189
  # 能量
 
210
  return np.zeros(len(vocals_audio), dtype=np.float32)
211
 
212
 
213
+ def detect_singing_hybrid(vocals_audio, sr, mode='strict'):
214
+ """
215
+ 混合检测策略:
216
+ 1. 先用 Silero VAD 检测"说话"
217
+ 2. 其余全部归入"唱歌/音乐"
218
+ """
219
+ try:
220
+ global SILERO_MODEL
221
+
222
+ if SILERO_MODEL is not None:
223
+ print("🎯 使用 Silero VAD 深度学习模型检测说话...")
224
+ speech_mask = detect_speech_with_silero(vocals_audio, sr)
225
+ else:
226
+ print("⚠️ Silero 不可用,使用传统算法...")
227
+ speech_mask = detect_speech_fallback(vocals_audio, sr)
228
+
229
+ if mode == 'strict':
230
+ # 严格模式:只保留明确的说话
231
+ from scipy.ndimage import binary_erosion
232
+ kernel_size = int(0.05 * sr) # 50ms
233
+ if kernel_size > 1:
234
+ speech_mask = binary_erosion(speech_mask, structure=np.ones(kernel_size)).astype(np.float32)
235
+
236
+ # 说话 = 1, 唱歌 = 0
237
+ # 返回唱歌掩码
238
+ singing_mask = 1 - speech_mask
239
+
240
+ return singing_mask
241
+
242
+ except Exception as e:
243
+ print(f"检测失败: {str(e)}")
244
+ return np.ones(len(vocals_audio), dtype=np.float32)
245
+
246
+
247
  def process_audio_full(audio_file, detection_mode, enable_singing_detection):
248
  """完整的音频分离流程"""
249
  if audio_file is None:
 
253
 
254
  try:
255
  with tempfile.TemporaryDirectory() as tmpdir:
256
+ # 0. 加载 Silero 模型(如果需要)
257
+ if enable_singing_detection:
258
+ status_messages.append("🔧 正在初始化 AI 检测器...")
259
+ yield None, None, None, "\n".join(status_messages)
260
+ silero_loaded = load_silero_model()
261
+ if silero_loaded:
262
+ status_messages.append(" ✅ Silero VAD 深度学习模型已就绪")
263
+ else:
264
+ status_messages.append(" ⚠️ Silero 加载失败,将使用传统算法")
265
+ yield None, None, None, "\n".join(status_messages)
266
+
267
  # 1. 加载音频
268
  status_messages.append("📂 正在加载文件...")
269
  yield None, None, None, "\n".join(status_messages)
 
282
 
283
  # 2. Demucs 分离
284
  status_messages.append("🎵 使用 Demucs AI 模型分离人声和伴奏...")
 
 
 
 
285
  yield None, None, None, "\n".join(status_messages)
286
 
287
  vocals_path, instrumental_path = run_demucs_separation(temp_wav, tmpdir)
 
291
 
292
  # 3. 说话/唱歌检测
293
  if enable_singing_detection:
294
+ status_messages.append("🎤 正在检测说话片段...")
295
  yield None, None, None, "\n".join(status_messages)
296
 
 
297
  singing_mask = detect_singing_hybrid(vocals, sr, mode=detection_mode)
298
  else:
299
  status_messages.append("⚠️ 已关闭智能检测,所有人声归入对白")
 
303
  status_messages.append("✂️ 正在分离对白和背景音乐...")
304
  yield None, None, None, "\n".join(status_messages)
305
 
306
+ dialog_mask = 1 - singing_mask
307
 
308
  dialog_vocals = vocals * dialog_mask
309
  singing_vocals = vocals * singing_mask
 
350
  status_messages.append(f" 运行设备: {DEVICE.upper()}")
351
 
352
  if enable_singing_detection:
353
+ if SILERO_MODEL is not None:
354
  status_messages.append(f"\n💡 检测算法: Silero VAD 深度学习")
 
355
  else:
356
  status_messages.append(f"\n💡 检测算法: 传统信号处理")
 
357
 
358
  status_messages.append(f"━━━━━━━━━━━━━━━━━━━━")
359
 
 
377
  gr.Markdown(f"""
378
  # 🎵 AI 音频分离工具 - 深度学习版
379
 
380
+ **当前运行设备**: {DEVICE.upper()} {'✅ GPU加速' if DEVICE == 'cuda' else '⚠️ CPU模式'}
 
381
 
382
+ ## 功能说明
383
  - **A - 纯对白**: 旁白、解说、对话(不含Rap/口号)
384
  - **B - 背景音乐+人声**: 伴奏 + 唱歌 + Rap + 和声
385
  - **C - 纯伴奏**: 去除所有人声的纯音乐
386
 
387
  💡 **核心技术**:
388
  - Demucs 4.0 深度学习模型(人声/伴奏分离)
389
+ - Silero VAD 神经网络(说话检测)
390
  """)
391
 
392
  with gr.Row():
 
418
  )
419
  gr.Markdown("""
420
  **模式说明**:
421
+ - **严格模式**(推荐):只有清晰的说话才归入对白
422
  - **平衡模式**:包含部分 Rap 风格的说话
423
 
424
  💡 **大部分场景用严格模式效果最好!**
 
450
 
451
  gr.Markdown("""
452
  ---
453
+ ## 📌 使用说明
 
 
 
 
 
 
 
 
 
 
 
 
 
 
454
 
455
+ ### 🎯 新版本改进
 
 
 
456
 
457
+ 1. **使用 Silero VAD 深度学习模型**
458
+ - 自动从 torch.hub 下载(约10MB)
459
+ - 准确率比传统算法提升 15-20%
460
+ - 专门训练识别"说话"
461
 
462
+ 2. **改变产品定义**
463
+ - A区域:只保留纯说话(旁白、对话)
464
+ - B区域:所有音乐性人声(唱歌、Rap、和声)
465
+ - 逻辑更清晰,用户需求更明确
466
 
467
+ 3. **两种检测模式**
468
+ - 严格模式:优先保证对白纯净度
469
+ - 平衡模式:包含部分快速说话
470
 
471
+ ### ⚠️ 技术限制
472
 
473
+ - **深度学习准确率**: 85-90%(已是免费方案极限)
474
+ - **边缘情况**: 说唱风格旁白、唱歌式说话仍有挑战
475
+ - **完美分离**: 需要付费商业软件或自训练模型
 
 
 
476
 
477
+ ### 💡 效果不满意?
478
 
479
+ 1. 尝试两种模式切换
480
+ 2. 在专业音频软件中手动微调(推荐 Audacity)
481
+ 3. 考虑使用付费商业软件(如 Adobe Audition)
 
 
 
482
  """)
483
 
484
  if __name__ == "__main__":
requirements.txt CHANGED
@@ -5,5 +5,4 @@ torchaudio==2.1.0
5
  librosa==0.10.1
6
  soundfile==0.12.1
7
  numpy==1.24.3
8
- scipy==1.11.4
9
- silero-vad==4.0.0
 
5
  librosa==0.10.1
6
  soundfile==0.12.1
7
  numpy==1.24.3
8
+ scipy==1.11.4