fix(transcribe): manejar vídeos sin audio + alerta de fallos honesta

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).
This commit is contained in:
juancarlos.cavero 2026-07-21 21:13:59 +02:00
parent 7d6c232165
commit b8159990a9
5 changed files with 106 additions and 6 deletions

View file

@ -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]}",
)

13
main.py
View file

@ -1168,7 +1168,18 @@ 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)

View file

@ -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"

View file

@ -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

View file

@ -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":