From b8159990a98c3c02527cbe9738ba39c73da5d203 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 21 Jul 2026 21:13:59 +0200 Subject: [PATCH] =?UTF-8?q?fix(transcribe):=20manejar=20v=C3=ADdeos=20sin?= =?UTF-8?q?=20audio=20+=20alerta=20de=20fallos=20honesta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El error del admin ('High download failure rate... rebuild image') era engañoso: el fallo real no era descarga sino transcripción de un vídeo SUBIDO sin pista de audio (un clip generado por IA, Gen-4 de Runway). faster-whisper revienta dentro de libav con 'tuple index out of range' cuando el fichero no tiene audio. - transcribe_media detecta la ausencia de pista de audio (ffprobe) ANTES de transcribir y lanza NoAudioError con mensaje claro; main.py lo convierte en un fallo user-facing ('NO_AUDIO: este vídeo no tiene audio...') en vez de un traceback. Verificado en contenedor con vídeo con/sin audio. - La alerta de tasa de fallos ya no culpa siempre a la descarga: clasifica el último error (proxy / youtube download / no audio / transcription / gemini / ffmpeg) y lo pone en el título. 123 tests (nuevos: vídeo mudo + clasificación de fallos). --- cloud/alerts.py | 28 +++++++++++++++++++++---- main.py | 15 ++++++++++++-- tests/test_alert_classify.py | 34 +++++++++++++++++++++++++++++++ tests/test_transcribe_backends.py | 8 ++++++++ transcribe_backends.py | 27 ++++++++++++++++++++++++ 5 files changed, 106 insertions(+), 6 deletions(-) create mode 100644 tests/test_alert_classify.py diff --git a/cloud/alerts.py b/cloud/alerts.py index e4f81e9..d6f4e36 100644 --- a/cloud/alerts.py +++ b/cloud/alerts.py @@ -40,6 +40,25 @@ def _looks_like_proxy_error(err: str) -> bool: return any(k in e for k in _PROXY_HINTS) +def _classify_failure(err: str) -> str: + """One-word category for the last error, so the alert points the right way.""" + e = (err or "").lower() + if _looks_like_proxy_error(e): + return "proxy" + if "no_audio" in e or "no audio" in e: + return "no audio" + if "sign in to confirm" in e or "not a bot" in e or "http error 403" in e \ + or "http error 429" in e or "video unavailable" in e or "read timed out" in e: + return "youtube download" + if "whisper" in e or "faster_whisper" in e or "transcrib" in e or "av/container" in e: + return "transcription" + if "gemini" in e or "google.genai" in e: + return "gemini" + if "ffmpeg" in e or "reframe" in e: + return "ffmpeg/render" + return "mixed" + + def _cooldown_ok(kind: str) -> bool: now = time.time() if now - _last_alert.get(kind, 0) < _ALERT_COOLDOWN: @@ -103,13 +122,14 @@ async def record_job_outcome(ok: bool, error_text: str = ""): ) return - # 2) High failure rate — the download path may be broken. + # 2) High failure rate — report it honestly and classify the last error + # instead of always blaming the download path (it's often transcription of + # a silent upload, a bad video, etc.). recent = list(_recent) fails = recent.count(False) if len(recent) >= _FAIL_WINDOW_MIN and fails >= _FAIL_THRESHOLD and _cooldown_ok("failrate"): await send_admin_alert( - "⚠️ High download failure rate", - f"{fails} of the last {len(recent)} managed jobs failed. The download " - "path may be broken. Rebuilding the backend image usually pulls a fix.\n\n" + f"⚠️ High job failure rate ({_classify_failure(error_text)})", + f"{fails} of the last {len(recent)} managed jobs failed.\n\n" f"Last error:\n{error_text[:1200]}", ) diff --git a/main.py b/main.py index e08f03d..99317ba 100644 --- a/main.py +++ b/main.py @@ -1168,8 +1168,19 @@ if __name__ == '__main__': render_clip(input_video, output_file, output_format) else: # 3. Transcribe - transcript = transcribe_video(input_video) - + from transcribe_backends import NoAudioError + try: + transcript = transcribe_video(input_video) + except NoAudioError as e: + # Clear, user-facing failure (not a Python traceback) so the UI can + # tell them exactly what's wrong. Prefixed so app.py surfaces it. + import sys + msg = f"❌ NO_AUDIO: {e}" + print(msg, file=sys.stdout) + print(msg, file=sys.stderr) + sys.stdout.flush(); sys.stderr.flush() + raise SystemExit(msg) + # Get duration cap = cv2.VideoCapture(input_video) fps = cap.get(cv2.CAP_PROP_FPS) diff --git a/tests/test_alert_classify.py b/tests/test_alert_classify.py new file mode 100644 index 0000000..433d6ca --- /dev/null +++ b/tests/test_alert_classify.py @@ -0,0 +1,34 @@ +"""Failure classification for the high-failure-rate alert.""" +from cloud.alerts import _classify_failure + + +def test_no_audio(): + assert _classify_failure("❌ NO_AUDIO: This video has no audio track.") == "no audio" + + +def test_youtube_bot_block(): + assert _classify_failure("ERROR: [youtube] x: Sign in to confirm you're not a bot") == "youtube download" + assert _classify_failure("HTTP Error 403: Forbidden") == "youtube download" + assert _classify_failure("HTTP Error 429: Too Many Requests") == "youtube download" + + +def test_proxy(): + assert _classify_failure("cannot connect to proxy") == "proxy" + assert _classify_failure("402 payment required") == "proxy" + + +def test_transcription(): + assert _classify_failure("File faster_whisper/audio.py IndexError") == "transcription" + assert _classify_failure("av/container/streams.py tuple index out of range") == "transcription" + + +def test_gemini(): + assert _classify_failure("google.genai error 500") == "gemini" + + +def test_ffmpeg(): + assert _classify_failure("ffmpeg failed during reframe") == "ffmpeg/render" + + +def test_unknown_is_mixed(): + assert _classify_failure("something weird happened") == "mixed" diff --git a/tests/test_transcribe_backends.py b/tests/test_transcribe_backends.py index 6cd2472..acb87c1 100644 --- a/tests/test_transcribe_backends.py +++ b/tests/test_transcribe_backends.py @@ -141,6 +141,7 @@ def test_transcribe_media_falls_back_on_parakeet_exception(monkeypatch): sentinel = {"text": "ok", "language": "en", "segments": []} monkeypatch.setenv("TRANSCRIBE_BACKEND", "parakeet") + monkeypatch.setattr(tb, "_has_audio_stream", lambda path: True) monkeypatch.setattr(tb, "_transcribe_with_parakeet", boom) monkeypatch.setattr(tb, "_transcribe_with_whisper", lambda path: sentinel) assert tb.transcribe_media("video.mp4") is sentinel @@ -149,6 +150,7 @@ def test_transcribe_media_falls_back_on_parakeet_exception(monkeypatch): def test_transcribe_media_default_is_whisper(monkeypatch): sentinel = {"text": "ok", "language": "en", "segments": []} monkeypatch.delenv("TRANSCRIBE_BACKEND", raising=False) + monkeypatch.setattr(tb, "_has_audio_stream", lambda path: True) monkeypatch.setattr( tb, "_transcribe_with_parakeet", lambda path: (_ for _ in ()).throw(AssertionError("should not run"))) @@ -156,6 +158,12 @@ def test_transcribe_media_default_is_whisper(monkeypatch): assert tb.transcribe_media("video.mp4") is sentinel +def test_transcribe_media_raises_on_silent_video(monkeypatch): + monkeypatch.setattr(tb, "_has_audio_stream", lambda path: False) + with pytest.raises(tb.NoAudioError): + tb.transcribe_media("silent.mp4") + + # --- whisper singleton ------------------------------------------------------ @pytest.fixture diff --git a/transcribe_backends.py b/transcribe_backends.py index 644ffef..405f8e8 100644 --- a/transcribe_backends.py +++ b/transcribe_backends.py @@ -332,8 +332,35 @@ def _parakeet_fallback_reason(transcript, duration_hint=None): # --- public entry point ----------------------------------------------------- +class NoAudioError(Exception): + """The media has no audio track — nothing to transcribe.""" + + +def _has_audio_stream(media_path) -> bool: + """True if the file has at least one audio stream (ffprobe).""" + import subprocess + try: + out = subprocess.run( + ["ffprobe", "-v", "error", "-select_streams", "a", + "-show_entries", "stream=index", "-of", "csv=p=0", media_path], + capture_output=True, text=True, timeout=60, + ) + return bool(out.stdout.strip()) + except Exception: + return True # probe failed — don't block, let the backend try + + def transcribe_media(media_path): """Transcribe with the configured backend, falling back to whisper.""" + # Silent videos (AI-generated clips, muted screen recordings) have no audio + # stream; every ASR backend then crashes deep inside libav with an opaque + # "tuple index out of range". Detect it up front and fail with a clear, + # actionable reason instead. + if not _has_audio_stream(media_path): + raise NoAudioError( + "This video has no audio track. OpenShorts finds viral moments from " + "speech, so it needs a video with audio.") + backend = os.environ.get("TRANSCRIBE_BACKEND", "whisper").strip().lower() if backend == "parakeet":