From ea251a11283a19e28feab08aa02d7ed2c4e33811 Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Mon, 5 Oct 2026 16:38:42 +0100 Subject: [PATCH 01/10] feat(profiles): channel profiles + shared prompt mapping --- channels/cseea.json | 30 +++ channels/pedro.json | 30 +++ clipwright/pipeline/profile_prompts.py | 125 +++++++++++ clipwright/pipeline/profiles.py | 295 +++++++++++++++++++++++++ tests/test_channels_endpoint.py | 41 ++++ tests/test_profile_prompts.py | 260 ++++++++++++++++++++++ tests/test_profiles.py | 214 ++++++++++++++++++ 7 files changed, 995 insertions(+) create mode 100644 channels/cseea.json create mode 100644 channels/pedro.json create mode 100644 clipwright/pipeline/profile_prompts.py create mode 100644 clipwright/pipeline/profiles.py create mode 100644 tests/test_channels_endpoint.py create mode 100644 tests/test_profile_prompts.py create mode 100644 tests/test_profiles.py diff --git a/channels/cseea.json b/channels/cseea.json new file mode 100644 index 0000000..bdfe037 --- /dev/null +++ b/channels/cseea.json @@ -0,0 +1,30 @@ +{ + "name": "cseea", + "language": "en", + "tone": "nostalgic and calm; curious, never hype", + "title_rules": { + "max_chars": 60, + "mobile_chars": 38, + "banned_patterns": ["in this video", "tutorial", "let's play", "how to"], + "keyword_position": "start", + "number_policy": "avoid", + "required_signal": "curiosity", + "banned_openers": ["Exploring", "Building", "Playing", "A look at"] + }, + "hook_patterns": [ + "this shouldn't be possible in Alpha", + "the mechanic Mojang forgot to remove", + "you were never supposed to see this", + "I broke the world in one block" + ], + "hook_style": "visual impossibility at frame 0; show the glitch before any words", + "description_template": "{hook}\n\nFull video: {link}\n\n#minecraft #alpha #retro", + "links": ["https://www.youtube.com/@cseea"], + "thumbnail": { + "role_order": ["curiosity", "emotion", "technical"], + "palette": ["mossy green", "cobblestone grey", "torch orange"], + "presenter_photo": false + }, + "default_postiz_integration_id": null, + "published_video_history": [] +} diff --git a/channels/pedro.json b/channels/pedro.json new file mode 100644 index 0000000..70e0945 --- /dev/null +++ b/channels/pedro.json @@ -0,0 +1,30 @@ +{ + "name": "Pedro Bento", + "language": "en", + "tone": "technical, direct, engineering-focused", + "title_rules": { + "max_chars": 70, + "mobile_chars": 42, + "banned_patterns": ["in this video", "for beginners", "quick tip"], + "keyword_position": "start", + "number_policy": "allow", + "required_signal": "consequence", + "banned_openers": ["Explaining", "Discussing", "Talking about"] + }, + "hook_patterns": [ + "it crashes the moment you resize", + "watch the benchmark number change", + "the bug that survived three rewrites", + "this one syscall cost 40% throughput" + ], + "hook_style": "show the working demo or the bug first, then state the stake in one line", + "description_template": "{hook}\n\nChapters and source: {link}\n\n#c #linux #systems", + "links": ["https://github.com/pbento"], + "thumbnail": { + "role_order": ["technical", "curiosity", "emotion"], + "palette": ["terminal black", "signal amber", "trace red"], + "presenter_photo": true + }, + "default_postiz_integration_id": null, + "published_video_history": [] +} diff --git a/clipwright/pipeline/profile_prompts.py b/clipwright/pipeline/profile_prompts.py new file mode 100644 index 0000000..2467a14 --- /dev/null +++ b/clipwright/pipeline/profile_prompts.py @@ -0,0 +1,125 @@ +"""Profile -> prompt fragments (PLAN #1, full). + +The single mapping between a channel :class:`~clipwright.pipeline.profiles.Profile` +and the text the generators read. Both generation paths use it and nothing else: + +* the clipping path (``gemini_worker.DETAIL_PROMPT_TEMPLATE``, via ``main.py``) +* the Studio path (``media/thumbnail.py``: titles, concepts, description) + +Every helper is pure and accepts ``profile=None``; a ``None`` profile returns the +empty string, so a caller that was never given a channel renders exactly the +prompt it did before profiles existed. A non-empty block ends with a single ``\\n`` +so it can be dropped onto its own line in an f-string without shifting anything +(an empty string leaves the line blank, byte-for-byte as today). + +Keep the blocks short: they are constraints on an already-long prompt, not a +second prompt. +""" + +from __future__ import annotations + +from clipwright.pipeline.profiles import Profile + +# Full sentences, keyed by the enums ``profiles.py`` validates. Kept here so a +# new enum value fails loudly (missing from the map) instead of silently +# dropping the constraint. +_KEYWORD_POSITION_TEXT = { + "start": "Put the main keyword or subject in the first 3 words", + "middle": "Put the main keyword or subject near the middle", + "end": "Put the main keyword or subject at the end", + "any": "Place the main keyword or subject wherever it reads best", +} +_NUMBER_POLICY_TEXT = { + "allow": "Numbers are allowed when they earn attention", + "avoid": "Avoid numbers unless a number is the point", + "require": "Every title must contain a concrete number", +} +_REQUIRED_SIGNAL_TEXT = { + "consequence": "Every title must carry a concrete consequence or stake", + "curiosity": "Every title must open a curiosity gap the video pays off", + "either": "Every title must carry a consequence or a curiosity gap", + "none": "", +} + + +def _quoted(items): + return "; ".join(f'"{item}"' for item in items) + + +def title_rules_block(profile: Profile | None) -> str: + """Title constraints: length, banned content, keyword/number/signal policy, tone.""" + if profile is None: + return "" + rules = profile.title_rules + lines = ["CHANNEL TITLE RULES:"] + if profile.tone: + lines.append(f"- Tone: {profile.tone}.") + lines.append( + f"- Hard maximum {rules.max_chars} characters; the payoff must land inside " + f"the first {rules.mobile_chars} (phones truncate there).") + position = _KEYWORD_POSITION_TEXT.get(rules.keyword_position) + if position: + lines.append(f"- {position}.") + signal = _REQUIRED_SIGNAL_TEXT.get(rules.required_signal) + if signal: + lines.append(f"- {signal}.") + number = _NUMBER_POLICY_TEXT.get(rules.number_policy) + if number: + lines.append(f"- {number}.") + if rules.banned_patterns: + lines.append(f"- Never use the phrases: {_quoted(rules.banned_patterns)}.") + if rules.banned_openers: + lines.append(f"- Never open a title with: {_quoted(rules.banned_openers)}.") + return "\n".join(lines) + "\n" + + +def hook_block(profile: Profile | None) -> str: + """Hook style and the patterns the channel already knows work.""" + if profile is None: + return "" + lines = [] + if profile.hook_style: + lines.append(f"- Hook style: {profile.hook_style}.") + if profile.hook_patterns: + lines.append(f"- Patterns that work for this channel: {_quoted(profile.hook_patterns)}.") + if not lines: + return "" + return "CHANNEL HOOK RULES:\n" + "\n".join(lines) + "\n" + + +def description_block(profile: Profile | None) -> str: + """Description structure, the channel's links and its tone.""" + if profile is None: + return "" + lines = [] + if profile.description_template: + template = profile.description_template.replace("\n", "\\n") + lines.append(f'- Follow this structure for the blurb: "{template}".') + if profile.links: + lines.append(f"- Include these links: {', '.join(profile.links)}.") + if profile.tone: + lines.append(f"- Tone: {profile.tone}.") + if not lines: + return "" + return "CHANNEL DESCRIPTION RULES:\n" + "\n".join(lines) + "\n" + + +def thumbnail_block(profile: Profile | None) -> str: + """Thumbnail roles, palette and whether a presenter photo is expected.""" + if profile is None: + return "" + thumb = profile.thumbnail + lines = [] + if thumb.role_order: + lines.append(f"- Concept roles, in priority order: {', '.join(thumb.role_order)}.") + if thumb.palette: + lines.append(f"- Palette: {', '.join(thumb.palette)}.") + presenter = ("available and encouraged" if thumb.presenter_photo + else "not expected; prefer objects, scenes or symbols") + lines.append(f"- Presenter photo is {presenter}.") + return "CHANNEL THUMBNAIL RULES:\n" + "\n".join(lines) + "\n" + + +def clip_rules_block(profile: Profile | None) -> str: + """The clipping path's block: hook guidance then title constraints.""" + return hook_block(profile) + title_rules_block(profile) diff --git a/clipwright/pipeline/profiles.py b/clipwright/pipeline/profiles.py new file mode 100644 index 0000000..f4983f8 --- /dev/null +++ b/clipwright/pipeline/profiles.py @@ -0,0 +1,295 @@ +"""Per-channel profiles (PLAN #1, v0). + +A profile is the machine-readable root for one channel's packaging rules: the +title constraints, hook patterns, description template and thumbnail roles that +later items (#3, #4, #6, #10) read. This v0 defines the schema, the validating +loader and the ``CHANNEL_PROFILE`` plumbing only -- nothing here changes how +titles, hooks or descriptions are generated yet. + +Files live at ``/channels/.json``. Every field is optional and +falls back to a sensible default, so a minimal ``{"language": "en"}`` file +loads. Unknown keys are ignored so a newer profile can ship ahead of the code; +known keys with the wrong type or an out-of-domain enum are refused with a +message that names the exact path. +""" + +from __future__ import annotations + +import json +import os +import re +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from clipwright.core.paths import REPO_ROOT + +# ``/channels`` (also ``/app/channels`` in the Docker image). +CHANNELS_DIR = REPO_ROOT / "channels" +# Fallback selector used when ``load_profile`` is called without a slug. +ENV_VAR = "CHANNEL_PROFILE" + +# A slug becomes a filename under CHANNELS_DIR, so it may not contain separators +# or traversal segments. +_SLUG_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$") + +KEYWORD_POSITIONS = frozenset({"start", "middle", "end", "any"}) +NUMBER_POLICIES = frozenset({"allow", "avoid", "require"}) +REQUIRED_SIGNALS = frozenset({"consequence", "curiosity", "either", "none"}) + + +class ProfileError(ValueError): + """A channel profile is missing, unreadable or does not match the schema.""" + + +# --- typed coercion -------------------------------------------------------- + +def _require_mapping(value: Any, where: str) -> Mapping: + if not isinstance(value, Mapping): + raise ProfileError(f"{where} must be a JSON object, got {type(value).__name__}") + return value + + +def _as_str(value: Any, where: str, default: str) -> str: + if value is None: + return default + if not isinstance(value, str): + raise ProfileError(f"{where} must be a string, got {type(value).__name__}") + return value + + +def _as_optional_str(value: Any, where: str) -> str | None: + if value is None: + return None + if not isinstance(value, str): + raise ProfileError(f"{where} must be a string or null, got {type(value).__name__}") + return value + + +def _as_int(value: Any, where: str, default: int) -> int: + if value is None: + return default + # bool is an int subclass in Python; a JSON true is not a valid count. + if isinstance(value, bool) or not isinstance(value, int): + raise ProfileError(f"{where} must be an integer, got {type(value).__name__}") + return value + + +def _as_bool(value: Any, where: str, default: bool) -> bool: + if value is None: + return default + if not isinstance(value, bool): + raise ProfileError(f"{where} must be a boolean, got {type(value).__name__}") + return value + + +def _as_str_list(value: Any, where: str, default: Sequence[str]) -> list[str]: + if value is None: + return list(default) + if isinstance(value, str) or not isinstance(value, Sequence): + raise ProfileError( + f"{where} must be a JSON array of strings, got {type(value).__name__}" + ) + out: list[str] = [] + for i, item in enumerate(value): + if not isinstance(item, str): + raise ProfileError(f"{where}[{i}] must be a string, got {type(item).__name__}") + out.append(item) + return out + + +def _as_dict_list(value: Any, where: str, default: Sequence[Mapping]) -> list[dict]: + if value is None: + return [dict(d) for d in default] + if isinstance(value, str) or not isinstance(value, Sequence): + raise ProfileError( + f"{where} must be a JSON array of objects, got {type(value).__name__}" + ) + out: list[dict] = [] + for i, item in enumerate(value): + if not isinstance(item, Mapping): + raise ProfileError( + f"{where}[{i}] must be a JSON object, got {type(item).__name__}" + ) + out.append(dict(item)) + return out + + +def _as_enum(value: Any, where: str, allowed: frozenset, default: str) -> str: + if value is None: + return default + if value not in allowed: + options = ", ".join(sorted(allowed)) + raise ProfileError(f"{where} must be one of {{{options}}}, got {value!r}") + return value + + +# --- schema ---------------------------------------------------------------- + +@dataclass +class TitleRules: + """Deterministic title constraints (consumed by the #3 validator).""" + + max_chars: int = 70 + mobile_chars: int = 40 + banned_patterns: list[str] = field(default_factory=list) + keyword_position: str = "start" + number_policy: str = "allow" + required_signal: str = "either" + banned_openers: list[str] = field(default_factory=list) + + @classmethod + def from_dict(cls, data: Mapping, where: str = "title_rules") -> "TitleRules": + data = _require_mapping(data, where) + return cls( + max_chars=_as_int(data.get("max_chars"), f"{where}.max_chars", 70), + mobile_chars=_as_int(data.get("mobile_chars"), f"{where}.mobile_chars", 40), + banned_patterns=_as_str_list( + data.get("banned_patterns"), f"{where}.banned_patterns", () + ), + keyword_position=_as_enum( + data.get("keyword_position"), f"{where}.keyword_position", + KEYWORD_POSITIONS, "start", + ), + number_policy=_as_enum( + data.get("number_policy"), f"{where}.number_policy", + NUMBER_POLICIES, "allow", + ), + required_signal=_as_enum( + data.get("required_signal"), f"{where}.required_signal", + REQUIRED_SIGNALS, "either", + ), + banned_openers=_as_str_list( + data.get("banned_openers"), f"{where}.banned_openers", () + ), + ) + + +@dataclass +class ThumbnailRules: + """Thumbnail concept roles and look (consumed by #4).""" + + role_order: list[str] = field( + default_factory=lambda: ["curiosity", "emotion", "technical"] + ) + palette: list[str] = field(default_factory=list) + presenter_photo: bool = False + + @classmethod + def from_dict(cls, data: Mapping, where: str = "thumbnail") -> "ThumbnailRules": + data = _require_mapping(data, where) + return cls( + role_order=_as_str_list( + data.get("role_order"), f"{where}.role_order", + ["curiosity", "emotion", "technical"], + ), + palette=_as_str_list(data.get("palette"), f"{where}.palette", ()), + presenter_photo=_as_bool( + data.get("presenter_photo"), f"{where}.presenter_photo", False + ), + ) + + +@dataclass +class Profile: + """One channel's packaging rules.""" + + slug: str + # Human-readable display name for selectors; falls back to ``slug`` when unset. + name: str = "" + language: str = "en" + tone: str = "" + title_rules: TitleRules = field(default_factory=TitleRules) + hook_patterns: list[str] = field(default_factory=list) + hook_style: str = "" + description_template: str = "" + links: list[str] = field(default_factory=list) + thumbnail: ThumbnailRules = field(default_factory=ThumbnailRules) + default_postiz_integration_id: str | None = None + published_video_history: list[dict] = field(default_factory=list) + + @classmethod + def from_dict(cls, data: Mapping, slug: str) -> "Profile": + data = _require_mapping(data, f"profile {slug!r}") + raw_title = data.get("title_rules") + raw_thumb = data.get("thumbnail") + return cls( + slug=slug, + name=_as_str(data.get("name"), "name", ""), + language=_as_str(data.get("language"), "language", "en"), + tone=_as_str(data.get("tone"), "tone", ""), + title_rules=TitleRules.from_dict({} if raw_title is None else raw_title), + hook_patterns=_as_str_list(data.get("hook_patterns"), "hook_patterns", ()), + hook_style=_as_str(data.get("hook_style"), "hook_style", ""), + description_template=_as_str( + data.get("description_template"), "description_template", "" + ), + links=_as_str_list(data.get("links"), "links", ()), + thumbnail=ThumbnailRules.from_dict({} if raw_thumb is None else raw_thumb), + default_postiz_integration_id=_as_optional_str( + data.get("default_postiz_integration_id"), + "default_postiz_integration_id", + ), + published_video_history=_as_dict_list( + data.get("published_video_history"), "published_video_history", () + ), + ) + + +def load_profile(slug: str | None = None, channels_dir: str | os.PathLike | None = None) -> Profile: + """Load and validate ``channels/.json``. + + ``slug`` wins; when it is omitted the ``CHANNEL_PROFILE`` env var is used. + ``channels_dir`` is test/embedding seam -- it defaults to the repo's + ``channels/`` directory. + """ + resolved = slug or os.environ.get(ENV_VAR) or None + if not resolved: + raise ProfileError(f"no channel profile selected; pass a slug or set {ENV_VAR}") + if not _SLUG_RE.match(resolved): + raise ProfileError( + f"invalid channel slug {resolved!r}; expected letters, digits, '-' or '_'" + ) + + directory = Path(channels_dir) if channels_dir is not None else CHANNELS_DIR + path = directory / f"{resolved}.json" + try: + text = path.read_text(encoding="utf-8") + except FileNotFoundError: + raise ProfileError(f"channel profile not found: {path}") + except OSError as e: + raise ProfileError(f"could not read channel profile {path}: {e}") + + try: + data = json.loads(text) + except json.JSONDecodeError as e: + raise ProfileError(f"malformed JSON in {path}: {e}") + + return Profile.from_dict(data, resolved) + + +def list_profiles(channels_dir: str | os.PathLike | None = None) -> list[dict]: + """List the loadable channel profiles as ``[{"slug", "name"}]``. + + Best-effort by design: every ``channels/*.json`` that validates is included + (sorted by slug) and everything else is skipped, so one malformed profile + cannot break a selector. ``slug`` is the filename stem and ``name`` is the + profile's display name, falling back to ``slug`` when the file omits it. + ``channels_dir`` is the same test/embedding seam as :func:`load_profile`. + """ + directory = Path(channels_dir) if channels_dir is not None else CHANNELS_DIR + if not directory.is_dir(): + return [] + + out: list[dict] = [] + for path in sorted(directory.glob("*.json")): + slug = path.stem + if not _SLUG_RE.match(slug): + continue + try: + profile = load_profile(slug, channels_dir=directory) + except ProfileError: + continue + out.append({"slug": slug, "name": profile.name or slug}) + return out diff --git a/tests/test_channels_endpoint.py b/tests/test_channels_endpoint.py new file mode 100644 index 0000000..f978874 --- /dev/null +++ b/tests/test_channels_endpoint.py @@ -0,0 +1,41 @@ +"""GET /api/channels (PLAN #1, dashboard profile selector). + +Pins the response shape ``{"channels": [{"slug", "name"}]}``, that the seeded +profiles show up with their display names, and that a malformed profile file is +skipped instead of breaking the list. +""" +import asyncio + +import httpx +import pytest + +app_module = pytest.importorskip("clipwright.api.app") + + +def _get(path): + 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.get(path) + return asyncio.run(_do()) + + +def test_returns_seeded_profiles_with_display_names(): + resp = _get("/api/channels") + assert resp.status_code == 200 + data = resp.json() + assert set(data) == {"channels"} + by_slug = {item["slug"]: item["name"] for item in data["channels"]} + assert by_slug["cseea"] == "cseea" + assert by_slug["pedro"] == "Pedro Bento" + assert all(set(item) == {"slug", "name"} for item in data["channels"]) + + +def test_skips_malformed_profile_files(monkeypatch, tmp_path): + (tmp_path / "good.json").write_text('{"name": "Good"}', encoding="utf-8") + (tmp_path / "broken.json").write_text("{ not json", encoding="utf-8") + monkeypatch.setattr(app_module.profiles, "CHANNELS_DIR", tmp_path) + resp = _get("/api/channels") + assert resp.status_code == 200 + assert resp.json() == {"channels": [{"slug": "good", "name": "Good"}]} diff --git a/tests/test_profile_prompts.py b/tests/test_profile_prompts.py new file mode 100644 index 0000000..c4ae0b6 --- /dev/null +++ b/tests/test_profile_prompts.py @@ -0,0 +1,260 @@ +"""Profile -> prompt mapping (PLAN #1, full). + +Two things are pinned here: +1. each ``profile_prompts`` helper encodes the right fields, and the seeded + cseea/pedro profiles produce visibly different blocks; +2. a profile actually reaches the clipping detail prompt and each Studio + generator, while a profile-less call renders the prompt it did before. +""" +from types import SimpleNamespace + +import pytest + +from clipwright.media import thumbnail +from clipwright.pipeline import gemini_worker, profile_prompts, profiles + + +@pytest.fixture(scope="module") +def cseea(): + return profiles.load_profile("cseea") + + +@pytest.fixture(scope="module") +def pedro(): + return profiles.load_profile("pedro") + + +# --- pure mapping ---------------------------------------------------------- + +def test_no_profile_is_the_empty_block(): + assert profile_prompts.title_rules_block(None) == "" + assert profile_prompts.hook_block(None) == "" + assert profile_prompts.description_block(None) == "" + assert profile_prompts.thumbnail_block(None) == "" + assert profile_prompts.clip_rules_block(None) == "" + + +def test_title_rules_block_encodes_every_field(cseea): + block = profile_prompts.title_rules_block(cseea) + assert "CHANNEL TITLE RULES" in block + assert "60" in block and "38" in block # max_chars / mobile_chars + assert "nostalgic and calm" in block # tone + assert "first 3 words" in block # keyword_position=start + assert "curiosity gap" in block # required_signal=curiosity + assert "Avoid numbers" in block # number_policy=avoid + assert '"in this video"' in block # banned_patterns + assert '"Exploring"' in block # banned_openers + + +def test_title_rules_block_differs_per_channel(cseea, pedro): + cseea_block = profile_prompts.title_rules_block(cseea) + pedro_block = profile_prompts.title_rules_block(pedro) + assert cseea_block != pedro_block + assert "consequence or stake" in pedro_block # required_signal=consequence + assert "technical, direct" in pedro_block + assert '"for beginners"' in pedro_block + assert "Avoid numbers" not in pedro_block # pedro allows numbers + + +def test_hook_block_carries_style_and_patterns(cseea, pedro): + cseea_block = profile_prompts.hook_block(cseea) + assert "CHANNEL HOOK RULES" in cseea_block + assert "visual impossibility" in cseea_block + assert '"this shouldn\'t be possible in Alpha"' in cseea_block + assert "working demo" in profile_prompts.hook_block(pedro) + + +def test_description_block_carries_template_links_and_tone(cseea, pedro): + block = profile_prompts.description_block(cseea) + assert "CHANNEL DESCRIPTION RULES" in block + assert "#minecraft #alpha #retro" in block # template, newlines escaped + assert "youtube.com/@cseea" in block # links + assert "nostalgic and calm" in block # tone + assert "github.com/pbento" in profile_prompts.description_block(pedro) + + +def test_thumbnail_block_carries_roles_palette_and_presenter(cseea, pedro): + block = profile_prompts.thumbnail_block(cseea) + assert "curiosity, emotion, technical" in block + assert "mossy green" in block + assert "not expected" in block # presenter_photo=false + pedro_block = profile_prompts.thumbnail_block(pedro) + assert "technical, curiosity, emotion" in pedro_block + assert "available and encouraged" in pedro_block + + +def test_clip_rules_block_composes_hook_then_title(cseea): + block = profile_prompts.clip_rules_block(cseea) + assert block == profile_prompts.hook_block(cseea) + profile_prompts.title_rules_block(cseea) + assert block.index("CHANNEL HOOK RULES") < block.index("CHANNEL TITLE RULES") + + +# --- the detail template is byte-identical without a profile ---------------- + +def _detail_kwargs(): + return dict(video_duration=100, language="es", min_clips=2, max_clips=4, + min_secs=10.0, max_secs=20.0, windows_json="[]") + + +def test_detail_template_empty_block_matches_the_old_template(): + # The old template is exactly the new one with the placeholder token removed; + # formatting both with an empty block must be byte-identical. + kwargs = _detail_kwargs() + old = gemini_worker.DETAIL_PROMPT_TEMPLATE.replace("{profile_rules}", "").format(**kwargs) + new = gemini_worker.DETAIL_PROMPT_TEMPLATE.format(profile_rules="", **kwargs) + assert new == old + assert "CHANNEL" not in new + + +def test_detail_template_block_changes_the_prompt(cseea): + kwargs = _detail_kwargs() + plain = gemini_worker.DETAIL_PROMPT_TEMPLATE.format(profile_rules="", **kwargs) + profiled = gemini_worker.DETAIL_PROMPT_TEMPLATE.format( + profile_rules=profile_prompts.clip_rules_block(cseea), **kwargs) + assert profiled != plain + assert "CHANNEL TITLE RULES" in profiled + assert "CHANNEL HOOK RULES" in profiled + assert "{profile_rules}" not in profiled + + +# --- the clipping detail call uses ACTIVE_PROFILE --------------------------- + +def _dense_transcript(): + return { + "text": "alpha beta gamma delta", + "language": "en", + "segments": [ + {"start": 0, "end": 30, "text": "alpha", + "words": [{"word": " alpha", "start": 0.0, "end": 1.0}]}, + {"start": 30, "end": 60, "text": "beta", + "words": [{"word": " beta", "start": 30.0, "end": 31.0}]}, + {"start": 60, "end": 90, "text": "gamma", + "words": [{"word": " gamma", "start": 60.0, "end": 61.0}]}, + {"start": 90, "end": 120, "text": "delta", + "words": [{"word": " delta", "start": 90.0, "end": 91.0}]}, + ], + } + + +def _capture_detail_prompt(monkeypatch, main, profile): + captured = [] + + def fake_run_stage(client, model_name, items, build_prompt, schema, key, costs, label): + if key == "shorts": + captured.append(build_prompt(items)) + return [] + + monkeypatch.setattr(main, "_run_stage_split", fake_run_stage) + monkeypatch.setattr(main, "ACTIVE_PROFILE", profile) + monkeypatch.setenv("GEMINI_API_KEY", "test") + monkeypatch.setattr(main.llm_backend, "active", lambda: False) + monkeypatch.setattr(main.genai, "Client", lambda **kwargs: object()) + main.get_viral_clips(_dense_transcript(), 120) + return captured + + +def test_active_profile_reaches_the_clip_detail_prompt(monkeypatch, cseea): + main = pytest.importorskip("clipwright.pipeline.main") + captured = _capture_detail_prompt(monkeypatch, main, cseea) + assert captured + assert "CHANNEL TITLE RULES" in captured[0] + assert "CHANNEL HOOK RULES" in captured[0] + + +def test_no_active_profile_leaves_the_clip_detail_prompt_plain(monkeypatch): + main = pytest.importorskip("clipwright.pipeline.main") + captured = _capture_detail_prompt(monkeypatch, main, None) + assert captured + assert "CHANNEL" not in captured[0] + + +# --- the Studio generators ------------------------------------------------ + +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 _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 [])) + + +_BRAINSTORM = '{"transcript_summary": "sum", "candidates": ["Alpha", "Beta"]}' +_CRITIC = ('{"titles": ["Why this broke everything"], "thumbnail_texts": ["A"], ' + '"recommended": []}') +_CONCEPTS = ('{"concepts": [{"text": "BIG", "text_position": "left", ' + '"text_color": "yellow", "scene": "a desk", "why": "w"}]}') + + +def _analyze_prompts(monkeypatch, profile): + client = _RecordingClient([_BRAINSTORM, _CRITIC]) + monkeypatch.setattr(thumbnail, "_frame_parts", lambda *a, **k: []) + monkeypatch.setattr(thumbnail, "genai", SimpleNamespace( + Client=lambda api_key=None, **k: client)) + transcript = {"language": "en", "text": "hello world", + "segments": [{"start": 0.0, "end": 10.0, "text": "hello"}]} + thumbnail.analyze_video_for_titles("key", "video.mp4", transcript=transcript, profile=profile) + return client.models.prompts + + +def test_titles_brainstorm_and_critic_are_profile_tuned(monkeypatch, pedro): + plain = _analyze_prompts(monkeypatch, None) + profiled = _analyze_prompts(monkeypatch, pedro) + assert len(plain) == 2 and len(profiled) == 2 + assert all("CHANNEL" not in p for p in plain) + # The blank line before OUTPUT JSON is preserved without a profile. + assert "no emojis.\n\nOUTPUT JSON" in plain[0] + assert "will win the click.\n\nOUTPUT JSON" in plain[1] + for prompt in profiled: + assert "CHANNEL TITLE RULES" in prompt + assert "CHANNEL HOOK RULES" in prompt + assert profiled != plain + + +def test_thumbnail_concepts_are_profile_tuned(monkeypatch, cseea): + plain_client = _RecordingClient([_CONCEPTS]) + thumbnail.plan_thumbnail_concepts(plain_client, "A title", 1) + profiled_client = _RecordingClient([_CONCEPTS]) + thumbnail.plan_thumbnail_concepts(profiled_client, "A title", 1, profile=cseea) + plain = plain_client.models.prompts[0] + profiled = profiled_client.models.prompts[0] + assert "CHANNEL" not in plain + assert "same layout.\n\nPer concept give:" in plain + assert "CHANNEL THUMBNAIL RULES" in profiled + assert "mossy green" in profiled + assert profiled != plain + + +def test_description_is_profile_tuned(monkeypatch, cseea): + plain_client = _RecordingClient(["DESC"]) + monkeypatch.setattr(thumbnail, "genai", SimpleNamespace( + Client=lambda api_key=None, **k: plain_client)) + thumbnail.generate_youtube_description( + "key", "A title", [{"start": 0, "end": 1, "text": "hi"}], "en", 60) + plain = plain_client.models.prompts[0] + + profiled_client = _RecordingClient(["DESC"]) + monkeypatch.setattr(thumbnail, "genai", SimpleNamespace( + Client=lambda api_key=None, **k: profiled_client)) + thumbnail.generate_youtube_description( + "key", "A title", [{"start": 0, "end": 1, "text": "hi"}], "en", 60, profile=cseea) + profiled = profiled_client.models.prompts[0] + + assert "CHANNEL" not in plain + assert "5000 characters\n\nOUTPUT:" in plain + assert "CHANNEL DESCRIPTION RULES" in profiled + assert "youtube.com/@cseea" in profiled + assert profiled != plain diff --git a/tests/test_profiles.py b/tests/test_profiles.py new file mode 100644 index 0000000..5ee6894 --- /dev/null +++ b/tests/test_profiles.py @@ -0,0 +1,214 @@ +"""Channel profile loader (PLAN #1 v0). + +Covers the happy path, the defaults for a minimal file, the failure modes a +bad ``channels/.json`` produces, slug hardening, and the +``CHANNEL_PROFILE`` env fallback. Also asserts the two seeded profiles load. +""" +import json + +import pytest + +from clipwright.pipeline import profiles + +FULL = { + "name": "Full Channel", + "language": "pt", + "tone": "calm", + "title_rules": { + "max_chars": 55, + "mobile_chars": 30, + "banned_patterns": ["lol"], + "keyword_position": "end", + "number_policy": "avoid", + "required_signal": "curiosity", + "banned_openers": ["Playing"], + }, + "hook_patterns": ["glitch at frame 0"], + "hook_style": "visual impossibility", + "description_template": "{hook}", + "links": ["https://example.test/a"], + "thumbnail": { + "role_order": ["curiosity", "technical"], + "palette": ["green"], + "presenter_photo": True, + }, + "default_postiz_integration_id": "int_1", + "published_video_history": [{"id": "vid_1"}], +} + + +def _write(dir_, slug, data): + path = dir_ / f"{slug}.json" + path.write_text(json.dumps(data), encoding="utf-8") + return path + + +# --- happy path ------------------------------------------------------------ + +def test_full_profile_round_trips(tmp_path): + _write(tmp_path, "full", FULL) + p = profiles.load_profile("full", channels_dir=tmp_path) + + assert p.slug == "full" + assert p.name == "Full Channel" + assert p.language == "pt" + assert p.tone == "calm" + assert p.title_rules.max_chars == 55 + assert p.title_rules.mobile_chars == 30 + assert p.title_rules.banned_patterns == ["lol"] + assert p.title_rules.keyword_position == "end" + assert p.title_rules.number_policy == "avoid" + assert p.title_rules.required_signal == "curiosity" + assert p.title_rules.banned_openers == ["Playing"] + assert p.hook_patterns == ["glitch at frame 0"] + assert p.hook_style == "visual impossibility" + assert p.description_template == "{hook}" + assert p.links == ["https://example.test/a"] + assert p.thumbnail.role_order == ["curiosity", "technical"] + assert p.thumbnail.palette == ["green"] + assert p.thumbnail.presenter_photo is True + assert p.default_postiz_integration_id == "int_1" + assert p.published_video_history == [{"id": "vid_1"}] + + +# --- defaults -------------------------------------------------------------- + +def test_minimal_profile_uses_defaults(tmp_path): + _write(tmp_path, "bare", {}) + p = profiles.load_profile("bare", channels_dir=tmp_path) + + assert p.language == "en" + assert p.name == "" + assert p.tone == "" + assert p.title_rules.max_chars == 70 + assert p.title_rules.mobile_chars == 40 + assert p.title_rules.banned_patterns == [] + assert p.title_rules.keyword_position == "start" + assert p.title_rules.number_policy == "allow" + assert p.title_rules.required_signal == "either" + assert p.title_rules.banned_openers == [] + assert p.hook_patterns == [] + assert p.links == [] + assert p.thumbnail.role_order == ["curiosity", "emotion", "technical"] + assert p.thumbnail.presenter_photo is False + assert p.default_postiz_integration_id is None + assert p.published_video_history == [] + + +def test_partial_nested_section_keeps_sibling_defaults(tmp_path): + _write(tmp_path, "partial", {"title_rules": {"max_chars": 12}}) + p = profiles.load_profile("partial", channels_dir=tmp_path) + assert p.title_rules.max_chars == 12 + assert p.title_rules.mobile_chars == 40 + + +# --- failure modes --------------------------------------------------------- + +def test_missing_file_raises_clear_error(tmp_path): + with pytest.raises(profiles.ProfileError) as exc: + profiles.load_profile("nope", channels_dir=tmp_path) + assert "not found" in str(exc.value) + assert "nope.json" in str(exc.value) + + +def test_malformed_json_raises_clear_error(tmp_path): + (tmp_path / "broken.json").write_text("{ not json", encoding="utf-8") + with pytest.raises(profiles.ProfileError) as exc: + profiles.load_profile("broken", channels_dir=tmp_path) + assert "malformed JSON" in str(exc.value) + + +def test_top_level_must_be_an_object(tmp_path): + (tmp_path / "list.json").write_text("[]", encoding="utf-8") + with pytest.raises(profiles.ProfileError) as exc: + profiles.load_profile("list", channels_dir=tmp_path) + assert "must be a JSON object" in str(exc.value) + + +@pytest.mark.parametrize("bad", [ + {"title_rules": {"max_chars": "big"}}, + {"title_rules": []}, + {"hook_patterns": "not-a-list"}, + {"thumbnail": {"presenter_photo": "yes"}}, + {"title_rules": {"required_signal": "profit"}}, + {"published_video_history": ["not-an-object"]}, +]) +def test_wrong_types_and_enums_are_refused(tmp_path, bad): + _write(tmp_path, "bad", bad) + with pytest.raises(profiles.ProfileError): + profiles.load_profile("bad", channels_dir=tmp_path) + + +def test_slug_cannot_escape_the_channels_dir(tmp_path): + with pytest.raises(profiles.ProfileError) as exc: + profiles.load_profile("../../etc/passwd", channels_dir=tmp_path) + assert "invalid channel slug" in str(exc.value) + + +# --- env fallback ---------------------------------------------------------- + +def test_env_var_selects_the_profile_when_no_slug_given(tmp_path, monkeypatch): + _write(tmp_path, "fromenv", {"tone": "from env"}) + monkeypatch.setenv(profiles.ENV_VAR, "fromenv") + p = profiles.load_profile(channels_dir=tmp_path) + assert p.slug == "fromenv" + assert p.tone == "from env" + + +def test_explicit_slug_wins_over_env(tmp_path, monkeypatch): + _write(tmp_path, "explicit", {"tone": "explicit"}) + _write(tmp_path, "fromenv", {"tone": "from env"}) + monkeypatch.setenv(profiles.ENV_VAR, "fromenv") + p = profiles.load_profile("explicit", channels_dir=tmp_path) + assert p.slug == "explicit" + + +def test_no_slug_and_no_env_is_an_error(tmp_path, monkeypatch): + monkeypatch.delenv(profiles.ENV_VAR, raising=False) + with pytest.raises(profiles.ProfileError): + profiles.load_profile(channels_dir=tmp_path) + + +# --- the seeded profiles --------------------------------------------------- + +@pytest.mark.parametrize("slug", ["cseea", "pedro"]) +def test_seeded_profiles_load(slug): + p = profiles.load_profile(slug) + assert p.slug == slug + assert p.language == "en" + assert p.title_rules.max_chars > 0 + assert p.hook_patterns + + +# --- list_profiles (dashboard selector) ------------------------------------ + +def test_list_profiles_seeded_slugs_use_display_names(): + listed = profiles.list_profiles() + by_slug = {item["slug"]: item["name"] for item in listed} + assert by_slug["cseea"] == "cseea" + assert by_slug["pedro"] == "Pedro Bento" + # Sorted by slug and every entry is exactly {slug, name}. + assert [item["slug"] for item in listed] == sorted(by_slug) + assert all(set(item) == {"slug", "name"} for item in listed) + + +def test_list_profiles_falls_back_to_slug_without_a_name(tmp_path): + _write(tmp_path, "noname", {"language": "en"}) + assert profiles.list_profiles(channels_dir=tmp_path) == [ + {"slug": "noname", "name": "noname"}, + ] + + +def test_list_profiles_skips_malformed_files(tmp_path): + _write(tmp_path, "good", {"name": "Good One"}) + (tmp_path / "broken.json").write_text("{ not json", encoding="utf-8") + (tmp_path / "list.json").write_text("[]", encoding="utf-8") + (tmp_path / "not a slug.json").write_text("{}", encoding="utf-8") + + assert profiles.list_profiles(channels_dir=tmp_path) == [ + {"slug": "good", "name": "Good One"}, + ] + + +def test_list_profiles_missing_dir_is_empty(tmp_path): + assert profiles.list_profiles(channels_dir=tmp_path / "absent") == [] -- 2.45.2 From 655cff2f6449970e268a87e551d10da3723bc91d Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Mon, 5 Oct 2026 16:38:42 +0100 Subject: [PATCH 02/10] feat(clips): word-aligned punch-ins + hook-first boundaries --- clipwright/layouts/punch_in.py | 100 ++++++++++---- clipwright/pipeline/clip_selection.py | 184 ++++++++++++++++++++++++++ tests/test_hook_start.py | 170 ++++++++++++++++++++++++ tests/test_punch_in_beats.py | 93 +++++++++++++ 4 files changed, 521 insertions(+), 26 deletions(-) create mode 100644 tests/test_hook_start.py create mode 100644 tests/test_punch_in_beats.py diff --git a/clipwright/layouts/punch_in.py b/clipwright/layouts/punch_in.py index c76ba8f..b306270 100644 --- a/clipwright/layouts/punch_in.py +++ b/clipwright/layouts/punch_in.py @@ -14,11 +14,14 @@ It rides the TRACK path, widening the existing per-frame crop command from x-only to w/h/x/y, so it composes with the camera trajectory instead of fighting it. Off by default (``PUNCH_IN=1``). -Beat times come from the audio envelope. The transcript would be a better -source (punch on the hook word, not on the loudest syllable), and render() has -no transcript today — ``emphasis_times`` is a plain list of seconds, so wiring -main.py's word timings in later needs no change here. +Beat times come from the audio envelope, aligned to the clip-relative word +onsets the transcript provides (``emphasis_times(word_times=...)``). The +envelope finds the emphasis; the word onset says exactly when it started, so +each peak snaps to the nearest word instead of sitting on the loudest +syllable. A clip with no envelope beats falls back to the word onsets alone, +and without ``word_times`` the beat derivation is exactly what it always was. """ +import bisect import os import numpy as np @@ -59,6 +62,11 @@ BEAT_WINDOW = 0.2 MIN_GAP_SECONDS = 18.0 BEAT_PROMINENCE = 0.60 +# How far an envelope peak may move to land on a word onset. The envelope frame +# is coarse (BEAT_WINDOW); the word's start is exact, so the tolerance is a bit +# wider than the frame rather than equal to it. +WORD_SNAP_SECONDS = 0.5 + def _ease(t): """Smoothstep on [0, 1]. Linear ramps look mechanical at this duration.""" @@ -155,32 +163,72 @@ def sendcmd_lines(boxes, fps, target="crop@c"): return lines -def emphasis_times(video_path, duration, window=BEAT_WINDOW, - min_gap=MIN_GAP_SECONDS, prominence=BEAT_PROMINENCE): - """Seconds where the audio leaps above its own baseline. +def _snap_to_word(t, words, snap): + """``t`` moved to the closest onset in the sorted ``words``, if within + ``snap``. Without a word in range the envelope beat is left where it is.""" + i = bisect.bisect_left(words, t) + best, best_d = t, snap + for j in (i - 1, i): + if 0 <= j < len(words): + d = abs(words[j] - t) + if d <= best_d: + best, best_d = words[j], d + return best - A stand-in for the hook words until the transcript is wired through. Returns - [] for silent or unreadable audio, which simply means no punches. + +def merge_beats(audio_beats, word_times, min_gap=MIN_GAP_SECONDS, + snap=WORD_SNAP_SECONDS): + """Punch beats: envelope emphasis, snapped onto the words that carry it. + + The envelope finds where the energy jumped; a word onset is the precise + instant to push. Each envelope beat is snapped to the nearest word onset + within ``snap`` seconds, which is what turns "the loudest syllable" into + "the word that was loud". With no envelope beats at all — silent or flat + audio — the word onsets themselves become the beats. The result is thinned + to ``min_gap`` so two pushes never overlap. Pure: no audio, no I/O, which + is what makes the beat timing testable without a clip. + """ + words = sorted(word_times or []) + if audio_beats: + candidates = [_snap_to_word(b, words, snap) if words else b + for b in audio_beats] + else: + candidates = list(words) + + times = [] + last = -1e9 + for t in sorted(candidates): + if t - last >= min_gap: + times.append(round(t, 3)) + last = t + return times + + +def emphasis_times(video_path, duration, window=BEAT_WINDOW, + min_gap=MIN_GAP_SECONDS, prominence=BEAT_PROMINENCE, + word_times=None): + """Seconds where the clip should punch in. + + Audio envelope peaks, merged with ``word_times`` — optional clip-relative + word onsets in seconds (clip start = 0), as produced from the transcript. + Returns [] for silent, word-less input, which simply means no punches. """ from clipwright.layouts import active_speaker envelope = active_speaker.audio_envelope(video_path, 0.0, duration, window_s=window) - if not envelope: - return [] + audio_beats = [] + if envelope: + values = np.asarray(envelope, dtype=float) + baseline = float(np.median(values)) + peak = float(values.max()) + if peak - baseline > 1e-6: + threshold = baseline + (peak - baseline) * prominence + last = -1e9 + for i, v in enumerate(values): + t = i * window + if v >= threshold and t - last >= min_gap: + audio_beats.append(t) + last = t - values = np.asarray(envelope, dtype=float) - baseline = float(np.median(values)) - peak = float(values.max()) - if peak - baseline <= 1e-6: - return [] - - threshold = baseline + (peak - baseline) * prominence - times = [] - last = -1e9 - for i, v in enumerate(values): - t = i * window - if v >= threshold and t - last >= min_gap: - times.append(round(t, 3)) - last = t - return times + return merge_beats(audio_beats, word_times, min_gap=min_gap) diff --git a/clipwright/pipeline/clip_selection.py b/clipwright/pipeline/clip_selection.py index 0b75093..229d8d8 100644 --- a/clipwright/pipeline/clip_selection.py +++ b/clipwright/pipeline/clip_selection.py @@ -5,6 +5,8 @@ Standard-library only so both main.py and gemini_worker.py can import it and the logic stays unit-testable without the heavy video dependencies. """ +import re + # USD per 1M tokens (input, output incl. thinking), from ai.google.dev pricing. MODEL_PRICES = { "gemini-3.5-flash": (1.50, 9.00), @@ -348,3 +350,185 @@ def snap_clip_to_words(start, end, words, video_duration, if new_end <= new_start or new_end - new_start < min_duration: return original return (round(new_start, 3), round(new_end, 3)) + + +# --- Hook-first boundaries (#2a) ------------------------------------------- +# The first seconds decide the swipe. A model-proposed clip routinely opens on +# wind-up ("so today we're going to...") and buries the question, the number or +# the stakes 3-8s in. Word timestamps are ground truth, so the start can be +# moved onto the first strong spoken hook deterministically — no LLM, no key. +# +# These are the signal vocabularies the scan combines. A token matching ANY set +# is a hook; the EARLIEST such token inside the allowed trim window wins. They +# are deliberately conservative: a miss leaves the clip untouched, a false +# positive only advances the start a bounded amount (see the env caps). +_HOOK_INTERROGATIVES = frozenset({ + "what", "why", "how", "when", "where", "who", "whom", "whose", "which", + "is", "are", "was", "were", "do", "does", "did", "can", "could", "would", + "should", "will", "shall", +}) +_HOOK_IMPERATIVES = frozenset({ + "look", "watch", "imagine", "think", "stop", "try", "check", "see", + "listen", "remember", "forget", "consider", "notice", "suppose", "picture", + "keep", "take", "put", "go", "come", "use", "make", "let", "dont", "show", + "tell", "explain", "build", "create", "write", "read", "open", "close", + "click", "press", "type", "install", "run", "fix", "never", "always", +}) +_HOOK_NUMBERS = frozenset({ + "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", + "nine", "ten", "eleven", "twelve", "hundred", "thousand", "million", + "billion", "half", "quarter", "twice", "once", "double", "triple", + "dozen", "percent", "first", "second", "third", +}) +_HOOK_CONTRAST = frozenset({ + "but", "until", "actually", "instead", "except", "however", "though", + "although", "whereas", "yet", "still", "suddenly", "wait", "unless", + "otherwise", "despite", "nevertheless", "contrary", "opposite", "reverse", +}) +_HOOK_STAKES = frozenset({ + "never", "always", "first", "worst", "bug", "bugs", "crash", "crashes", + "crashed", "crashing", "broke", "broken", "break", "wrong", "lost", "lose", + "losing", "fail", "failed", "fails", "failure", "dies", "death", "dead", + "kill", "killed", "destroy", "destroyed", "ruin", "ruined", "disaster", + "mistake", "error", "errors", "segfault", "danger", "dangerous", "scared", + "terrified", "panic", "emergency", "critical", "fatal", "illegal", + "corrupt", "corrupted", "hacked", "stolen", "missing", "gone", "worse", +}) +# Pure hesitation / connective words that are never hooks. The scan simply +# walks past them, so they end up in the trimmed wind-up; they must not count. +_HOOK_FILLER = frozenset({ + "uh", "um", "erm", "ah", "eh", "hmm", "mmm", "so", "well", "okay", "ok", + "yeah", "yep", "right", "and", "then", "like", "basically", "just", + "you", "know", "i", "mean", "we", "the", "a", "an", "it", "that", "this", +}) + +# Conservative defaults: HOOK_FIRST is on, but a start only ever moves a few +# seconds and never more than a quarter of the clip. +_HOOK_FIRST_DEFAULT_MAX_TRIM = 4.0 +_HOOK_FIRST_DEFAULT_MAX_FRACTION = 0.25 +# A trim smaller than this is noise; leaving the clip alone is kinder than a +# sub-frame jitter that only complicates the render. +_MIN_HOOK_TRIM = 0.2 + + +def _env_float(name, default): + """Read a float env var, falling back to ``default`` on garbage/absence.""" + import os + + raw = os.environ.get(name) + if raw is None or str(raw).strip() == "": + return default + try: + return float(raw) + except (TypeError, ValueError): + return default + + +def hook_first_enabled(): + """Whether to move clip starts onto the first spoken hook. + + ``HOOK_FIRST`` defaults ON (conservatively capped); set it to ``0`` / + ``false`` / ``no`` / ``off`` to disable the pass for A/B runs. + """ + import os + + raw = os.environ.get("HOOK_FIRST") + if raw is None: + return True + return str(raw).strip().lower() not in ("", "0", "false", "no", "off") + + +def _hook_token(raw): + """Normalise a Whisper word to a bare lowercase token. + + Words are inconsistent about a leading space (" word" vs "word") and carry + trailing punctuation ("crash!"), so both are stripped before matching. + """ + token = str(raw or "").strip().lower() + token = re.sub(r"^[^0-9a-z]+", "", token) + token = re.sub(r"[^0-9a-z]+$", "", token) + return token + + +def _is_hook_token(token): + """True when a normalised token carries one of the hook signals.""" + if not token or token in _HOOK_FILLER: + return False + if any(ch.isdigit() for ch in token): + return True + return (token in _HOOK_INTERROGATIVES + or token in _HOOK_IMPERATIVES + or token in _HOOK_NUMBERS + or token in _HOOK_CONTRAST + or token in _HOOK_STAKES) + + +def find_hook_start(words, clip_start, clip_end, min_duration=15.0, + max_trim=None, max_fraction=None): + """The strongest deterministic start for a clip, or ``None``. + + Scans the opening of ``[clip_start, clip_end]`` for the EARLIEST word that + matches a hook signal (question, imperative, number/quantity, contrast or + stakes — see the vocabularies above). Leading hesitation, silence and + filler do not match, so they fall into the trimmed wind-up. Returns the + hook word's start when it is a legal trim, else ``None`` (no change — a + clip without a clear hook is left exactly where snapping put it). + + ``words`` is the whole-video ``[{'w','s','e'}, ...]`` list (same shape + ``snap_clip_to_words`` takes). The trim is bounded three ways so the pass + can never wreck a clip: + + * ``max_trim`` seconds (env ``HOOK_FIRST_MAX_TRIM``, default 4.0) + * ``max_fraction`` of the clip's duration (env ``HOOK_FIRST_MAX_FRACTION``, + default 0.25) + * the remaining clip must still be at least ``min_duration`` seconds. + """ + try: + clip_start = float(clip_start) + clip_end = float(clip_end) + except (TypeError, ValueError): + return None + duration = clip_end - clip_start + if duration <= 0: + return None + + if max_trim is None: + max_trim = _env_float("HOOK_FIRST_MAX_TRIM", + _HOOK_FIRST_DEFAULT_MAX_TRIM) + if max_fraction is None: + max_fraction = _env_float("HOOK_FIRST_MAX_FRACTION", + _HOOK_FIRST_DEFAULT_MAX_FRACTION) + try: + max_trim = max(0.0, float(max_trim)) + max_fraction = max(0.0, float(max_fraction)) + min_duration = float(min_duration) + except (TypeError, ValueError): + return None + + cap = min(max_trim, max_fraction * duration) + if cap < _MIN_HOOK_TRIM: + return None + latest = clip_start + cap + + hook_start = None + for word in words or []: + try: + word_start = float(word.get("s", 0)) + except (AttributeError, TypeError, ValueError): + continue + if word_start < clip_start or word_start > latest: + continue + if word_start >= clip_end: + continue + if _is_hook_token(_hook_token(word.get("w"))): + if hook_start is None or word_start < hook_start: + hook_start = word_start + + if hook_start is None: + return None + trim = hook_start - clip_start + if trim < _MIN_HOOK_TRIM: + return None + if clip_end - hook_start < min_duration: + return None + return round(hook_start, 3) diff --git a/tests/test_hook_start.py b/tests/test_hook_start.py new file mode 100644 index 0000000..02390ab --- /dev/null +++ b/tests/test_hook_start.py @@ -0,0 +1,170 @@ +"""Hook-first clip boundaries: the pure ``find_hook_start`` pass (#2a). + +The first two seconds decide the swipe, so the pass moves a clip's start off +its wind-up and onto the earliest strong spoken token. It is deterministic and +word-based (no LLM) and must fail safe: no clear hook -> no change, and the +trim is capped by seconds, by fraction of the clip, and by the minimum clip +duration. +""" + +from clipwright.pipeline.clip_selection import ( + find_hook_start, + hook_first_enabled, +) + + +def _w(word, s, e): + return {"w": word, "s": s, "e": e} + + +class TestPicksEarliestHook: + def test_picks_the_earliest_hook_after_the_wind_up(self): + words = [ + _w(" so", 0.0, 0.3), + _w(" uh", 0.3, 0.6), + _w(" why", 1.2, 1.6), # interrogative — first hook + _w(" do", 1.6, 1.8), + _w(" we", 1.8, 2.0), + ] + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0, + max_trim=5.0, max_fraction=0.5) == 1.2 + + def test_earliest_wins_across_signal_categories(self): + words = [ + _w(" okay", 0.0, 0.3), + _w(" 3", 0.8, 1.1), # number + _w(" but", 1.4, 1.7), # contrast + _w(" crash", 2.0, 2.4), # stakes + ] + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0, + max_trim=5.0, max_fraction=0.5) == 0.8 + + def test_start_is_absolute_not_relative_to_the_clip(self): + words = [_w(" huh", 100.0, 100.3), _w(" why", 103.0, 103.4)] + assert find_hook_start(words, 100.0, 140.0, min_duration=15.0, + max_trim=5.0, max_fraction=0.5) == 103.0 + + def test_a_clip_already_on_its_hook_is_left_alone(self): + # trim ~0 is noise; returning None means "do not touch". + words = [_w(" bug", 10.0, 10.3), _w(" but", 12.0, 12.3)] + assert find_hook_start(words, 10.0, 40.0, min_duration=15.0, + max_trim=5.0, max_fraction=0.5) is None + + +class TestTrimCaps: + def test_respects_max_trim_seconds(self): + words = [_w(" uh", 0.0, 0.3), _w(" why", 6.0, 6.4)] + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0, + max_trim=4.0, max_fraction=1.0) is None + # Just inside the cap it fires. + words[1] = _w(" why", 3.9, 4.3) + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0, + max_trim=4.0, max_fraction=1.0) == 3.9 + + def test_respects_max_fraction_of_the_clip(self): + words = [_w(" uh", 0.0, 0.3), _w(" why", 4.0, 4.4)] + # duration 20, 10% -> 2.0s cap, so a 4.0s hook is out of reach. + assert find_hook_start(words, 0.0, 20.0, min_duration=5.0, + max_trim=100.0, max_fraction=0.1) is None + # 50% -> 10s cap, the same hook is reachable. + assert find_hook_start(words, 0.0, 20.0, min_duration=5.0, + max_trim=100.0, max_fraction=0.5) == 4.0 + + def test_zero_cap_never_moves(self): + words = [_w(" why", 1.0, 1.4)] + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0, + max_trim=0.0, max_fraction=1.0) is None + + def test_min_duration_wins_over_the_caps(self): + # Hook at 2.0 is within the trim cap but would leave 14s < 15s. + words = [_w(" why", 2.0, 2.4)] + assert find_hook_start(words, 0.0, 16.0, min_duration=15.0, + max_trim=5.0, max_fraction=0.5) is None + + def test_degenerate_bounds_do_not_crash(self): + words = [_w(" why", 1.0, 1.4)] + assert find_hook_start(words, 5.0, 5.0, min_duration=15.0) is None + assert find_hook_start(words, 0.0, 0.0, min_duration=15.0) is None + + +class TestNoHook: + def test_returns_none_without_a_hook(self): + words = [ + _w(" and", 0.0, 0.3), + _w(" then", 0.3, 0.6), + _w(" we", 0.6, 0.9), + _w(" the", 0.9, 1.2), + ] + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0, + max_trim=5.0, max_fraction=0.5) is None + + def test_filler_alone_is_not_a_hook(self): + words = [_w(" um", 0.0, 0.2), _w(" okay", 0.2, 0.5), + _w(" yeah", 0.5, 0.8)] + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0) is None + + def test_empty_or_malformed_words_fail_safe(self): + assert find_hook_start(None, 0.0, 30.0, min_duration=15.0) is None + assert find_hook_start([], 0.0, 30.0, min_duration=15.0) is None + assert find_hook_start(["junk", {"no_s": 1}], 1.0, 30.0, + min_duration=15.0) is None + + def test_clip_bounds_that_do_not_parse(self): + assert find_hook_start([_w(" why", 1.0, 1.4)], None, 30.0) is None + + +class TestTokenNormalisation: + def test_words_without_leading_spaces_still_match(self): + words = [_w("uh", 0.0, 0.3), _w("Why", 1.0, 1.4)] + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0, + max_trim=5.0, max_fraction=0.5) == 1.0 + + def test_case_and_trailing_punctuation_are_stripped(self): + words = [_w(" Uh,", 0.0, 0.3), _w("CRASH!", 1.0, 1.4)] + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0, + max_trim=5.0, max_fraction=0.5) == 1.0 + + def test_numeric_tokens_are_hooks(self): + assert find_hook_start([_w(" 2024", 1.0, 1.4)], 0.0, 30.0, + min_duration=15.0, max_trim=5.0, + max_fraction=0.5) == 1.0 + + def test_empty_word_text_is_ignored(self): + words = [_w("", 0.5, 0.6), _w(" ", 0.6, 0.7), _w(" how", 1.0, 1.4)] + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0, + max_trim=5.0, max_fraction=0.5) == 1.0 + + +class TestEnvConfig: + def test_reads_max_trim_from_env(self, monkeypatch): + monkeypatch.setenv("HOOK_FIRST_MAX_TRIM", "1.0") + monkeypatch.setenv("HOOK_FIRST_MAX_FRACTION", "1.0") + words = [_w(" uh", 0.0, 0.3), _w(" why", 2.0, 2.4)] + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0) is None + words[1] = _w(" why", 0.8, 1.2) + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0) == 0.8 + + def test_reads_max_fraction_from_env(self, monkeypatch): + monkeypatch.setenv("HOOK_FIRST_MAX_TRIM", "100") + monkeypatch.setenv("HOOK_FIRST_MAX_FRACTION", "0.1") + words = [_w(" uh", 0.0, 0.3), _w(" why", 4.0, 4.4)] + assert find_hook_start(words, 0.0, 20.0, min_duration=5.0) is None + + def test_garbage_env_falls_back_to_defaults(self, monkeypatch): + monkeypatch.setenv("HOOK_FIRST_MAX_TRIM", "not-a-number") + monkeypatch.setenv("HOOK_FIRST_MAX_FRACTION", "") + words = [_w(" why", 3.5, 3.9)] + assert find_hook_start(words, 0.0, 30.0, min_duration=15.0) == 3.5 + + def test_enabled_is_on_by_default(self, monkeypatch): + monkeypatch.delenv("HOOK_FIRST", raising=False) + assert hook_first_enabled() is True + + def test_enabled_can_be_switched_off(self, monkeypatch): + for raw in ("0", "false", "FALSE", "no", "off"): + monkeypatch.setenv("HOOK_FIRST", raw) + assert hook_first_enabled() is False + + def test_enabled_explicit_true(self, monkeypatch): + monkeypatch.setenv("HOOK_FIRST", "1") + assert hook_first_enabled() is True diff --git a/tests/test_punch_in_beats.py b/tests/test_punch_in_beats.py new file mode 100644 index 0000000..3884509 --- /dev/null +++ b/tests/test_punch_in_beats.py @@ -0,0 +1,93 @@ +"""Word-aligned punch-in beats: the pure derivation in punch_in.emphasis_times. + +#2b moved beat timing from audio-envelope-only to the envelope snapped onto +clip-relative word onsets. These tests pin the merge itself (no audio file +needed) and the one behaviour that must not change: no word times -> exactly +the old audio-only result. +""" +import pytest + +from clipwright.layouts import punch_in +from clipwright.layouts.punch_in import merge_beats + + +class TestMergeBeats: + def test_no_words_is_audio_only(self): + assert merge_beats([1.0, 15.0], [], min_gap=4.0) == [1.0, 15.0] + assert merge_beats([1.0, 15.0], None, min_gap=4.0) == [1.0, 15.0] + + def test_envelope_beat_snaps_to_a_nearby_word(self): + # The envelope peak sits 0.2s off the spoken word: the word is exact. + assert merge_beats([10.0], [10.2], min_gap=4.0) == [10.2] + + def test_a_distant_word_does_not_move_the_envelope_beat(self): + # 5.0 is nowhere near either peak, so neither peak is re-timed. + assert merge_beats([1.0, 30.0], [5.0], min_gap=4.0) == [1.0, 30.0] + + def test_words_become_beats_when_audio_has_none(self): + assert merge_beats([], [3.0, 40.0], min_gap=18.0) == [3.0, 40.0] + + def test_beats_are_thinned_to_the_minimum_gap(self): + # 2 and 4 collide at gap 10; the earliest wins, 20 keeps its own slot. + assert merge_beats([2.0, 4.0, 20.0], [], min_gap=10.0) == [2.0, 20.0] + + def test_result_is_sorted_and_rounded(self): + assert merge_beats([12.3456], [], min_gap=4.0) == [12.346] + assert merge_beats([], [3.0, 12.3456], min_gap=4.0) == [3.0, 12.346] + + +class TestEmphasisTimesWithWords: + def _envelope_spike(self, monkeypatch, beat_index=10, value=1.0, length=50): + from clipwright.layouts import active_speaker + envelope = [0.0] * length + envelope[beat_index] = value + monkeypatch.setattr(active_speaker, "audio_envelope", + lambda *a, **k: envelope) + return beat_index * 0.2 # window defaults to BEAT_WINDOW + + def test_silent_audio_with_words_still_yields_word_beats(self, monkeypatch): + from clipwright.layouts import active_speaker + monkeypatch.setattr(active_speaker, "audio_envelope", + lambda *a, **k: []) + assert punch_in.emphasis_times("x.mp4", 30.0, word_times=[4.0]) == [4.0] + + def test_no_words_keeps_the_old_audio_only_result(self, monkeypatch): + beat = self._envelope_spike(monkeypatch, beat_index=10) + assert punch_in.emphasis_times("x.mp4", 20.0) == [round(beat, 3)] + + def test_word_snaps_the_envelope_spike_onto_itself(self, monkeypatch): + beat = self._envelope_spike(monkeypatch, beat_index=10) + times = punch_in.emphasis_times("x.mp4", 20.0, word_times=[beat + 0.1]) + assert times == [round(beat + 0.1, 3)] + + def test_empty_word_list_is_backward_compatible(self, monkeypatch): + beat = self._envelope_spike(monkeypatch, beat_index=5) + assert (punch_in.emphasis_times("x.mp4", 20.0, word_times=[]) + == [round(beat, 3)]) + + +class TestClipWordOnsets: + def _onsets(self, transcript, start, end): + pytest.importorskip("clipwright.pipeline.main") + from clipwright.pipeline.main import clip_word_onsets + return clip_word_onsets(transcript, start, end) + + def test_words_become_clip_relative_seconds(self): + transcript = {"segments": [{"words": [ + {"word": "a", "start": 100.0, "end": 100.5}, + {"word": "b", "start": 102.0, "end": 102.5}, + {"word": "c", "start": 111.0, "end": 111.5}, # after the clip + ]}]} + assert self._onsets(transcript, 100.0, 110.0) == [0.0, 2.0] + + def test_boundary_words_are_clamped_into_the_clip(self): + transcript = {"segments": [{"words": [ + {"word": "x", "start": 98.0, "end": 101.0}, # starts before + {"word": "y", "start": 109.0, "end": 112.0}, # ends after + ]}]} + assert self._onsets(transcript, 100.0, 110.0) == [0.0, 9.0] + + def test_no_transcript_or_words_is_empty(self): + assert self._onsets(None, 0.0, 10.0) == [] + assert self._onsets({"segments": []}, 0.0, 10.0) == [] + assert self._onsets({"segments": [{"text": "hi"}]}, 0.0, 10.0) == [] -- 2.45.2 From ba1d337f3afe454dae7b011baadd9acfbf5473b5 Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Mon, 5 Oct 2026 16:38:42 +0100 Subject: [PATCH 03/10] feat(layout): code/terminal vertical layout + screencast dead-wire fix --- clipwright/layouts/code_layout.py | 909 ++++++++++++++++++++++++ clipwright/layouts/layout_picker.py | 3 + clipwright/layouts/reframe_v2.py | 88 ++- clipwright/pipeline/hook_grounding.py | 2 +- clipwright/tools/verify_code_layout.py | 169 +++++ tests/e2e/pipeline/test_layout_stage.py | 88 +++ tests/test_code_layout.py | 231 ++++++ tests/test_layout_picker.py | 3 +- 8 files changed, 1487 insertions(+), 6 deletions(-) create mode 100644 clipwright/layouts/code_layout.py create mode 100644 clipwright/tools/verify_code_layout.py create mode 100644 tests/test_code_layout.py diff --git a/clipwright/layouts/code_layout.py b/clipwright/layouts/code_layout.py new file mode 100644 index 0000000..ac2f424 --- /dev/null +++ b/clipwright/layouts/code_layout.py @@ -0,0 +1,909 @@ +"""CODE/TERMINAL vertical layout: an IDE or terminal recording in 9:16. + +The case every screen layout here handles badly: a maximized 1440p editor or a +terminal window. The existing SCREENCAST layout treats it as "content over a +presenter", which on a code recording means the output is the whole 1440p frame +shrunk to a 608px strip — 24px of glyph height at best, unreadable on a phone. + +What a code recording actually needs is the opposite trade. The viewer has to +read characters, so the *pane* is cropped to one column of code and scaled up to +fill the width, with the source's blur as decorative filler above and below, and +the bottom ~15% left clear for captions. When the pane is taller than the output +band, a crop window has to follow the active line (a `sendcmd` pan) so the line +being typed stays on screen. + +Design, following the ``camera_inset`` pattern: + + - module ``ENABLED`` read from ``CODE_LAYOUT`` (off by default); + - ``detect_code_pane`` -> geometry (a self-contained edge/row-column detector, + like ``split_layout.detect_split_scenes``: no ``content_ranges`` dead wire); + - pure geometry helpers (``pane_from_projections``, ``stable_pane``, + ``fit_window``, ``follow_sendcmd_lines``) so the decisions are unit-testable + without OpenCV; + - ``code_filtergraph`` -> crop -> scale -> overlay on a blurred backdrop. + +Everything tunable is an env-overridable constant. The thresholds were set from +first principles and *must* be calibrated against a real 1440p corpus with +``clipwright/tools/verify_code_layout.py`` before the layout is enabled by +default. + +Import-time cost is ``numpy`` only; ``cv2`` is imported lazily inside the frame +functions so the unit suite (which has no OpenCV) still collects this module. +""" +import os + +import numpy as np + +from clipwright.media.ffmpeg_utils import blurred_backdrop + +# Off by default: a wrong CODE crop shows a wall of clipped glyphs, which is a +# worse failure than leaving a code clip on the TRACK/WIDE default. +ENABLED = os.environ.get("CODE_LAYOUT", "0") == "1" + +# --------------------------------------------------------------------------- +# Env-overridable tuning. See clipwright/tools/verify_code_layout.py for the +# corpus pass that produces real numbers for these; the defaults are estimates. +# --------------------------------------------------------------------------- + +# Pan the crop window to keep the active line visible on a tall pane. +FOLLOW_ENABLED = os.environ.get("CODE_FOLLOW", "1") == "1" + +# Extra zoom on top of "fit the pane width to the output width". 1.0 keeps the +# whole pane width; >1 crops a narrower column and scales it up (bigger glyphs). +ZOOM = float(os.environ.get("CODE_ZOOM", "1.0")) + +# Minimum horizontal scale (out_w / pane_w). Below this the pane is being +# downscaled so far that the text stops being readable, and the caller should +# fall back to SCREENCAST/WIDE. At 1440p maximized, out_w/pane_w == 1080/1440 == +# 0.75 exactly, so a maximized editor sits on the boundary and a maximized +# ultrawide falls through. +MIN_SCALE = float(os.environ.get("CODE_MIN_SCALE", "0.75")) + +# Face/camera band height, as a fraction of out_h, when a cam_box is supplied. +CAMERA_BAND_RATIO = float(os.environ.get("CODE_CAMERA_BAND", "0.18")) + +# Bottom band reserved for captions, as a fraction of out_h. +CAPTION_BAND_RATIO = float(os.environ.get("CODE_CAPTION_BAND", "0.15")) + +# Pane gates, as a fraction of the frame. A corner panel is not a code pane. +PANE_MIN_WIDTH_FRAC = float(os.environ.get("CODE_PANE_MIN_WIDTH", "0.35")) +PANE_MIN_HEIGHT_FRAC = float(os.environ.get("CODE_PANE_MIN_HEIGHT", "0.25")) + +# Edge-density floor inside the pane (fraction of pixels above the Sobel +# threshold). Flat wallpapers and photos fall below it. +EDGE_DENSITY_FLOOR = float(os.environ.get("CODE_EDGE_DENSITY", "0.02")) + +# Temporal stability: the pane centre must stay within this fraction of the +# frame across samples, for at least this fraction of them. +STABILITY_TOLERANCE = float(os.environ.get("CODE_STABILITY_TOLERANCE", "0.04")) +STABILITY_MIN_FRAC = float(os.environ.get("CODE_STABILITY_FRAC", "0.6")) + +# Detection runs on a copy at most this wide. Sobel/close is O(pixels) and the +# pane geometry does not need full resolution. +DETECT_MAX_WIDTH = int(os.environ.get("CODE_DETECT_WIDTH", "960")) + +# Wide-short morphological close: joins glyphs into horizontal line runs +# without merging adjacent text lines (which a square kernel does). +CLOSE_KERNEL = (35, 3) + +# Fraction of the projection max that counts as pane edge mass. +PROJ_THRESHOLD_RATIO = float(os.environ.get("CODE_PROJ_THRESHOLD", "0.15")) + +# Below this scaled Sobel magnitude a frame contributes no edge map. +SOBEL_FLOOR = float(os.environ.get("CODE_SOBEL_FLOOR", "8.0")) +SOBEL_RATIO = 0.15 + +# Active-line tracking. +ACTIVE_MAX_WIDTH = int(os.environ.get("CODE_ACTIVE_WIDTH", "480")) +ACTIVE_BAND_FRAC = 0.20 +ACTIVE_MIN_CONCENTRATION = float( + os.environ.get("CODE_ACTIVE_CONCENTRATION", "0.35")) +ACTIVE_MIN_MASS = float(os.environ.get("CODE_ACTIVE_MASS", "1500")) + +# Editor classification: syntax highlighting raises chroma variance above a +# plain terminal's. +EDITOR_SAT_STD = float(os.environ.get("CODE_EDITOR_SAT_STD", "28")) +GUTTER_FRACTION = 0.12 + +# IDE chrome masking. A maximized editor's window is the whole 2560px of a 1440p +# source, so a whole-window pane scales at 1080/2560 ~= 0.42 and trips +# MIN_SCALE. What we want is the TEXT COLUMN: the activity bar and sidebar sit +# in the left margin and the minimap in the right, each separated from the code +# by a sustained blank border. The detector searches within these margins for +# that blank run and cuts there; with no chrome (a bare terminal) there is no +# run and the full width is kept. Widths vary by theme and zoom — tune +# CODE_CHROME_* and CODE_TEXT_* from tools/verify_code_layout.py. +CHROME_LEFT_FRAC = float(os.environ.get("CODE_CHROME_LEFT", "0.22")) +CHROME_RIGHT_FRAC = float(os.environ.get("CODE_CHROME_RIGHT", "0.10")) +CHROME_BOTTOM_FRAC = float(os.environ.get("CODE_CHROME_BOTTOM", "0.03")) +# A "gap" is a sustained run of columns below this share of the text max. +GAP_FRAC = float(os.environ.get("CODE_GAP_FRAC", "0.08")) +GAP_PX = int(os.environ.get("CODE_GAP_PX", "4")) +TEXT_CORE_FRAC = float(os.environ.get("CODE_TEXT_CORE", "0.35")) +TEXT_MIN_WIDTH_FRAC = float(os.environ.get("CODE_TEXT_MIN_WIDTH", "0.2")) + +# Per-scene verification: share of frames sampled inside the pane that must +# still read as code for the scene to keep CODE (otherwise its other verdict +# stands). A cutaway to the facecam fails the texture/palette checks. +SCENE_CODE_FRAC = float(os.environ.get("CODE_SCENE_FRAC", "0.5")) + + +# --------------------------------------------------------------------------- +# Pure geometry (no cv2): projections -> pane, stability, band layout, sendcmd. +# --------------------------------------------------------------------------- + +def _extent(projection, threshold): + """First/last index above ``threshold`` (end exclusive), or None.""" + idx = np.flatnonzero(np.asarray(projection, dtype=float) > threshold) + if idx.size == 0: + return None + return int(idx[0]), int(idx[-1]) + 1 + + +def pane_from_projections(row_proj, col_proj, frame_w, frame_h, + min_width_frac=PANE_MIN_WIDTH_FRAC, + min_height_frac=PANE_MIN_HEIGHT_FRAC, + threshold_ratio=PROJ_THRESHOLD_RATIO): + """Locate the code pane from 1-D row/column edge projections. + + ``row_proj`` is per-row edge mass (length = pane-space height) and + ``col_proj`` per-column. The pane is the bounding extent of edge mass above + a fraction of each projection's own max: text lines are many separated rows + of mass, so a "longest contiguous run" would lock onto a single line. The + extent is in the same coordinate space as ``frame_w``/``frame_h`` (detection + passes the downscaled size; the fractions are scale-invariant). + + Returns ``(x, y, w, h)`` or None when the box is missing or fails either + size gate. + """ + rows = np.asarray(row_proj, dtype=float) + cols = np.asarray(col_proj, dtype=float) + if rows.size == 0 or cols.size == 0: + return None + if rows.max() <= 0 or cols.max() <= 0: + return None + ry = _extent(rows, threshold_ratio * rows.max()) + cx = _extent(cols, threshold_ratio * cols.max()) + if ry is None or cx is None: + return None + y0, y1 = ry + x0, x1 = cx + w, h = x1 - x0, y1 - y0 + if w < min_width_frac * frame_w or h < min_height_frac * frame_h: + return None + return (x0, y0, w, h) + + +def _smooth(values, window=9): + v = np.asarray(values, dtype=float) + if window <= 1 or v.size < window: + return v + kernel = np.ones(window, dtype=float) / window + return np.convolve(v, kernel, mode="same") + + +def _gaps(below, gap_px): + """(start, end) of every sustained True run in a boolean array.""" + out = [] + start = None + for i, flag in enumerate(below): + if flag and start is None: + start = i + elif not flag and start is not None: + if i - start >= gap_px: + out.append((start, i)) + start = None + if start is not None and len(below) - start >= gap_px: + out.append((start, len(below))) + return out + + +def text_column_extent(col_proj, frame_w, left_skip_frac=CHROME_LEFT_FRAC, + right_skip_frac=CHROME_RIGHT_FRAC, + core_frac=TEXT_CORE_FRAC, + min_width_frac=TEXT_MIN_WIDTH_FRAC, + gap_frac=GAP_FRAC, gap_px=GAP_PX, smooth=9): + """(x0, x1) of the editor text column, with IDE chrome cut off. + + ``col_proj`` is per-column edge mass. The whole extent of edge mass is + first-to-last above ``core_frac`` of the max (text fills nearly every + column across many lines, so a longest-run would lock onto one block). The + left and right margins are then searched for a sustained blank border — the + gap between the sidebar and the code, and between the code and the + minimap — and the extent is cut at the innermost one. A bare terminal has + no such border and keeps its full width. Returns None when no run clears + ``min_width_frac``. + """ + cols = _smooth(col_proj, smooth) + if cols.size == 0: + return None + top = float(cols.max()) + if top <= 0: + return None + core = cols > core_frac * top + if not core.any(): + return None + first = int(np.argmax(core)) + last = int(len(core) - np.argmax(core[::-1])) + + thr = gap_frac * top + x0 = first + window = cols[first:first + int(round(left_skip_frac * frame_w))] + gaps = _gaps(window < thr, max(2, gap_px)) + if gaps: + x0 = first + gaps[-1][1] + + x1 = last + rstart = max(x0, last - int(round(right_skip_frac * frame_w))) + window = cols[rstart:last] + gaps = _gaps(window < thr, max(2, gap_px)) + if gaps: + x1 = rstart + gaps[-1][0] + + if x1 - x0 < min_width_frac * frame_w: + return None + return x0, x1 + + +def clamp_pane_width(pane, max_width, anchor="left"): + """Narrow a pane to at most ``max_width`` columns. + + Used when the text column is still wider than the readable scale allows + (1080 / MIN_SCALE ~= 1440 on a 1440p source): code is left-aligned, so + keeping the left edge keeps indentation and line starts. Returns an even + ``(x, y, w, h)`` tuple. + """ + x, y, w, h = _pane_box(pane) + max_width = int(max_width) - (int(max_width) % 2) + if max_width < 2: + max_width = 2 + if w <= max_width: + return (x, y, w, h) + nx = x + (w - max_width) // 2 if anchor == "center" else x + nx = max(0, nx - (nx % 2)) + return (nx, y, max_width, h) + + +def _stable_members(boxes, frame_w, frame_h, tolerance): + arr = np.asarray(boxes, dtype=float) + cx = arr[:, 0] + arr[:, 2] / 2.0 + cy = arr[:, 1] + arr[:, 3] / 2.0 + mid_x, mid_y = float(np.median(cx)), float(np.median(cy)) + close = ((np.abs(cx - mid_x) <= tolerance * frame_w) + & (np.abs(cy - mid_y) <= tolerance * frame_h)) + return arr, close + + +def stable_pane(boxes, frame_w, frame_h, tolerance=STABILITY_TOLERANCE, + min_frac=STABILITY_MIN_FRAC): + """Median box over the samples that agree, or None. + + A pane that jumps around the screen is a moving camera or a slideshow, not a + fixed editor window; clustering around the median tolerates one stray sample + without tolerating real movement. + """ + if not boxes: + return None + arr, close = _stable_members(boxes, frame_w, frame_h, tolerance) + if int(close.sum()) < max(2, int(round(min_frac * len(boxes)))): + return None + return tuple(int(round(v)) for v in np.median(arr[close], axis=0)) + + +def stability_fraction(boxes, frame_w, frame_h, tolerance=STABILITY_TOLERANCE): + """Fraction of samples whose centre agrees with the median.""" + if not boxes: + return 0.0 + _, close = _stable_members(boxes, frame_w, frame_h, tolerance) + return float(close.mean()) if close.size else 0.0 + + +def edge_density(mask, box): + """Fraction of set pixels inside ``box`` (mask may be 0/1 or 0/255).""" + x, y, w, h = (int(v) for v in box[:4]) + m = np.asarray(mask) + sub = m[max(0, y):y + h, max(0, x):x + w] + if sub.size == 0: + return 0.0 + scale = 255.0 if sub.max() > 1 else 1.0 + return float(sub.mean()) / scale + + +def code_bands(out_h, caption_ratio=None): + """(content_h, caption_h): even, positive, and summing to ``out_h``.""" + ratio = CAPTION_BAND_RATIO if caption_ratio is None else caption_ratio + caption_h = int(round(out_h * ratio)) + caption_h -= caption_h % 2 + caption_h = max(2, min(caption_h, out_h - 2)) + content_h = out_h - caption_h + return content_h, caption_h + + +def fit_window(pane_h, scale, band_h): + """(crop_h, scaled_h, needs_follow) for a pane of ``pane_h`` at ``scale``. + + ``crop_h`` is the source window height, ``scaled_h`` its height after + scaling, both even and clamped so ``scaled_h <= band_h``. ``needs_follow`` + is True when the pane is taller than the band and only a window can fit. + """ + pane_h = max(2, int(pane_h)) + if scale <= 0: + return None + full_scaled = pane_h * scale + if full_scaled <= band_h: + scaled_h = int(round(full_scaled)) + scaled_h += scaled_h % 2 + scaled_h = max(2, min(scaled_h, band_h)) + crop_h = pane_h - (pane_h % 2) + return max(2, crop_h), scaled_h, False + crop_h = int(round(band_h / scale)) + crop_h += crop_h % 2 + crop_h = max(2, min(crop_h, pane_h - (pane_h % 2))) + scaled_h = band_h - (band_h % 2) + return crop_h, max(2, scaled_h), True + + +def follow_sendcmd_lines(follow, pane_y, window_h, pane_h, start=0.0, + target="crop@c"): + """sendcmd lines panning a crop window to the active line. + + ``follow`` is ``[(timestamp, source_y), ...]`` where ``timestamp`` is in the + source's clock; ``start`` is the segment start, subtracted so the emitted + timestamps are relative to the segment (the render seeks per scene). Only + change-points are emitted: ``y`` is clamped to the pane and deduped. + """ + lines = [] + prev = None + lo = int(pane_y) + hi = max(lo, int(pane_y + pane_h - window_h)) + for t, y in follow: + rel = float(t) - float(start) + if rel < 0: + continue + top = int(round(float(y) - window_h / 2.0)) + top = max(lo, min(top, hi)) + top -= top % 2 + if top == prev: + continue + lines.append(f"{rel:.4f} {target} y {top};") + prev = top + return lines + + +def _pane_box(pane): + if isinstance(pane, dict): + return (int(pane["x"]), int(pane["y"]), int(pane["w"]), int(pane["h"])) + return tuple(int(v) for v in pane[:4]) + + +def code_filtergraph(pane, out_w, out_h, follow=None, cam_box=None, + min_scale=MIN_SCALE, caption_ratio=None, zoom=None): + """Crop the code pane, scale it to ``out_w``, overlay on a blurred backdrop. + + ``pane`` is an ``(x, y, w, h)`` tuple or a ``detect_code_pane`` dict in + SOURCE coordinates. ``follow`` is a segment-relative + ``[(t, source_y), ...]`` series from ``active_line_series``; it produces a + ``sendcmd`` pan when the pane is taller than the content band. ``cam_box`` + optionally overlays a face in the caption band. + + Returns the filtergraph string ending in ``[v]``, or None when + ``out_w / pane_w < min_scale`` so the caller can fall back to + SCREENCAST/WIDE. + """ + x, y, w, h = _pane_box(pane) + x = max(0, x - (x % 2)) + y = max(0, y - (y % 2)) + w = max(2, w - (w % 2)) + h = max(2, h - (h % 2)) + + fit = out_w / float(w) + if fit < min_scale: + return None + + z = ZOOM if zoom is None else zoom + scale = fit * max(0.1, float(z)) + if scale <= 0: + return None + + content_h, caption_h = code_bands(out_h, caption_ratio) + + # Horizontal crop window: at zoom 1 this is the whole pane width. + crop_w = int(round(out_w / scale)) + crop_w += crop_w % 2 + crop_w = max(2, min(crop_w, w)) + crop_x = x + (w - crop_w) // 2 + crop_x = max(0, crop_x - (crop_x % 2)) + + fitted = fit_window(h, scale, content_h) + if fitted is None: + return None + crop_h, scaled_h, needs_follow = fitted + y_off = max(0, (content_h - scaled_h) // 2) + + window_top = None + if needs_follow: + window_top = y + (h - crop_h) // 2 + if follow: + window_top = int(round(float(follow[0][1]) - crop_h / 2.0)) + window_top = max(y, min(window_top, y + h - crop_h)) + window_top -= window_top % 2 + + if needs_follow and follow: + lines = follow_sendcmd_lines(follow, y, crop_h, h, start=0.0) + else: + lines = [] + + if lines: + # Each line is already ';'-terminated; concatenating avoids the empty + # command a second separator would produce. + commands = "".join(lines) + fg = (f"sendcmd=c='{commands}'," + f"crop@c=w={crop_w}:h={crop_h}:x={crop_x}:y={window_top}," + f"scale={out_w}:{scaled_h}[code]") + else: + static_y = (window_top if window_top is not None + else y + (h - crop_h) // 2) + static_y = max(y, min(static_y, y + h - crop_h)) + static_y -= static_y % 2 + fg = (f"crop=w={crop_w}:h={crop_h}:x={crop_x}:y={static_y}," + f"scale={out_w}:{scaled_h}[code]") + + parts = [] + if cam_box is not None: + cx, cy, cw, ch = _pane_box(cam_box) + cx = max(0, cx - (cx % 2)) + cy = max(0, cy - (cy % 2)) + cw = max(2, cw - (cw % 2)) + ch = max(2, ch - (ch % 2)) + cam_h = int(round(out_h * CAMERA_BAND_RATIO)) + cam_h -= cam_h % 2 + cam_h = max(2, min(cam_h, caption_h)) + parts.append("[0:v]split=3[bga][fga][cama];") + parts.append(f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];") + parts.append(f"[fga]{fg};") + parts.append(f"[cama]crop=w={cw}:h={ch}:x={cx}:y={cy}," + f"scale={out_w}:{cam_h}[cam];") + parts.append(f"[bg][code]overlay=x=0:y={y_off}[withcode];") + parts.append(f"[withcode][cam]overlay=x=0:y={out_h - caption_h}," + f"setsar=1[v]") + else: + parts.append("[0:v]split=2[bga][fga];") + parts.append(f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];") + parts.append(f"[fga]{fg};") + parts.append(f"[bg][code]overlay=x=0:y={y_off},setsar=1[v]") + return "".join(parts) + + +# --------------------------------------------------------------------------- +# OpenCV detection (lazy import). +# --------------------------------------------------------------------------- + +def _downscale(frame, max_width): + import cv2 + h, w = frame.shape[:2] + if w <= max_width: + return frame + factor = max_width / float(w) + return cv2.resize(frame, (max_width, max(2, int(round(h * factor)))), + interpolation=cv2.INTER_AREA) + + +def _edge_maps(frame, max_width=DETECT_MAX_WIDTH): + """Sobel edge mask + wide-short close + row/column projections. + + Returns a dict with the mask, closed mask, projections and the working + dimensions, or None when the frame has no gradient (black/frozen). + """ + import cv2 + small = _downscale(frame, max_width) + gray = cv2.cvtColor(small, cv2.COLOR_BGR2GRAY) + gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3) + gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3) + mag = cv2.magnitude(gx, gy) + top = float(mag.max()) + if top <= 1e-6: + return None + threshold = max(SOBEL_FLOOR, SOBEL_RATIO * top) + mask = (mag > threshold).astype(np.uint8) * 255 + kernel = cv2.getStructuringElement(cv2.MORPH_RECT, CLOSE_KERNEL) + closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) + return { + "mask": mask, + "closed": closed, + "row_proj": closed.sum(axis=1).astype(np.float64), + "col_proj": closed.sum(axis=0).astype(np.float64), + # The close joins glyphs into line runs, which is what the row + # projection needs — but it also bridges the blank IDE chrome borders, + # so the column projection for TEXT-COLUMN masking comes from the RAW + # mask, where the border survives. + "col_proj_raw": mask.sum(axis=0).astype(np.float64), + "w": small.shape[1], + "h": small.shape[0], + } + + +def _classify_pane(frame, box): + """Editor vs terminal. Defaults to editor when the signal is weak. + + An editor shows a left gutter of stable digit rows (line numbers) and + syntax highlighting raises the crop's saturation variance. A terminal has + neither: text starts at the left margin and is mostly one foreground colour. + """ + import cv2 + x, y, w, h = (int(v) for v in box) + crop = frame[max(0, y):y + h, max(0, x):x + w] + if crop.size == 0: + return "editor" + hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV) + sat_std = float(hsv[:, :, 1].std()) + + gutter_w = max(4, int(w * GUTTER_FRACTION)) + gutter = crop[:, :gutter_w] + gg = cv2.cvtColor(gutter, cv2.COLOR_BGR2GRAY) + gx = np.abs(cv2.Sobel(gg, cv2.CV_32F, 1, 0, ksize=3)) + per_col = gx.sum(axis=0) + total = float(per_col.sum()) + 1e-6 + gutter_peak = float(per_col.max() / total) if per_col.size else 0.0 + + if sat_std >= EDITOR_SAT_STD and gutter_peak > 0.08: + return "editor" + if sat_std < EDITOR_SAT_STD and gutter_peak <= 0.08: + return "terminal" + return "editor" + + +def detect_code_pane(video_path, samples=12): + """Median code pane across sampled frames, or None. + + Pipeline per sample: downscale to <= DETECT_MAX_WIDTH, Sobel magnitude mask, + wide-short morphological close (joins glyphs into line runs), row/column + projection -> bounding pane. Gates: pane width/height fractions, in-pane + edge-density floor, and temporal stability of the pane centre. + + Returns ``{"x", "y", "w", "h", "mode", "confidence", "frame_w", + "frame_h"}`` in source coordinates, or None meaning "use another layout". + """ + if not ENABLED: + return None + try: + import cv2 + except ImportError: + return None + + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + return None + total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + if total <= 0 or frame_w <= 0 or frame_h <= 0: + cap.release() + return None + + n = max(2, int(samples)) + boxes = [] + densities = [] + votes = {"editor": 0, "terminal": 0} + try: + for i in range(n): + cap.set(cv2.CAP_PROP_POS_FRAMES, int(i * total / n)) + ok, frame = cap.read() + if not ok: + continue + maps = _edge_maps(frame) + if maps is None: + continue + det_box = pane_from_projections( + maps["row_proj"], maps["col_proj"], maps["w"], maps["h"]) + if det_box is None: + continue + # The plain projection returns the whole window; cut it down to the + # text column so a maximized 1440p editor does not scale at 0.42. + # Raw projection: the morphological close would bridge the chrome + # borders this is looking for. + text_cols = text_column_extent(maps["col_proj_raw"], maps["w"]) + if text_cols is not None: + x0, x1 = text_cols + else: + x0, x1 = det_box[0], det_box[0] + det_box[2] + y0 = det_box[1] + y1 = det_box[1] + det_box[3] + # Shave the status bar / window border off the bottom. + y1 -= int(round(CHROME_BOTTOM_FRAC * (y1 - y0))) + w, h = x1 - x0, y1 - y0 + if (w < PANE_MIN_WIDTH_FRAC * maps["w"] + or h < PANE_MIN_HEIGHT_FRAC * maps["h"]): + continue + det_box = (x0, y0, w, h) + density = edge_density(maps["closed"], det_box) + if density < EDGE_DENSITY_FLOOR: + continue + sx = frame_w / float(maps["w"]) + sy = frame_h / float(maps["h"]) + box = (int(round(det_box[0] * sx)), int(round(det_box[1] * sy)), + int(round(det_box[2] * sx)), int(round(det_box[3] * sy))) + boxes.append(box) + densities.append(density) + votes[_classify_pane(frame, box)] += 1 + finally: + cap.release() + + if len(boxes) < 2: + return None + stable = stable_pane(boxes, frame_w, frame_h) + if stable is None: + return None + x, y, w, h = stable + if w < PANE_MIN_WIDTH_FRAC * frame_w or h < PANE_MIN_HEIGHT_FRAC * frame_h: + return None + + mode = "editor" if votes["editor"] >= votes["terminal"] else "terminal" + stable_frac = stability_fraction(boxes, frame_w, frame_h) + density = float(np.mean(densities)) if densities else 0.0 + confidence = max(0.0, min(1.0, 0.6 * stable_frac + + 0.4 * min(1.0, density / (4 * EDGE_DENSITY_FLOOR)))) + return {"x": x, "y": y, "w": w, "h": h, "mode": mode, + "confidence": confidence, "frame_w": frame_w, "frame_h": frame_h} + + +def _active_point(row_mass, total, band_frac=ACTIVE_BAND_FRAC, + min_concentration=ACTIVE_MIN_CONCENTRATION): + """(normalised centroid, concentration, mass) of the top-mass row band. + + The centroid is the mass-weighted centre of the busiest ``band_frac`` of + rows, normalised to 0..1 over the region. ``concentration`` is that band's + share of all changed pixels: a caret or highlighted line is concentrated, a + whole-screen redraw is not. + """ + n = len(row_mass) + if n == 0 or total <= 0: + return None + k = max(1, int(round(n * band_frac))) + order = np.argsort(row_mass)[-k:] + band_mass = float(row_mass[order].sum()) + if band_mass <= 0: + return None + concentration = band_mass / float(total) + if concentration < min_concentration: + return None + idx = order.astype(float) + cy = float((idx * row_mass[order]).sum() / band_mass) + return (cy / (n - 1) if n > 1 else 0.0), concentration, band_mass + + +def _median_smooth(values, window=3): + values = np.asarray(values, dtype=float) + if window <= 1 or len(values) < window: + return values + half = window // 2 + out = values.copy() + for i in range(len(values)): + lo = max(0, i - half) + hi = min(len(values), i + half + 1) + out[i] = np.median(values[lo:hi]) + return out + + +def active_line_series(video_path, pane, start, end, sample_fps=2.0): + """Track the active line (caret/current-line highlight) over a range. + + Low-res decode at ``sample_fps``; ``absdiff`` between consecutive samples + masked to the pane; per-row changed mass; the top-mass band's centroid is + kept only when it concentrates >= ``ACTIVE_MIN_CONCENTRATION`` of the change + and the band mass clears the floor. The y series is median-smoothed. + + Returns ``[(timestamp, source_y), ...]`` in the source's absolute clock (the + caller subtracts the segment start when building sendcmd lines), or None + when fewer than three reliable points are found. + """ + if not ENABLED or not FOLLOW_ENABLED: + return None + try: + import cv2 + except ImportError: + return None + if end <= start: + return None + + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + return None + frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + if frame_w <= 0 or frame_h <= 0: + cap.release() + return None + x, y, w, h = _pane_box(pane) + if w <= 0 or h <= 0: + cap.release() + return None + + step = 1.0 / max(0.1, float(sample_fps)) + points = [] + prev_region = None + try: + t = float(start) + while t <= end + 1e-6: + cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000.0) + ok, frame = cap.read() + if not ok: + break + small = _downscale(frame, ACTIVE_MAX_WIDTH) + sw, sh = small.shape[1], small.shape[0] + rx = int(round(x * sw / float(frame_w))) + ry = int(round(y * sh / float(frame_h))) + rw = max(2, int(round(w * sw / float(frame_w)))) + rh = max(2, int(round(h * sh / float(frame_h)))) + rx = max(0, min(rx, sw - 2)) + ry = max(0, min(ry, sh - 2)) + rw = max(2, min(rw, sw - rx)) + rh = max(2, min(rh, sh - ry)) + region = small[ry:ry + rh, rx:rx + rw] + if prev_region is not None and prev_region.shape == region.shape: + diff = cv2.absdiff(region, prev_region) + gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) + row_mass = gray.sum(axis=1).astype(np.float64) + total = float(row_mass.sum()) + if total >= ACTIVE_MIN_MASS: + point = _active_point(row_mass, total) + if point is not None: + points.append((t, y + point[0] * h)) + prev_region = region + t += step + finally: + cap.release() + + if len(points) < 3: + return None + ys = _median_smooth([p[1] for p in points], 3) + return [(float(ts), float(yy)) for (ts, _), yy in zip(points, ys)] + + +def _regular_rows(row_proj, min_period=6, max_period=60, min_peak=0.25): + """True when the row projection has a periodic peak (monospace line pitch). + + Autocorrelation of the mean-subtracted projection; a peak in the plausible + line-height band means evenly spaced text lines rather than prose or a UI. + """ + v = np.asarray(row_proj, dtype=float) + if v.size < min_period + 2: + return False + v = v - v.mean() + denom = float((v * v).sum()) + if denom <= 0: + return False + ac = np.correlate(v, v, mode="full")[len(v) - 1:] + ac = ac / denom + hi = min(max_period, len(ac) - 1) + if hi <= min_period: + return False + return float(ac[min_period:hi + 1].max()) >= min_peak + + +def _texture_ok(maps): + """Edge-density floor + monospace row regularity on an edge-map dict.""" + density = edge_density(maps["closed"], (0, 0, maps["w"], maps["h"])) + if density < EDGE_DENSITY_FLOOR: + return False + return _regular_rows(maps["row_proj"]) + + +def _palette_ok(crop): + """Editor/terminal palette: dark background or mostly monochrome.""" + hsv = _hsv(crop) + sat_std = float(hsv[:, :, 1].std()) + dark = float((hsv[:, :, 2] < 102).mean()) + return bool(dark >= 0.35 or sat_std <= 45.0) + + +def frame_shows_code(frame, pane): + """True when the pane region of THIS frame still reads as code. + + Text density (edge-density floor + monospace row regularity) plus the + editor/terminal palette. A facecam cutaway puts skin/room inside the pane + rectangle, which fails both the row pitch and the dark/monochrome palette. + """ + try: + import cv2 # noqa: F401 + except ImportError: + return False + x, y, w, h = _pane_box(pane) + frame_h, frame_w = frame.shape[:2] + x0 = max(0, min(x, frame_w - 2)) + y0 = max(0, min(y, frame_h - 2)) + x1 = max(x0 + 2, min(x + w, frame_w)) + y1 = max(y0 + 2, min(y + h, frame_h)) + crop = frame[y0:y1, x0:x1] + if crop.size == 0: + return False + maps = _edge_maps(crop) + if maps is None: + return False + return _texture_ok(maps) and _palette_ok(crop) + + +def scene_shows_code(video_path, pane, start, end, samples=3): + """Sample a scene's frames inside the pane; True on a majority that read + as code. A cutaway to the camera fails and keeps the scene's other verdict. + """ + if end <= start: + return False + try: + import cv2 + except ImportError: + return False + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + return False + frames = [] + try: + n = max(1, int(samples)) + for i in range(n): + t = start + (end - start) * (i + 0.5) / n + cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000.0) + ok, frame = cap.read() + if ok: + frames.append(frame) + finally: + cap.release() + if len(frames) < 2: + return False + good = sum(1 for f in frames if frame_shows_code(f, pane)) + return good >= max(2, int(round(SCENE_CODE_FRAC * len(frames)))) + + +def looks_like_code(frames): + """Conservative fallback for deployments with no Gemini key. + + ``frames`` is a list of BGR arrays. True only when all three hold across the + samples: a static pane (centres agree), monospace row regularity, and an + editor/terminal palette (dark or mostly monochrome). This is deliberately + strict — a false positive demotes a real talking-head clip — and callers + MUST NOT invoke it over an explicit operator layout. + """ + if not frames or len(frames) < 2: + return False + planes = [] + row_projs = [] + sat_stds = [] + dark_fracs = [] + for frame in frames: + maps = _edge_maps(frame) + if maps is None: + continue + box = pane_from_projections( + maps["row_proj"], maps["col_proj"], maps["w"], maps["h"]) + if box is None: + continue + if edge_density(maps["closed"], box) < EDGE_DENSITY_FLOOR: + continue + x, y, w, h = box + crop = frame[y:y + h, x:x + w] + if crop.size == 0: + continue + hsv = _hsv(crop) + planes.append((x, y, w, h, maps["w"], maps["h"])) + row_projs.append(maps["row_proj"]) + sat_stds.append(float(hsv[:, :, 1].std())) + dark_fracs.append(float((hsv[:, :, 2] < 102).mean())) + + if len(planes) < max(2, int(round(0.6 * len(frames)))): + return False + + centres_x = np.array([(p[0] + p[2] / 2.0) / p[4] for p in planes]) + centres_y = np.array([(p[1] + p[3] / 2.0) / p[5] for p in planes]) + if centres_x.std() > 0.05 or centres_y.std() > 0.05: + return False + + median_proj = np.median(np.array(row_projs, dtype=float), axis=0) + if not _regular_rows(median_proj): + return False + + sat_std = float(np.median(sat_stds)) + dark = float(np.median(dark_fracs)) + return bool(dark >= 0.35 or sat_std <= 45.0) + + +def _hsv(crop): + import cv2 + return cv2.cvtColor(crop, cv2.COLOR_BGR2HSV) diff --git a/clipwright/layouts/layout_picker.py b/clipwright/layouts/layout_picker.py index a34e150..7deea07 100644 --- a/clipwright/layouts/layout_picker.py +++ b/clipwright/layouts/layout_picker.py @@ -64,6 +64,7 @@ SAMPLE_WIDTH = int(os.environ.get("LAYOUT_SAMPLE_WIDTH", "1024")) DECISION_FLAGS = { "none": [], "screencast": ["screencast_layout"], + "code": ["code_layout"], "split": ["split_layout", "active_speaker"], } @@ -83,11 +84,13 @@ def apply(decision): must not quietly undo that. """ from clipwright.layouts import active_speaker + from clipwright.layouts import code_layout from clipwright.layouts import screencast_layout from clipwright.layouts import split_layout modules = {"split_layout": split_layout, "screencast_layout": screencast_layout, + "code_layout": code_layout, "active_speaker": active_speaker} touched = [] diff --git a/clipwright/layouts/reframe_v2.py b/clipwright/layouts/reframe_v2.py index ba53c1c..b16d3b8 100644 --- a/clipwright/layouts/reframe_v2.py +++ b/clipwright/layouts/reframe_v2.py @@ -23,6 +23,7 @@ import tempfile from clipwright.layouts import active_speaker from clipwright.layouts import camera_inset +from clipwright.layouts import code_layout from clipwright.layouts import punch_in from clipwright.layouts import screencast_layout from clipwright.layouts import layout_ranges @@ -341,12 +342,15 @@ def _run(cmd): def render(input_video, final_output_video, aspect_ratio, content_ranges=None, - force_strategy=None, crop_overrides=None): + force_strategy=None, crop_overrides=None, word_times=None): """Full v2 reframe of one clip. Raises on failure (caller falls back). ``content_ranges`` comes from screencast_layout.detect_content_ranges() on - the SOURCE video, already translated into this clip's timeline. None or [] - means the layout never triggers, which is the default. + the SOURCE video, already translated into this clip's timeline. When it is + None, the render computes it itself on ``input_video`` if the screencast + module is on (see below); this used to be a dead wire no production caller + filled, so the picker's "screencast" option did nothing. Pass [] to force + the upgrade off, or a list to supply pre-computed ranges. ``force_strategy`` ('WIDE' / 'TRACK' / any layout the render loop knows) applies that layout to EVERY scene, skipping the classifier and the layout @@ -357,8 +361,13 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, listed keep the automatic camera, so correcting one bad shot never disturbs the ones the tracker got right. Applied AFTER force_strategy: a per-scene hand position always beats the whole-clip choice for the scenes it names. + + ``word_times`` are clip-relative word onsets in seconds (clip start = 0) + from the transcript, optional. They steer the punch-in beats toward spoken + emphasis; None leaves the audio envelope as the only beat source. """ from clipwright.pipeline import main as m + auto_content_ranges = content_ranges is None content_ranges = content_ranges or [] print(" 🚀 Reframe engine v2 (ffmpeg-native render)") @@ -434,6 +443,57 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, if alternates: print(f" 🎬 Speaker-cut layout on {len(alternates)} scene(s)") + # The SCREENCAST/WIDE/INSET upgrades gate on content_ranges, which no + # production caller ever passed: screencast_layout.detect_content_ranges + # was called by tests only, so the picker's "screencast" option silently did + # nothing (dead wire found in review). Compute them here, once per render, + # when the module is on and nothing overrides the layout. CODE does NOT use + # this external-ranges path — it self-detects below. + if (auto_content_ranges and screencast_layout.ENABLED + and not force_strategy and not passthrough): + duration = scene_boundaries[-1][1] / fps if scene_boundaries else 0.0 + try: + content_ranges = screencast_layout.detect_content_ranges( + input_video, duration) + except Exception as e: + print(f" ⚠️ On-screen content check failed ({e}).") + content_ranges = [] + + # CODE is geometric and self-contained, like split_layout: the pane box is + # found once for the whole video (screen recordings are usually one long + # scene) and then each scene is verified by sampling frames inside that box. + # A scene that cuts to the facecam fails the text check and keeps TRACK. + # Inserted before SCREENCAST so a code editor with a webcam wins, and the + # screencast loop below skips scenes already claimed here. + codes = {} + code_pane = None + if code_layout.ENABLED and not passthrough and not force_strategy: + try: + code_pane = code_layout.detect_code_pane(input_video) + except Exception as e: + print(f" ⚠️ Code-pane check failed ({e}) — using other layouts.") + code_pane = None + if code_pane: + max_w = max(2, int(out_w / code_layout.MIN_SCALE)) + pane_box = code_layout.clamp_pane_width(code_pane, max_w) + scale = out_w / float(pane_box[2]) + print(f" 💻 Code pane {code_pane['w']}x{code_pane['h']} " + f"@ {code_pane['x']},{code_pane['y']} " + f"mode={code_pane['mode']} conf={code_pane['confidence']:.2f}" + f" -> crop {pane_box[2]}px (scale {scale:.2f})") + code_pane = dict(code_pane, x=pane_box[0], y=pane_box[1], + w=pane_box[2], h=pane_box[3]) + for scene_idx, (start_f, end_f) in enumerate(scene_boundaries): + if strategies[scene_idx] not in ("TRACK", "GENERAL"): + continue + if code_layout.scene_shows_code( + input_video, code_pane, start_f / fps, end_f / fps): + strategies[scene_idx] = "CODE" + codes[start_f] = code_pane + splits.pop(start_f, None) + if codes: + print(f" 💻 CODE layout on {len(codes)} scene(s)") + # SCREENCAST wins over SPLIT on the rare scene that qualifies for both: two # faces beside a chart still means the chart is what the shot is about, and # stacking the two speakers would crop it away entirely. @@ -457,6 +517,9 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, if content_ranges: for scene_idx, (plan, centre) in screencast_layout.detect_screencast_scenes( input_video, scenes, strategies, content_ranges).items(): + # CODE was detected geometrically and wins over the screen layouts. + if strategies[scene_idx] == 'CODE': + continue # An inset beats both screen plans: it is the only one that can show # the screen whole AND the person at a readable size. if inset: @@ -492,7 +555,8 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, # Beats are found once per clip; each scene takes the ones inside it. beats = [] if punch_in.ENABLED: - beats = punch_in.emphasis_times(input_video, len(xs) / fps) + beats = punch_in.emphasis_times(input_video, len(xs) / fps, + word_times=word_times) if beats: print(f" 🔍 Punch-in on {len(beats)} beat(s)") @@ -544,6 +608,22 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, left, right = splits[start_f] graph = split_layout.split_filtergraph( orig_w, orig_h, out_w, out_h, left, right) + elif strategy == 'CODE' and start_f in codes: + pane = codes[start_f] + follow = None + if code_layout.FOLLOW_ENABLED: + try: + series = code_layout.active_line_series( + input_video, pane, ss, ss + dur) + if series: + follow = [(t - ss, y) for t, y in series] + except Exception: + follow = None + graph = code_layout.code_filtergraph( + pane, out_w, out_h, follow=follow) + if graph is None: + graph = general_filtergraph(out_w, out_h, + orig_w=orig_w, orig_h=orig_h) elif strategy == 'GENERAL': graph = general_filtergraph(out_w, out_h, orig_w=orig_w, orig_h=orig_h) diff --git a/clipwright/pipeline/hook_grounding.py b/clipwright/pipeline/hook_grounding.py index 12d744e..3a6bc24 100644 --- a/clipwright/pipeline/hook_grounding.py +++ b/clipwright/pipeline/hook_grounding.py @@ -24,7 +24,7 @@ import json import os from typing import Optional -SCREEN_LAYOUTS = {"screencast", "wide", "inset"} +SCREEN_LAYOUTS = {"screencast", "code", "wide", "inset"} FRAMES = int(os.environ.get("HOOK_GROUNDING_FRAMES", "3")) WIDTH = int(os.environ.get("HOOK_GROUNDING_WIDTH", "1024")) # Ignore a blip: the screen stretches must cover this share of the clip. diff --git a/clipwright/tools/verify_code_layout.py b/clipwright/tools/verify_code_layout.py new file mode 100644 index 0000000..eed3ea0 --- /dev/null +++ b/clipwright/tools/verify_code_layout.py @@ -0,0 +1,169 @@ +"""Calibration tool for the CODE/TERMINAL layout. + +Usage (from the repo root): + + python -m clipwright.tools.verify_code_layout path/to/recording.mp4 \ + --start 12.0 --duration 8 --out-dir output/code_layout + +It forces the layout on (ignoring ``CODE_LAYOUT``), detects the pane, prints +pane / confidence / mode, writes: + + - ``debug_bands.png`` — a schematic of the 9:16 output with the code band and + the caption reserve marked; + - ``still.png`` — a real render through ``code_filtergraph`` at ``--start``. + +Exit codes: 0 on a detected pane and a rendered still; 1 when nothing detects +(so a corpus sweep can flag misses); 2 when cv2 is unavailable. + +The detection thresholds in ``code_layout`` are estimates from first +principles. Run this across a set of real 1440p IDE and terminal recordings and +tune ``CODE_*`` from what actually lands here. +""" +import argparse +import os +import subprocess +import sys + +DEFAULT_OUT = "output/code_layout" + + +def _parse_args(argv): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("video", help="path to the source recording") + parser.add_argument("--start", type=float, default=0.0, + help="segment start in seconds") + parser.add_argument("--duration", type=float, default=6.0, + help="seconds of active-line tracking to sample") + parser.add_argument("--samples", type=int, default=12, + help="frames sampled for pane detection") + parser.add_argument("--out-w", type=int, default=1080) + parser.add_argument("--out-h", type=int, default=1920) + parser.add_argument("--out-dir", default=DEFAULT_OUT) + parser.add_argument("--no-follow", action="store_true", + help="skip active-line tracking (static window)") + return parser.parse_args(argv) + + +def _draw_bands(path, pane, out_w, out_h, graph): + """Schematic of the output: backdrop, code band, caption reserve.""" + import cv2 + import numpy as np + + canvas = np.full((out_h, out_w, 3), 32, dtype=np.uint8) + content_h, caption_h = _bands(out_h) + scale = out_w / float(pane["w"]) + scaled_h = min(content_h, int(round(pane["h"] * scale))) + y_off = max(0, (content_h - scaled_h) // 2) + + cv2.rectangle(canvas, (0, y_off), (out_w - 1, y_off + scaled_h), + (40, 160, 40), thickness=-1) + cv2.rectangle(canvas, (0, out_h - caption_h), (out_w - 1, out_h - 1), + (160, 90, 40), thickness=-1) + cv2.putText(canvas, f"pane {pane['w']}x{pane['h']} @ {pane['x']},{pane['y']}", + (16, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2) + cv2.putText(canvas, f"code band h={scaled_h}", + (16, y_off + max(30, scaled_h // 2)), + cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2) + cv2.putText(canvas, "caption reserve", + (16, out_h - caption_h + max(30, caption_h // 2)), + cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2) + if "sendcmd" in graph: + cv2.putText(canvas, "sendcmd follow ON", + (16, out_h - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, + (80, 220, 255), 2) + cv2.imwrite(path, canvas) + + +def _bands(out_h): + from clipwright.layouts import code_layout + return code_layout.code_bands(out_h) + + +def _render_still(video, start, graph, out_path): + cmd = [ + "ffmpeg", "-y", "-loglevel", "error", + "-ss", f"{start:.4f}", "-i", video, + "-frames:v", "1", + "-filter_complex", graph, "-map", "[v]", + out_path, + ] + proc = subprocess.run(cmd, capture_output=True, text=True) + if proc.returncode != 0: + print(f"❌ ffmpeg failed:\n{proc.stderr}") + return False + return os.path.exists(out_path) and os.path.getsize(out_path) > 0 + + +def main(argv=None): + args = _parse_args(argv if argv is not None else sys.argv[1:]) + try: + import cv2 # noqa: F401 (presence check only) + except ImportError: + print("❌ OpenCV (cv2) is required to run this tool.") + return 2 + + from clipwright.layouts import code_layout + code_layout.ENABLED = True + code_layout.FOLLOW_ENABLED = True + + if not os.path.exists(args.video): + print(f"❌ No such video: {args.video}") + return 1 + + os.makedirs(args.out_dir, exist_ok=True) + + pane = code_layout.detect_code_pane(args.video, samples=args.samples) + if pane is None: + print("❌ No code pane detected — nothing to render. " + "Tune CODE_PANE_MIN_* / CODE_EDGE_DENSITY / CODE_STABILITY_*.") + return 1 + + print(f"✅ Pane: x={pane['x']} y={pane['y']} w={pane['w']} h={pane['h']} " + f"({pane['w']}x{pane['h']})") + print(f" mode={pane['mode']} confidence={pane['confidence']:.2f} " + f"frame={pane['frame_w']}x{pane['frame_h']}") + + # Mirror reframe_v2: if the text column is still wider than the readable + # scale allows, crop it to out_w / MIN_SCALE rather than falling back. + max_w = max(2, int(args.out_w / code_layout.MIN_SCALE)) + clamped = code_layout.clamp_pane_width(pane, max_w) + if clamped[2] != pane["w"]: + print(f" clamped text column {pane['w']} -> {clamped[2]}px " + f"(CODE_MIN_SCALE={code_layout.MIN_SCALE})") + pane = dict(pane, x=clamped[0], y=clamped[1], w=clamped[2], h=clamped[3]) + print(f" scale: {args.out_w / float(pane['w']):.2f}") + + follow = None + if not args.no_follow: + series = code_layout.active_line_series( + args.video, pane, args.start, args.start + args.duration) + if series: + # code_filtergraph expects timestamps relative to the segment start. + follow = [(t - args.start, y) for t, y in series] + print(f" follow: {len(follow)} points over " + f"{follow[0][0]:.1f}-{follow[-1][0]:.1f}s") + else: + print(" follow: no reliable active-line series (static window)") + + graph = code_layout.code_filtergraph(pane, args.out_w, args.out_h, + follow=follow) + if graph is None: + scale = args.out_w / float(max(1, pane["w"])) + print(f"❌ Scale {scale:.2f} < CODE_MIN_SCALE " + f"({code_layout.MIN_SCALE}) — this clip falls back to " + f"SCREENCAST/WIDE.") + return 1 + + debug_path = os.path.join(args.out_dir, "debug_bands.png") + still_path = os.path.join(args.out_dir, "still.png") + _draw_bands(debug_path, pane, args.out_w, args.out_h, graph) + if not _render_still(args.video, args.start, graph, still_path): + return 1 + + print(f"🖼️ wrote {debug_path}") + print(f"🖼️ wrote {still_path}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/e2e/pipeline/test_layout_stage.py b/tests/e2e/pipeline/test_layout_stage.py index b28fda1..dbd2088 100644 --- a/tests/e2e/pipeline/test_layout_stage.py +++ b/tests/e2e/pipeline/test_layout_stage.py @@ -14,6 +14,9 @@ import pytest from clipwright.layouts import layout_ranges from clipwright.layouts import layout_picker +from clipwright.layouts import code_layout +from clipwright.layouts import camera_inset +from clipwright.layouts import active_speaker from clipwright.layouts import punch_in from clipwright.layouts import screencast_layout from clipwright.layouts import split_layout @@ -26,6 +29,7 @@ VERTICAL = 9 / 16 _FAKE_LAYOUT_MODULES = { "split_layout": "clipwright.layouts.split_layout", "screencast_layout": "clipwright.layouts.screencast_layout", + "code_layout": "clipwright.layouts.code_layout", "active_speaker": "clipwright.layouts.active_speaker", } @@ -59,6 +63,15 @@ class TestPickerFlagMapping: assert mods["clipwright.layouts.screencast_layout"].ENABLED is True assert mods["clipwright.layouts.split_layout"].ENABLED is False + def test_code_enables_only_its_module(self, monkeypatch): + # The CODE layout is gated by its own module flag; picking it must not + # touch SPLIT or SCREENCAST. + mods = fake_modules(monkeypatch) + assert layout_picker.apply("code") == ["code_layout"] + assert mods["clipwright.layouts.code_layout"].ENABLED is True + assert mods["clipwright.layouts.screencast_layout"].ENABLED is False + assert mods["clipwright.layouts.split_layout"].ENABLED is False + def test_none_is_inert(self, monkeypatch): mods = fake_modules(monkeypatch) assert layout_picker.apply("none") == [] @@ -104,6 +117,7 @@ class TestApiLayoutEnv: def test_explicit_picks_map_to_their_env_vars(self, layout_env): assert layout_env(["split"])["SPLIT_LAYOUT"] == "1" assert layout_env(["screencast"])["SCREENCAST_LAYOUT"] == "1" + assert layout_env(["code"])["CODE_LAYOUT"] == "1" assert layout_env(["punch_in"])["PUNCH_IN"] == "1" def test_split_implies_the_speaker_signal(self, layout_env): @@ -243,3 +257,77 @@ class TestLayoutRangesRoundTrip: got = layout_ranges.remap(ranges, [{"start": 5, "end": 12}]) assert got == [{"start": 0.0, "end": 5.0, "layout": "split"}, {"start": 5.0, "end": 7.0, "layout": "track"}] + + +# --- CODE precedence -------------------------------------------------------- + +class _TC: + """Minimal FrameTimecode stand-in: render only reads ``get_frames``.""" + + def __init__(self, frame): + self._frame = frame + + def get_frames(self): + return self._frame + + +class _DummyCameraman: + crop_width = 640 + crop_height = 360 + + +class TestCodePrecedence: + """CODE self-detects and wins over SCREENCAST on the same scene, while a + scene that fails per-scene verification keeps TRACK.""" + + def _wire(self, monkeypatch): + from clipwright.pipeline import main as m + + # No ML, no ffmpeg, no Gemini: every external call is a stand-in. + monkeypatch.setattr(reframe_v2, "_run", lambda cmd: None) + monkeypatch.setattr(reframe_v2, "_analyze_trajectory", + lambda *a, **k: [0.0] * 60) + monkeypatch.setattr(split_layout, "detect_split_scenes", + lambda *a, **k: {}) + monkeypatch.setattr(camera_inset, "detect", lambda *a, **k: None) + monkeypatch.setattr(active_speaker, "ENABLED", False) + monkeypatch.setattr(punch_in, "ENABLED", False) + monkeypatch.setattr(m, "detect_scenes", + lambda *a, **k: ([(_TC(0), _TC(30)), + (_TC(30), _TC(60))], 30.0)) + monkeypatch.setattr(m, "get_video_resolution", + lambda *a, **k: (2560, 1440)) + monkeypatch.setattr(m, "analyze_scenes_strategy", + lambda *a, **k: ["TRACK", "TRACK"]) + monkeypatch.setattr(m, "SmoothedCameraman", + lambda *a, **k: _DummyCameraman()) + monkeypatch.setattr(m, "SpeakerTracker", lambda *a, **k: object()) + + # SCREENCAST is on and would claim scene 0... + monkeypatch.setattr(screencast_layout, "ENABLED", True) + monkeypatch.setattr(screencast_layout, "detect_content_ranges", + lambda *a, **k: [(0.0, 20.0, "chart", 0.9)]) + monkeypatch.setattr(screencast_layout, "detect_screencast_scenes", + lambda *a, **k: {0: ("SCREENCAST", (100.0, 100.0))}) + + # ...but CODE detects the pane and verifies only scene 0. + monkeypatch.setattr(code_layout, "ENABLED", True) + monkeypatch.setattr(code_layout, "FOLLOW_ENABLED", False) + pane = {"x": 300, "y": 100, "w": 1200, "h": 800, "mode": "editor", + "confidence": 0.9, "frame_w": 2560, "frame_h": 1440} + monkeypatch.setattr(code_layout, "detect_code_pane", + lambda *a, **k: dict(pane)) + monkeypatch.setattr( + code_layout, "scene_shows_code", + lambda path, pane, start, end, samples=3: start < 0.5) + + def test_code_wins_over_screencast_and_leaves_other_scenes( + self, monkeypatch, tmp_path): + self._wire(monkeypatch) + final = str(tmp_path / "clip.mp4") + assert reframe_v2.render("in.mp4", final, VERTICAL) is True + + by_start = {r["start"]: r["layout"] for r in layout_ranges.read(final)} + assert by_start[0.0] == "code" # CODE beat the SCREENCAST claim + assert by_start[1.0] == "track" # failed verification, untouched + assert "screencast" not in set(by_start.values()) diff --git a/tests/test_code_layout.py b/tests/test_code_layout.py new file mode 100644 index 0000000..74070c8 --- /dev/null +++ b/tests/test_code_layout.py @@ -0,0 +1,231 @@ +"""Pure tests for the CODE/TERMINAL layout geometry. + +No OpenCV here on purpose: the detection entry points import cv2 lazily, and CI +does not install it. Everything asserted below is decided by the pure helpers +(projections -> pane, stability, band fitting, sendcmd lines, filtergraph). +""" +from clipwright.layouts.code_layout import ( + CAPTION_BAND_RATIO, + clamp_pane_width, + code_bands, + code_filtergraph, + fit_window, + follow_sendcmd_lines, + pane_from_projections, + stable_pane, + text_column_extent, +) + +HD = (1920, 1080) + + +def _projections(row_span, col_span, h=1080, w=1920): + rows = [0.0] * h + cols = [0.0] * w + for i in range(*row_span): + rows[i] = 100.0 + for i in range(*col_span): + cols[i] = 100.0 + return rows, cols + + +class TestPaneFromProjections: + def test_locates_the_pane_block(self): + rows, cols = _projections((100, 400), (200, 1000)) + assert pane_from_projections(rows, cols, *HD) == (200, 100, 800, 300) + + def test_ignores_mass_below_the_threshold(self): + rows, cols = _projections((100, 400), (200, 1000)) + # A stray edge column far from the pane is under 15% of the max. + cols[1500] = 10.0 + assert pane_from_projections(rows, cols, *HD) == (200, 100, 800, 300) + + def test_rejects_a_narrow_pane(self): + rows, cols = _projections((100, 400), (200, 500)) + assert pane_from_projections(rows, cols, *HD) is None + + def test_rejects_a_short_pane(self): + rows, cols = _projections((100, 200), (200, 1000)) + assert pane_from_projections(rows, cols, *HD) is None + + def test_empty_projections_are_none(self): + assert pane_from_projections([], [], *HD) is None + assert pane_from_projections([0, 0], [0, 0], *HD) is None + + +class TestTextColumnExtent: + def test_no_chrome_keeps_the_full_text_width(self): + cols = [0.0] * 2560 + for i in range(100, 2400): + cols[i] = 100.0 + x0, x1 = text_column_extent(cols, 2560) + assert 90 <= x0 <= 110 + assert 2390 <= x1 <= 2410 + + def test_sidebar_and_minimap_are_masked(self): + cols = [0.0] * 2560 + for i in range(0, 60): # activity bar + cols[i] = 90.0 + for i in range(80, 400): # sidebar + cols[i] = 70.0 + for i in range(500, 2050): # code text + cols[i] = 100.0 + for i in range(2450, 2560): # minimap + cols[i] = 110.0 + x0, x1 = text_column_extent(cols, 2560) + # Cut after the sidebar/editor border and before the minimap border. + assert 400 <= x0 <= 520 + assert 2050 <= x1 <= 2450 + + def test_too_narrow_is_none(self): + cols = [0.0] * 2560 + for i in range(0, 100): + cols[i] = 100.0 + assert text_column_extent(cols, 2560) is None + + +class TestClampPaneWidth: + def test_narrows_from_the_left_by_default(self): + assert clamp_pane_width((300, 100, 2100, 1200), 1440) == ( + 300, 100, 1440, 1200) + + def test_noop_when_it_already_fits(self): + assert clamp_pane_width((300, 100, 1200, 1200), 1440) == ( + 300, 100, 1200, 1200) + + def test_centred_anchor_splits_the_difference(self): + assert clamp_pane_width((0, 0, 2000, 1000), 1000, anchor="center") == ( + 500, 0, 1000, 1000) + + def test_odd_width_is_made_even(self): + _x, _y, w, _h = clamp_pane_width((0, 0, 2000, 1000), 1441) + assert w % 2 == 0 and w <= 1441 + + +class TestStablePane: + def test_agreement_returns_the_median(self): + boxes = [(100, 100, 800, 300), (105, 102, 800, 300), + (98, 99, 802, 301), (300, 300, 800, 300)] + box = stable_pane(boxes, *HD) + assert box is not None + assert abs(box[0] - 100) <= 6 and abs(box[1] - 100) <= 4 + + def test_a_scattered_set_is_rejected(self): + boxes = [(0, 0, 400, 300), (1500, 800, 400, 300), + (700, 400, 400, 300)] + assert stable_pane(boxes, *HD) is None + + def test_too_few_samples_is_rejected(self): + assert stable_pane([], *HD) is None + assert stable_pane([(100, 100, 800, 300)], *HD) is None + + +class TestCodeBands: + def test_bands_fill_the_output_and_are_even(self): + content_h, caption_h = code_bands(1920) + assert content_h + caption_h == 1920 + assert content_h % 2 == 0 and caption_h % 2 == 0 + + def test_caption_reserve_is_about_fifteen_percent(self): + _, caption_h = code_bands(1920) + assert abs(caption_h / 1920 - CAPTION_BAND_RATIO) <= 0.01 + + def test_large_caption_ratio_still_leaves_a_band(self): + content_h, caption_h = code_bands(1000, 0.9) + assert content_h >= 2 and caption_h >= 2 + assert content_h + caption_h == 1000 + + +class TestFitWindow: + def test_short_pane_fits_without_follow(self): + crop_h, scaled_h, needs_follow = fit_window(300, 2.0, 1632) + assert crop_h == 300 and scaled_h == 600 + assert needs_follow is False + + def test_tall_pane_needs_a_follow_window(self): + crop_h, scaled_h, needs_follow = fit_window(2000, 2.7, 1632) + assert needs_follow is True + assert scaled_h == 1632 + assert crop_h <= 2000 and crop_h % 2 == 0 + + def test_scaled_height_never_exceeds_the_band(self): + for pane_h, scale in ((300, 2.0), (2000, 2.7), (1080, 0.75)): + _, scaled_h, _ = fit_window(pane_h, scale, 1632) + assert scaled_h <= 1632 and scaled_h % 2 == 0 + + def test_degenerate_pane_is_clamped_not_zero(self): + crop_h, scaled_h, _ = fit_window(10, 0.01, 100) + assert crop_h >= 2 and scaled_h >= 2 + + +class TestFollowSendcmd: + def test_dedupes_change_points_and_is_segment_relative(self): + follow = [(1.0, 100.0), (2.0, 100.0), (3.0, 200.0), (4.0, 200.0)] + lines = follow_sendcmd_lines(follow, 0, 100, 500, start=1.0) + assert len(lines) == 2 + assert lines[0].startswith("0.0000") + assert lines[1].startswith("2.0000") + assert "y 50;" in lines[0] + assert "y 150;" in lines[1] + + def test_window_is_clamped_to_the_pane(self): + lines = follow_sendcmd_lines( + [(0.0, -500.0), (1.0, 99999.0)], 100, 100, 500) + ys = [int(ln.split(" y ")[1].rstrip(";")) for ln in lines] + assert ys == [100, 500] + + def test_points_before_the_segment_start_are_dropped(self): + follow = [(0.0, 100.0), (2.0, 300.0)] + lines = follow_sendcmd_lines(follow, 0, 100, 500, start=1.0) + assert len(lines) == 1 + assert lines[0].startswith("1.0000") + + +class TestCodeFiltergraph: + def test_graph_crops_scales_and_overlays(self): + graph = code_filtergraph((200, 100, 1440, 800), 1080, 1920) + assert graph is not None + assert "crop=" in graph + assert "scale=1080:600" in graph + assert "overlay=x=0:y=" in graph + assert graph.endswith("[v]") + + def test_no_follow_means_no_sendcmd(self): + graph = code_filtergraph((200, 100, 1440, 800), 1080, 1920, follow=None) + assert graph is not None + assert "sendcmd" not in graph + + def test_follow_on_a_tall_pane_emits_sendcmd(self): + pane = (100, 0, 800, 4000) + graph = code_filtergraph(pane, 1080, 1920, + follow=[(0.0, 500.0), (2.0, 1500.0)]) + assert graph is not None + assert "sendcmd=c=" in graph + assert "crop@c=" in graph + assert graph.endswith("[v]") + + def test_follow_without_a_window_does_not_emit_sendcmd(self): + graph = code_filtergraph((200, 100, 1440, 800), 1080, 1920, + follow=[(0.0, 500.0)]) + assert graph is not None + assert "sendcmd" not in graph + + def test_min_scale_fallback_returns_none(self): + # out_w / pane_w = 1080 / 2000 = 0.54 < 0.75. + assert code_filtergraph((0, 0, 2000, 800), 1080, 1920) is None + + def test_min_scale_can_be_overridden(self): + graph = code_filtergraph((0, 0, 2000, 800), 1080, 1920, min_scale=0.5) + assert graph is not None + + def test_accepts_a_detector_dict(self): + pane = {"x": 200, "y": 100, "w": 1440, "h": 800, "mode": "editor"} + assert code_filtergraph(pane, 1080, 1920) is not None + + def test_camera_box_adds_a_third_branch(self): + graph = code_filtergraph((200, 100, 1440, 800), 1080, 1920, + cam_box=(0, 0, 300, 200)) + assert graph is not None + assert "split=3" in graph + assert "[cam]" in graph + assert graph.endswith("[v]") diff --git a/tests/test_layout_picker.py b/tests/test_layout_picker.py index b419fc5..8d16808 100644 --- a/tests/test_layout_picker.py +++ b/tests/test_layout_picker.py @@ -101,7 +101,8 @@ class TestPick: class TestValidDecisions: def test_every_valid_decision_maps_to_known_modules(self): - known = {"split_layout", "screencast_layout", "active_speaker"} + known = {"split_layout", "screencast_layout", "code_layout", + "active_speaker"} for decision in layout_picker.VALID: assert set(_module_flags(decision)) <= known -- 2.45.2 From 2d77269337fa99095e00052180374977cdb4e92d Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Mon, 5 Oct 2026 16:38:42 +0100 Subject: [PATCH 04/10] 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" -- 2.45.2 From 446bbbe061a9c85376251a3d9acd14c5a09b2598 Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Mon, 5 Oct 2026 16:38:42 +0100 Subject: [PATCH 05/10] feat(bridge): shorts-to-long-form bridge + dashboard UI --- clipwright/integrations/youtube_data.py | 154 +++++++++++ clipwright/pipeline/bridge.py | 207 ++++++++++++++ dashboard/src/App.jsx | 3 + dashboard/src/components/BridgeModal.jsx | 331 +++++++++++++++++++++++ dashboard/src/components/MediaInput.jsx | 53 ++++ dashboard/src/components/ResultCard.jsx | 18 ++ tests/test_bridge.py | 101 +++++++ tests/test_bridge_endpoint.py | 132 +++++++++ tests/test_youtube_data.py | 130 +++++++++ 9 files changed, 1129 insertions(+) create mode 100644 clipwright/integrations/youtube_data.py create mode 100644 clipwright/pipeline/bridge.py create mode 100644 dashboard/src/components/BridgeModal.jsx create mode 100644 tests/test_bridge.py create mode 100644 tests/test_bridge_endpoint.py create mode 100644 tests/test_youtube_data.py diff --git a/clipwright/integrations/youtube_data.py b/clipwright/integrations/youtube_data.py new file mode 100644 index 0000000..8c08f75 --- /dev/null +++ b/clipwright/integrations/youtube_data.py @@ -0,0 +1,154 @@ +"""Minimal YouTube Data API v3 client -- first comment only (PLAN #6). + +The Shorts "Related video" link and comment pinning are Studio-UI only and are +**not** exposed by any API, so this module deliberately does one thing: post a +top-level comment on a video via ``commentThreads.insert``. Pinning that comment +stays manual. + +Auth is a real-channel OAuth refresh token (service accounts do not work for +this scope). Credentials come from the environment and the integration is +**opt-in**: with any of them missing, :func:`is_configured` is false and no +network call is ever made. Callers must check :func:`is_configured` (or handle +:class:`YoutubeDataError`) before asking for a comment. + +Quota: ``commentThreads.insert`` costs 50 units of the default 10,000/day +project quota (~200 comments/day). That is the whole reason posting is a +deliberate, caller-triggered action and never automatic. + +Blocking, like ``postiz.py``: call through ``asyncio.to_thread`` from async +handlers. Every function accepts an optional pre-built ``httpx.Client`` so tests +can inject a ``httpx.MockTransport`` and no live OAuth is ever needed. +""" + +from __future__ import annotations + +import os +from typing import Any, Dict, Optional + +import httpx + +TOKEN_URI = "https://oauth2.googleapis.com/token" +COMMENT_THREADS_URL = "https://www.googleapis.com/youtube/v3/commentThreads" +# Required by insert (the comment posting endpoint). Read-only analytics use a +# different scope; this module never reads. +SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl" + +# Environment variable names, kept as constants so the API layer can name them +# in its "not configured" message without duplicating strings. +CLIENT_ID_ENV = "YOUTUBE_OAUTH_CLIENT_ID" +CLIENT_SECRET_ENV = "YOUTUBE_OAUTH_CLIENT_SECRET" +REFRESH_TOKEN_ENV = "YOUTUBE_OAUTH_REFRESH_TOKEN" +TOKEN_URI_ENV = "YOUTUBE_OAUTH_TOKEN_URI" + + +class YoutubeDataError(Exception): + """A missing config or non-2xx response from the YouTube Data API. + + Carries the status and body so the FastAPI layer can translate it into the + same status/detail it would have surfaced otherwise. + """ + + def __init__(self, status_code: int, detail: str): + super().__init__(detail) + self.status_code = status_code + self.detail = detail + + +def _env(name: str, default: Optional[str] = None) -> Optional[str]: + value = os.environ.get(name) + if value is None: + return default + value = value.strip() + return value or default + + +def credentials() -> Dict[str, Optional[str]]: + """The OAuth credentials read from the environment (values may be None).""" + return { + "client_id": _env(CLIENT_ID_ENV), + "client_secret": _env(CLIENT_SECRET_ENV), + "refresh_token": _env(REFRESH_TOKEN_ENV), + "token_uri": _env(TOKEN_URI_ENV, TOKEN_URI), + } + + +def is_configured() -> bool: + """True when a refresh-token flow can run. False = no-op, never called.""" + creds = credentials() + return all(creds[key] for key in ("client_id", "client_secret", "refresh_token")) + + +def _access_token(client: httpx.Client, creds: Dict[str, Optional[str]]) -> str: + resp = client.post(str(creds["token_uri"]), data={ + "client_id": creds["client_id"], + "client_secret": creds["client_secret"], + "refresh_token": creds["refresh_token"], + "grant_type": "refresh_token", + }) + if resp.status_code != 200: + raise YoutubeDataError( + 502, + f"YouTube OAuth token refresh failed: {(resp.text or '')[:300]}", + ) + try: + token = (resp.json() or {}).get("access_token") + except ValueError: + token = None + if not token: + raise YoutubeDataError(502, "YouTube OAuth token refresh returned no access_token") + return token + + +def post_first_comment(video_id: str, text: str, timeout: float = 60.0, + client: Optional[httpx.Client] = None) -> Dict[str, Any]: + """Post ``text`` as a top-level comment on ``video_id``. + + Returns the API's ``commentThreads.insert`` response (id + snippet). + + Raises :class:`YoutubeDataError` when unconfigured, given bad input, or when + YouTube rejects the insert. ``client`` is the test seam; pass an + ``httpx.Client`` built with a ``MockTransport`` to exercise this offline. + """ + if not video_id or not str(video_id).strip(): + raise YoutubeDataError(400, "video_id is required") + if not text or not str(text).strip(): + raise YoutubeDataError(400, "comment text is required") + if not is_configured(): + raise YoutubeDataError( + 400, + "YouTube Data API is not configured; set " + f"{CLIENT_ID_ENV}, {CLIENT_SECRET_ENV} and {REFRESH_TOKEN_ENV}", + ) + + owns_client = client is None + client = client or httpx.Client(timeout=timeout) + try: + token = _access_token(client, credentials()) + resp = client.post( + COMMENT_THREADS_URL, + params={"part": "snippet"}, + headers={"Authorization": f"Bearer {token}"}, + json={"snippet": { + "videoId": str(video_id).strip(), + "topLevelComment": { + "snippet": {"textOriginal": str(text)}, + }, + }}, + ) + finally: + if owns_client: + client.close() + + if resp.status_code not in (200, 201): + # 4xx are the caller's (invalid video / scope); 5xx become 502 so the + # API layer does not claim the upstream is down with a gateway code + # that came from YouTube, not this server. + status = resp.status_code if resp.status_code < 500 else 502 + raise YoutubeDataError( + status, + f"YouTube commentThreads.insert failed: {(resp.text or '')[:300]}", + ) + try: + return resp.json() or {} + except ValueError: + return {} diff --git a/clipwright/pipeline/bridge.py b/clipwright/pipeline/bridge.py new file mode 100644 index 0000000..ceaf713 --- /dev/null +++ b/clipwright/pipeline/bridge.py @@ -0,0 +1,207 @@ +"""Shorts -> long-form bridge copy (PLAN #6). + +Pure, network-free helpers that turn the active channel profile (+ its +``published_video_history``) into the copy a Short needs to funnel viewers to a +long-form video: + +* ``description_bridge`` -- a block appended to the Short's YouTube description; +* ``first_comment`` -- the top-level comment to post (and pin). + +Two "related video" features are Studio-UI only and are **not** exposed by any +API: the Shorts "Related video" link and comment pinning. Those therefore stay +manual, and ``checklist`` spells out the exact Studio steps including the +target long-form URL. + +The explicit target wins over the profile history. Callers pass it from the CLI +(``--longform-url``) or the API (``related_video_url``); nothing here performs +I/O. +""" + +from __future__ import annotations + +from typing import Any, Mapping, Optional + +from clipwright.pipeline import profile_prompts +from clipwright.pipeline.profiles import Profile + +# Fallback label when the target URL is provided but the profile says nothing. +DEFAULT_TARGET_LABEL = "Full video" + +# Keys a published_video_history entry may carry to identify the video. The +# first match wins; ``id``/``video_id`` build a watch URL. +_URL_KEYS = ("url", "video_url", "watch_url", "link") +_ID_KEYS = ("id", "video_id", "youtube_id") +_DATE_KEYS = ("published_at", "published", "date", "uploaded_at") + + +def _entry_url(entry: Mapping) -> Optional[str]: + """The watch URL for one ``published_video_history`` entry, or None.""" + if not isinstance(entry, Mapping): + return None + for key in _URL_KEYS: + value = entry.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + for key in _ID_KEYS: + value = entry.get(key) + if isinstance(value, str) and value.strip(): + return f"https://www.youtube.com/watch?v={value.strip()}" + return None + + +def _entry_sort_key(entry: Mapping) -> str: + for key in _DATE_KEYS: + value = entry.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + +def target_video(profile: Optional[Profile], + related_video_url: Optional[str] = None) -> Optional[str]: + """The long-form target: the explicit URL, else the newest history entry. + + An explicit ``related_video_url`` always wins. Otherwise the profile's + ``published_video_history`` is searched for an entry that names a video + (``url``/``video_url``/... or an ``id``); the newest by a best-effort date + field is chosen, falling back to the last entry listed. + """ + if isinstance(related_video_url, str) and related_video_url.strip(): + return related_video_url.strip() + history = list(getattr(profile, "published_video_history", None) or []) + candidates = [(k, e) for e in history if (k := _entry_url(e))] + if not candidates: + return None + candidates.sort(key=lambda pair: _entry_sort_key(pair[1])) + return candidates[-1][0] + + +def _target_label(profile: Optional[Profile]) -> str: + """A human label for the target, derived from the profile's description.""" + template = getattr(profile, "description_template", "") if profile else "" + # Templates look like "{hook}\n\nFull video: {link}\n\n#tags" -- lift the + # words before "{link}" when they name the long-form video. + if "{link}" in template: + prefix = template.split("{link}")[0].strip().splitlines()[-1].strip() + prefix = prefix.rstrip(":").strip() + if prefix and "{hook}" not in prefix: + return prefix + return DEFAULT_TARGET_LABEL + + +def _clip_hook(clip: Optional[Mapping]) -> str: + """The clip's hook text if the pipeline produced one, else its title.""" + if not isinstance(clip, Mapping): + return "" + for key in ("viral_hook_text", "hook_text", "video_title_for_youtube_short"): + value = clip.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + +def _render_description_template(template: str, target: Optional[str], + clip: Optional[Mapping]) -> str: + """Fill the profile's ``{hook}``/``{link}`` slots without str.format. + + ``str.format`` would explode on any other brace in the template (or + hashtags that are fine today); a literal replace can only touch the two + documented placeholders. + """ + rendered = template.replace("{hook}", _clip_hook(clip)) + rendered = rendered.replace("{link}", target or "") + return "\n".join(line.rstrip() for line in rendered.splitlines()).strip() + + +def description_bridge(profile: Optional[Profile], + related_video_url: Optional[str] = None, + clip: Optional[Mapping] = None) -> str: + """The description block: a target CTA plus the profile's description copy. + + The target URL appears first (and in the rendered template when the profile + has one). Without a target the channel links/description still render, so a + bridge is produced even before a long-form URL is chosen. + """ + target = target_video(profile, related_video_url) + parts: list[str] = [] + if target: + parts.append(f"▶ {_target_label(profile)}: {target}") + + template = (getattr(profile, "description_template", "") if profile else "") or "" + rendered = _render_description_template(template, target, clip) if template else "" + if rendered: + parts.append(rendered) + else: + # No template: fall back to the profile's plain description block. + block = profile_prompts.description_block(profile) if profile else "" + if block: + parts.append(block.rstrip()) + + # The profile's links belong in the bridge even when the template's {link} + # slot was empty (no target yet) or the template does not mention them. + links = [link for link in (getattr(profile, "links", None) or []) + if isinstance(link, str) and link.strip()] + if links and not any(link in "\n".join(parts) for link in links): + parts.append("More from this channel: " + " | ".join(links)) + + return "\n\n".join(p for p in parts if p).strip() + + +def first_comment(profile: Optional[Profile], + related_video_url: Optional[str] = None, + clip: Optional[Mapping] = None) -> str: + """The top-level comment text. Always carries the long-form reference. + + With no target it points at the channel's links (or the description) rather + than inventing a URL; it is never empty. + """ + target = target_video(profile, related_video_url) + hook = _clip_hook(clip) + if target: + text = f"▶ {_target_label(profile)}: {target}" + if hook: + text += f"\n\n{_target_label(profile)} covers this: {hook}" + return text + links = list(getattr(profile, "links", None) or []) + if links: + return f"Watch the long-form videos here: {links[0]}" + return "The full long-form video is linked in the description." + + +def checklist(profile: Optional[Profile], + related_video_url: Optional[str] = None) -> list[str]: + """The manual Studio steps for this Short (both are Studio-UI only). + + The Shorts "Related video" link and comment pinning have no public API, so + they are copy-paste steps, not something the server can do. + """ + target = target_video(profile, related_video_url) + target_text = target or "" + return [ + "Open YouTube Studio -> Content -> this Short -> Edit.", + f"Details -> Related video: set it to {target_text} " + "(the Shorts related-video link is Studio-UI only; no API can set it).", + "Post the generated first comment " + "(or call this clip's bridge/comment endpoint if the YouTube Data API " + "is configured).", + "Pin the first comment: hover it -> the three-dot menu -> Pin. " + "Pinning stays manual (no API).", + ] + + +def build_bridge(profile: Optional[Profile], + clip: Optional[Mapping] = None, + related_video_url: Optional[str] = None) -> dict[str, Any]: + """All bridge fields for one clip, ready to merge into clip metadata. + + ``related_video_url`` is the explicit target (CLI ``--longform-url`` / API + ``related_video_url``); when omitted the profile history is used. + """ + target = target_video(profile, related_video_url) + return { + "related_video_url": target, + "description_bridge": description_bridge(profile, target, clip), + "first_comment": first_comment(profile, target, clip), + "checklist": checklist(profile, target), + "manual_pin_required": True, + } diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index e2b79b6..81005bd 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -673,6 +673,9 @@ function App() { auto_hook_style: data.autoHook ? (data.autoHookStyle || 'pill') : null, // 'auto' is the server default, so only a deliberate choice travels. layouts: data.layout && data.layout !== 'auto' ? data.layout : null, + // Channel profile slug (channels/.json). Absent = no profile, so + // the default request stays byte-identical to the pre-feature one. + channel: data.channel || null, }; if (data.type === 'url') { diff --git a/dashboard/src/components/BridgeModal.jsx b/dashboard/src/components/BridgeModal.jsx new file mode 100644 index 0000000..85ea0ac --- /dev/null +++ b/dashboard/src/components/BridgeModal.jsx @@ -0,0 +1,331 @@ +import React, { useState, useEffect } from 'react'; +import { Copy, Check, CheckCircle2, AlertCircle, Loader2, Link2, Youtube, MessageSquare } from 'lucide-react'; +import Modal from './ui/Modal'; +import { apiFetch } from '../lib/api'; + +// Shorts -> long-form bridge (PLAN #6). The related-video link and comment +// pinning are Studio-UI only, so this panel always carries the manual steps: +// it never pretends the server can set them. +// +// Copy it? Use the copy buttons. Post the first comment automatically? Only +// when you click it, and only on a server with the YouTube Data API wired up. + +// Accept a full YouTube URL or a bare id and return just the id. The published +// Short's id is what the comment endpoint needs; people usually have the URL. +function videoIdFrom(raw) { + const value = String(raw || '').trim(); + if (!value) return ''; + const urlMatch = value.match(/(?:v=|\/shorts\/|youtu\.be\/|\/embed\/)([A-Za-z0-9_-]{6,})/); + if (urlMatch) return urlMatch[1]; + const bare = value.match(/^([A-Za-z0-9_-]{6,})$/); + return bare ? bare[1] : value; +} + +export default function BridgeModal({ isOpen, onClose, jobId, clipIndex }) { + const [data, setData] = useState(null); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const [copied, setCopied] = useState(null); + + // Checked-off Studio steps, remembered per clip so closing the sheet while + // working through the manual steps doesn't lose your place. + const storageKey = `cw_bridge_check_${jobId}_${clipIndex}`; + const [checkedSteps, setCheckedSteps] = useState({}); + + const [videoId, setVideoId] = useState(''); + const [posting, setPosting] = useState(false); + const [postStatus, setPostStatus] = useState(null); + + useEffect(() => { + if (!isOpen) return undefined; + let cancelled = false; + + setLoading(true); + setError(null); + setData(null); + setPostStatus(null); + setVideoId(''); + try { + setCheckedSteps(JSON.parse(localStorage.getItem(storageKey)) || {}); + } catch { + setCheckedSteps({}); + } + + apiFetch(`/api/clip/${jobId}/${clipIndex}/bridge`) + .then(async (res) => { + if (!res.ok) { + let detail = ''; + const text = await res.text().catch(() => ''); + try { + const j = JSON.parse(text); + if (typeof j.detail === 'string') detail = j.detail; + } catch { /* keep the raw body */ } + throw new Error(detail || `Could not load the bridge (${res.status}).`); + } + return res.json(); + }) + .then((payload) => { if (!cancelled) setData(payload); }) + .catch((e) => { if (!cancelled) setError(e.message || 'Could not load the bridge.'); }) + .finally(() => { if (!cancelled) setLoading(false); }); + + return () => { cancelled = true; }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isOpen, jobId, clipIndex]); + + const handleCopy = async (field, text) => { + try { + await navigator.clipboard.writeText(text || ''); + setCopied(field); + setTimeout(() => setCopied(null), 2000); + } catch { + // clipboard unavailable — silent + } + }; + + const toggleStep = (i) => { + setCheckedSteps((prev) => { + const next = { ...prev, [i]: !prev[i] }; + try { localStorage.setItem(storageKey, JSON.stringify(next)); } catch { /* storage unavailable */ } + return next; + }); + }; + + const handlePostComment = async () => { + const vid = videoIdFrom(videoId); + if (!vid) return; + setPosting(true); + setPostStatus(null); + try { + const res = await apiFetch(`/api/clip/${jobId}/${clipIndex}/bridge/comment`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ video_id: vid, text: data?.first_comment || undefined }), + }); + if (!res.ok) { + let detail = ''; + const text = await res.text().catch(() => ''); + try { + const j = JSON.parse(text); + if (typeof j.detail === 'string') detail = j.detail; + } catch { /* keep the raw body */ } + // A 400 here almost always means the YouTube integration is not + // configured; say that plainly and point at the manual route. + const fallback = res.status === 400 + ? "This server can't post comments yet — the YouTube Data API isn't set up. Copy the comment above and post it in Studio instead." + : `Could not post the comment (${res.status}).`; + setPostStatus({ ok: false, msg: detail || fallback }); + return; + } + await res.json().catch(() => ({})); + setPostStatus({ ok: true, msg: 'Comment posted. Open YouTube Studio and pin it — pinning stays manual.' }); + } catch (e) { + setPostStatus({ ok: false, msg: e.message || 'Could not post the comment.' }); + } finally { + setPosting(false); + } + }; + + // The endpoint reports whether comment posting is available on this server. + // An older/absent field is treated as "try it" — a 400 is handled above. + const configured = data ? data.comment_api_configured !== false : true; + const canPostComment = configured && !!videoId.trim() && !!data?.first_comment; + + return ( + + {loading && ( +
+ loading bridge… +
+ )} + + {!loading && error && ( +
+ + {error} +
+ )} + + {!loading && !error && data && ( +
+

+ Funnel viewers of this Short to a long-form video. The related-video link and the comment pin live only in YouTube Studio, so those steps stay manual. +

+ + {/* Related-video target */} +
+ + {data.related_video_url ? ( +
+ + + {data.related_video_url} + + +
+ ) : ( +
+ + + No related video set for this clip yet. Paste the long-form URL into YouTube Studio's + {' '}Related video field when you set it up — the checklist below has the steps. + +
+ )} +
+ + {/* Manual Studio checklist */} +
+
+ + manual · no api +
+ {Array.isArray(data.checklist) && data.checklist.length > 0 ? ( +
    + {data.checklist.map((step, i) => { + const done = !!checkedSteps[i]; + return ( +
  1. + +
  2. + ); + })} +
+ ) : ( +

no checklist saved for this clip.

+ )} +
+ + {/* Copy-paste copy */} +
+
+ + +
+ {data.description_bridge ? ( +

+ {data.description_bridge} +

+ ) : ( +

+ no description copy generated for this clip. +

+ )} +
+ +
+
+ + +
+ {data.first_comment ? ( +

+ {data.first_comment} +

+ ) : ( +

+ no first comment generated for this clip. +

+ )} +
+ + {/* Optional opt-in comment posting */} +
+
+ + opt-in +
+

+ Optional. clipwright never posts on its own — this runs only when you click the button. Pinning the comment still has to be done by hand in Studio. +

+ + {!configured ? ( +
+ + + This server has no YouTube Data API credentials, so it can't post for you. Copy the comment above and post it in Studio instead. + +
+ ) : ( +
+
+ setVideoId(e.target.value)} + className="input-field sm:flex-1" + placeholder="published Short video id or URL" + aria-label="published Short video id or URL" + /> + +
+ {postStatus && ( +
+ {postStatus.ok + ? + : } + {postStatus.msg} +
+ )} +
+ )} + +

+ related-video link + pin: Studio only +

+
+
+ )} +
+ ); +} diff --git a/dashboard/src/components/MediaInput.jsx b/dashboard/src/components/MediaInput.jsx index 38c1891..4da9c6b 100644 --- a/dashboard/src/components/MediaInput.jsx +++ b/dashboard/src/components/MediaInput.jsx @@ -61,6 +61,13 @@ export default function MediaInput({ onProcess, isProcessing }) { const [layout, setLayout] = useState(() => { try { return localStorage.getItem('cw_layout') || 'auto'; } catch { return 'auto'; } }); + // Channel profile (channels/.json on the server): tunes how the AI + // writes titles, hooks and the description, and how it art-directs the + // thumbnail. Per job and off by default, so nothing changes for anyone who + // does not use profiles. Fetched from GET /api/channels; when that list is + // empty or unreachable the selector simply does not render. + const [channels, setChannels] = useState([]); + const [channel, setChannel] = useState('none'); const infoRef = useRef(null); // Close the compatibility popover on any outside click. @@ -99,6 +106,22 @@ export default function MediaInput({ onProcess, isProcessing }) { .catch(() => {}); }, []); + // Channel profiles available on this install. A missing route, an empty + // directory or a network error all leave the list empty, which keeps the + // selector hidden — profiles are opt-in and never block a job. + useEffect(() => { + let cancelled = false; + fetch(getApiUrl('/api/channels')) + .then((r) => (r.ok ? r.json() : null)) + .then((data) => { + if (cancelled || !data) return; + const list = Array.isArray(data.channels) ? data.channels : []; + setChannels(list.filter((c) => c && c.slug)); + }) + .catch(() => {}); + return () => { cancelled = true; }; + }, []); + // A link pasted in the landing hero: preload it here so the user picks up // where they left off. Not auto-submitted — the rights attestation below // has to be ticked by the user. @@ -124,6 +147,9 @@ export default function MediaInput({ onProcess, isProcessing }) { autoHook, autoHookStyle, layout, + // 'none' = no profile; only a real slug travels, so the default + // request stays byte-identical to the pre-feature one. + channel: channel === 'none' ? null : channel, }; try { localStorage.setItem('cw_auto_hook', autoHook ? '1' : '0'); @@ -291,6 +317,32 @@ export default function MediaInput({ onProcess, isProcessing }) { + {/* Channel profile — only rendered when the install has profiles, + so an empty list or a failed fetch leaves no trace. Tunes the + packaging the AI writes for a job: title, hook, description + and thumbnail. Defaults to no profile. */} + {channels.length > 0 && ( +
+
+

channel profile

+ +
+

+ Tailors titles, hooks, description and thumbnail for that channel. +

+
+ )} + {/* Advanced generation controls — collapsed by default; blank = AI decides */}
diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index bfcb038..dd5eddb 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -4,6 +4,7 @@ import { getApiUrl } from '../config'; import { apiFetch } from '../lib/api'; import SubtitleModal from './SubtitleModal'; import HookModal from './HookModal'; +import BridgeModal from './BridgeModal'; import Modal from './ui/Modal'; import { renderInBrowser } from '../lib/renderInBrowser'; @@ -214,6 +215,7 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g const [isSubtitling, setIsSubtitling] = useState(false); const [isHooking, setIsHooking] = useState(false); const [showHookModal, setShowHookModal] = useState(false); + const [showBridgeModal, setShowBridgeModal] = useState(false); const [editError, setEditError] = useState(null); const [clipDuration, setClipDuration] = useState(() => { @@ -924,6 +926,15 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g {isHooking ? 'saving…' : 'edit hook'} + + + + ) : ( + + )} + + )} + {/* Output format selector */}

