clipwright/clipwright/media/title_validation.py

170 lines
7.5 KiB
Python

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