diff --git a/app.py b/app.py index 6d95cc0..c58d045 100644 --- a/app.py +++ b/app.py @@ -56,6 +56,11 @@ UPLOADS_MAX_GB = int(os.environ.get("UPLOADS_MAX_GB", "15")) # Pre-flight quality gate: warn before processing a YouTube source below this # height (0 disables). Only applies to URLs; uploads are whatever the user gave. QUALITY_GATE_MIN_HEIGHT = int(os.environ.get("QUALITY_GATE_MIN_HEIGHT", "720")) +# Reject sources shorter than this before starting (0 disables). A 24s YouTube +# Short cannot yield 15-60s clips: Gemini returns nothing, the job burns +# managed minutes and dies with "no usable clips" (prod 20-ago: 3 of 5 recent +# failures were exactly this, one user retrying the same 24s video). +MIN_SOURCE_SECONDS = int(os.environ.get("MIN_SOURCE_SECONDS", "45")) QUALITY_PROBE_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quality_probe.py") DISABLE_YOUTUBE_URL = os.environ.get("DISABLE_YOUTUBE_URL", "false").lower() in ("1", "true", "yes") @@ -962,7 +967,10 @@ async def _notify_clip_activity(job_id): # Markers that identify a line as an actual error rather than progress noise. -_ERROR_MARKERS = ("❌", "ERROR:", "Traceback", "FATAL", "Exception", +# "Error:" (capital E) catches raised exception lines — RuntimeError:, +# DownloadError:, GeminiBlockedError: — which "ERROR:" alone missed, leaving +# alerts with a bare "Traceback ... exit code 1" and no cause (prod 20-ago). +_ERROR_MARKERS = ("❌", "ERROR:", "Error:", "Traceback", "FATAL", "Exception", "Process failed with exit code", "No metadata file generated", "Execution error:") @@ -975,7 +983,15 @@ def _job_error_text(logs) -> str: a silent upload got reported as a broken download path, and a Gemini blip as an ffmpeg problem. Pick the error-bearing lines instead, newest last. """ - hits = [ln for ln in logs if any(m in ln for m in _ERROR_MARKERS)] + # Per-attempt download warnings are only noise when a later attempt + # RECOVERED: HD-direct fails on every job (banned server IP) and a static + # proxy takes over, yet its "Video unavailable" made whole alerts read as + # download outages when the job actually died in Gemini. When no attempt + # succeeded, those lines carry the real cause and must stay. + recovered = any("Download succeeded" in ln for ln in logs) + hits = [ln for ln in logs + if any(m in ln for m in _ERROR_MARKERS) + and not (recovered and "Download attempt" in ln)] if not hits: return " ".join(logs[-10:]) # nothing recognisable — fall back to the tail return " ".join(hits[-6:]) @@ -1418,6 +1434,25 @@ async def _probe_youtube_quality(url: str) -> dict: return await loop.run_in_executor(None, _run) +def _media_duration_seconds(path: str) -> float: + """Container duration via ffprobe; 0.0 on any failure (fail-open).""" + try: + proc = subprocess.run( + ["ffprobe", "-v", "error", "-show_entries", "format=duration", + "-of", "csv=p=0", path], + capture_output=True, timeout=30) + return float(proc.stdout.decode().strip() or 0) + except Exception: + return 0.0 + + +def _reject_short_source(duration: float): + raise HTTPException(status_code=400, detail=( + f"This video is only {int(duration)}s long — clip generation needs at " + f"least {MIN_SOURCE_SECONDS}s of material to cut from. It already is " + f"short-form content.")) + + # Layouts the caller can let the renderer choose from, mapped to the env var # each one is gated on. The renderer only ever picks between layouts that are # switched on here. @@ -1555,10 +1590,18 @@ async def process_endpoint( # Pre-flight quality gate: probe the offered resolution BEFORE starting, so # the user can abort (refresh cookies / update yt-dlp) instead of burning # 20 min on a 360p-only source. Fail-open: any probe error starts normally. - if url and not force_low and QUALITY_GATE_MIN_HEIGHT > 0: + # The probe also runs under force_low_quality so the short-source check + # can't be bypassed through the quality-gate confirm. + if url and (QUALITY_GATE_MIN_HEIGHT > 0 or MIN_SOURCE_SECONDS > 0): probe = await _probe_youtube_quality(url) + # Hard reject, no confirm-and-retry: a too-short source fails the same + # way on every retry, so letting the user force it just burns the job. + source_duration = int(probe.get("duration") or 0) + if MIN_SOURCE_SECONDS > 0 and 0 < source_duration < MIN_SOURCE_SECONDS: + _reject_short_source(source_duration) max_height = int(probe.get("max_height") or 0) - if 0 < max_height < QUALITY_GATE_MIN_HEIGHT: + if not force_low and QUALITY_GATE_MIN_HEIGHT > 0 \ + and 0 < max_height < QUALITY_GATE_MIN_HEIGHT: print(f"⚠️ Quality gate: only {max_height}p available for {url} — asking user first.") return JSONResponse({ "needs_confirmation": True, @@ -1656,6 +1699,10 @@ async def process_endpoint( # lookup, the clip editor and the preview treat it exactly like a normal # upload; the transcript rides along so the pipeline skips Whisper. src = thumb_session["video_path"] + src_duration = _media_duration_seconds(src) + if MIN_SOURCE_SECONDS > 0 and 0 < src_duration < MIN_SOURCE_SECONDS: + shutil.rmtree(job_output_dir, ignore_errors=True) + _reject_short_source(src_duration) input_path = os.path.join(UPLOAD_DIR, f"{job_id}_{os.path.basename(src)}") try: os.link(src, input_path) @@ -1689,6 +1736,12 @@ async def process_endpoint( raise HTTPException(status_code=413, detail=f"File too large. Max size {MAX_FILE_SIZE_MB}MB") buffer.write(content) + upload_duration = _media_duration_seconds(input_path) + if MIN_SOURCE_SECONDS > 0 and 0 < upload_duration < MIN_SOURCE_SECONDS: + os.remove(input_path) + shutil.rmtree(job_output_dir, ignore_errors=True) + _reject_short_source(upload_duration) + cmd.extend(["-i", input_path]) cmd.extend(["-o", job_output_dir]) diff --git a/cloud/alerts.py b/cloud/alerts.py index 8b4ffcb..3535f06 100644 --- a/cloud/alerts.py +++ b/cloud/alerts.py @@ -58,6 +58,10 @@ def _classify_failure(err: str) -> str: # not actionable on our side. Named so the alert doesn't read as an outage. if "prohibited_content" in e or "blocked this video" in e or "blocked its answer" in e: return "blocked content (user video)" + # The source held nothing clip-shaped (typically an already-short video) — + # content-shaped like the policy block above, not an outage. + if "did not return usable clips" in e or "clip detection failed" in e: + return "no clips found (user video)" if "gemini" in e or "google.genai" in e: return "gemini" if "ffmpeg" in e or "reframe" in e: diff --git a/quality_probe.py b/quality_probe.py index de3d2d2..8440efb 100644 --- a/quality_probe.py +++ b/quality_probe.py @@ -37,7 +37,7 @@ def main() -> int: parser.add_argument("--url", required=True) args = parser.parse_args() - result = {"max_height": 0, "mode": None, "cookies_invalid": False} + result = {"max_height": 0, "mode": None, "cookies_invalid": False, "duration": 0} try: import yt_dlp @@ -90,6 +90,8 @@ def main() -> int: if max_height > result["max_height"]: result["max_height"] = max_height result["mode"] = mode + if not result["duration"]: + result["duration"] = int(info.get('duration') or 0) if result["max_height"] >= 1080: break except Exception: diff --git a/tests/test_alert_classify.py b/tests/test_alert_classify.py index ed2601b..43472a1 100644 --- a/tests/test_alert_classify.py +++ b/tests/test_alert_classify.py @@ -38,3 +38,43 @@ def test_blocked_content_is_not_reported_as_outage(): assert _classify_failure( "🚫 Gemini blocked this video's content (PROHIBITED_CONTENT)." ) == "blocked content (user video)" + + +def test_no_usable_clips_is_not_reported_as_outage(): + assert _classify_failure( + "RuntimeError: Clip detection failed — Gemini did not return usable clips for this video." + ) == "no clips found (user video)" + + +# --- _job_error_text: which log lines feed the classifier ----------------------- + +def test_recovered_download_attempts_do_not_mask_the_terminal_error(): + """HD-direct fails on every job (banned server IP) and a later attempt + succeeds; that per-attempt noise must not turn a Gemini failure into a + 'youtube download' alert (prod 20-ago).""" + import pytest + app_module = pytest.importorskip("app") + logs = [ + "📥 Download attempt: HD-direct", + "⚠️ Download attempt 'HD-direct' failed: ERROR: [youtube] x: Video unavailable.", + "📥 Download attempt: HD-static1", + "✅ Download succeeded (HD-static1).", + "Traceback (most recent call last):", + "RuntimeError: Clip detection failed — Gemini did not return usable clips for this video.", + ] + err = app_module._job_error_text(logs) + assert "Video unavailable" not in err + assert _classify_failure(err) == "no clips found (user video)" + + +def test_terminal_download_failure_still_classifies_as_download(): + import pytest + app_module = pytest.importorskip("app") + logs = [ + "⚠️ Download attempt 'HD-direct' failed: ERROR: [youtube] x: Video unavailable.", + "❌ FATAL ERROR: YOUTUBE DOWNLOAD FAILED (all strategies)", + "Technical Details: ERROR: [youtube] x: Video unavailable. This content isn't available.", + "Process failed with exit code 1", + ] + err = app_module._job_error_text(logs) + assert _classify_failure(err) == "youtube download" diff --git a/tests/test_short_source_gate.py b/tests/test_short_source_gate.py new file mode 100644 index 0000000..ef0db1d --- /dev/null +++ b/tests/test_short_source_gate.py @@ -0,0 +1,109 @@ +"""HTTP tests for the too-short-source gate on /api/process. + +A 24s YouTube Short cannot yield 15-60s clips: Gemini returns nothing and the +job dies with "no usable clips" after burning managed minutes (prod 20-ago). +The gate rejects such sources at submit, on all three ingest paths, with the +duration probes stubbed at their seams (_probe_youtube_quality for URLs, +_media_duration_seconds for local files). Probe failures (duration 0) fail +open — the job starts normally. +""" + +import asyncio +import os + +import httpx +import pytest + +app_module = pytest.importorskip("app") + + +def _post_process(json_body=None, files=None, data=None): + async def _do(): + transport = httpx.ASGITransport(app=app_module.app) + async with httpx.AsyncClient(transport=transport, + base_url="http://testserver") as client: + return await client.post( + "/api/process", json=json_body, files=files, data=data, + headers={"X-Gemini-Key": "test-key"}, + ) + return asyncio.run(_do()) + + +@pytest.fixture() +def dirs(tmp_path, monkeypatch): + out_root = tmp_path / "output" + up_root = tmp_path / "uploads" + out_root.mkdir() + up_root.mkdir() + monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root)) + monkeypatch.setattr(app_module, "UPLOAD_DIR", str(up_root)) + return out_root, up_root + + +def _stub_probe(monkeypatch, duration, max_height=1080): + async def _probe(url): + return {"max_height": max_height, "duration": duration} + monkeypatch.setattr(app_module, "_probe_youtube_quality", _probe) + + +def test_short_url_source_is_rejected(dirs, monkeypatch): + _stub_probe(monkeypatch, duration=24) + resp = _post_process({"url": "https://www.youtube.com/watch?v=short", "acknowledged": True}) + assert resp.status_code == 400 + assert "24s" in resp.json()["detail"] + + +def test_short_url_rejected_even_with_force_low_quality(dirs, monkeypatch): + """force_low_quality skips the quality confirm, not the short-source gate.""" + _stub_probe(monkeypatch, duration=24, max_height=360) + resp = _post_process({"url": "https://www.youtube.com/watch?v=short", + "acknowledged": True, "force_low_quality": True}) + assert resp.status_code == 400 + + +def test_unknown_duration_fails_open(dirs, monkeypatch): + _stub_probe(monkeypatch, duration=0) + resp = _post_process({"url": "https://www.youtube.com/watch?v=ok", "acknowledged": True}) + assert resp.status_code == 200 + assert "job_id" in resp.json() + + +def test_long_url_source_passes(dirs, monkeypatch): + _stub_probe(monkeypatch, duration=600) + resp = _post_process({"url": "https://www.youtube.com/watch?v=ok", "acknowledged": True}) + assert resp.status_code == 200 + + +def test_gate_disabled_lets_short_sources_through(dirs, monkeypatch): + _stub_probe(monkeypatch, duration=24) + monkeypatch.setattr(app_module, "MIN_SOURCE_SECONDS", 0) + resp = _post_process({"url": "https://www.youtube.com/watch?v=short", "acknowledged": True}) + assert resp.status_code == 200 + + +def test_short_upload_is_rejected_and_cleaned_up(dirs, monkeypatch): + out_root, up_root = dirs + monkeypatch.setattr(app_module, "_media_duration_seconds", lambda path: 24.0) + resp = _post_process(files={"file": ("short.mp4", b"fake-bytes", "video/mp4")}, + data={"acknowledged": "true"}) + assert resp.status_code == 400 + assert "24s" in resp.json()["detail"] + # The rejected upload and its job dir must not linger on disk. + assert os.listdir(up_root) == [] + assert os.listdir(out_root) == [] + + +def test_short_thumbnail_session_is_rejected(dirs, monkeypatch): + out_root, up_root = dirs + video = up_root / "thumb_sess1_source.mp4" + video.write_bytes(b"fake-video-bytes") + monkeypatch.setitem(app_module.thumbnail_sessions, "sess1", { + "user_id": None, "video_path": str(video), + "transcript_ready": False, "transcript": None, + }) + monkeypatch.setattr(app_module, "_media_duration_seconds", lambda path: 24.0) + resp = _post_process({"thumbnail_session_id": "sess1", "acknowledged": True}) + assert resp.status_code == 400 + # The session's own video stays; only the aborted job dir is cleaned. + assert os.path.exists(video) + assert os.listdir(out_root) == []