Output format

-- 2.45.2 From 7c260b3fa185bae9cf18629aecbe3d550b592d5f Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Mon, 5 Oct 2026 18:23:21 +0100 Subject: [PATCH 08/10] fix(dashboard): stop discarding the saved Postiz base URL every load The retired maintainer default is now blanked once (marker-guarded) instead of on every read, so a self-hoster whose own Postiz instance lives on that host no longer has to retype the URL each session. --- dashboard/src/App.jsx | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index e8baad6..650482a 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -159,14 +159,23 @@ const postizHeaders = (key, url) => { // Older builds defaulted to a maintainer-hosted Postiz instance and persisted // it to localStorage on mount, so an upgrade could silently keep sending a -// user's API key to someone else's server. Recognize that retired default and -// treat it as unset. The host is assembled from parts so no live reference to -// it remains in the source. +// user's API key to a server they never chose. Retire that one legacy value +// ONCE (guarded by a marker) instead of on every read: blanking it on each load +// also threw away a URL the user deliberately saved — a self-hoster's own +// instance can legitimately live on that host — and forced them to retype it +// every session. The host is assembled from parts so no live reference to it +// remains in the source. const RETIRED_POSTIZ_HOST = ['postiz', 'pbento', 'pt'].join('.'); +const POSTIZ_URL_RETIRED_KEY = 'postiz_url_retired_v1'; const normalizeStoredPostizUrl = (url) => { const base = String(url || '').trim().replace(/\/$/, ''); if (!base) return ''; - return base === `https://${RETIRED_POSTIZ_HOST}` ? '' : base; + let retired = false; + try { + retired = localStorage.getItem(POSTIZ_URL_RETIRED_KEY) === '1'; + localStorage.setItem(POSTIZ_URL_RETIRED_KEY, '1'); + } catch (_) { /* storage unavailable: nothing to migrate */ } + return !retired && base === `https://${RETIRED_POSTIZ_HOST}` ? '' : base; }; const SESSION_KEY = 'clipwright_session'; -- 2.45.2 From 38045a3c5010ae2597bb6ab4755eef09ba1cc458 Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Mon, 5 Oct 2026 18:23:21 +0100 Subject: [PATCH 09/10] feat(dashboard): native schedule date picker Replace the dd/mm/yyyy free-text field with a native date input (min=today, dark chrome) and parse YYYY-MM-DD; time input, payload and publish logic unchanged. --- dashboard/src/components/ResultCard.jsx | 36 +++++++++++++++---------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index dd5eddb..854ae83 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -26,17 +26,26 @@ const PlatformIcon = ({ identifier, size = 16 }) => { return ; }; -// DD/MM/YYYY + HH:MM parsed into a local Date, with explicit range checks so -// 31/02/2026 is rejected instead of silently rolling over to March. +// Today as YYYY-MM-DD in the user's own timezone, for the date input's `min`. +// Built from local parts (not toISOString, which would shift the day across the +// UTC boundary for users west of Greenwich). +function todayInputValue() { + const n = new Date(); + return `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`; +} + +// YYYY-MM-DD (a native date picker's value) + HH:MM parsed into a local Date, +// with explicit range checks so 2026-02-31 is rejected instead of silently +// rolling over to March. function parseSchedule(dateStr, timeStr) { const d = String(dateStr || '').trim(); const t = String(timeStr || '').trim(); - if (!d || !t) return { error: 'Enter both a date (dd/mm/yyyy) and a time.' }; - const dm = d.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/); - if (!dm) return { error: 'Date must be in dd/mm/yyyy format.' }; - const day = Number(dm[1]); + if (!d || !t) return { error: 'Pick a date and a time.' }; + const dm = d.match(/^(\d{4})-(\d{2})-(\d{2})$/); + if (!dm) return { error: 'Date must be in yyyy-mm-dd format.' }; + const year = Number(dm[1]); const month = Number(dm[2]); - const year = Number(dm[3]); + const day = Number(dm[3]); if (month < 1 || month > 12) return { error: 'Month must be between 01 and 12.' }; if (day < 1 || day > 31) return { error: 'Day must be between 01 and 31.' }; const tm = t.match(/^(\d{1,2}):(\d{2})$/); @@ -1048,7 +1057,7 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g />
- {/* Scheduling — dd/mm/yyyy + HH:MM */} + {/* Scheduling — native date picker + HH:MM */}
)} -- 2.45.2 From 6aa3b0ec8228b27a9ea19e4e40a7ac487c50a80d Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Mon, 5 Oct 2026 19:23:27 +0100 Subject: [PATCH 10/10] chore(docker): keep runtime caches out of the bind-mounted repo HOME=/tmp + MPLCONFIGDIR/HF_HOME/YOLO_CONFIG_DIR stop matplotlib, fontconfig and ASR caches writing into the host bind mount (unwritable by the non-root appuser). A persistent huggingface-cache named volume holds the model downloads; .fontconfig/ is now gitignored. --- .gitignore | 1 + Dockerfile | 12 ++++++++++++ docker-compose.yml | 9 +++++++++ 3 files changed, 22 insertions(+) diff --git a/.gitignore b/.gitignore index dc37ef1..982d997 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,7 @@ output/ # Cache dirs .cache/ .config/ +.fontconfig/ .pytest_cache/ .ruff_cache/ diff --git a/Dockerfile b/Dockerfile index a16c400..6ac97f9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -71,6 +71,18 @@ COPY --from=builder /opt/venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" ENV PYTHONUNBUFFERED=1 +# Runtime caches must not land inside the bind-mounted source tree. Compose +# mounts the host repo at /app, and the container's non-root appuser cannot +# write there, so matplotlib/fontconfig logged permission errors and dropped a +# stray .fontconfig (owned by the container's uid) into the repo. Point HOME +# and the disposable caches at writable /tmp; keep the ASR model cache on the +# named volume mounted at HF_HOME (see docker-compose.yml) so it survives +# container recreates. +ENV HOME=/tmp \ + MPLCONFIGDIR=/tmp/.cache/matplotlib \ + YOLO_CONFIG_DIR=/tmp/Ultralytics \ + HF_HOME=/app/.cache/huggingface + # GPU runtime wiring — harmless no-ops on CPU builds / hosts without the # NVIDIA runtime. LD_LIBRARY_PATH points at the pip-installed CUDA libs # (paths simply don't exist in CPU images); DRIVER_CAPABILITIES asks the diff --git a/docker-compose.yml b/docker-compose.yml index 9a6fdde..57ee97d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,6 +8,12 @@ services: - .:/app - /app/__pycache__ - ./output:/app/output + # Persistent, writable cache for the ASR model downloads. Without this the + # bind mount above shadows /app/.cache with a host-owned dir the non-root + # appuser cannot write (HF cache permission-denied warnings). The named + # volume is initialised from the image's appuser-owned dir, so it stays + # writable and the model survives container recreates. + - huggingface-cache:/app/.cache/huggingface restart: unless-stopped frontend: @@ -29,3 +35,6 @@ services: restart: unless-stopped depends_on: - backend + +volumes: + huggingface-cache: -- 2.45.2