"""Deterministic title QA and thumbnail roles (PLAN #3 + #4). The validator is pure; the retry is exercised with a scripted fake client, both for the Studio brainstorm path and the free_tools endpoint. """ from types import SimpleNamespace import pytest from PIL import Image from clipwright.api import free_tools as ft from clipwright.media import thumbnail from clipwright.media import title_validation as tv from clipwright.pipeline import profiles @pytest.fixture(scope="module") def cseea(): return profiles.load_profile("cseea") @pytest.fixture(scope="module") def pedro(): return profiles.load_profile("pedro") # --- single-title rules ---------------------------------------------------- def test_good_cseea_title_has_no_violations(cseea): assert tv.validate_title("Why this Alpha world broke", cseea) == [] def test_banned_phrase_and_opener_are_reported(cseea): assert any("banned phrase" in p for p in tv.validate_title( "How to break Alpha in a tutorial", cseea)) assert any("banned opener" in p for p in tv.validate_title( "Exploring Alpha's forgotten mechanic", cseea)) def test_length_limits(cseea): # cseea: max 60, mobile 38. 45 chars is under max but over mobile. over_mobile = "Why this forgotten Alpha mechanic still works" assert 38 < len(over_mobile) <= 60 problems = tv.validate_title(over_mobile, cseea) assert any("mobile limit" in p for p in problems) over_max = "Why " + "x" * 60 assert any("maximum" in p for p in tv.validate_title(over_max, cseea)) def test_number_policy_avoid_and_require(cseea, pedro): assert any("number" in p for p in tv.validate_title( "Why 3 blocks broke the world", cseea)) assert tv.validate_title("Why 3 blocks broke the world", pedro) == [] def test_required_signal_consequence_and_curiosity(cseea, pedro): assert any("curiosity" in p for p in tv.validate_title( "Alpha world seed tour", cseea)) assert any("consequence" in p for p in tv.validate_title( "Alpha channel overview", pedro)) def test_keyword_position_start_rejects_a_filler_opener(cseea): assert any("filler word" in p for p in tv.validate_title( "The Alpha glitch", cseea)) def test_task_descriptive_opener_is_rejected_without_a_profile(): assert any("task-descriptive" in p for p in tv.validate_title( "In this video we break Alpha", None)) assert tv.validate_title("Why this Alpha world broke", None) == [] # --- structural rules across a set ----------------------------------------- def test_more_than_three_same_first_word_is_a_violation(): titles = ["Alpha one", "Alpha two", "Alpha three", "Alpha four"] assert any("same word" in p for p in tv.validate_titles(titles, None)) def test_more_than_two_colons_is_a_violation(): titles = ["A: one", "B: two", "C: three"] assert any("colon" in p for p in tv.validate_titles(titles, None)) def test_no_titles_is_reported(): assert "no titles" in tv.validate_titles([], None) def test_violations_are_prefixed_with_the_title_number(cseea): problems = tv.validate_titles(["Alpha world seed tour", "Why this broke"], cseea) assert any(p.startswith("title 1:") for p in problems) assert not any(p.startswith("title 2:") for p in problems) # --- run_with_validation ---------------------------------------------------- def test_retry_runs_exactly_once_and_keeps_the_better_attempt(): calls = {"retry": 0} def generate(): return ["Alpha channel overview"] def validate(candidate): return [] if candidate == ["Why this broke"] else ["bad"] def retry_once(violations): calls["retry"] += 1 return ["Why this broke"] best = tv.run_with_validation(generate, validate, retry_once) assert best == ["Why this broke"] assert calls["retry"] == 1 def test_no_retry_when_the_first_attempt_is_valid(): calls = {"retry": 0} best = tv.run_with_validation( lambda: ["Why this broke"], lambda c: [], lambda v: calls.__setitem__("retry", calls["retry"] + 1)) assert best == ["Why this broke"] assert calls["retry"] == 0 def test_a_retry_that_does_not_improve_keeps_the_first_attempt(): best = tv.run_with_validation( lambda: ["first"], lambda c: ["still bad"], lambda v: ["second"]) assert best == ["first"] def test_a_retry_that_raises_keeps_the_first_attempt(): def boom(violations): raise RuntimeError("model down") best = tv.run_with_validation(lambda: ["first"], lambda c: ["bad"], boom) assert best == ["first"] def test_a_retry_that_returns_none_keeps_the_first_attempt(): best = tv.run_with_validation(lambda: ["first"], lambda c: ["bad"], lambda v: None) assert best == ["first"] # --- the Studio path retries exactly once ---------------------------------- _GOOD_TITLE = "Why this broke everything" _BAD_TITLE = "Alpha channel overview" def _prompt_text(contents): if isinstance(contents, str): return contents return "\n".join(c if isinstance(c, str) else (getattr(c, "text", "") or "") for c in (contents or [])) class _RecordingModels: def __init__(self, responses): self.prompts = [] self.responses = list(responses) def generate_content(self, model=None, contents=None, config=None): self.prompts.append(_prompt_text(contents)) return SimpleNamespace(text=self.responses.pop(0)) class _RecordingClient: def __init__(self, responses): self.models = _RecordingModels(responses) def _critic_json(title): return ('{"titles": ["%s"], "thumbnail_texts": ["A"], "recommended": []}' % title) _BRAINSTORM = ('{"transcript_summary": "s", "candidates": ["%s", "%s"]}' % (_GOOD_TITLE, _BAD_TITLE)) _TRANSCRIPT = {"language": "en", "text": "hello world", "segments": [{"start": 0.0, "end": 10.0, "text": "hello"}]} def _analyze(monkeypatch, responses, profile): client = _RecordingClient(responses) monkeypatch.setattr(thumbnail, "_frame_parts", lambda *a, **k: []) monkeypatch.setattr(thumbnail, "genai", SimpleNamespace( Client=lambda api_key=None, **k: client)) result = thumbnail.analyze_video_for_titles( "key", "video.mp4", transcript=_TRANSCRIPT, profile=profile) return result, client.models.prompts def test_analyze_retries_once_on_invalid_titles(monkeypatch, pedro): result, prompts = _analyze( monkeypatch, [_BRAINSTORM, _critic_json(_BAD_TITLE), _critic_json(_GOOD_TITLE)], pedro) assert result["titles"] == [_GOOD_TITLE] assert len(prompts) == 3 # brainstorm + critic + one retry assert "VALIDATION FAILED" in prompts[2] def test_analyze_keeps_the_first_attempt_when_the_retry_is_also_invalid(monkeypatch, pedro): result, prompts = _analyze( monkeypatch, [_BRAINSTORM, _critic_json(_BAD_TITLE), _critic_json(_BAD_TITLE)], pedro) assert result["titles"] == [_BAD_TITLE] assert len(prompts) == 3 def test_analyze_never_blocks_when_the_retry_call_fails(monkeypatch, pedro): # No third response: the retry raises, and the first attempt must still ship. result, prompts = _analyze(monkeypatch, [_BRAINSTORM, _critic_json(_BAD_TITLE)], pedro) assert result["titles"] == [_BAD_TITLE] def test_analyze_does_not_retry_a_valid_critic(monkeypatch, pedro): result, prompts = _analyze( monkeypatch, [_BRAINSTORM, _critic_json(_GOOD_TITLE)], pedro) assert result["titles"] == [_GOOD_TITLE] assert len(prompts) == 2 # --- #4 roles --------------------------------------------------------------- def test_normalise_forces_emotion_and_technical(): raw = [ {"text": "A", "scene": "s1", "role": "curiosity"}, {"text": "B", "scene": "s2", "role": "curiosity"}, ] out = thumbnail.normalise_concepts(raw, 2, "My title") roles = [c["role"] for c in out] assert "emotion" in roles and "technical" in roles assert len(out) == 2 def test_normalise_uses_role_order_for_padding(): out = thumbnail.normalise_concepts([], 2, "My title", role_order=["technical", "emotion", "curiosity"]) assert [c["role"] for c in out] == ["technical", "emotion"] def test_normalise_single_concept_does_not_crash(): out = thumbnail.normalise_concepts( [{"text": "A", "scene": "s", "role": "curiosity"}], 1, "My title") assert len(out) == 1 def test_normalise_replaces_an_unknown_role(): out = thumbnail.normalise_concepts( [{"text": "A", "scene": "s", "role": "banana"}], 2, "My title") assert all(c["role"] in thumbnail.CONCEPT_ROLES for c in out) def test_plan_prompt_requires_a_role_and_output_carries_one(): concepts = ('{"concepts": [' '{"text": "A", "text_position": "left", "text_color": "yellow",' ' "role": "curiosity", "scene": "a desk", "why": "w"},' '{"text": "B", "text_position": "right", "text_color": "white",' ' "role": "technical", "scene": "a screen", "why": "w"}]}') client = _RecordingClient([concepts]) out = thumbnail.plan_thumbnail_concepts(client, "My title", 2) assert '"role"' in client.models.prompts[0] assert all(c["role"] in thumbnail.CONCEPT_ROLES for c in out) # --- #4 bottom-right safe area --------------------------------------------- def test_burn_text_keeps_clear_of_the_bottom_right_corner(): img = Image.new("RGB", (1280, 720), (0, 0, 0)) out = thumbnail.burn_thumbnail_text( img, "WHY THIS BROKE EVERYTHING", "bottom", "white").convert("RGB") bottom = out.crop((0, int(720 * 0.80), 1280, 720)) assert max(bottom.getextrema()[0]) < 60, "ink intrudes into the bottom 20%" right = out.crop((int(1280 * 0.95), 0, 1280, 720)) assert max(right.getextrema()[0]) < 60, "ink touches the right edge" # Sanity: something was actually drawn outside the reserved corner. middle = out.crop((0, 0, 1280, int(720 * 0.80))) assert max(middle.getextrema()[0]) > 200 # --- free_tools endpoint ---------------------------------------------------- def _metadata_client(): from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() app.include_router(ft.router) return TestClient(app) def test_metadata_titles_retry_once_on_violations(monkeypatch): calls = [] def fake_generate(prompt): calls.append(prompt) if "VALIDATION FAILED" in prompt: return {"titles": [{"title": _GOOD_TITLE, "angle": "a"}]} return {"titles": [{"title": _BAD_TITLE, "angle": "a"}]} monkeypatch.setattr(ft, "_gemini_key", lambda: "k") monkeypatch.setattr(ft, "_generate", fake_generate) r = _metadata_client().post("/api/tools/youtube-metadata", json={ "mode": "titles", "topic": "A talk about low level systems", "channel": "pedro"}) assert r.status_code == 200, r.text assert [t["title"] for t in r.json()["titles"]] == [_GOOD_TITLE] assert len(calls) == 2 assert "violations" not in r.json() def test_metadata_unknown_channel_is_400(monkeypatch): monkeypatch.setattr(ft, "_gemini_key", lambda: "k") r = _metadata_client().post("/api/tools/youtube-metadata", json={ "mode": "titles", "topic": "A talk about low level systems", "channel": "nope"}) assert r.status_code == 400 assert r.json()["detail"]["code"] == "bad_channel"