feat: add ASR garbled text detection and retry mechanism
- Add is_garbled() function to detect transcription errors: * Repetitive character detection (>40% same char) * Language-script mismatch detection * Compression ratio check for long text - Expand COMMON_LANGUAGES fallback list: ja, en, zh, ko, th, vi, fr, de, es - Add get_vad_settings() to disable VAD for short audio (<15s) - Fix VAD filter causing 0 segments for short clips - Improve language detection retry logic with garbled output check Fixes: ASR producing garbled Sinhala text for Japanese audio
This commit is contained in:
+114
-13
@@ -31,7 +31,7 @@ MODEL_SIZE = "large-v3" # Upgraded from small to large-v3 for better language d
|
||||
DEVICE = "cpu"
|
||||
|
||||
# Common languages to try when auto-detection fails
|
||||
COMMON_LANGUAGES = ["en", "zh", "ja"] # English, Chinese (auto繁简), Japanese
|
||||
COMMON_LANGUAGES = ["ja", "en", "zh", "ko", "th", "vi", "fr", "de", "es"] # English, Chinese (auto繁简), Japanese
|
||||
|
||||
|
||||
def segment_confidence(segment) -> float:
|
||||
@@ -89,6 +89,100 @@ def calculate_transcription_quality(segments, info) -> dict:
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
def is_garbled(text: str, detected_lang: str) -> bool:
|
||||
"""檢測 ASR 輸出是否為亂碼。
|
||||
|
||||
亂碼特徵:
|
||||
1. 重複字元佔比過高(如 වවවවවව...)
|
||||
2. 偵測語言與實際文字的字元範圍不符
|
||||
3. Compression ratio 過高(亂碼熵值高)
|
||||
"""
|
||||
if not text or len(text.strip()) < 3:
|
||||
return True
|
||||
|
||||
# 1. 重複字元檢測:最常見字元佔比 > 40%
|
||||
from collections import Counter
|
||||
most_common_count = Counter(text).most_common(1)[0][1]
|
||||
if most_common_count / len(text) > 0.4:
|
||||
return True
|
||||
|
||||
# 2. 語言-文字不一致檢測
|
||||
lang_script_ranges = {
|
||||
'nn': [(0x0020, 0x024F)],
|
||||
'en': [(0x0020, 0x024F)],
|
||||
'ja': [(0x3040, 0x9FFF), (0x3000, 0x303F)],
|
||||
'zh': [(0x4E00, 0x9FFF), (0x3400, 0x4DBF)],
|
||||
'ko': [(0xAC00, 0xD7AF), (0x1100, 0x11FF)],
|
||||
'th': [(0x0E00, 0x0E7F)],
|
||||
'vi': [(0x0020, 0x024F)],
|
||||
'fr': [(0x0020, 0x024F)],
|
||||
'de': [(0x0020, 0x024F)],
|
||||
'es': [(0x0020, 0x024F)],
|
||||
}
|
||||
|
||||
expected_ranges = lang_script_ranges.get(detected_lang)
|
||||
if expected_ranges:
|
||||
matching_chars = 0
|
||||
for c in text:
|
||||
for start, end in expected_ranges:
|
||||
if start <= ord(c) <= end:
|
||||
matching_chars += 1
|
||||
break
|
||||
if len(text) > 0 and matching_chars / len(text) < 0.3:
|
||||
return True
|
||||
|
||||
# 3. Compression ratio 檢測(僅對長文字)
|
||||
import gzip
|
||||
if len(text) > 100:
|
||||
try:
|
||||
compressed = gzip.compress(text.encode('utf-8'))
|
||||
ratio = len(compressed) / len(text.encode('utf-8'))
|
||||
if ratio > 0.95:
|
||||
return True
|
||||
except:
|
||||
pass
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def get_vad_settings(video_path):
|
||||
"""根據音訊長度決定 VAD 設定。
|
||||
|
||||
短音訊(< 15 秒)停用 VAD,避免過濾掉所有語音。
|
||||
"""
|
||||
import subprocess
|
||||
try:
|
||||
cmd = [
|
||||
"ffprobe", "-v", "error",
|
||||
"-show_entries", "format=duration",
|
||||
"-of", "csv=p=0",
|
||||
video_path
|
||||
]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
||||
duration = float(result.stdout.strip())
|
||||
|
||||
if duration < 15:
|
||||
return {"vad_filter": False}
|
||||
elif duration < 60:
|
||||
return {
|
||||
"vad_filter": True,
|
||||
"vad_parameters": dict(
|
||||
min_speech_duration_ms=200,
|
||||
max_silence_duration_ms=1000,
|
||||
min_silence_duration_ms=300,
|
||||
speech_pad_ms=300
|
||||
)
|
||||
}
|
||||
else:
|
||||
return {
|
||||
"vad_filter": True,
|
||||
"vad_parameters": dict(min_silence_duration_ms=500, speech_pad_ms=200)
|
||||
}
|
||||
except:
|
||||
return {"vad_filter": True, "vad_parameters": dict(min_silence_duration_ms=500, speech_pad_ms=200)}
|
||||
|
||||
def transcribe_with_common_languages(model, video_path, publisher=None):
|
||||
"""Transcribe video using common languages when auto-detection fails.
|
||||
|
||||
@@ -125,8 +219,16 @@ def transcribe_with_common_languages(model, video_path, publisher=None):
|
||||
if publisher:
|
||||
publisher.info("asr", f"Auto-detection: {detected_lang}, quality: {quality['quality_score']:.2f}")
|
||||
|
||||
# Step 2: Check if detected language is in common languages
|
||||
if detected_lang in COMMON_LANGUAGES:
|
||||
# Step 2: Check if auto-detected output is garbled
|
||||
full_text = "".join(seg.text for seg in segments)
|
||||
if is_garbled(full_text, detected_lang):
|
||||
msg = f"[ASR] Auto-detection produced garbled output (lang={detected_lang}), trying common languages..."
|
||||
sys.stderr.write(msg + "\n")
|
||||
sys.stderr.flush()
|
||||
if publisher:
|
||||
publisher.info("asr", f"Auto-detection garbled, trying common languages...")
|
||||
# Step 3: Check if detected language is in common languages AND not garbled
|
||||
elif detected_lang in COMMON_LANGUAGES:
|
||||
# Good detection, return it
|
||||
msg = f"[ASR] Using auto-detected language: {detected_lang}"
|
||||
sys.stderr.write(msg + "\n")
|
||||
@@ -135,8 +237,8 @@ def transcribe_with_common_languages(model, video_path, publisher=None):
|
||||
publisher.info("asr", f"Using auto-detected language: {detected_lang}")
|
||||
return segments, info
|
||||
|
||||
# Step 3: If quality is good enough, accept auto-detection even if not common
|
||||
if quality["quality_score"] > 0.5 and quality["segment_count"] > 10:
|
||||
# Step 4: If quality is good enough AND not garbled, accept auto-detection
|
||||
if not is_garbled(full_text, detected_lang) and quality["quality_score"] > 0.5 and quality["segment_count"] > 10:
|
||||
msg = f"[ASR] Auto-detected {detected_lang} has good quality, using it"
|
||||
sys.stderr.write(msg + "\n")
|
||||
sys.stderr.flush()
|
||||
@@ -144,8 +246,8 @@ def transcribe_with_common_languages(model, video_path, publisher=None):
|
||||
publisher.info("asr", f"Auto-detected {detected_lang} has good quality, using it")
|
||||
return segments, info
|
||||
|
||||
# Step 4: Try common languages
|
||||
msg = "[ASR] Auto-detection poor, trying common languages..."
|
||||
# Step 5: Try common languages
|
||||
msg = "[ASR] Trying common languages..."
|
||||
sys.stderr.write(msg + "\n")
|
||||
sys.stderr.flush()
|
||||
if publisher:
|
||||
@@ -282,11 +384,11 @@ def transcribe_with_fallback(model, video_path, publisher=None, language=None):
|
||||
publisher.info("asr", "Direct transcription attempt...")
|
||||
|
||||
# Build transcription kwargs
|
||||
vad_settings = get_vad_settings(video_path)
|
||||
transcribe_kwargs = {
|
||||
"beam_size": 5,
|
||||
"vad_filter": True,
|
||||
"vad_parameters": dict(min_silence_duration_ms=500, speech_pad_ms=200),
|
||||
}
|
||||
transcribe_kwargs.update(vad_settings)
|
||||
|
||||
# Add language if specified
|
||||
if language:
|
||||
@@ -320,11 +422,11 @@ def transcribe_with_fallback(model, video_path, publisher=None, language=None):
|
||||
publisher.info("asr", "Transcribing extracted WAV audio...")
|
||||
|
||||
# Build transcription kwargs for fallback
|
||||
vad_settings = get_vad_settings(wav_path)
|
||||
fallback_kwargs = {
|
||||
"beam_size": 5,
|
||||
"vad_filter": True,
|
||||
"vad_parameters": dict(min_silence_duration_ms=500, speech_pad_ms=200),
|
||||
}
|
||||
fallback_kwargs.update(vad_settings)
|
||||
|
||||
# Add language if specified
|
||||
if language:
|
||||
@@ -566,8 +668,7 @@ def run_asr(video_path, output_path, uuid: str = "", fps: float = None, language
|
||||
# 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),
|
||||
**get_vad_settings(video_path),
|
||||
}
|
||||
|
||||
# Add language if specified
|
||||
|
||||
Reference in New Issue
Block a user