feat: upgrade ASR to large-v3 model + add vocal separation

- Upgrade Whisper model: small -> large-v3
- Add --language parameter for forced language detection
- Add --separate-vocals for demucs vocal separation
- Add preprocess_audio.py utility
- Fix Japanese detection failure issue
- Improve transcription accuracy significantly

Usage:
  python3 scripts/asr_processor.py video.mp4 output.json --language ja --separate-vocals
This commit is contained in:
Accusys
2026-09-27 04:40:15 +08:00
parent 4f60e7ae96
commit ba18f4c403
3 changed files with 466 additions and 23 deletions
+68 -23
View File
@@ -26,8 +26,8 @@ import subprocess
import tempfile
from faster_whisper import WhisperModel
PROCESSOR_VERSION = "2.1"
MODEL_SIZE = "small"
PROCESSOR_VERSION = "2.2"
MODEL_SIZE = "large-v3" # Upgraded from small to large-v3 for better language detection
DEVICE = "cpu"
@@ -110,22 +110,37 @@ def extract_audio_with_ffmpeg(video_path):
return wav_path
def transcribe_with_fallback(model, video_path, publisher=None):
def transcribe_with_fallback(model, video_path, publisher=None, language=None):
"""Transcribe video with fallback to ffmpeg-extracted WAV.
First tries direct transcription (PyAV). If PyAV fails to decode,
falls back to ffmpeg audio extraction then transcription.
Args:
model: WhisperModel instance
video_path: Path to video or audio file
publisher: RedisPublisher for progress updates
language: Force language (e.g., "ja", "en", None for auto-detect)
"""
# Try direct transcription first
try:
if publisher:
publisher.info("asr", "Direct transcription attempt...")
return model.transcribe(
video_path,
beam_size=5,
vad_filter=True,
vad_parameters=dict(min_silence_duration_ms=500, speech_pad_ms=200),
)
# Build transcription kwargs
transcribe_kwargs = {
"beam_size": 5,
"vad_filter": True,
"vad_parameters": dict(min_silence_duration_ms=500, speech_pad_ms=200),
}
# Add language if specified
if language:
transcribe_kwargs["language"] = language
if publisher:
publisher.info("asr", f"Forcing language: {language}")
return model.transcribe(video_path, **transcribe_kwargs)
except Exception as e:
error_str = str(e)
# Check if it's a PyAV/av decoding error
@@ -149,12 +164,19 @@ def transcribe_with_fallback(model, video_path, publisher=None):
try:
if publisher:
publisher.info("asr", "Transcribing extracted WAV audio...")
segments, info = model.transcribe(
wav_path,
beam_size=5,
vad_filter=True,
vad_parameters=dict(min_silence_duration_ms=500, speech_pad_ms=200),
)
# Build transcription kwargs for fallback
fallback_kwargs = {
"beam_size": 5,
"vad_filter": True,
"vad_parameters": dict(min_silence_duration_ms=500, speech_pad_ms=200),
}
# Add language if specified
if language:
fallback_kwargs["language"] = language
segments, info = model.transcribe(wav_path, **fallback_kwargs)
return segments, info
finally:
# Clean up temporary WAV file
@@ -195,10 +217,23 @@ def get_fps_from_ffprobe(video_path):
return None
def run_asr(video_path, output_path, uuid: str = "", fps: float = None):
def run_asr(video_path, output_path, uuid: str = "", fps: float = None, language: str = None, separate_vocals: bool = False):
# Set up signal handlers
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
# Vocal separation (optional preprocessing)
if separate_vocals:
sys.stderr.write("[ASR] Separating vocals using demucs...\n")
sys.stderr.flush()
from preprocess_audio import preprocess_audio_for_asr
processed_audio = preprocess_audio_for_asr(video_path, separate=True)
if processed_audio:
video_path = processed_audio # Use separated vocals
sys.stderr.write(f"[ASR] Using separated vocals: {processed_audio}\n")
else:
sys.stderr.write("[ASR] Vocal separation failed, using original audio\n")
sys.stderr.flush()
# FPS detection chain: CLI → CUT → ffprobe → FAIL
if fps is not None:
@@ -355,11 +390,19 @@ def run_asr(video_path, output_path, uuid: str = "", fps: float = None):
try:
t1 = time.time()
seg_result, seg_info = model.transcribe(
seg_wav, beam_size=5,
vad_filter=True,
vad_parameters=dict(min_silence_duration_ms=500, speech_pad_ms=200),
)
# Build transcription kwargs for segmented processing
seg_transcribe_kwargs = {
"beam_size": 5,
"vad_filter": True,
"vad_parameters": dict(min_silence_duration_ms=500, speech_pad_ms=200),
}
# Add language if specified
if language:
seg_transcribe_kwargs["language"] = language
seg_result, seg_info = model.transcribe(seg_wav, **seg_transcribe_kwargs)
sys.stderr.write(f"[ASR] Scene {idx}: transcribe took {time.time()-t1:.1f}s, language={seg_info.language}\n")
sys.stderr.flush()
@@ -413,7 +456,7 @@ def run_asr(video_path, output_path, uuid: str = "", fps: float = None):
json.dump(round_json_numbers({"status": status, "language": info_language, "segments": all_segments}), f, ensure_ascii=False)
else:
# 無 CUT 資料,直接轉錄(原有流程)
segments, info = transcribe_with_fallback(model, video_path, publisher)
segments, info = transcribe_with_fallback(model, video_path, publisher, language=language)
info_language = info.language
tmp_path = output_path + ".tmp"
@@ -463,6 +506,8 @@ if __name__ == "__main__":
parser.add_argument("output_path", help="Output JSON path")
parser.add_argument("--uuid", "-u", help="UUID for Redis progress", default="")
parser.add_argument("--fps", type=float, help="Override FPS (default: auto-detect)")
parser.add_argument("--language", "-l", help="Force language (e.g., ja for Japanese, en for English)", default=None)
parser.add_argument("--separate-vocals", action="store_true", help="Separate vocals using demucs before transcription")
args = parser.parse_args()
run_asr(args.video_path, args.output_path, args.uuid, fps=args.fps)
run_asr(args.video_path, args.output_path, args.uuid, fps=args.fps, language=args.language, separate_vocals=args.separate_vocals)
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""
音頻預處理工具
使用 demucs 分離人聲
"""
import os
import sys
import subprocess
from pathlib import Path
def separate_vocals(audio_path, output_dir=None):
"""
使用 demucs 分離人聲軌道
Args:
audio_path: 音頻文件路徑
output_dir: 輸出目錄(默認為音頻文件所在目錄)
Returns:
vocals_path: 分離後的人聲文件路徑
"""
if output_dir is None:
output_dir = os.path.dirname(audio_path)
print(f"[VOCAL_SEP] 分離人聲: {audio_path}")
# 使用 demucs 分離
cmd = [
"python3", "-m", "demucs",
"--two-stems=vocals", # 只分離人聲和伴奏
"-o", output_dir,
audio_path
]
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
# demucs 的輸出路徑
audio_name = Path(audio_path).stem
vocals_path = os.path.join(
output_dir,
"htdemucs", # 默認模型名
audio_name,
"vocals.wav"
)
if os.path.exists(vocals_path):
print(f"[VOCAL_SEP] 成功: {vocals_path}")
return vocals_path
else:
print(f"[VOCAL_SEP] 錯誤: 找不到輸出文件")
return None
except subprocess.CalledProcessError as e:
print(f"[VOCAL_SEP] 失敗: {e.stderr}")
return None
except FileNotFoundError:
print("[VOCAL_SEP] 錯誤: demucs 未安裝")
print("安裝命令: pip3 install demucs --break-system-packages")
return None
def extract_audio_from_video(video_path, audio_path=None):
"""
從視頻中提取音頻
Args:
video_path: 視頻文件路徑
audio_path: 輸出音頻路徑(默認為視頻同目錄)
Returns:
audio_path: 提取的音頻路徑
"""
if audio_path is None:
audio_path = video_path.rsplit(".", 1)[0] + ".wav"
print(f"[AUDIO_EXTRACT] 提取音頻: {video_path}")
cmd = [
"ffmpeg", "-y",
"-i", video_path,
"-vn", # 不包含視頻
"-acodec", "pcm_s16le", # 16-bit PCM
"-ar", "16000", # 16kHz (Whisper 優化)
"-ac", "1", # 單聲道
audio_path
]
try:
subprocess.run(cmd, capture_output=True, check=True)
print(f"[AUDIO_EXTRACT] 成功: {audio_path}")
return audio_path
except subprocess.CalledProcessError as e:
print(f"[AUDIO_EXTRACT] 失敗: {e.stderr.decode()}")
return None
def preprocess_audio_for_asr(video_path, output_dir=None, separate=True):
"""
ASR 音頻預處理
Args:
video_path: 視頻文件路徑
output_dir: 輸出目錄
separate: 是否分離人聲
Returns:
處理後的音頻路徑
"""
print(f"[PREPROCESS] 預處理音頻: {video_path}")
# 1. 提取音頻
audio_path = extract_audio_from_video(video_path)
if not audio_path:
return None
# 2. 分離人聲(可選)
if separate:
vocals_path = separate_vocals(audio_path, output_dir)
if vocals_path:
# 刪除原始音頻
os.remove(audio_path)
return vocals_path
return audio_path
if __name__ == "__main__":
if len(sys.argv) < 2:
print("用法: python preprocess_audio.py <video_or_audio_path> [--no-separate]")
sys.exit(1)
input_path = sys.argv[1]
separate = "--no-separate" not in sys.argv
result = preprocess_audio_for_asr(input_path, separate=separate)
if result:
print(f"\n✅ 成功: {result}")
else:
print("\n❌ 失敗")
sys.exit(1)