From ea251a11283a19e28feab08aa02d7ed2c4e33811 Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Mon, 5 Oct 2026 16:38:42 +0100 Subject: [PATCH] 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") == []