From 2d77269337fa99095e00052180374977cdb4e92d Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Mon, 5 Oct 2026 16:38:42 +0100 Subject: [PATCH] feat(packaging): title validator + thumbnail concept roles + mobile safe areas --- clipwright/api/free_tools.py | 59 +++- clipwright/media/thumbnail.py | 246 +++++++++++++--- clipwright/media/title_validation.py | 170 +++++++++++ tests/e2e/pipeline/test_thumbnail_stage.py | 4 +- tests/test_thumbnail_studio.py | 8 +- tests/test_title_validator.py | 316 +++++++++++++++++++++ 6 files changed, 754 insertions(+), 49 deletions(-) create mode 100644 clipwright/media/title_validation.py create mode 100644 tests/test_title_validator.py diff --git a/clipwright/api/free_tools.py b/clipwright/api/free_tools.py index 4ff61a3..ff568db 100644 --- a/clipwright/api/free_tools.py +++ b/clipwright/api/free_tools.py @@ -41,6 +41,8 @@ from urllib.parse import parse_qs, urlparse from fastapi import APIRouter, HTTPException, Request from pydantic import BaseModel +from clipwright.media import title_validation + router = APIRouter() # --------------------------------------------------------------------------- # @@ -476,6 +478,7 @@ class MetadataRequest(BaseModel): topic: str keyword: Optional[str] = "" audience: Optional[str] = "" + channel: Optional[str] = None _COMMON_RULES = """ @@ -543,8 +546,13 @@ def _clean(s: str) -> str: return re.sub(r"\s*—\s*", ", ", (s or "")).strip() -def shape_result(mode: str, data: dict) -> dict: - """Validate and tidy the model's JSON into what the page renders.""" +def shape_result(mode: str, data: dict, profile=None) -> dict: + """Validate and tidy the model's JSON into what the page renders. + + For ``titles``, ``profile`` adds the channel's rule checks (PLAN #3) and the + result carries a ``violations`` list so the caller can re-ask once. The + caller pops ``violations`` before returning it to the client. + """ if mode == "titles": items = [] for t in (data.get("titles") or [])[:12]: @@ -555,7 +563,11 @@ def shape_result(mode: str, data: dict) -> dict: items.append({"title": title, "angle": _clean(str(t.get("angle", "")))[:40]}) if not items: raise ValueError("no titles") - return {"titles": items} + return { + "titles": items, + "violations": title_validation.validate_titles( + [i["title"] for i in items], profile), + } if mode == "description": desc = _clean(str(data.get("description", "")))[:5000] if not desc: @@ -576,6 +588,37 @@ def shape_result(mode: str, data: dict) -> dict: return {"tags": tags, "characters": len(",".join(tags))} +def _profile_for_channel(channel): + """Resolve the optional channel field to a Profile (PLAN #3).""" + slug = str(channel or "").strip() + if not slug: + return None + from clipwright.pipeline.profiles import ProfileError, load_profile + try: + return load_profile(slug) + except ProfileError as e: + raise HTTPException(status_code=400, + detail={"code": "bad_channel", "message": str(e)}) + + +def _retry_titles(prompt, candidate, profile): + """One re-ask with the critique; keeps the first attempt if it fails.""" + def validate(c): + return title_validation.validate_titles([t["title"] for t in c["titles"]], profile) + + def retry_once(violations): + try: + data = _generate(prompt + "\n\n" + title_validation.critique_block(violations)) + return shape_result("titles", data, profile) + except Exception as e: # a failed re-ask must not lose the first attempt + print(f"[free_tools] title retry failed: {e}") + return None + + best = title_validation.run_with_validation(lambda: candidate, validate, retry_once) + best.pop("violations", None) + return best + + def _gemini_key(): return os.environ.get("GEMINI_API_KEY", "").strip() or None @@ -631,12 +674,20 @@ async def youtube_metadata(payload: MetadataRequest, request: Request): raise HTTPException(status_code=503, detail={ "code": "not_configured", "message": "This tool needs a Gemini API key on the server."}) _enforce("metadata", request) + profile = _profile_for_channel(payload.channel) prompt = build_prompt(mode, topic.replace("{", "(").replace("}", ")"), keyword, audience) last = None for _ in range(2): try: data = await asyncio.wait_for(asyncio.to_thread(_generate, prompt), timeout=40) - return {"mode": mode, **shape_result(mode, data)} + shaped = shape_result(mode, data, profile) + # Deterministic title QA (PLAN #3): one re-ask if the titles break + # the rules, then keep the better attempt. Never blocks the job. + if mode == "titles" and shaped.get("violations"): + shaped = await asyncio.wait_for( + asyncio.to_thread(_retry_titles, prompt, shaped, profile), timeout=80) + shaped.pop("violations", None) + return {"mode": mode, **shaped} except asyncio.TimeoutError: last = "timeout" break diff --git a/clipwright/media/thumbnail.py b/clipwright/media/thumbnail.py index 45fbf14..a3754a7 100644 --- a/clipwright/media/thumbnail.py +++ b/clipwright/media/thumbnail.py @@ -10,6 +10,8 @@ from google.genai import types from google.genai import errors as genai_errors from PIL import Image, ImageDraw, ImageFont, ImageFilter from clipwright.core.paths import FONTS_DIR +from clipwright.media import title_validation +from clipwright.pipeline import profile_prompts # Text/analysis model (titles, concepts, description). Deliberately NOT tied to # GEMINI_MODEL: the pipeline runs flash-lite for a closed-choice layout pick, @@ -34,6 +36,14 @@ THUMB_MAX_BYTES = 2 * 1024 * 1024 # YouTube's upload limit THUMB_FONT = str(FONTS_DIR / "Anton-Regular.ttf") TEXT_POSITIONS = ("left", "right", "top", "bottom") +# Mobile viewers (the majority of the audience) watch with YouTube's +# timestamp/badge overlays in the bottom-right; keep the headline clear of that +# corner and off the right edge. +THUMB_SAFE_BOTTOM = 0.20 # bottom fraction reserved for YouTube's UI +THUMB_SAFE_RIGHT = 0.05 # margin off the right edge +THUMB_SAFE_LEFT = 0.04 # margin off the left edge +THUMB_SAFE_TOP = 0.04 # margin off the top edge + def _parse_json(text): """Gemini JSON, tolerant of code fences and prose around the object.""" @@ -62,11 +72,14 @@ def _frame_parts(video_path, n=TITLE_FRAMES, width=TITLE_FRAME_WIDTH): # Titles # --------------------------------------------------------------------------- -def analyze_video_for_titles(api_key, video_path, transcript=None): +def analyze_video_for_titles(api_key, video_path, transcript=None, profile=None): """ Suggests YouTube titles from the transcript plus a handful of frames. Two calls: a wide brainstorm, then a critic that scores and picks a diverse top 10 and pairs each title with a 1-4 word thumbnail hook. + + ``profile`` (optional channel Profile, PLAN #1) adds the channel's title and + hook rules to both calls; ``None`` leaves the prompts unchanged. Returns: { "titles", "thumbnail_texts", "transcript_summary", "language", "segments", "video_duration", "recommended" } """ @@ -84,6 +97,11 @@ def analyze_video_for_titles(api_key, video_path, transcript=None): video_duration = segments[-1]["end"] if segments else 0 # Enough transcript for a title; a 3-hour podcast does not need all of it. transcript_text = transcript.get("text", "")[:60000] + # Empty for profile=None, so the f-strings below render exactly as before. + channel_rules = profile_prompts.clip_rules_block(profile) + if channel_rules: + print(f"📦 [Thumbnail] Applying channel profile " + f"{getattr(profile, 'slug', '')} to title prompts.") brainstorm_prompt = f"""You are a YouTube packaging expert (titles + thumbnails) for a channel that wants maximum CTR without lying. @@ -109,7 +127,7 @@ TITLE RULES: - Put the main keyword / subject in the first 3 words. - Be specific to THIS video: names, numbers, tools, places from the transcript. Nothing generic. - No ALL CAPS words, at most one exclamation mark, no emojis. - +{channel_rules} OUTPUT JSON: {{ "transcript_summary": "...", @@ -154,7 +172,7 @@ Then return the 10 best, ordered best first, with NO two titles using the same a For each of the 10, write the THUMBNAIL TEXT: 1-4 words, ALL CAPS, in {language}, that COMPLEMENTS the title instead of repeating it (the title says what, the thumbnail says the emotion, the number or the twist). Examples of the relationship: title "How I got 10k subscribers in 30 days" -> thumbnail "0 TO 10K"; title "Por qué dejé mi trabajo en Google" -> thumbnail "ME FUI". Pick the top 2 and explain in one sentence each why they will win the click. - +{channel_rules} OUTPUT JSON: {{ "titles": ["...", ... 10 items], @@ -166,21 +184,50 @@ OUTPUT JSON: }}""" print("🧐 [Thumbnail] Scoring titles...") - response = client.models.generate_content( - model=TEXT_MODEL, - contents=[critic_prompt], - config=types.GenerateContentConfig(response_mime_type="application/json"), - ) - try: - picked = _parse_json(response.text) - titles = [t for t in picked.get("titles", []) if isinstance(t, str) and t.strip()] - if not titles: - raise ValueError("no titles") - except (json.JSONDecodeError, AttributeError, ValueError): - print(f"⚠️ [Thumbnail] Critic failed, falling back to the brainstorm: {getattr(response, 'text', '')[:300]}") - titles = candidates[:10] - picked = {"thumbnail_texts": [], "recommended": []} + def _critic(violations=None): + """One critic call. ``violations`` appends the re-ask critique.""" + prompt = critic_prompt + if violations: + prompt = critic_prompt + "\n\n" + title_validation.critique_block(violations) + response = client.models.generate_content( + model=TEXT_MODEL, + contents=[prompt], + config=types.GenerateContentConfig(response_mime_type="application/json"), + ) + try: + picked_local = _parse_json(response.text) + titles_local = [t for t in picked_local.get("titles", []) + if isinstance(t, str) and t.strip()] + if not titles_local: + raise ValueError("no titles") + except (json.JSONDecodeError, AttributeError, ValueError): + print(f"⚠️ [Thumbnail] Critic failed: {getattr(response, 'text', '')[:300]}") + return None + texts_local = [str(t) for t in picked_local.get("thumbnail_texts", [])][:len(titles_local)] + texts_local += [""] * (len(titles_local) - len(texts_local)) + return { + "titles": titles_local, + "thumbnail_texts": texts_local, + "recommended": [r for r in picked_local.get("recommended", []) + if isinstance(r, dict) and isinstance(r.get("index"), int) + and 0 <= r["index"] < len(titles_local)], + } + + def _validate(candidate): + if not candidate: + return [] + return title_validation.validate_titles(candidate["titles"], profile) + + # Deterministic QA (PLAN #3): one re-ask if the critic's titles break the + # channel rules, then keep the best attempt. Never blocks the response. + picked = title_validation.run_with_validation( + _critic, _validate, lambda violations: _critic(violations)) + if picked is None: + print("⚠️ [Thumbnail] Critic failed, falling back to the brainstorm candidates.") + picked = {"titles": candidates[:10], "thumbnail_texts": [], "recommended": []} + + titles = picked["titles"] thumbnail_texts = [str(t) for t in picked.get("thumbnail_texts", [])][:len(titles)] thumbnail_texts += [""] * (len(titles) - len(thumbnail_texts)) return { @@ -190,9 +237,7 @@ OUTPUT JSON: "language": language, "segments": segments, "video_duration": video_duration, - "recommended": [r for r in picked.get("recommended", []) - if isinstance(r, dict) and isinstance(r.get("index"), int) - and 0 <= r["index"] < len(titles)], + "recommended": picked.get("recommended", []), } @@ -370,11 +415,15 @@ def _crop_face_reference(frame_path, face_box, out_path): # --------------------------------------------------------------------------- def plan_thumbnail_concepts(client, title, count, video_context="", extra_prompt="", - thumbnail_text_hint="", has_person=False, language="en"): + thumbnail_text_hint="", has_person=False, language="en", + profile=None): """ One text call that designs `count` DIFFERENT thumbnails before any pixel is drawn. Asking the image model to invent the concept and render it in one go gives N variations of one idea; splitting it gives N ideas. + + ``profile`` (optional channel Profile, PLAN #1) adds the channel's palette, + role order and presenter expectation; ``None`` leaves the prompt unchanged. """ person_line = ("A real photo of the presenter is provided and MUST be the focal point, " "with a clear, natural expression that reads at small size (no caricature)." @@ -385,6 +434,8 @@ def plan_thumbnail_concepts(client, title, count, video_context="", extra_prompt hint_line = (f'\nSUGGESTED THUMBNAIL TEXT (use it for the first concept unless it is poor): "{thumbnail_text_hint}"' if thumbnail_text_hint else "") extra_line = f"\nMANDATORY USER INSTRUCTIONS (override everything else):\n{extra_prompt}\n" if extra_prompt else "" + # Empty for profile=None, so the f-string below renders exactly as before. + channel_rules = profile_prompts.thumbnail_block(profile) prompt = f"""You are a YouTube thumbnail art director. Design {count} DIFFERENT thumbnail concepts for this video. VIDEO TITLE: "{title}" @@ -394,17 +445,18 @@ VIDEO CONTEXT: {video_context or "(none)"} The thumbnail must show WHAT the video is about, not only how the presenter feels: name the concrete subject (the product, the tool, the result, the numbers) and build the picture around it. A face alone with two words is the lazy default; use it at most once, and only combined with a strong prop or scene. Each concept must use a different device, e.g.: the presenter + a prop that IS the topic (a phone showing vertical clips, a laptop with the app, a counter/badge with the number); before/after or "long video -> short clips" split; product/UI hero shot with the presenter small; a giant number or stat as the hero with the subject behind; "X vs Y" comparison; a red circle/arrow on a detail; a dramatic reveal with depth (foreground object, blurred background). Layered, cinematic, premium: real props, depth of field, rim light, particles, glow on the key object. Never flat, never a plain wall behind the person. No two concepts may share the same text or the same layout. - +{channel_rules} Per concept give: - "text": 1-4 words, ALL CAPS, in {language}. Complements the title (the title says what, the text says the emotion, the number or the twist). Never repeat the title. No emoji. - "text_position": one of "left", "right", "top", "bottom" (where the text block sits; the subject goes on the opposite side). - "text_color": "white" or "yellow" (yellow for money/energy, white otherwise). +- "role": exactly one of "emotion", "technical", "curiosity" — the job this concept does for the click. Cover ALL THREE roles across the set (at least one of each): "emotion" is a human face or feeling, "technical" is the product, tool, code, diagram or concrete result, "curiosity" is a question, a reveal or a hidden detail. - "scene": a precise image-generation prompt in English, 2-4 sentences: subject, expression/pose, background, lighting, colours, camera. Say that the text_position side is clean negative space (simple, dark or plain) so a headline can sit there. It must NOT ask for any text, letters, captions or logos in the image. - The image model REFUSES prompts that name or depict real people, companies or brands. Never write a real name (person, company, product, logo) in "scene". Refer to the presenter only as "the person in the provided photo" when a photo is provided, otherwise as a generic, unnamed person or use objects and symbols. - "why": one short sentence on why this earns the click. OUTPUT JSON: -{{"concepts": [{{"text": "...", "text_position": "left", "text_color": "yellow", "scene": "...", "why": "..."}}, ...]}}""" +{{"concepts": [{{"text": "...", "text_position": "left", "text_color": "yellow", "role": "emotion", "scene": "...", "why": "..."}}, ...]}}""" response = client.models.generate_content( model=TEXT_MODEL, @@ -416,32 +468,96 @@ OUTPUT JSON: except (json.JSONDecodeError, AttributeError): print(f"⚠️ [Thumbnail] Concept JSON unreadable, using a generic concept: {getattr(response, 'text', '')[:200]}") concepts = [] - return normalise_concepts(concepts, count, title, thumbnail_text_hint) + role_order = list(profile.thumbnail.role_order) if profile else None + return normalise_concepts(concepts, count, title, thumbnail_text_hint, + role_order=role_order) -def normalise_concepts(concepts, count, title, thumbnail_text_hint=""): - """Clamp model output to what the renderer accepts and pad to `count`.""" +# #4: every concept declares the job it does for the click, and the set must +# cover emotion + technical. Kept here (not in the prompt alone) because a +# prompt is not a contract. +CONCEPT_ROLES = ("emotion", "technical", "curiosity") + +_ROLE_SCENES = { + "emotion": ( + "A dramatic, high-contrast YouTube thumbnail centred on a person's face and " + "expression (surprise, focus or relief), warm rim light, blurred background, " + "the {pos} side clean dark negative space."), + "technical": ( + "A clean product/UI hero shot for a video titled '{title}': the tool, code, " + "diagram or result sharp and large, cool cinematic light, the {pos} side " + "clean dark negative space."), + "curiosity": ( + "A cinematic reveal for a video titled '{title}': a key detail partly hidden " + "or circled, depth of field, dramatic light, the {pos} side clean dark " + "negative space."), +} + + +def _role_scene(role, title, position): + template = _ROLE_SCENES.get(role, _ROLE_SCENES["curiosity"]) + return template.format(title=title, pos=position) + + +def _fallback_concept(title, hint, role, position="left"): + return { + "text": (hint or "").upper()[:40], + "text_position": position, + "text_color": "white", + "role": role, + "scene": _role_scene(role, title, position), + "why": f"fallback ({role})", + } + + +def normalise_concepts(concepts, count, title, thumbnail_text_hint="", role_order=None): + """Clamp model output to what the renderer accepts and pad to `count`. + + Also enforces the #4 role mix: every concept carries a role and the set is + guaranteed at least one "emotion" and one "technical" concept. A missing + role is filled by converting the last available concept to a role-appropriate + scene, so no concept is dropped. + """ cleaned = [] for c in concepts: if not isinstance(c, dict) or not c.get("scene"): continue + role = c.get("role") if c.get("role") in CONCEPT_ROLES else None cleaned.append({ "text": str(c.get("text") or thumbnail_text_hint or "").strip().upper()[:40], "text_position": c.get("text_position") if c.get("text_position") in TEXT_POSITIONS else "left", "text_color": "yellow" if c.get("text_color") == "yellow" else "white", + "role": role, "scene": str(c["scene"]), "why": str(c.get("why", "")), }) + + order = [r for r in (role_order or []) if r in CONCEPT_ROLES] or list(CONCEPT_ROLES) while len(cleaned) < count: - cleaned.append({ - "text": thumbnail_text_hint.upper()[:40], - "text_position": "left", - "text_color": "white", - "scene": (f"A bold, high-contrast YouTube thumbnail scene for a video titled '{title}'. " - "Dramatic lighting, vibrant colours, the left third is clean dark negative space."), - "why": "fallback", - }) - return cleaned[:count] + role = order[len(cleaned) % len(order)] + cleaned.append(_fallback_concept(title, thumbnail_text_hint, role)) + cleaned = cleaned[:count] + + if count < 2: + return cleaned + + present = {c["role"] for c in cleaned} + used: set[int] = set() + for role in ("emotion", "technical"): + if role in present: + continue + target = next((c for c in reversed(cleaned) + if c["role"] is None and id(c) not in used), None) + if target is None: + target = next((c for c in reversed(cleaned) if id(c) not in used), None) + if target is None: + break + used.add(id(target)) + target["role"] = role + target["scene"] = _role_scene(role, title, target["text_position"]) + target["why"] = target["why"] or f"{role} concept" + present.add(role) + return cleaned def _wrap_lines(draw, text, font, max_width): @@ -502,8 +618,46 @@ def burn_thumbnail_text(img, text, position="left", color="white"): else: x0, y0 = int(W * 0.04), H - total_h - int(H * 0.06) - top_pad + # Bottom-right safe area (#4): the headline must not sit under YouTube's + # timestamp/badge corner nor run off the right edge. Whatever the requested + # position, the rendered block is clamped inside the safe box. + bottom_limit = int(H * (1.0 - THUMB_SAFE_BOTTOM)) + right_limit = int(W * (1.0 - THUMB_SAFE_RIGHT)) + left_limit = int(W * THUMB_SAFE_LEFT) + top_limit = int(H * THUMB_SAFE_TOP) + + center_x = W // 2 + ink_w = widest + stroke + ink_h = total_h + stroke + if horizontal: + block_left, block_right = x0, x0 + ink_w + else: + block_left, block_right = center_x - ink_w // 2, center_x + ink_w // 2 + if block_right > right_limit: + shift = block_right - right_limit + if horizontal: + x0 -= shift + else: + center_x -= shift + if block_left < left_limit: + shift = left_limit - block_left + if horizontal: + x0 += shift + else: + center_x += shift + + visual_top = y0 + top_pad + if visual_top < top_limit: + y0 += top_limit - visual_top + visual_top = top_limit + if visual_top + ink_h > bottom_limit: + y0 = bottom_limit - ink_h - top_pad + y0 = max(y0, -top_pad) # keep the ink on the canvas + def line_x(line): - return x0 if horizontal else (W - draw.textlength(line, font=font)) // 2 + if horizontal: + return x0 + return center_x - int(draw.textlength(line, font=font)) // 2 shadow = Image.new("RGBA", img.size, (0, 0, 0, 0)) sdraw = ImageDraw.Draw(shadow) @@ -663,11 +817,13 @@ Style: high contrast, saturated colours, crisp subject separation, cinematic lig def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_image_path=None, extra_prompt="", count=3, video_context="", burn_text=True, - thumbnail_text_hint="", language="en", frame_reference=None): + thumbnail_text_hint="", language="en", frame_reference=None, + profile=None): """ Generates `count` thumbnails, each from its own concept, in parallel. frame_reference: {"path", "face"} from extract_face_frames, used as the person reference when the user picked a frame instead of uploading a photo. + profile: optional channel Profile (PLAN #1), forwarded to the concept call. Returns [{"url", "text", "why"}] (only the ones that rendered). """ client = genai.Client(api_key=api_key) @@ -688,7 +844,8 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag concepts = plan_thumbnail_concepts( client, title, count, video_context=video_context, extra_prompt=extra_prompt, - thumbnail_text_hint=thumbnail_text_hint, has_person=bool(reference_images), language=language) + thumbnail_text_hint=thumbnail_text_hint, has_person=bool(reference_images), + language=language, profile=profile) for i, c in enumerate(concepts): print(f"🎨 [Thumbnail] Concept {i + 1}: \"{c['text']}\" ({c['text_position']}) - {c['why']}") @@ -720,7 +877,8 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag fallback = True print(f"✅ [Thumbnail] Saved: {out_path}") return {"url": f"/thumbnails/{session_id}/{os.path.basename(out_path)}", - "text": concept["text"], "why": concept["why"], "fallback": fallback} + "text": concept["text"], "why": concept["why"], + "role": concept.get("role"), "fallback": fallback} except Exception as e: print(f"❌ [Thumbnail] Generation {i + 1} failed: {e}") return {"error": str(e)} @@ -739,9 +897,12 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag # Description # --------------------------------------------------------------------------- -def generate_youtube_description(api_key, title, transcript_segments, language, video_duration): +def generate_youtube_description(api_key, title, transcript_segments, language, video_duration, + profile=None): """ Uses Gemini to generate a YouTube description with chapter markers from transcript segments. + ``profile`` (optional channel Profile, PLAN #1) adds the channel's description + structure, links and tone; ``None`` leaves the prompt unchanged. Returns: { "description": "full description text with chapters" } """ client = genai.Client(api_key=api_key) @@ -762,6 +923,9 @@ def generate_youtube_description(api_key, title, transcript_segments, language, dur_secs = int(video_duration % 60) duration_str = f"{dur_mins}:{dur_secs:02d}" + # Empty for profile=None, so the f-string below renders exactly as before. + channel_rules = profile_prompts.description_block(profile) + prompt = f"""You are a YouTube SEO expert. Generate a complete YouTube video description for the following video. VIDEO TITLE: "{title}" @@ -783,7 +947,7 @@ REQUIREMENTS: - Place chapters in their own section with a blank line before and after 5. Add 5-10 relevant hashtags at the end 6. Keep the total description under 5000 characters - +{channel_rules} OUTPUT: Return ONLY the description text (no JSON wrapper, no markdown code blocks). The description should be ready to paste directly into YouTube.""" print("🤖 [Thumbnail] Generating YouTube description with chapters...") diff --git a/clipwright/media/title_validation.py b/clipwright/media/title_validation.py new file mode 100644 index 0000000..51b4b9d --- /dev/null +++ b/clipwright/media/title_validation.py @@ -0,0 +1,170 @@ +"""Deterministic YouTube title QA (PLAN #3 + #4, merged). + +No LLM call lives here: the rules are the active channel profile's +``title_rules`` plus a few universal structural checks, so validation is cheap +enough to run on every generated title and cannot itself hallucinate. + +Two entry points: +* :func:`validate_title` / :func:`validate_titles` return the list of human- + readable violations for one title, or for a set (structural rules). +* :func:`run_with_validation` wraps generation: try, and on violations re-ask + exactly once with the critique; if the retry does not improve, keep the first + attempt. It NEVER raises on a validation failure and never blocks the job. +""" + +from __future__ import annotations + +import re +from collections import Counter + +from clipwright.pipeline.profiles import Profile + +# Task-descriptive openers that describe what the video *does* rather than what +# the viewer gets. The profile's ``banned_openers`` add the channel's own. +_TASK_OPENERS = ( + "in this video", "in today's video", "this video", "explaining", "discussing", + "talking about", "a look at", "let's", "watch me", "i'm going to", + "im going to", "here's how i", "step by step", +) +_TASK_OPENER_RE = re.compile( + r"^(?:" + "|".join(re.escape(o) for o in _TASK_OPENERS) + r")\b", re.I) + +# Words that carry no topic, so a title starting with one has not front-loaded +# its keyword. This is the deterministic proxy for ``keyword_position="start"`` +# (the profile carries no keyword to locate precisely). +_STOPWORDS = frozenset({ + "the", "a", "an", "this", "that", "these", "those", "my", "your", "our", + "their", "his", "her", "its", "it", "i", "we", "you", "they", "he", "she", + "is", "are", "was", "were", "be", "been", "being", "as", "if", "when", + "while", "so", "just", "in", "on", "at", "of", "for", "to", "with", "from", + "by", "and", "but", "or", +}) + +# Broad cue sets for required_signal. Deliberately generous: a false negative +# would force a retry, and a false positive only lets a weaker title through. +_CONSEQUENCE_RE = re.compile( + r"\b(why|because|so that|cost|costs|costing|ruin|ruined|ruins|broke|broken|" + r"breaks|lost|lose|loses|win|won|wins|crashed|crash|crashes|fail|failed|" + r"fails|failure|change|changed|changes|makes|made|turns|turned|becomes|became|" + r"stops|stopped|kills|killed|destroy|destroyed|saved|saves|before|after|" + r"mistake|mistakes|warning|warns|secretly|almost|never again|no longer|" + r"instead)\b", re.I) +_CURIOSITY_RE = re.compile( + r"\?|\b(why|how|what|secret|truth|real reason|reason|hidden|nobody|everyone|" + r"no one|shouldn'?t|should not|impossible|actually|forgot|forgotten|never|" + r"finally|revealed|reveal|mystery|unknown|here'?s|looks like|seems)\b", re.I) + + +def _first_word(title: str) -> str: + match = re.match(r"\s*([A-Za-zÀ-ÿ0-9']+)", title or "") + return match.group(1).lower() if match else "" + + +def validate_title(title: str, profile: Profile | None) -> list[str]: + """Every reason this one title breaks the profile's title rules. + + Structural checks (task-descriptive openers) run with or without a profile; + the profile-specific checks are skipped when ``profile`` is None. + """ + title = (title or "").strip() + if not title: + return ["title is empty"] + + problems: list[str] = [] + rules = getattr(profile, "title_rules", None) + if rules is not None: + if len(title) > rules.max_chars: + problems.append(f"{len(title)} chars exceeds the {rules.max_chars}-char maximum") + elif len(title) > rules.mobile_chars: + problems.append( + f"{len(title)} chars exceeds the {rules.mobile_chars}-char mobile limit") + lowered = title.lower() + for pattern in rules.banned_patterns: + if pattern.lower() in lowered: + problems.append(f'uses the banned phrase "{pattern}"') + for opener in rules.banned_openers: + if lowered.startswith(opener.lower()): + problems.append(f'opens with the banned opener "{opener}"') + break + first = _first_word(title) + if rules.keyword_position == "start" and first in _STOPWORDS: + problems.append(f'starts with the filler word "{first}" instead of the keyword') + if rules.number_policy == "avoid" and re.search(r"\d", title): + problems.append("uses a number where the channel avoids them") + elif rules.number_policy == "require" and not re.search(r"\d", title): + problems.append("has no number, which this channel requires") + signal = rules.required_signal + consequence = bool(_CONSEQUENCE_RE.search(title)) + curiosity = bool(_CURIOSITY_RE.search(title)) + if signal == "consequence" and not consequence: + problems.append("carries no consequence or stake") + elif signal == "curiosity" and not curiosity: + problems.append("opens no curiosity gap the video pays off") + elif signal == "either" and not (consequence or curiosity): + problems.append("carries no consequence or curiosity signal") + + if _TASK_OPENER_RE.match(title): + problems.append("opens with a task-descriptive phrase") + return problems + + +def validate_titles(titles, profile: Profile | None) -> list[str]: + """Per-title violations plus the structural rules that span a title set.""" + clean = [t for t in (titles or []) if isinstance(t, str) and t.strip()] + problems: list[str] = [] + for i, title in enumerate(clean): + for problem in validate_title(title, profile): + problems.append(f"title {i + 1}: {problem}") + + if not clean: + problems.append("no titles") + + firsts = Counter(_first_word(t) for t in clean) + for word, count in firsts.items(): + if word and count > 3: + problems.append(f'{count} titles start with the same word "{word}" (max 3)') + colons = sum(1 for t in clean if ":" in t) + if colons > 2: + problems.append(f"{colons} titles use a colon pattern (max 2)") + return problems + + +def critique_block(violations) -> str: + """An instruction block that hands the model the exact violations to fix.""" + lines = ["VALIDATION FAILED — the previous titles broke these rules:"] + lines += [f"- {v}" for v in violations] + lines.append("Rewrite the titles so every rule passes; keep every other instruction.") + return "\n".join(lines) + + +def run_with_validation(generate, validate, retry_once): + """Try ``generate``; on violations re-ask exactly once and keep the best. + + ``generate()`` -> candidate + ``validate(candidate)`` -> list of violations + ``retry_once(violations)`` -> a new candidate, or None if it could not run + + Returns the candidate with the fewest violations (the first one on a tie or + a failed retry). Never raises because of a validation failure. + """ + candidate = generate() + violations = list(validate(candidate) or []) + if not violations: + return candidate + + try: + retry = retry_once(violations) + except Exception as e: # a broken retry must not lose the first attempt + print(f"⚠️ [titles] validation retry failed ({e}); keeping the first attempt.") + return candidate + if retry is None: + return candidate + + retry_violations = list(validate(retry) or []) + if len(retry_violations) < len(violations): + print(f"✅ [titles] retry reduced violations " + f"{len(violations)} -> {len(retry_violations)}.") + return retry + print(f"⚠️ [titles] retry did not improve " + f"({len(violations)} -> {len(retry_violations)}); keeping the first attempt.") + return candidate diff --git a/tests/e2e/pipeline/test_thumbnail_stage.py b/tests/e2e/pipeline/test_thumbnail_stage.py index 1a9b8e7..42b42f1 100644 --- a/tests/e2e/pipeline/test_thumbnail_stage.py +++ b/tests/e2e/pipeline/test_thumbnail_stage.py @@ -164,7 +164,9 @@ class TestConcepts: assert len(out) == 3 assert out[0]["text"] == "ESTO FUNCIONA" assert out[0]["text_position"] == "left" - assert out[1]["why"] == "fallback" + # #4: a role is always present and the set covers emotion + technical. + assert {"emotion", "technical"} <= {c["role"] for c in out} + assert out[1]["text"] == "HINT" def test_plan_thumbnail_concepts_parses_the_client_json(self): concepts = thumbnail.plan_thumbnail_concepts(_FakeClient(), "A title", 2) diff --git a/tests/test_thumbnail_studio.py b/tests/test_thumbnail_studio.py index d3932a8..01d0c93 100644 --- a/tests/test_thumbnail_studio.py +++ b/tests/test_thumbnail_studio.py @@ -56,9 +56,11 @@ def test_normalise_concepts_clamps_and_pads(): ] out = thumbnail.normalise_concepts(raw, 3, "My title", thumbnail_text_hint="hint") assert len(out) == 3 - assert out[0] == {"text": "ESTO FUNCIONA", "text_position": "left", "text_color": "white", - "scene": "a desk", "why": ""} - assert out[1]["why"] == "fallback" and out[1]["text"] == "HINT" + assert out[0]["text"] == "ESTO FUNCIONA" + assert out[0]["text_position"] == "left" + # #4: a role is always present and the set covers emotion + technical. + assert {"emotion", "technical"} <= {c["role"] for c in out} + assert out[1]["text"] == "HINT" def test_parse_json_tolerates_fences_and_prose(): diff --git a/tests/test_title_validator.py b/tests/test_title_validator.py new file mode 100644 index 0000000..d158091 --- /dev/null +++ b/tests/test_title_validator.py @@ -0,0 +1,316 @@ +"""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"