feat: add common language polling for ASR
Features: - New --try-common-languages flag for smart language detection - Tries en, zh, ja when auto-detection fails or quality is poor - Quality scoring based on avg_logprob, no_speech_prob, segment count - Automatically selects best result from all attempts Quality metrics: - avg_logprob (higher is better) - no_speech_prob (lower is better) - segment count (more is better) Use case: - Fixes garbled output from wrong language detection - Prevents Sinhala character output for Japanese audio - Provides better language detection for common languages
This commit is contained in:
+167
-3
@@ -30,6 +30,9 @@ PROCESSOR_VERSION = "2.2"
|
|||||||
MODEL_SIZE = "large-v3" # Upgraded from small to large-v3 for better language detection
|
MODEL_SIZE = "large-v3" # Upgraded from small to large-v3 for better language detection
|
||||||
DEVICE = "cpu"
|
DEVICE = "cpu"
|
||||||
|
|
||||||
|
# Common languages to try when auto-detection fails
|
||||||
|
COMMON_LANGUAGES = ["en", "zh", "ja"] # English, Chinese (auto繁简), Japanese
|
||||||
|
|
||||||
|
|
||||||
def segment_confidence(segment) -> float:
|
def segment_confidence(segment) -> float:
|
||||||
"""Derive a 0-1 confidence from faster-whisper's avg_logprob.
|
"""Derive a 0-1 confidence from faster-whisper's avg_logprob.
|
||||||
@@ -42,6 +45,157 @@ def segment_confidence(segment) -> float:
|
|||||||
return min(1.0, math.exp(logprob))
|
return min(1.0, math.exp(logprob))
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_transcription_quality(segments, info) -> dict:
|
||||||
|
"""Calculate transcription quality metrics.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict with:
|
||||||
|
- avg_logprob: Average log probability (higher is better)
|
||||||
|
- avg_no_speech_prob: Average no_speech_prob (lower is better)
|
||||||
|
- segment_count: Number of segments
|
||||||
|
- quality_score: Combined quality score (higher is better)
|
||||||
|
"""
|
||||||
|
# Convert generator to list if needed
|
||||||
|
if not isinstance(segments, list):
|
||||||
|
segments = list(segments)
|
||||||
|
|
||||||
|
if not segments:
|
||||||
|
return {
|
||||||
|
"avg_logprob": -1.0,
|
||||||
|
"avg_no_speech_prob": 1.0,
|
||||||
|
"segment_count": 0,
|
||||||
|
"quality_score": 0.0,
|
||||||
|
}
|
||||||
|
|
||||||
|
total_logprob = sum(getattr(s, "avg_logprob", -0.5) for s in segments)
|
||||||
|
total_no_speech = sum(getattr(s, "no_speech_prob", 0.5) for s in segments)
|
||||||
|
|
||||||
|
avg_logprob = total_logprob / len(segments)
|
||||||
|
avg_no_speech_prob = total_no_speech / len(segments)
|
||||||
|
|
||||||
|
# Quality score: combination of metrics
|
||||||
|
# Higher logprob is better, lower no_speech_prob is better
|
||||||
|
quality_score = (
|
||||||
|
(1 + avg_logprob) * # Normalize logprob to positive
|
||||||
|
(1 - avg_no_speech_prob) * # Lower no_speech is better
|
||||||
|
min(len(segments) / 100, 1.0) # Prefer more segments (cap at 100)
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"avg_logprob": avg_logprob,
|
||||||
|
"avg_no_speech_prob": avg_no_speech_prob,
|
||||||
|
"segment_count": len(segments),
|
||||||
|
"quality_score": quality_score,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def transcribe_with_common_languages(model, video_path, publisher=None):
|
||||||
|
"""Transcribe video using common languages when auto-detection fails.
|
||||||
|
|
||||||
|
Strategy:
|
||||||
|
1. Try auto-detection first
|
||||||
|
2. If detected language is in COMMON_LANGUAGES, use it
|
||||||
|
3. If not, or quality is poor, try common languages
|
||||||
|
4. Return the best result
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model: WhisperModel instance
|
||||||
|
video_path: Path to video or audio file
|
||||||
|
publisher: RedisPublisher for progress updates
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (segments_list, info)
|
||||||
|
"""
|
||||||
|
# Step 1: Try auto-detection
|
||||||
|
msg = "[ASR] Trying auto language detection..."
|
||||||
|
sys.stderr.write(msg + "\n")
|
||||||
|
sys.stderr.flush()
|
||||||
|
if publisher:
|
||||||
|
publisher.info("asr", "Trying auto language detection...")
|
||||||
|
|
||||||
|
segments_gen, info = transcribe_with_fallback(model, video_path, publisher, language=None)
|
||||||
|
segments = list(segments_gen) # Convert generator to list
|
||||||
|
|
||||||
|
detected_lang = info.language
|
||||||
|
quality = calculate_transcription_quality(segments, info)
|
||||||
|
|
||||||
|
msg = f"[ASR] Auto-detection: {detected_lang}, quality: {quality['quality_score']:.2f}"
|
||||||
|
sys.stderr.write(msg + "\n")
|
||||||
|
sys.stderr.flush()
|
||||||
|
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:
|
||||||
|
# Good detection, return it
|
||||||
|
msg = f"[ASR] Using auto-detected language: {detected_lang}"
|
||||||
|
sys.stderr.write(msg + "\n")
|
||||||
|
sys.stderr.flush()
|
||||||
|
if publisher:
|
||||||
|
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:
|
||||||
|
msg = f"[ASR] Auto-detected {detected_lang} has good quality, using it"
|
||||||
|
sys.stderr.write(msg + "\n")
|
||||||
|
sys.stderr.flush()
|
||||||
|
if publisher:
|
||||||
|
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..."
|
||||||
|
sys.stderr.write(msg + "\n")
|
||||||
|
sys.stderr.flush()
|
||||||
|
if publisher:
|
||||||
|
publisher.info("asr", "Auto-detection poor, trying common languages...")
|
||||||
|
|
||||||
|
best_result = (segments, info)
|
||||||
|
best_quality = quality
|
||||||
|
|
||||||
|
for lang in COMMON_LANGUAGES:
|
||||||
|
if lang == detected_lang:
|
||||||
|
continue # Already tried
|
||||||
|
|
||||||
|
msg = f"[ASR] Trying language: {lang}"
|
||||||
|
sys.stderr.write(msg + "\n")
|
||||||
|
sys.stderr.flush()
|
||||||
|
if publisher:
|
||||||
|
publisher.info("asr", f"Trying language: {lang}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
seg_gen, inf = transcribe_with_fallback(model, video_path, publisher, language=lang)
|
||||||
|
seg = list(seg_gen) # Convert generator to list
|
||||||
|
q = calculate_transcription_quality(seg, inf)
|
||||||
|
|
||||||
|
msg = f"[ASR] Language {lang}: quality {q['quality_score']:.2f}"
|
||||||
|
sys.stderr.write(msg + "\n")
|
||||||
|
sys.stderr.flush()
|
||||||
|
if publisher:
|
||||||
|
publisher.info("asr", f"Language {lang}: quality {q['quality_score']:.2f}")
|
||||||
|
|
||||||
|
# Compare quality
|
||||||
|
if q["quality_score"] > best_quality["quality_score"]:
|
||||||
|
best_quality = q
|
||||||
|
best_result = (seg, inf)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
sys.stderr.write(f"ASR: Failed to transcribe with {lang}: {e}\n")
|
||||||
|
sys.stderr.flush()
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Step 5: Return best result
|
||||||
|
final_lang = best_result[1].language
|
||||||
|
msg = f"[ASR] Best language: {final_lang}, quality: {best_quality['quality_score']:.2f}"
|
||||||
|
sys.stderr.write(msg + "\n")
|
||||||
|
sys.stderr.flush()
|
||||||
|
if publisher:
|
||||||
|
publisher.info("asr", f"Best language: {final_lang}, quality: {best_quality['quality_score']:.2f}")
|
||||||
|
|
||||||
|
return best_result
|
||||||
|
|
||||||
|
|
||||||
def round_json_numbers(obj):
|
def round_json_numbers(obj):
|
||||||
"""Recursively round all float values to 2 decimal places (JSON output only)."""
|
"""Recursively round all float values to 2 decimal places (JSON output only)."""
|
||||||
if isinstance(obj, float):
|
if isinstance(obj, float):
|
||||||
@@ -217,7 +371,7 @@ def get_fps_from_ffprobe(video_path):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def run_asr(video_path, output_path, uuid: str = "", fps: float = None, language: str = None, separate_vocals: bool = False):
|
def run_asr(video_path, output_path, uuid: str = "", fps: float = None, language: str = None, separate_vocals: bool = False, try_common_languages: bool = False):
|
||||||
# Set up signal handlers
|
# Set up signal handlers
|
||||||
signal.signal(signal.SIGTERM, signal_handler)
|
signal.signal(signal.SIGTERM, signal_handler)
|
||||||
signal.signal(signal.SIGINT, signal_handler)
|
signal.signal(signal.SIGINT, signal_handler)
|
||||||
@@ -234,6 +388,11 @@ def run_asr(video_path, output_path, uuid: str = "", fps: float = None, language
|
|||||||
else:
|
else:
|
||||||
sys.stderr.write("[ASR] Vocal separation failed, using original audio\n")
|
sys.stderr.write("[ASR] Vocal separation failed, using original audio\n")
|
||||||
sys.stderr.flush()
|
sys.stderr.flush()
|
||||||
|
|
||||||
|
# If try_common_languages is enabled and no language specified, use smart detection
|
||||||
|
if try_common_languages and not language:
|
||||||
|
sys.stderr.write("[ASR] Smart language detection enabled (common languages)\n")
|
||||||
|
sys.stderr.flush()
|
||||||
|
|
||||||
# FPS detection chain: CLI → CUT → ffprobe → FAIL
|
# FPS detection chain: CLI → CUT → ffprobe → FAIL
|
||||||
if fps is not None:
|
if fps is not None:
|
||||||
@@ -456,7 +615,11 @@ def run_asr(video_path, output_path, uuid: str = "", fps: float = None, language
|
|||||||
json.dump(round_json_numbers({"status": status, "language": info_language, "segments": all_segments}), f, ensure_ascii=False)
|
json.dump(round_json_numbers({"status": status, "language": info_language, "segments": all_segments}), f, ensure_ascii=False)
|
||||||
else:
|
else:
|
||||||
# 無 CUT 資料,直接轉錄(原有流程)
|
# 無 CUT 資料,直接轉錄(原有流程)
|
||||||
segments, info = transcribe_with_fallback(model, video_path, publisher, language=language)
|
if try_common_languages and not language:
|
||||||
|
# Use smart language detection
|
||||||
|
segments, info = transcribe_with_common_languages(model, video_path, publisher)
|
||||||
|
else:
|
||||||
|
segments, info = transcribe_with_fallback(model, video_path, publisher, language=language)
|
||||||
info_language = info.language
|
info_language = info.language
|
||||||
|
|
||||||
tmp_path = output_path + ".tmp"
|
tmp_path = output_path + ".tmp"
|
||||||
@@ -508,6 +671,7 @@ if __name__ == "__main__":
|
|||||||
parser.add_argument("--fps", type=float, help="Override FPS (default: auto-detect)")
|
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("--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")
|
parser.add_argument("--separate-vocals", action="store_true", help="Separate vocals using demucs before transcription")
|
||||||
|
parser.add_argument("--try-common-languages", action="store_true", help="Try common languages (en, zh, ja) if auto-detection fails or produces garbled output")
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
run_asr(args.video_path, args.output_path, args.uuid, fps=args.fps, language=args.language, separate_vocals=args.separate_vocals)
|
run_asr(args.video_path, args.output_path, args.uuid, fps=args.fps, language=args.language, separate_vocals=args.separate_vocals, try_common_languages=args.try_common_languages)
|
||||||
|
|||||||
Reference in New Issue
Block a user