clipwright/clipwright/pipeline/profiles.py

295 lines
11 KiB
Python

"""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 ``<repo>/channels/<slug>.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
# ``<repo>/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/<slug>.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