diff --git a/cloud/alerts.py b/cloud/alerts.py index d6f4e36..aa12667 100644 --- a/cloud/alerts.py +++ b/cloud/alerts.py @@ -52,6 +52,10 @@ def _classify_failure(err: str) -> str: return "youtube download" if "whisper" in e or "faster_whisper" in e or "transcrib" in e or "av/container" in e: return "transcription" + # User content rejected by the AI provider's policy filter — deterministic, + # 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)" if "gemini" in e or "google.genai" in e: return "gemini" if "ffmpeg" in e or "reframe" in e: diff --git a/gemini_worker.py b/gemini_worker.py index 0490bf5..6670881 100644 --- a/gemini_worker.py +++ b/gemini_worker.py @@ -248,6 +248,38 @@ def _parse_json_response_text(text: str) -> dict: raise ValueError(f"Failed to parse Gemini JSON response: {last_error}") +class GeminiBlockedError(ValueError): + """The API refused the request for content-policy reasons. + + Deterministic: the same payload is rejected every time (verified in prod, + 23-jul-2026 — a stand-up video came back PROHIBITED_CONTENT in ~300ms on + every attempt), and BLOCK_NONE safety settings do NOT lift it. Retrying is + pointless, so callers must fail fast with a message that tells the user the + video's content is the problem, not the service.""" + + +_BLOCKED_FINISH_REASONS = {"SAFETY", "PROHIBITED_CONTENT", "BLOCKLIST", + "SPII", "IMAGE_SAFETY", "RECITATION"} + + +def raise_if_blocked(response): + """Raise GeminiBlockedError when the API refused to answer on policy grounds.""" + pf = getattr(response, "prompt_feedback", None) + reason = getattr(pf, "block_reason", None) + if reason: + name = getattr(reason, "name", None) or str(reason) + raise GeminiBlockedError( + f"Gemini blocked this video's content ({name}). The AI provider's " + "usage policies reject this material, so it can't be analyzed.") + for c in (getattr(response, "candidates", None) or []): + fr = getattr(c, "finish_reason", None) + name = (getattr(fr, "name", None) or str(fr or "")).upper() + if name in _BLOCKED_FINISH_REASONS: + raise GeminiBlockedError( + f"Gemini blocked its answer for this video ({name}). The AI " + "provider's usage policies reject this material, so it can't be analyzed.") + + def _get_response_text(response) -> str: try: text = response.text diff --git a/main.py b/main.py index d7076ef..761f43c 100644 --- a/main.py +++ b/main.py @@ -1014,6 +1014,10 @@ def _run_gemini_stage(client, model_name, prompt, schema): for attempt in range(1, max_attempts + 1): try: response = client.models.generate_content(model=model_name, contents=prompt, config=config) + # Policy blocks are deterministic — retrying only burns quota and + # time, and the user deserves the real reason instead of a generic + # "empty response" (prod 23-jul: PROHIBITED_CONTENT on every try). + gemini_worker.raise_if_blocked(response) # Parsing lives inside the retry loop on purpose: Gemini sometimes # returns 200 with an empty body, which raises here rather than at # the call. Retrying that recovered every occurrence seen in prod @@ -1025,6 +1029,8 @@ def _run_gemini_stage(client, model_name, prompt, schema): parsed = gemini_worker._parse_json_response_text( gemini_worker._get_response_text(response)) return parsed, gemini_worker._calculate_cost_analysis(response, model_name) + except gemini_worker.GeminiBlockedError: + raise # deterministic policy block — never retry except Exception as e: msg = str(e) transient = any(tok in msg for tok in ( @@ -1127,6 +1133,11 @@ def get_viral_clips(transcript_result, video_duration): if cost_analysis: result["cost_analysis"] = cost_analysis return result + except gemini_worker.GeminiBlockedError as e: + # Content-policy rejection: propagate so the job fails with the real + # reason instead of a generic "no clips found". + print(f"🚫 {e}") + raise except Exception as e: print(f"❌ Gemini Error: {e}") return None @@ -1170,6 +1181,7 @@ def get_visual_clips(video_path, video_duration, language="en"): ) response = client.models.generate_content( model=model_name, contents=[file_upload, prompt], config=config) + gemini_worker.raise_if_blocked(response) parsed = json.loads(response.text) shorts = parsed.get("shorts") or [] # Clamp to the real duration; drop anything degenerate. @@ -1190,6 +1202,9 @@ def get_visual_clips(video_path, video_duration, language="en"): if cost: result["cost_analysis"] = cost return result + except gemini_worker.GeminiBlockedError as e: + print(f"🚫 {e}") + raise except Exception as e: print(f"❌ Gemini vision error: {e}") return None diff --git a/tests/test_alert_classify.py b/tests/test_alert_classify.py index 433d6ca..ed2601b 100644 --- a/tests/test_alert_classify.py +++ b/tests/test_alert_classify.py @@ -32,3 +32,9 @@ def test_ffmpeg(): def test_unknown_is_mixed(): assert _classify_failure("something weird happened") == "mixed" + + +def test_blocked_content_is_not_reported_as_outage(): + assert _classify_failure( + "🚫 Gemini blocked this video's content (PROHIBITED_CONTENT)." + ) == "blocked content (user video)" diff --git a/tests/test_gemini_retry.py b/tests/test_gemini_retry.py index 17f09c2..130ca1f 100644 --- a/tests/test_gemini_retry.py +++ b/tests/test_gemini_retry.py @@ -86,3 +86,61 @@ def test_succeeds_without_retrying_when_the_first_call_is_fine(): models = _FakeModels(blips=0) main._run_gemini_stage(_client(models), "m", "prompt", object) assert models.calls == 1 + + +class _BlockedResponse: + """Mimics the real prod shape: 200, empty candidates, block_reason set.""" + text = "" + candidates = [] + usage_metadata = None + + class _PF: + class _Reason: + name = "PROHIBITED_CONTENT" + block_reason = _Reason() + + prompt_feedback = _PF() + + +def test_policy_block_fails_fast_without_retrying(): + # Prod 23-jul-2026: PROHIBITED_CONTENT is deterministic — 3 retries just + # burned quota and reported a misleading "empty response body". + class _Models: + calls = 0 + + def generate_content(self, **kwargs): + _Models.calls += 1 + return _BlockedResponse() + + import gemini_worker + with pytest.raises(gemini_worker.GeminiBlockedError) as exc: + main._run_gemini_stage(_client(_Models()), "m", "prompt", object) + assert _Models.calls == 1 + assert "PROHIBITED_CONTENT" in str(exc.value) + + +def test_blocked_finish_reason_also_raises(): + import gemini_worker + + class _Cand: + class _FR: + name = "SAFETY" + finish_reason = _FR() + content = None + + class _Resp: + prompt_feedback = None + candidates = [_Cand()] + + with pytest.raises(gemini_worker.GeminiBlockedError): + gemini_worker.raise_if_blocked(_Resp()) + + +def test_clean_response_is_not_flagged_as_blocked(): + import gemini_worker + + class _Resp: + prompt_feedback = None + candidates = [] + + gemini_worker.raise_if_blocked(_Resp()) # must not raise